feat(controls): ship a CRA catalog snapshot, map without the backend #250
No files matched your search
@@ -87,6 +87,17 @@ KEYCLOAK_CLIENT_ID=compliance-dashboard
|
||||
REDIRECT_URI=http://localhost:8080/auth/callback
|
||||
APP_URL=http://localhost:8080
|
||||
|
||||
# Control mapping (OSCAL catalog from breakpilot-compliance)
|
||||
# Unset BREAKPILOT_BASE_URL to run snapshot-only: the image ships a CRA catalog
|
||||
# snapshot, so findings still carry control_refs without the backend. The
|
||||
# master-controls catalog is DB-derived and not shipped — turn the semantic pass
|
||||
# off when running snapshot-only.
|
||||
# BREAKPILOT_BASE_URL=https://api-dev.breakpilot.ai
|
||||
# BREAKPILOT_TOKEN=
|
||||
BREAKPILOT_SNAPSHOT_DIR=/data/compliance-scanner/oscal
|
||||
# BREAKPILOT_SEMANTIC_MAPPING=false
|
||||
# BREAKPILOT_GROUNDED_CHECKS=true
|
||||
|
||||
# OpenTelemetry (optional - omit to disable)
|
||||
# OTEL_EXPORTER_OTLP_ENDPOINT=http://localhost:4317
|
||||
# OTEL_SERVICE_NAME=compliance-agent
|
||||
@@ -69,6 +69,10 @@ RUN mkdir -p /etc/nix && printf '%s\n' \
|
||||
|
||||
COPY --from=builder /app/target/release/compliance-agent /usr/local/bin/compliance-agent
|
||||
COPY docker/agent-entrypoint.sh /usr/local/bin/agent-entrypoint.sh
|
||||
# OSCAL control-catalog snapshot: lets control mapping run without the
|
||||
# breakpilot-compliance backend. The entrypoint seeds it into
|
||||
# BREAKPILOT_SNAPSHOT_DIR on start (copy-if-absent).
|
||||
COPY --from=builder /app/compliance-agent/controls/snapshot /opt/breakpilot/oscal-snapshot
|
||||
RUN chmod +x /usr/local/bin/agent-entrypoint.sh
|
||||
|
||||
# Copy documentation for the help chat assistant
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -7,7 +7,7 @@
|
||||
//! consumes. The producer owns the catalog; we own the assessment — this is the
|
||||
//! ingest half of the loop.
|
||||
|
||||
use std::path::PathBuf;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use secrecy::{ExposeSecret, SecretString};
|
||||
|
||||
@@ -20,34 +20,53 @@ use compliance_core::traits::{Control, ControlQuery, ControlsProvider};
|
||||
/// and snapshots it locally for deterministic / offline reuse.
|
||||
pub struct OscalControlsProvider {
|
||||
http: reqwest::Client,
|
||||
base_url: String,
|
||||
/// `None` = snapshot-only: no fetch, serve whatever is under `snapshot_dir`
|
||||
/// (baked into the image or written by an earlier online run).
|
||||
base_url: Option<String>,
|
||||
token: Option<SecretString>,
|
||||
snapshot_dir: PathBuf,
|
||||
}
|
||||
|
||||
impl OscalControlsProvider {
|
||||
/// Create a provider. `base_url` is the breakpilot-compliance root (e.g.
|
||||
/// `http://backend-compliance:8002`); `snapshot_dir` is where catalog
|
||||
/// snapshots are written so a later scan can reuse them without the network.
|
||||
/// `http://backend-compliance:8002`) or `None` for snapshot-only mode;
|
||||
/// `snapshot_dir` is where catalog snapshots are written so a later scan can
|
||||
/// reuse them without the network.
|
||||
pub fn new(
|
||||
http: reqwest::Client,
|
||||
base_url: impl Into<String>,
|
||||
base_url: Option<String>,
|
||||
token: Option<SecretString>,
|
||||
snapshot_dir: impl Into<PathBuf>,
|
||||
) -> Self {
|
||||
Self {
|
||||
http,
|
||||
base_url: base_url.into(),
|
||||
base_url,
|
||||
token,
|
||||
snapshot_dir: snapshot_dir.into(),
|
||||
}
|
||||
}
|
||||
|
||||
fn catalog_url(&self, framework: &str) -> String {
|
||||
format!(
|
||||
"{}/api/compliance/v1/oscal/catalog?framework={framework}",
|
||||
self.base_url.trim_end_matches('/')
|
||||
)
|
||||
fn catalog_url(&self, framework: &str) -> Option<String> {
|
||||
self.base_url.as_deref().map(|b| {
|
||||
format!(
|
||||
"{}/api/compliance/v1/oscal/catalog?framework={framework}",
|
||||
b.trim_end_matches('/')
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
/// True when at least one `oscal-catalog-*.json` snapshot exists, i.e. the
|
||||
/// provider can serve catalogs without a backend.
|
||||
pub fn has_snapshots(snapshot_dir: &Path) -> bool {
|
||||
std::fs::read_dir(snapshot_dir)
|
||||
.map(|rd| {
|
||||
rd.flatten().any(|e| {
|
||||
let n = e.file_name();
|
||||
let n = n.to_string_lossy();
|
||||
n.starts_with("oscal-catalog-") && n.ends_with(".json")
|
||||
})
|
||||
})
|
||||
.unwrap_or(false)
|
||||
}
|
||||
|
||||
fn snapshot_path(&self, framework: &str) -> PathBuf {
|
||||
@@ -57,7 +76,12 @@ impl OscalControlsProvider {
|
||||
|
||||
/// Fetch the raw catalog bytes for a framework token over HTTP.
|
||||
async fn fetch_raw(&self, framework: &str) -> Result<Vec<u8>, CoreError> {
|
||||
let mut req = self.http.get(self.catalog_url(framework));
|
||||
let Some(url) = self.catalog_url(framework) else {
|
||||
return Err(CoreError::Http(
|
||||
"no catalog backend configured (snapshot-only mode)".to_string(),
|
||||
));
|
||||
};
|
||||
let mut req = self.http.get(url);
|
||||
if let Some(token) = &self.token {
|
||||
req = req.bearer_auth(token.expose_secret());
|
||||
}
|
||||
@@ -178,15 +202,20 @@ mod tests {
|
||||
"props":[],"parts":[{"name":"statement","prose":"require mfa"}]}]}]}}"#;
|
||||
|
||||
fn provider(dir: &std::path::Path) -> OscalControlsProvider {
|
||||
OscalControlsProvider::new(reqwest::Client::new(), "http://unused/", None, dir)
|
||||
OscalControlsProvider::new(
|
||||
reqwest::Client::new(),
|
||||
Some("http://unused/".to_string()),
|
||||
None,
|
||||
dir,
|
||||
)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn builds_catalog_url_and_snapshot_path() {
|
||||
let p = provider(std::path::Path::new("/snap"));
|
||||
assert_eq!(
|
||||
p.catalog_url("cra"),
|
||||
"http://unused/api/compliance/v1/oscal/catalog?framework=cra"
|
||||
p.catalog_url("cra").as_deref(),
|
||||
Some("http://unused/api/compliance/v1/oscal/catalog?framework=cra")
|
||||
);
|
||||
assert_eq!(
|
||||
p.snapshot_path("cra"),
|
||||
@@ -226,4 +255,33 @@ mod tests {
|
||||
assert_eq!(doc.framework(), Some(ComplianceFramework::Cra));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// The snapshot shipped in the image must parse and carry the full CRA
|
||||
/// catalog — a truncated or reshaped refresh would silently disable control
|
||||
/// mapping in snapshot-only environments.
|
||||
#[test]
|
||||
fn shipped_cra_snapshot_parses_with_all_controls() {
|
||||
const SHIPPED: &str = include_str!("../../controls/snapshot/oscal-catalog-cra.json");
|
||||
let doc: OscalDocument = serde_json::from_str(SHIPPED).unwrap();
|
||||
assert_eq!(doc.framework(), Some(ComplianceFramework::Cra));
|
||||
assert_eq!(doc.to_controls().len(), 40);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn snapshot_only_mode_serves_baked_catalog() {
|
||||
let dir = std::env::temp_dir().join(format!("oscal-test-{}", uuid::Uuid::new_v4()));
|
||||
assert!(!OscalControlsProvider::has_snapshots(&dir));
|
||||
let online = provider(&dir);
|
||||
online
|
||||
.write_snapshot("cra", MINI_CATALOG.as_bytes())
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(OscalControlsProvider::has_snapshots(&dir));
|
||||
let offline = OscalControlsProvider::new(reqwest::Client::new(), None, None, &dir);
|
||||
assert!(offline.catalog_url("cra").is_none());
|
||||
let doc = offline.load(ComplianceFramework::Cra).await.unwrap();
|
||||
assert_eq!(doc.to_controls().len(), 1);
|
||||
assert!(offline.load_master_controls().await.is_err());
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
}
|
||||
@@ -38,15 +38,9 @@ pub async fn triage_repo_findings(
|
||||
repo_path: &Path,
|
||||
findings: &mut [Finding],
|
||||
) -> usize {
|
||||
let Some(base_url) = config.breakpilot.base_url.clone() else {
|
||||
return 0; // control triage is opt-in via BREAKPILOT_BASE_URL
|
||||
let Some(provider) = provider_for(config) else {
|
||||
return 0; // control triage is opt-in via BREAKPILOT_BASE_URL or a snapshot
|
||||
};
|
||||
let provider = OscalControlsProvider::new(
|
||||
reqwest::Client::new(),
|
||||
base_url,
|
||||
config.breakpilot.token.clone(),
|
||||
&config.breakpilot.snapshot_dir,
|
||||
);
|
||||
let specs = build_specs(&provider).await;
|
||||
if specs.is_empty() {
|
||||
return 0;
|
||||
@@ -84,6 +78,22 @@ pub async fn triage_repo_findings(
|
||||
}
|
||||
|
||||
/// Build the control requirement specs (by id) from the ingested OSCAL catalog.
|
||||
/// The catalog source for this agent: the breakpilot backend when
|
||||
/// `BREAKPILOT_BASE_URL` is set, else the baked/previously written snapshots
|
||||
/// under `BREAKPILOT_SNAPSHOT_DIR`. `None` = control triage is off.
|
||||
fn provider_for(config: &AgentConfig) -> Option<OscalControlsProvider> {
|
||||
let snapshot_dir = Path::new(&config.breakpilot.snapshot_dir);
|
||||
if config.breakpilot.base_url.is_none() && !OscalControlsProvider::has_snapshots(snapshot_dir) {
|
||||
return None;
|
||||
}
|
||||
Some(OscalControlsProvider::new(
|
||||
reqwest::Client::new(),
|
||||
config.breakpilot.base_url.clone(),
|
||||
config.breakpilot.token.clone(),
|
||||
snapshot_dir,
|
||||
))
|
||||
}
|
||||
|
||||
async fn build_specs(provider: &OscalControlsProvider) -> HashMap<String, ControlCheckSpec> {
|
||||
let mut specs = HashMap::new();
|
||||
match provider.load(ComplianceFramework::Cra).await {
|
||||
@@ -121,15 +131,9 @@ pub async fn grounded_surface_findings(
|
||||
repo_path: &Path,
|
||||
repo_id: &str,
|
||||
) -> Vec<Finding> {
|
||||
let Some(base_url) = config.breakpilot.base_url.clone() else {
|
||||
let Some(provider) = provider_for(config) else {
|
||||
return Vec::new();
|
||||
};
|
||||
let provider = OscalControlsProvider::new(
|
||||
reqwest::Client::new(),
|
||||
base_url,
|
||||
config.breakpilot.token.clone(),
|
||||
&config.breakpilot.snapshot_dir,
|
||||
);
|
||||
let specs = build_specs(&provider).await;
|
||||
if specs.is_empty() {
|
||||
return Vec::new();
|
||||
@@ -183,15 +187,9 @@ pub async fn semantic_stamp_findings(
|
||||
repo_path: &Path,
|
||||
findings: &mut [Finding],
|
||||
) -> usize {
|
||||
let Some(base_url) = config.breakpilot.base_url.clone() else {
|
||||
let Some(provider) = provider_for(config) else {
|
||||
return 0;
|
||||
};
|
||||
let provider = OscalControlsProvider::new(
|
||||
reqwest::Client::new(),
|
||||
base_url,
|
||||
config.breakpilot.token.clone(),
|
||||
&config.breakpilot.snapshot_dir,
|
||||
);
|
||||
let doc = match provider.load_master_controls().await {
|
||||
Ok(d) => d,
|
||||
Err(e) => {
|
||||
|
||||
@@ -45,7 +45,7 @@ async fn c5_ingest_master_controls_catalog() {
|
||||
|
||||
let provider = OscalControlsProvider::new(
|
||||
reqwest::Client::new(),
|
||||
env("BREAKPILOT_BASE_URL"),
|
||||
Some(env("BREAKPILOT_BASE_URL")),
|
||||
None,
|
||||
std::env::temp_dir().join("c5-ingest-snap"),
|
||||
);
|
||||
|
||||
@@ -16,4 +16,19 @@ if [ ! -e /nix/store ]; then
|
||||
fi
|
||||
fi
|
||||
|
||||
# Seed the OSCAL control-catalog snapshot. The image ships a catalog snapshot so
|
||||
# control mapping works without the breakpilot-compliance backend
|
||||
# (BREAKPILOT_BASE_URL unset). Copy-if-absent, so a snapshot refreshed from a
|
||||
# live backend (or a mounted volume) always wins.
|
||||
SNAP_DIR="${BREAKPILOT_SNAPSHOT_DIR:-/data/compliance-scanner/oscal}"
|
||||
if [ -d /opt/breakpilot/oscal-snapshot ]; then
|
||||
mkdir -p "$SNAP_DIR"
|
||||
for f in /opt/breakpilot/oscal-snapshot/*.json; do
|
||||
[ -e "$f" ] || continue
|
||||
if [ ! -e "$SNAP_DIR/$(basename "$f")" ]; then
|
||||
cp "$f" "$SNAP_DIR/" && echo "agent-entrypoint: seeded $(basename "$f") into $SNAP_DIR"
|
||||
fi
|
||||
done
|
||||
fi
|
||||
|
||||
exec compliance-agent "$@"
|
||||
@@ -49,7 +49,7 @@ All three paths converge on the same **grounded judge** and the same **grounding
|
||||
|
||||
### Stage 5b — deterministic LUT triage
|
||||
|
||||
The default path. A tool finding is matched to controls via `control_map.controls_for_finding(tool, cwe, rule_id)`; the judge then confirms each mapped control against the code region. Outcomes: `Confirmed([ids])` (stamp them), `FalsePositive` (drop the finding), or `Unmapped` (keep it untagged). Runs whenever `BREAKPILOT_BASE_URL` is set.
|
||||
The default path. A tool finding is matched to controls via `control_map.controls_for_finding(tool, cwe, rule_id)`; the judge then confirms each mapped control against the code region. Outcomes: `Confirmed([ids])` (stamp them), `FalsePositive` (drop the finding), or `Unmapped` (keep it untagged). Runs whenever a catalog is available — either `BREAKPILOT_BASE_URL` points at a breakpilot-compliance backend, or a catalog snapshot is present (see [snapshot-only mode](#snapshot-only-mode)).
|
||||
|
||||
### Stage 5c — semantic retrieval (master-controls scale)
|
||||
|
||||
@@ -121,12 +121,18 @@ Findings don't just land in the dashboard; they flow to breakpilot-compliance as
|
||||
|
||||
| Variable | Effect |
|
||||
| --- | --- |
|
||||
| `BREAKPILOT_BASE_URL` | breakpilot-compliance root; enables control ingest + all mapping passes. **Unset disables all control mapping** — findings are produced without `control_refs`. |
|
||||
| `BREAKPILOT_BASE_URL` | breakpilot-compliance root; enables live control ingest. **Unset** falls back to the catalog snapshots in `BREAKPILOT_SNAPSHOT_DIR`; with neither, control mapping is off and findings carry no `control_refs`. |
|
||||
| `BREAKPILOT_SEMANTIC_MAPPING` | Stage 5c (semantic master-controls mapping). **Default on** (validated live). |
|
||||
| `BREAKPILOT_GROUNDED_CHECKS` | Stage 5d (grounded surface checks). **Default on** (validated live). |
|
||||
| `BREAKPILOT_SNAPSHOT_DIR` | Where OSCAL catalog snapshots and the cached control-embedding index live. |
|
||||
|
||||
The semantic and grounded passes default **on** now that both are validated live; each is still a no-op if `BREAKPILOT_BASE_URL` is unset or the catalog is unreachable, so they only ever add coverage. The live verifications live in `compliance-agent/tests/c5_semantic_live.rs` and `grounded_surface_live.rs` (ignored; run with `--ignored`).
|
||||
The semantic and grounded passes default **on** now that both are validated live; each is still a no-op if no catalog is reachable, so they only ever add coverage.
|
||||
|
||||
### Snapshot-only mode
|
||||
|
||||
The catalog loader already snapshots the exact bytes it fetches (`oscal-catalog-<framework>.json` under `BREAKPILOT_SNAPSHOT_DIR`) and falls back to that snapshot when the backend is unreachable. Snapshot-only mode is the same path without ever having been online: the agent image ships `compliance-agent/controls/snapshot/oscal-catalog-cra.json` (CRA Annex I, 40 controls, built by breakpilot-compliance's `build_cra_catalog`), and the entrypoint copies it into `BREAKPILOT_SNAPSHOT_DIR` if no file of that name is there yet. With `BREAKPILOT_BASE_URL` unset the deterministic LUT triage (5b) and the grounded surface checks (5d) therefore run and findings carry CRA `control_refs`, while the semantic pass (5c) stays a no-op because `master-controls` is DB-derived and is not shipped — set `BREAKPILOT_SEMANTIC_MAPPING=false` in that environment to skip its warning.
|
||||
|
||||
Refresh the committed snapshot from a live backend with `scripts/refresh-oscal-snapshot.sh` (see its header); a fetched snapshot always wins over the baked one, because the entrypoint only copies what is absent. The live verifications live in `compliance-agent/tests/c5_semantic_live.rs` and `grounded_surface_live.rs` (ignored; run with `--ignored`).
|
||||
|
||||
## Appendix — the master-controls data pipeline
|
||||
|
||||
|
||||
Executable
+37
@@ -0,0 +1,37 @@
|
||||
#!/usr/bin/env bash
|
||||
# Refresh the committed OSCAL catalog snapshots from a breakpilot-compliance
|
||||
# backend. The agent image ships these files and seeds them into
|
||||
# BREAKPILOT_SNAPSHOT_DIR on start, so control mapping works without the
|
||||
# backend (see docs/features/control-mapping.md).
|
||||
#
|
||||
# BREAKPILOT_BASE_URL=https://api-dev.breakpilot.ai \
|
||||
# BREAKPILOT_TOKEN=<bearer> \
|
||||
# scripts/refresh-oscal-snapshot.sh [framework ...]
|
||||
#
|
||||
# Default frameworks: cra. `master-controls` is DB-derived and large (~3k
|
||||
# controls); pass it explicitly when the backend is healthy and you want the
|
||||
# semantic pass to work offline too.
|
||||
set -euo pipefail
|
||||
|
||||
: "${BREAKPILOT_BASE_URL:?set BREAKPILOT_BASE_URL}"
|
||||
out="$(cd "$(dirname "$0")/.." && pwd)/compliance-agent/controls/snapshot"
|
||||
mkdir -p "$out"
|
||||
frameworks=("$@")
|
||||
[ ${#frameworks[@]} -eq 0 ] && frameworks=(cra)
|
||||
|
||||
for fw in "${frameworks[@]}"; do
|
||||
url="${BREAKPILOT_BASE_URL%/}/api/compliance/v1/oscal/catalog?framework=${fw}"
|
||||
tmp="$(mktemp)"
|
||||
code=$(curl -sS -o "$tmp" -w '%{http_code}' \
|
||||
${BREAKPILOT_TOKEN:+-H "Authorization: Bearer ${BREAKPILOT_TOKEN}"} "$url")
|
||||
if [ "$code" != "200" ]; then
|
||||
echo "refresh-oscal-snapshot: $fw -> HTTP $code" >&2
|
||||
head -c 200 "$tmp" >&2; echo >&2
|
||||
rm -f "$tmp"; exit 1
|
||||
fi
|
||||
python3 -c 'import json,sys; json.dump(json.load(open(sys.argv[1])), open(sys.argv[2],"w"), indent=2, ensure_ascii=False); open(sys.argv[2],"a").write("\n")' \
|
||||
"$tmp" "$out/oscal-catalog-${fw}.json"
|
||||
rm -f "$tmp"
|
||||
n=$(python3 -c 'import json,sys; d=json.load(open(sys.argv[1])); c=d.get("catalog",d); print(sum(len(g.get("controls",[])) for g in c.get("groups",[])))' "$out/oscal-catalog-${fw}.json")
|
||||
echo "refresh-oscal-snapshot: $fw -> $out/oscal-catalog-${fw}.json ($n controls)"
|
||||
done
|
||||
Reference in new issue
Block a user