feat(ci): nightly scan regression against the built image (#188)
CI / Check (push) Skipped
CI / Detect Changes (pull_request) Skipped
CI / Deploy Agent (pull_request) Skipped
CI / Deploy Dashboard (pull_request) Skipped
CI / Deploy Docs (pull_request) Skipped
CI / Deploy MCP (pull_request) Skipped
CI / Check (pull_request) Successful in 6m31s
CI / Check (push) Skipped
CI / Detect Changes (pull_request) Skipped
CI / Deploy Agent (pull_request) Skipped
CI / Deploy Dashboard (pull_request) Skipped
CI / Deploy Docs (pull_request) Skipped
CI / Deploy MCP (pull_request) Skipped
CI / Check (pull_request) Successful in 6m31s
The nightly workflow only ran the stale e2e suite (#298). It lacked the firmwerk git auth, so it could not even compile. - tests/nightly.rs: seeds the demo-target corpus on a running agent (NIGHTLY_AGENT_URL), waits for every scan, and compares the results with: - the manifest's `expect` block, now `Expect::violations`, reusable; - blessed snapshots in fixtures/nightly/baselines/: exact for scan status, skipped stages, SBOM and deterministic findings; at-least for CVEs and semgrep registry rules. LLM code review is ignored. Control refs, which only the LLM control judge stamps, are reported as advisory (`Expect::llm_violations`). NIGHTLY_BLESS=1 re-blesses. The report goes to target/nightly/. - nightly.yml: mongo + the :latest agent image as services (dev mode, source_only, optional LLM), the harness in rust:1.94, the report as an artifact, and one tracking issue while the nightly stays red (NIGHTLY_ALERT_TOKEN). workflow_dispatch has a "bless" input. Bugs the first runs found, fixed here: - Scan phases control_triage / semantic_control_mapping / grounded_control_checks / plc_provision were missing from ScanPhase. Runs failed to deserialize and silently dropped out of GET /scan-runs (and the dashboard's scan list). update_phase now takes ScanPhase, so this cannot drift again. - The PLC pump-station demo failed every scan since #256: its optional live endpoint fell back to modbus://plc-sim:502, and live URLs only accepted http(s). NetGuard::check_live_url now also allows modbus:// and opc.tcp://, with the same host rules; DAST only takes http(s) live URLs. Optional env-backed demo artifacts are skipped when their env var is unset, as the shell seeder already did. - SBOM clean-up: - The pipeline's stale-entry delete compared the target id as an ObjectId against the stored hex string, so it never deleted anything, and removed dependencies stayed in the SBOM forever. - The firmware step deleted every entry, so a rescan with no new commits wiped the Syft entries. Each step now replaces only its own package managers. - Manifest: `control_refs_any` was silently ignored (not in Expect). Zephyr's detected build system is "zephyr (west)". Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01EYKjxacrr6K88DruUmP48p
This commit is contained in:
1 parent
40c7557349
commit
3efa2be1e1
14 files changed
+1023
-46
No files matched your search
+122
-13
@@ -1,24 +1,46 @@
|
||||
name: Nightly E2E Tests
|
||||
name: Nightly scan regression
|
||||
|
||||
# Scans the fixture corpus (fixtures/demo-targets) with the agent image built
|
||||
# from main and compares the results with the blessed baselines in
|
||||
# fixtures/nightly/baselines (#188, epic #309). A regression anywhere between
|
||||
# a tool bump and a parser change turns this red before a customer sees it.
|
||||
#
|
||||
# Run it by hand with "bless" ticked after an intended change: the job then
|
||||
# rewrites the baselines instead of comparing, and the new files are in the
|
||||
# `nightly-report` artifact to commit.
|
||||
|
||||
on:
|
||||
schedule:
|
||||
- cron: '0 3 * * *' # 3 AM UTC daily
|
||||
workflow_dispatch: # Allow manual trigger
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
bless:
|
||||
description: "Rewrite the baselines from this run (commit them from the artifact)"
|
||||
type: boolean
|
||||
default: false
|
||||
|
||||
env:
|
||||
CARGO_TERM_COLOR: always
|
||||
RUSTFLAGS: "-D warnings"
|
||||
RUSTC_WRAPPER: /usr/local/bin/sccache
|
||||
SCCACHE_DIR: /tmp/sccache
|
||||
TEST_MONGODB_URI: "mongodb://root:example@mongo:27017/?authSource=admin"
|
||||
SCCACHE_BUCKET: bp-sccache
|
||||
SCCACHE_ENDPOINT: https://nbg1.your-objectstorage.com
|
||||
SCCACHE_REGION: auto
|
||||
SCCACHE_S3_USE_SSL: "true"
|
||||
SCCACHE_S3_KEY_PREFIX: compliance-scanner
|
||||
AWS_ACCESS_KEY_ID: ${{ secrets.HETZNER_S3_ACCESS_KEY }}
|
||||
AWS_SECRET_ACCESS_KEY: ${{ secrets.HETZNER_S3_SECRET_KEY }}
|
||||
CARGO_NET_GIT_FETCH_WITH_CLI: "true"
|
||||
CARGO_NET_RETRY: "10"
|
||||
CARGO_HTTP_MULTIPLEXING: "false"
|
||||
|
||||
concurrency:
|
||||
group: nightly-e2e
|
||||
group: nightly-scans
|
||||
cancel-in-progress: true
|
||||
|
||||
jobs:
|
||||
e2e:
|
||||
name: E2E Tests
|
||||
scans:
|
||||
name: Scan regression
|
||||
runs-on: docker
|
||||
container:
|
||||
image: rust:1.94-bookworm
|
||||
@@ -28,6 +50,22 @@ jobs:
|
||||
env:
|
||||
MONGO_INITDB_ROOT_USERNAME: root
|
||||
MONGO_INITDB_ROOT_PASSWORD: example
|
||||
# The image main deployed. Dev mode (no Keycloak): the harness talks to
|
||||
# the unauthenticated dev tenant; source_only matches staging.
|
||||
agent:
|
||||
image: repo.breakpilot.com/pruefwerk/compliance-agent:latest
|
||||
credentials:
|
||||
username: ${{ secrets.REGISTRY_USERNAME }}
|
||||
password: ${{ secrets.REGISTRY_PASSWORD }}
|
||||
env:
|
||||
APP_ENV: dev
|
||||
MONGODB_URI: mongodb://root:example@mongo:27017/?authSource=admin
|
||||
MONGODB_DATABASE: nightly
|
||||
PW_FEATURES: source_only
|
||||
# Optional. Without an LLM the control judge stamps no control refs,
|
||||
# which the report lists as advisory; it never fails the run.
|
||||
LITELLM_URL: ${{ secrets.NIGHTLY_LITELLM_URL }}
|
||||
LITELLM_API_KEY: ${{ secrets.NIGHTLY_LITELLM_API_KEY }}
|
||||
steps:
|
||||
- name: Checkout
|
||||
run: |
|
||||
@@ -36,17 +74,88 @@ jobs:
|
||||
git fetch --depth=1 origin "${GITHUB_SHA:-refs/heads/main}"
|
||||
git checkout FETCH_HEAD
|
||||
|
||||
- name: Use Kellnr crates.io mirror
|
||||
run: |
|
||||
: "${CARGO_HOME:=/usr/local/cargo}"
|
||||
mkdir -p "$CARGO_HOME"
|
||||
{
|
||||
echo '[source.crates-io]'
|
||||
echo 'replace-with = "kellnr"'
|
||||
echo '[registries.kellnr]'
|
||||
echo 'index = "sparse+https://crates.breakpilot.com/api/v1/cratesio/"'
|
||||
} >> "$CARGO_HOME/config.toml"
|
||||
env:
|
||||
RUSTC_WRAPPER: ""
|
||||
|
||||
- name: Install sccache
|
||||
run: |
|
||||
curl -fsSL https://github.com/mozilla/sccache/releases/download/v0.9.1/sccache-v0.9.1-x86_64-unknown-linux-musl.tar.gz \
|
||||
| tar xz --strip-components=1 -C /usr/local/bin/ sccache-v0.9.1-x86_64-unknown-linux-musl/sccache
|
||||
curl -fsSL https://github.com/mozilla/sccache/releases/download/v0.10.0/sccache-v0.10.0-x86_64-unknown-linux-musl.tar.gz \
|
||||
| tar xz --strip-components=1 -C /usr/local/bin/ sccache-v0.10.0-x86_64-unknown-linux-musl/sccache
|
||||
chmod +x /usr/local/bin/sccache
|
||||
env:
|
||||
RUSTC_WRAPPER: ""
|
||||
|
||||
- name: Run E2E tests
|
||||
run: cargo test -p compliance-agent --test e2e -- --test-threads=4
|
||||
# The harness links compliance-agent, which depends on the private
|
||||
# firmwerk repo; same PAT rewrite as in ci.yml.
|
||||
- name: Configure git auth for the private firmwerk dependency
|
||||
run: |
|
||||
git config --global \
|
||||
url."https://platform-ci:${{ secrets.PLATFORM_CI_TOKEN }}@git.breakpilot.com/".insteadOf \
|
||||
"ssh://git@git.breakpilot.com:22222/"
|
||||
env:
|
||||
RUSTC_WRAPPER: ""
|
||||
|
||||
- name: Show sccache stats
|
||||
run: sccache --show-stats
|
||||
- name: Wait for the agent
|
||||
run: |
|
||||
for i in $(seq 1 90); do
|
||||
curl -fsS http://agent:3001/api/v1/health && exit 0
|
||||
sleep 2
|
||||
done
|
||||
echo "agent did not become healthy" >&2
|
||||
exit 1
|
||||
env:
|
||||
RUSTC_WRAPPER: ""
|
||||
|
||||
- name: Scan the corpus and compare with the baselines
|
||||
run: cargo test -p compliance-agent --test nightly -- --nocapture
|
||||
env:
|
||||
NIGHTLY_AGENT_URL: http://agent:3001
|
||||
NIGHTLY_BLESS: ${{ inputs.bless && '1' || '0' }}
|
||||
|
||||
- name: Keep the report and this run's snapshots
|
||||
if: always()
|
||||
uses: actions/upload-artifact@v3
|
||||
with:
|
||||
name: nightly-report
|
||||
path: |
|
||||
target/nightly/
|
||||
fixtures/nightly/baselines/
|
||||
|
||||
# One open issue tracks a red nightly: opened on the first failure,
|
||||
# commented on while it stays red. Needs NIGHTLY_ALERT_TOKEN (issue write
|
||||
# on this repo); without it the job still fails, just without the issue.
|
||||
- name: Alert
|
||||
if: failure() && github.event_name == 'schedule'
|
||||
env:
|
||||
RUSTC_WRAPPER: ""
|
||||
TOKEN: ${{ secrets.NIGHTLY_ALERT_TOKEN }}
|
||||
RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}
|
||||
run: |
|
||||
if [ -z "$TOKEN" ]; then
|
||||
echo "::warning::NIGHTLY_ALERT_TOKEN is not set; not opening an issue"
|
||||
exit 0
|
||||
fi
|
||||
api="${GITHUB_SERVER_URL}/api/v1/repos/${GITHUB_REPOSITORY}"
|
||||
title="Nightly scan regression is red"
|
||||
body="The nightly scan regression failed: ${RUN_URL} (report in the nightly-report artifact)."
|
||||
number=$(curl -fsS -H "Authorization: token $TOKEN" \
|
||||
"$api/issues?state=open&type=issues&q=$(printf %s "$title" | sed 's/ /%20/g')" \
|
||||
| python3 -c "import json,sys; print(next((i['number'] for i in json.load(sys.stdin) if i['title']==sys.argv[1]), ''))" "$title")
|
||||
payload=$(python3 -c "import json,sys; print(json.dumps({'title': sys.argv[1], 'body': sys.argv[2]}))" "$title" "$body")
|
||||
if [ -n "$number" ]; then
|
||||
curl -fsS -X POST -H "Authorization: token $TOKEN" -H "Content-Type: application/json" \
|
||||
"$api/issues/$number/comments" -d "$payload" >/dev/null
|
||||
else
|
||||
curl -fsS -X POST -H "Authorization: token $TOKEN" -H "Content-Type: application/json" \
|
||||
"$api/issues" -d "$payload" >/dev/null
|
||||
fi
|
||||
@@ -146,6 +146,23 @@ docker compose up -d
|
||||
|
||||
This starts MongoDB, SearXNG, the agent (port 3001), and the dashboard (port 8080).
|
||||
|
||||
### Nightly scan regression
|
||||
|
||||
Every night CI scans the demo-target corpus (`fixtures/demo-targets/targets.json`)
|
||||
with the agent image built from `main` and compares the results with the
|
||||
baselines in `fixtures/nightly/baselines/` (`.gitea/workflows/nightly.yml`). To
|
||||
run it against any agent in dev mode (use a fresh database: a rescan of an
|
||||
unchanged repo skips most stages, so it records less than a first scan):
|
||||
|
||||
```bash
|
||||
NIGHTLY_AGENT_URL=http://localhost:3001 \
|
||||
cargo test -p compliance-agent --test nightly -- --nocapture
|
||||
```
|
||||
|
||||
After an intended change to scan results, re-bless with `NIGHTLY_BLESS=1` (or
|
||||
run the workflow by hand with "bless" ticked) and commit the baseline diff with
|
||||
the change. The report lands in `target/nightly/report.md`.
|
||||
|
||||
## REST API
|
||||
|
||||
The agent exposes a REST API on port 3001:
|
||||
|
||||
@@ -26,7 +26,7 @@
|
||||
//! are skipped when their env var is unset, so the set seeds cleanly without
|
||||
//! OT infra.
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use compliance_core::models::onboarding::{ArtifactKind, PlcFormat, TargetType};
|
||||
@@ -200,14 +200,18 @@ impl DemoArtifact {
|
||||
}
|
||||
|
||||
/// The reference to onboard for a reference-style artifact: the env
|
||||
/// override when set, else the literal `source_ref`. `None` when neither
|
||||
/// is available (an optional env-only artifact without its var).
|
||||
/// override when set, else the literal `source_ref`. `None` for an
|
||||
/// optional artifact whose env var is unset: its literal points at
|
||||
/// infrastructure (an in-cluster PLC simulator) that only exists where the
|
||||
/// var is set, and onboarding it anyway failed the whole scan once
|
||||
/// internal hosts were refused (#256). Same rule as
|
||||
/// `scripts/seed-demo-targets.sh`.
|
||||
pub fn resolved_source_ref(&self) -> Option<String> {
|
||||
if let Some(var) = &self.source_ref_env {
|
||||
if let Ok(v) = std::env::var(var) {
|
||||
if !v.is_empty() {
|
||||
return Some(v);
|
||||
}
|
||||
match std::env::var(var) {
|
||||
Ok(v) if !v.is_empty() => return Some(v),
|
||||
_ if self.optional => return None,
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
self.source_ref.clone()
|
||||
@@ -267,6 +271,9 @@ pub struct Expect {
|
||||
/// Control refs (e.g. `cra-ai-8`) that must be stamped on some finding.
|
||||
#[serde(default)]
|
||||
pub control_refs: Vec<String>,
|
||||
/// At least one finding must carry some control ref.
|
||||
#[serde(default)]
|
||||
pub control_refs_any: bool,
|
||||
/// Lower bound on SBOM components.
|
||||
#[serde(default)]
|
||||
pub min_sbom_components: Option<usize>,
|
||||
@@ -280,6 +287,95 @@ pub struct Expect {
|
||||
pub detected_facts: BTreeMap<String, String>,
|
||||
}
|
||||
|
||||
/// What a finished scan of one target produced, reduced to what [`Expect`]
|
||||
/// can assert on. Built by the nightly harness from the agent's API.
|
||||
#[derive(Debug, Clone, Default, PartialEq, Eq)]
|
||||
pub struct Observed {
|
||||
pub findings: usize,
|
||||
pub rule_ids: BTreeSet<String>,
|
||||
pub cwes: BTreeSet<String>,
|
||||
pub control_refs: BTreeSet<String>,
|
||||
/// Whether any finding carries a control ref.
|
||||
pub any_control_ref: bool,
|
||||
pub sbom_components: usize,
|
||||
pub scans_offered: BTreeSet<String>,
|
||||
pub pentest_supported: Option<bool>,
|
||||
pub detected_facts: BTreeMap<String, String>,
|
||||
}
|
||||
|
||||
impl Expect {
|
||||
/// Every way `observed` falls short of the deterministic part of this
|
||||
/// baseline, as readable lines. Empty means the target meets it.
|
||||
///
|
||||
/// Control refs are checked separately by [`Self::llm_violations`]: they
|
||||
/// are stamped by the grounded LLM control judge, and LLM output never
|
||||
/// gates the nightly regression.
|
||||
pub fn violations(&self, observed: &Observed) -> Vec<String> {
|
||||
let mut out = Vec::new();
|
||||
if let Some(min) = self.min_findings {
|
||||
if observed.findings < min {
|
||||
out.push(format!(
|
||||
"{} findings, expected at least {min}",
|
||||
observed.findings
|
||||
));
|
||||
}
|
||||
}
|
||||
if let Some(min) = self.min_sbom_components {
|
||||
if observed.sbom_components < min {
|
||||
out.push(format!(
|
||||
"{} SBOM components, expected at least {min}",
|
||||
observed.sbom_components
|
||||
));
|
||||
}
|
||||
}
|
||||
let missing = |what: &str, wanted: &[String], got: &BTreeSet<String>| {
|
||||
wanted
|
||||
.iter()
|
||||
.filter(|w| !got.contains(w.as_str()))
|
||||
.map(|w| format!("missing {what} {w}"))
|
||||
.collect::<Vec<_>>()
|
||||
};
|
||||
out.extend(missing("rule", &self.sast_rule_ids, &observed.rule_ids));
|
||||
out.extend(missing("CWE", &self.cwes, &observed.cwes));
|
||||
out.extend(missing(
|
||||
"offered scan",
|
||||
&self.scans_offered,
|
||||
&observed.scans_offered,
|
||||
));
|
||||
if let Some(want) = self.pentest_supported {
|
||||
if observed.pentest_supported != Some(want) {
|
||||
out.push(format!(
|
||||
"pentest_supported is {:?}, expected {want}",
|
||||
observed.pentest_supported
|
||||
));
|
||||
}
|
||||
}
|
||||
for (key, want) in &self.detected_facts {
|
||||
match observed.detected_facts.get(key) {
|
||||
Some(got) if got == want => {}
|
||||
Some(got) => out.push(format!("fact {key} = {got}, expected {want}")),
|
||||
None => out.push(format!("fact {key} not detected, expected {want}")),
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Shortfalls in the control refs, which only the LLM control judge
|
||||
/// stamps today. Reported, not gating.
|
||||
pub fn llm_violations(&self, observed: &Observed) -> Vec<String> {
|
||||
let mut out: Vec<String> = self
|
||||
.control_refs
|
||||
.iter()
|
||||
.filter(|r| !observed.control_refs.contains(r.as_str()))
|
||||
.map(|r| format!("missing control ref {r}"))
|
||||
.collect();
|
||||
if self.control_refs_any && !observed.any_control_ref {
|
||||
out.push("no finding carries a control ref".to_string());
|
||||
}
|
||||
out
|
||||
}
|
||||
}
|
||||
|
||||
impl DemoTargets {
|
||||
/// Workspace root, derived from this crate's manifest dir.
|
||||
pub fn workspace_root() -> PathBuf {
|
||||
@@ -510,6 +606,18 @@ mod tests {
|
||||
.unwrap();
|
||||
assert!(fw.optional && fw.env_only());
|
||||
assert!(fw.upload_content().unwrap().is_none());
|
||||
|
||||
// An optional reference with an env override is skipped when the var
|
||||
// is unset, not onboarded with its in-cluster default.
|
||||
let live = pump
|
||||
.artifacts
|
||||
.iter()
|
||||
.find(|a| a.kind == ArtifactKind::LiveUrl)
|
||||
.unwrap();
|
||||
assert!(live.optional && live.source_ref.is_some());
|
||||
if std::env::var("DEMO_PLC_MODBUS_URL").is_err() {
|
||||
assert_eq!(live.resolved_source_ref(), None);
|
||||
}
|
||||
}
|
||||
|
||||
/// Offline golden baseline: the checked-in PLC fixtures must keep producing
|
||||
@@ -564,4 +672,57 @@ mod tests {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn expect_reports_each_shortfall_and_passes_a_match() {
|
||||
let expect = Expect {
|
||||
min_findings: Some(3),
|
||||
sast_rule_ids: vec!["plc-safety-bypass".into()],
|
||||
cwes: vec!["CWE-798".into()],
|
||||
control_refs: vec!["cra-ai-8".into()],
|
||||
control_refs_any: true,
|
||||
min_sbom_components: Some(1),
|
||||
scans_offered: vec!["sast".into()],
|
||||
pentest_supported: Some(false),
|
||||
detected_facts: BTreeMap::from([("build_system".into(), "zephyr".into())]),
|
||||
};
|
||||
let good = Observed {
|
||||
findings: 3,
|
||||
rule_ids: BTreeSet::from(["plc-safety-bypass".into()]),
|
||||
cwes: BTreeSet::from(["CWE-798".into()]),
|
||||
control_refs: BTreeSet::from(["cra-ai-8".into()]),
|
||||
any_control_ref: true,
|
||||
sbom_components: 1,
|
||||
scans_offered: BTreeSet::from(["sast".into()]),
|
||||
pentest_supported: Some(false),
|
||||
detected_facts: BTreeMap::from([("build_system".into(), "zephyr".into())]),
|
||||
};
|
||||
assert!(expect.violations(&good).is_empty());
|
||||
assert!(expect.llm_violations(&good).is_empty());
|
||||
|
||||
let empty = Observed::default();
|
||||
let v = expect.violations(&empty);
|
||||
for needle in [
|
||||
"0 findings",
|
||||
"0 SBOM components",
|
||||
"missing rule plc-safety-bypass",
|
||||
"missing CWE CWE-798",
|
||||
"missing offered scan sast",
|
||||
"pentest_supported is None",
|
||||
"fact build_system not detected",
|
||||
] {
|
||||
assert!(
|
||||
v.iter().any(|l| l.contains(needle)),
|
||||
"{needle} not in {v:?}"
|
||||
);
|
||||
}
|
||||
assert!(!v.iter().any(|l| l.contains("control ref")), "{v:?}");
|
||||
assert_eq!(
|
||||
expect.llm_violations(&empty),
|
||||
[
|
||||
"missing control ref cra-ai-8",
|
||||
"no finding carries a control ref"
|
||||
]
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -120,8 +120,9 @@ pub fn ingest_artifact(
|
||||
ArtifactKind::LiveUrl => {
|
||||
// A live URL is scanned by the DAST and ICS stages, so it is an
|
||||
// outbound request the tenant chose: check it before recording it.
|
||||
// PLC endpoints (`modbus://`, `opc.tcp://`) are live URLs too.
|
||||
ctx.net_guard
|
||||
.check_url(&artifact.source_ref)
|
||||
.check_live_url(&artifact.source_ref)
|
||||
.map_err(|e| AgentError::Other(e.to_string()))?;
|
||||
Ok(metadata_only(
|
||||
artifact,
|
||||
|
||||
@@ -20,6 +20,11 @@ use firmwerk_repro::ReproBackend;
|
||||
use firmwerk_sbom::ComponentKind;
|
||||
|
||||
/// Whether firmware SBOM applies to this target family.
|
||||
/// The `package_manager` values firmware SBOM entries use. The firmware step
|
||||
/// replaces exactly these, and the SBOM stage leaves them alone, so neither
|
||||
/// wipes the other's entries.
|
||||
pub const FIRMWARE_MANAGERS: [&str; 3] = ["firmware", "library", "toolchain"];
|
||||
|
||||
pub fn is_firmware_target(target_type: TargetType) -> bool {
|
||||
matches!(
|
||||
target_type,
|
||||
|
||||
@@ -91,7 +91,7 @@ impl PipelineOrchestrator {
|
||||
|
||||
// Stage 1: Semgrep SAST
|
||||
tracing::info!("[{repo_id}] Stage 1: Semgrep SAST");
|
||||
self.update_phase(scan_run_id, "sast").await;
|
||||
self.update_phase(scan_run_id, ScanPhase::Sast).await;
|
||||
match async {
|
||||
let semgrep = SemgrepScanner;
|
||||
semgrep.scan(&repo_path, &repo_id).await
|
||||
@@ -105,7 +105,8 @@ impl PipelineOrchestrator {
|
||||
|
||||
// Stage 2: SBOM Generation
|
||||
tracing::info!("[{repo_id}] Stage 2: SBOM Generation");
|
||||
self.update_phase(scan_run_id, "sbom_generation").await;
|
||||
self.update_phase(scan_run_id, ScanPhase::SbomGeneration)
|
||||
.await;
|
||||
let mut sbom_entries = match async {
|
||||
let sbom_scanner =
|
||||
SbomScanner::new(compliance_core::ExecPolicy::from_env(self.config.app_env));
|
||||
@@ -123,7 +124,7 @@ impl PipelineOrchestrator {
|
||||
|
||||
// Stage 3: CVE Scanning
|
||||
tracing::info!("[{repo_id}] Stage 3: CVE Scanning");
|
||||
self.update_phase(scan_run_id, "cve_scanning").await;
|
||||
self.update_phase(scan_run_id, ScanPhase::CveScanning).await;
|
||||
let cve_scanner = CveScanner::new(
|
||||
self.http.clone(),
|
||||
self.config.searxng_url.clone(),
|
||||
@@ -156,7 +157,8 @@ impl PipelineOrchestrator {
|
||||
|
||||
// Stage 4: Pattern Scanning (GDPR + OAuth)
|
||||
tracing::info!("[{repo_id}] Stage 4: Pattern Scanning");
|
||||
self.update_phase(scan_run_id, "pattern_scanning").await;
|
||||
self.update_phase(scan_run_id, ScanPhase::PatternScanning)
|
||||
.await;
|
||||
{
|
||||
let pattern_findings = async {
|
||||
let mut findings = Vec::new();
|
||||
@@ -179,7 +181,8 @@ impl PipelineOrchestrator {
|
||||
|
||||
// Stage 4a: Secret Detection (Gitleaks)
|
||||
tracing::info!("[{repo_id}] Stage 4a: Secret Detection");
|
||||
self.update_phase(scan_run_id, "secret_detection").await;
|
||||
self.update_phase(scan_run_id, ScanPhase::SecretDetection)
|
||||
.await;
|
||||
match async {
|
||||
let gitleaks = GitleaksScanner;
|
||||
gitleaks.scan(&repo_path, &repo_id).await
|
||||
@@ -193,7 +196,8 @@ impl PipelineOrchestrator {
|
||||
|
||||
// Stage 4b: Lint Scanning
|
||||
tracing::info!("[{repo_id}] Stage 4b: Lint Scanning");
|
||||
self.update_phase(scan_run_id, "lint_scanning").await;
|
||||
self.update_phase(scan_run_id, ScanPhase::LintScanning)
|
||||
.await;
|
||||
match async {
|
||||
let lint = LintScanner::new(compliance_core::ExecPolicy::from_env(self.config.app_env));
|
||||
lint.scan(&repo_path, &repo_id).await
|
||||
@@ -207,7 +211,8 @@ impl PipelineOrchestrator {
|
||||
|
||||
// Stage 4.5: Graph Building
|
||||
tracing::info!("[{repo_id}] Stage 4.5: Graph Building");
|
||||
self.update_phase(scan_run_id, "graph_building").await;
|
||||
self.update_phase(scan_run_id, ScanPhase::GraphBuilding)
|
||||
.await;
|
||||
let graph_context = match async {
|
||||
self.build_code_graph(&repo_path, &repo_id, &all_findings)
|
||||
.await
|
||||
@@ -227,7 +232,7 @@ impl PipelineOrchestrator {
|
||||
"[{repo_id}] Stage 5: LLM Triage ({} findings)",
|
||||
all_findings.len()
|
||||
);
|
||||
self.update_phase(scan_run_id, "llm_triage").await;
|
||||
self.update_phase(scan_run_id, ScanPhase::LlmTriage).await;
|
||||
let triaged = crate::llm::triage::triage_findings(
|
||||
&self.llm,
|
||||
&mut all_findings,
|
||||
@@ -239,7 +244,8 @@ impl PipelineOrchestrator {
|
||||
// Stage 5b: control triage — stamp findings with the compliance control(s)
|
||||
// they're evidence for and flag control false positives (grounded LLM over
|
||||
// deterministic tool output). No-op unless breakpilot is configured.
|
||||
self.update_phase(scan_run_id, "control_triage").await;
|
||||
self.update_phase(scan_run_id, ScanPhase::ControlTriage)
|
||||
.await;
|
||||
let tagged = crate::controls::triage_repo_findings(
|
||||
&self.config,
|
||||
self.llm.clone(),
|
||||
@@ -257,7 +263,7 @@ impl PipelineOrchestrator {
|
||||
// default (validated live); the corpus embedding is cached so only the
|
||||
// first scan after a catalog change pays it.
|
||||
if self.config.breakpilot.semantic_mapping {
|
||||
self.update_phase(scan_run_id, "semantic_control_mapping")
|
||||
self.update_phase(scan_run_id, ScanPhase::SemanticControlMapping)
|
||||
.await;
|
||||
let sem = crate::controls::semantic_stamp_findings(
|
||||
&self.config,
|
||||
@@ -280,7 +286,7 @@ impl PipelineOrchestrator {
|
||||
// findings already tagged + grounded. On by default (validated live); it
|
||||
// covers the 8 absence-based CRA controls.
|
||||
if self.config.breakpilot.grounded_control_checks {
|
||||
self.update_phase(scan_run_id, "grounded_control_checks")
|
||||
self.update_phase(scan_run_id, ScanPhase::GroundedControlChecks)
|
||||
.await;
|
||||
let grounded = crate::controls::grounded_surface_findings(
|
||||
&self.config,
|
||||
@@ -336,11 +342,21 @@ impl PipelineOrchestrator {
|
||||
);
|
||||
}
|
||||
|
||||
// Remove stale SBOM entries for this repo before reinserting
|
||||
// Replace this stage's SBOM entries (not the firmware or CODESYS ones,
|
||||
// which their own steps own). Entries store the target id as a hex
|
||||
// string; filtering on the ObjectId matched nothing, so dependencies
|
||||
// removed from a repo used to stay in its SBOM forever.
|
||||
if !sbom_entries.is_empty() {
|
||||
let owned_elsewhere: Vec<&str> = crate::pipeline::firmware_sbom::FIRMWARE_MANAGERS
|
||||
.into_iter()
|
||||
.chain(["codesys"])
|
||||
.collect();
|
||||
self.db
|
||||
.sbom_entries()
|
||||
.delete_many(doc! { "repo_id": &repo.id })
|
||||
.delete_many(doc! {
|
||||
"repo_id": &repo_id,
|
||||
"package_manager": { "$nin": owned_elsewhere },
|
||||
})
|
||||
.await?;
|
||||
}
|
||||
|
||||
@@ -371,7 +387,8 @@ impl PipelineOrchestrator {
|
||||
|
||||
// Stage 6: Issue Creation
|
||||
tracing::info!("[{repo_id}] Stage 6: Issue Creation");
|
||||
self.update_phase(scan_run_id, "issue_creation").await;
|
||||
self.update_phase(scan_run_id, ScanPhase::IssueCreation)
|
||||
.await;
|
||||
if let Err(e) = self
|
||||
.create_tracker_issues(repo, &repo_id, &new_findings)
|
||||
.await
|
||||
@@ -385,7 +402,8 @@ impl PipelineOrchestrator {
|
||||
|
||||
// Stage 8: DAST (async, optional — only if a DastTarget is configured)
|
||||
tracing::info!("[{repo_id}] Stage 8: Checking for DAST targets");
|
||||
self.update_phase(scan_run_id, "dast_scanning").await;
|
||||
self.update_phase(scan_run_id, ScanPhase::DastScanning)
|
||||
.await;
|
||||
self.maybe_trigger_dast(&repo_id, scan_run_id).await;
|
||||
|
||||
tracing::info!("[{repo_id}] Scan complete: {new_count} new findings");
|
||||
@@ -534,7 +552,8 @@ impl PipelineOrchestrator {
|
||||
// run from re-triggering. The control-logic scan already consumed the
|
||||
// code artifact, so the SAST pipeline is not re-run.
|
||||
if plan.has(ScanType::Dast) {
|
||||
self.update_phase(scan_run_id, "dast_scanning").await;
|
||||
self.update_phase(scan_run_id, ScanPhase::DastScanning)
|
||||
.await;
|
||||
self.maybe_trigger_dast(&target_id, scan_run_id).await;
|
||||
}
|
||||
return Ok(new_count);
|
||||
@@ -562,7 +581,8 @@ impl PipelineOrchestrator {
|
||||
target_id = %target_id,
|
||||
"Unified pipeline: no code artifact; attempting DAST"
|
||||
);
|
||||
self.update_phase(scan_run_id, "dast_scanning").await;
|
||||
self.update_phase(scan_run_id, ScanPhase::DastScanning)
|
||||
.await;
|
||||
self.maybe_trigger_dast(&target_id, scan_run_id).await;
|
||||
}
|
||||
}
|
||||
@@ -578,7 +598,7 @@ impl PipelineOrchestrator {
|
||||
scan_run_id: &str,
|
||||
) -> Result<u32, AgentError> {
|
||||
tracing::info!(target_id, "[{target_id}] PLC control-logic analysis");
|
||||
self.update_phase(scan_run_id, "plc_analysis").await;
|
||||
self.update_phase(scan_run_id, ScanPhase::PlcAnalysis).await;
|
||||
|
||||
let ctx =
|
||||
crate::ingest::IngestContext::from_config(&self.config, &self.tenant_id, target_id);
|
||||
@@ -713,7 +733,8 @@ impl PipelineOrchestrator {
|
||||
.await;
|
||||
return Ok(0);
|
||||
}
|
||||
self.update_phase(scan_run_id, "plc_provision").await;
|
||||
self.update_phase(scan_run_id, ScanPhase::PlcProvision)
|
||||
.await;
|
||||
|
||||
// Locate a loadable control-logic program among the PLC-source artifacts
|
||||
// (same selection as the static PLC scan: dedicated PLC projects plus code
|
||||
@@ -811,7 +832,7 @@ impl PipelineOrchestrator {
|
||||
.await;
|
||||
return Ok(0);
|
||||
}
|
||||
self.update_phase(scan_run_id, "ics_probe").await;
|
||||
self.update_phase(scan_run_id, ScanPhase::IcsProbe).await;
|
||||
let Some(endpoint) = target.live_url().map(|a| a.source_ref.clone()) else {
|
||||
tracing::warn!(target_id, "ICS probe: no live URL");
|
||||
return Ok(0);
|
||||
@@ -995,7 +1016,8 @@ impl PipelineOrchestrator {
|
||||
target_id: &str,
|
||||
scan_run_id: &str,
|
||||
) {
|
||||
self.update_phase(scan_run_id, "classification").await;
|
||||
self.update_phase(scan_run_id, ScanPhase::Classification)
|
||||
.await;
|
||||
let ctx =
|
||||
crate::ingest::IngestContext::from_config(&self.config, &self.tenant_id, target_id);
|
||||
let ingest_set = match crate::ingest::ingest_all(target, &ctx) {
|
||||
@@ -1050,10 +1072,18 @@ impl PipelineOrchestrator {
|
||||
)
|
||||
.await;
|
||||
if !entries.is_empty() {
|
||||
// Only the firmware entries: a rescan with no new
|
||||
// commits skips the SBOM stage, so deleting everything
|
||||
// here wiped the Syft entries until the next commit.
|
||||
let _ = self
|
||||
.db
|
||||
.sbom_entries()
|
||||
.delete_many(doc! { "repo_id": target_id })
|
||||
.delete_many(doc! {
|
||||
"repo_id": target_id,
|
||||
"package_manager": {
|
||||
"$in": crate::pipeline::firmware_sbom::FIRMWARE_MANAGERS.to_vec()
|
||||
},
|
||||
})
|
||||
.await;
|
||||
for entry in &entries {
|
||||
let filter = doc! {
|
||||
@@ -1095,6 +1125,11 @@ impl PipelineOrchestrator {
|
||||
let (Some(url), Some(oid)) = (target.live_url(), target.id) else {
|
||||
return;
|
||||
};
|
||||
// A PLC endpoint (`modbus://`, `opc.tcp://`) is for the ICS probe, not
|
||||
// a web application to crawl.
|
||||
if !url.source_ref.starts_with("http://") && !url.source_ref.starts_with("https://") {
|
||||
return;
|
||||
}
|
||||
let target_id = oid.to_hex();
|
||||
if self
|
||||
.db
|
||||
@@ -1208,7 +1243,13 @@ impl PipelineOrchestrator {
|
||||
.await;
|
||||
}
|
||||
|
||||
pub(super) async fn update_phase(&self, scan_run_id: &str, phase: &str) {
|
||||
/// Record that `phase` started. Typed, so a phase the model cannot read
|
||||
/// back cannot be written: an unknown one made the whole run fail to
|
||||
/// deserialize and drop out of `GET /scan-runs`.
|
||||
pub(super) async fn update_phase(&self, scan_run_id: &str, phase: ScanPhase) {
|
||||
let Ok(phase) = mongodb::bson::to_bson(&phase) else {
|
||||
return;
|
||||
};
|
||||
if let Ok(oid) = mongodb::bson::oid::ObjectId::parse_str(scan_run_id) {
|
||||
let _ = self
|
||||
.db
|
||||
@@ -1216,7 +1257,7 @@ impl PipelineOrchestrator {
|
||||
.update_one(
|
||||
doc! { "_id": oid },
|
||||
doc! {
|
||||
"$set": { "current_phase": phase },
|
||||
"$set": { "current_phase": phase.clone() },
|
||||
"$push": { "phases_completed": phase },
|
||||
},
|
||||
)
|
||||
|
||||
@@ -0,0 +1,503 @@
|
||||
//! Nightly scan regression (#188).
|
||||
//!
|
||||
//! Seeds the demo-target corpus on a **running** agent (the nightly job points
|
||||
//! `NIGHTLY_AGENT_URL` at the built image), waits for every scan, and compares
|
||||
//! the results with two baselines per target:
|
||||
//!
|
||||
//! - the hand-written `expect` block in `fixtures/demo-targets/targets.json`:
|
||||
//! invariants such as the rules and CWEs that must appear;
|
||||
//! - a blessed snapshot in `fixtures/nightly/baselines/<key>.json`:
|
||||
//! - **exact**: scan status, skipped stages, SBOM components, and findings
|
||||
//! from deterministic scanners (PLC rules, secrets, patterns, lint, our own
|
||||
//! `cra-ai-*` semgrep rules);
|
||||
//! - **at least**: CVE and advisory ids, and semgrep registry rules, whose
|
||||
//! sources change daily;
|
||||
//! - **ignored**: LLM code review and triage. Control refs, which the LLM
|
||||
//! control judge stamps, are reported under "advisory" but do not gate.
|
||||
//!
|
||||
//! `NIGHTLY_BLESS=1` rewrites the snapshots from this run; the `expect` block
|
||||
//! still has to hold. Without `NIGHTLY_AGENT_URL` the test skips, so a plain
|
||||
//! `cargo test` never needs a running agent.
|
||||
//!
|
||||
//! Other settings: `NIGHTLY_AGENT_TOKEN` (bearer, for a hardened agent),
|
||||
//! `NIGHTLY_ONLY` (comma-separated target keys), `NIGHTLY_TIMEOUT_SECS`
|
||||
//! (default 1500). The report and this run's snapshots are written to
|
||||
//! `target/nightly/`.
|
||||
|
||||
#![allow(clippy::expect_used, clippy::unwrap_used)]
|
||||
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::{json, Value};
|
||||
|
||||
use compliance_agent::fixtures::{DemoTarget, DemoTargets, Observed};
|
||||
|
||||
/// Page size the agent allows at most (`MAX_PAGE_SIZE`).
|
||||
const PAGE: usize = 200;
|
||||
/// How often the scan runs are polled.
|
||||
const POLL: Duration = Duration::from_secs(10);
|
||||
|
||||
/// A thin client for the agent API.
|
||||
struct Agent {
|
||||
base: String,
|
||||
http: reqwest::Client,
|
||||
token: Option<String>,
|
||||
}
|
||||
|
||||
impl Agent {
|
||||
async fn call(&self, method: reqwest::Method, path: &str, body: Option<Value>) -> Value {
|
||||
let mut req = self
|
||||
.http
|
||||
.request(method.clone(), format!("{}{path}", self.base));
|
||||
if let Some(t) = &self.token {
|
||||
req = req.bearer_auth(t);
|
||||
}
|
||||
if let Some(b) = body {
|
||||
req = req.json(&b);
|
||||
}
|
||||
let resp = req
|
||||
.send()
|
||||
.await
|
||||
.unwrap_or_else(|e| panic!("{method} {path}: {e}"));
|
||||
let status = resp.status();
|
||||
let text = resp.text().await.unwrap_or_default();
|
||||
assert!(status.is_success(), "{method} {path}: {status} {text}");
|
||||
serde_json::from_str(&text).unwrap_or_else(|e| panic!("{method} {path}: {e}: {text}"))
|
||||
}
|
||||
|
||||
async fn get(&self, path: &str) -> Value {
|
||||
self.call(reqwest::Method::GET, path, None).await
|
||||
}
|
||||
|
||||
/// Every item of a paginated list endpoint (`?limit=&page=`, `data`, `total`).
|
||||
async fn all(&self, path: &str) -> Vec<Value> {
|
||||
let sep = if path.contains('?') { '&' } else { '?' };
|
||||
let mut items = Vec::new();
|
||||
for page in 1.. {
|
||||
let body = self
|
||||
.get(&format!("{path}{sep}limit={PAGE}&page={page}"))
|
||||
.await;
|
||||
let data = body["data"].as_array().cloned().unwrap_or_default();
|
||||
let total = body["total"].as_u64().map(|t| t as usize);
|
||||
let done = data.len() < PAGE || total.is_some_and(|t| items.len() + data.len() >= t);
|
||||
items.extend(data);
|
||||
if done {
|
||||
break;
|
||||
}
|
||||
}
|
||||
items
|
||||
}
|
||||
}
|
||||
|
||||
fn oid(v: &Value) -> String {
|
||||
v["_id"]["$oid"]
|
||||
.as_str()
|
||||
.or_else(|| v["_id"].as_str())
|
||||
.unwrap_or_default()
|
||||
.to_string()
|
||||
}
|
||||
|
||||
fn text(v: &Value, key: &str) -> String {
|
||||
v[key].as_str().unwrap_or_default().to_string()
|
||||
}
|
||||
|
||||
/// A semgrep rule id is prefixed with the path of the config it came from; our
|
||||
/// own rules are recognised by their `cra-ai-` id wherever it sits.
|
||||
fn normalise_rule(scanner: &str, rule: &str) -> String {
|
||||
match rule.find("cra-ai-") {
|
||||
Some(i) if scanner == "semgrep" => rule[i..].to_string(),
|
||||
_ => rule.to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The blessed, per-target snapshot.
|
||||
#[derive(Debug, Default, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
struct Snapshot {
|
||||
scan_status: String,
|
||||
skipped_stages: BTreeSet<String>,
|
||||
/// `package_manager:name@version`, compared exactly.
|
||||
sbom: BTreeSet<String>,
|
||||
/// Deterministic findings as `scanner:rule file:line`, compared exactly.
|
||||
findings: BTreeSet<String>,
|
||||
/// CVE and advisory ids; the run must contain at least these.
|
||||
cves: BTreeSet<String>,
|
||||
/// Semgrep registry rules; the run must contain at least these.
|
||||
registry_rules: BTreeSet<String>,
|
||||
}
|
||||
|
||||
impl Snapshot {
|
||||
/// Differences between this run (`self`) and the blessed `baseline`.
|
||||
fn diff(&self, baseline: &Snapshot) -> Vec<String> {
|
||||
let mut out = Vec::new();
|
||||
if self.scan_status != baseline.scan_status {
|
||||
out.push(format!(
|
||||
"scan status {}, blessed {}",
|
||||
self.scan_status, baseline.scan_status
|
||||
));
|
||||
}
|
||||
let exact = |what: &str, got: &BTreeSet<String>, want: &BTreeSet<String>| {
|
||||
let mut lines: Vec<String> = want
|
||||
.difference(got)
|
||||
.map(|m| format!("missing {what}: {m}"))
|
||||
.collect();
|
||||
lines.extend(
|
||||
got.difference(want)
|
||||
.map(|u| format!("unexpected {what}: {u}")),
|
||||
);
|
||||
lines
|
||||
};
|
||||
let at_least = |what: &str, got: &BTreeSet<String>, want: &BTreeSet<String>| {
|
||||
want.difference(got)
|
||||
.map(|m| format!("missing {what}: {m}"))
|
||||
.collect::<Vec<_>>()
|
||||
};
|
||||
out.extend(exact(
|
||||
"skipped stage",
|
||||
&self.skipped_stages,
|
||||
&baseline.skipped_stages,
|
||||
));
|
||||
out.extend(exact("SBOM component", &self.sbom, &baseline.sbom));
|
||||
out.extend(exact("finding", &self.findings, &baseline.findings));
|
||||
out.extend(at_least("CVE", &self.cves, &baseline.cves));
|
||||
out.extend(at_least(
|
||||
"registry rule",
|
||||
&self.registry_rules,
|
||||
&baseline.registry_rules,
|
||||
));
|
||||
out
|
||||
}
|
||||
}
|
||||
|
||||
/// Everything one finished target produced.
|
||||
struct Collected {
|
||||
snapshot: Snapshot,
|
||||
observed: Observed,
|
||||
}
|
||||
|
||||
async fn collect(agent: &Agent, target_id: &str, run: &Value) -> Collected {
|
||||
let findings = agent
|
||||
.all(&format!("/api/v1/findings?repo_id={target_id}"))
|
||||
.await;
|
||||
let sbom = agent
|
||||
.all(&format!("/api/v1/sbom?repo_id={target_id}"))
|
||||
.await;
|
||||
let target = agent.get(&format!("/api/v1/targets/{target_id}")).await["data"].clone();
|
||||
let scans = agent
|
||||
.get(&format!("/api/v1/targets/{target_id}/applicable-scans"))
|
||||
.await["data"]
|
||||
.clone();
|
||||
|
||||
let mut snapshot = Snapshot {
|
||||
scan_status: text(run, "status"),
|
||||
skipped_stages: run["skipped_stages"]
|
||||
.as_array()
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.map(|s| text(s, "stage"))
|
||||
.collect(),
|
||||
..Default::default()
|
||||
};
|
||||
let mut observed = Observed {
|
||||
findings: findings.len(),
|
||||
sbom_components: sbom.len(),
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
for f in &findings {
|
||||
let scanner = text(f, "scanner");
|
||||
let scan_type = text(f, "scan_type");
|
||||
let rule = normalise_rule(&scanner, &text(f, "rule_id"));
|
||||
if !rule.is_empty() {
|
||||
observed.rule_ids.insert(rule.clone());
|
||||
}
|
||||
if let Some(cwe) = f["cwe"].as_str() {
|
||||
observed.cwes.insert(cwe.to_string());
|
||||
}
|
||||
let refs: Vec<String> = f["control_refs"]
|
||||
.as_array()
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.filter_map(|r| r.as_str().map(str::to_string))
|
||||
.collect();
|
||||
observed.any_control_ref |= !refs.is_empty();
|
||||
observed.control_refs.extend(refs);
|
||||
|
||||
if let Some(cve) = f["cve"].as_str() {
|
||||
snapshot.cves.insert(cve.to_string());
|
||||
} else if scan_type == "cve" || scan_type == "sbom" {
|
||||
snapshot.cves.insert(rule);
|
||||
} else if scan_type == "codereview" {
|
||||
// LLM output: runs, never gates.
|
||||
} else if scanner == "semgrep" && !rule.starts_with("cra-ai-") {
|
||||
snapshot.registry_rules.insert(rule);
|
||||
} else {
|
||||
let file = Path::new(&text(f, "file_path"))
|
||||
.file_name()
|
||||
.map(|n| n.to_string_lossy().into_owned())
|
||||
.unwrap_or_default();
|
||||
let line = f["line_number"].as_u64().unwrap_or(0);
|
||||
snapshot
|
||||
.findings
|
||||
.insert(format!("{scanner}:{rule} {file}:{line}"));
|
||||
}
|
||||
}
|
||||
for e in &sbom {
|
||||
snapshot.sbom.insert(format!(
|
||||
"{}:{}@{}",
|
||||
text(e, "package_manager"),
|
||||
text(e, "name"),
|
||||
text(e, "version")
|
||||
));
|
||||
for v in e["known_vulnerabilities"].as_array().into_iter().flatten() {
|
||||
snapshot.cves.insert(text(v, "id"));
|
||||
}
|
||||
}
|
||||
|
||||
let facts = target["classification"]["facts"]
|
||||
.as_array()
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.chain(
|
||||
target["artifacts"]
|
||||
.as_array()
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.flat_map(|a| a["detected"].as_array().into_iter().flatten()),
|
||||
);
|
||||
for fact in facts {
|
||||
observed
|
||||
.detected_facts
|
||||
.insert(text(fact, "key"), text(fact, "value"));
|
||||
}
|
||||
observed.scans_offered = scans["scans"]
|
||||
.as_array()
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.map(|s| text(s, "scan"))
|
||||
.collect();
|
||||
observed.pentest_supported = scans["pentest_supported"].as_bool();
|
||||
|
||||
Collected { snapshot, observed }
|
||||
}
|
||||
|
||||
/// Wait until each target has a finished scan run that did not exist before
|
||||
/// seeding. Returns the run per target id; targets still running at the
|
||||
/// deadline are left out.
|
||||
async fn wait_for_runs(
|
||||
agent: &Agent,
|
||||
targets: &[String],
|
||||
before: &BTreeSet<String>,
|
||||
timeout: Duration,
|
||||
) -> BTreeMap<String, Value> {
|
||||
let deadline = Instant::now() + timeout;
|
||||
let mut done = BTreeMap::new();
|
||||
while done.len() < targets.len() && Instant::now() < deadline {
|
||||
tokio::time::sleep(POLL).await;
|
||||
for run in agent.all("/api/v1/scan-runs").await {
|
||||
let repo = text(&run, "repo_id");
|
||||
if done.contains_key(&repo)
|
||||
|| !targets.contains(&repo)
|
||||
|| before.contains(&oid(&run))
|
||||
|| text(&run, "status") == "running"
|
||||
{
|
||||
continue;
|
||||
}
|
||||
done.insert(repo, run);
|
||||
}
|
||||
}
|
||||
done
|
||||
}
|
||||
|
||||
fn baseline_path(root: &Path, key: &str) -> PathBuf {
|
||||
root.join("fixtures/nightly/baselines")
|
||||
.join(format!("{key}.json"))
|
||||
}
|
||||
|
||||
fn write_json<T: Serialize>(path: &Path, value: &T) {
|
||||
std::fs::create_dir_all(path.parent().expect("parent")).expect("create dir");
|
||||
let mut body = serde_json::to_string_pretty(value).expect("serialise");
|
||||
body.push('\n');
|
||||
std::fs::write(path, body).expect("write");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn nightly_scan_regression() {
|
||||
let Ok(base) = std::env::var("NIGHTLY_AGENT_URL") else {
|
||||
eprintln!("SKIP nightly: NIGHTLY_AGENT_URL is not set");
|
||||
return;
|
||||
};
|
||||
let bless = std::env::var("NIGHTLY_BLESS").is_ok_and(|v| v == "1");
|
||||
let timeout = Duration::from_secs(
|
||||
std::env::var("NIGHTLY_TIMEOUT_SECS")
|
||||
.ok()
|
||||
.and_then(|v| v.parse().ok())
|
||||
.unwrap_or(1500),
|
||||
);
|
||||
let only: Vec<String> = std::env::var("NIGHTLY_ONLY")
|
||||
.map(|v| v.split(',').map(str::trim).map(String::from).collect())
|
||||
.unwrap_or_default();
|
||||
let agent = Agent {
|
||||
base: base.trim_end_matches('/').to_string(),
|
||||
http: reqwest::Client::builder()
|
||||
.timeout(Duration::from_secs(60))
|
||||
.build()
|
||||
.unwrap(),
|
||||
token: std::env::var("NIGHTLY_AGENT_TOKEN").ok(),
|
||||
};
|
||||
let root = DemoTargets::workspace_root();
|
||||
let manifest = DemoTargets::load().expect("manifest");
|
||||
let selected: Vec<&DemoTarget> = manifest.select(&only).expect("targets");
|
||||
|
||||
// Seed (or rescan) every selected target, noting the runs that existed.
|
||||
let before: BTreeSet<String> = agent
|
||||
.all("/api/v1/scan-runs")
|
||||
.await
|
||||
.iter()
|
||||
.map(oid)
|
||||
.collect();
|
||||
let seeded = agent
|
||||
.call(
|
||||
reqwest::Method::POST,
|
||||
"/api/v1/targets/demo-seed",
|
||||
Some(json!({ "names": only, "rescan": true })),
|
||||
)
|
||||
.await;
|
||||
let mut failures: BTreeMap<String, Vec<String>> = BTreeMap::new();
|
||||
let mut ids: BTreeMap<String, String> = BTreeMap::new();
|
||||
for s in seeded["seeded"].as_array().into_iter().flatten() {
|
||||
let key = text(s, "name");
|
||||
match s["target_id"].as_str() {
|
||||
Some(id) if text(s, "status") != "failed" => {
|
||||
ids.insert(key, id.to_string());
|
||||
}
|
||||
_ => failures
|
||||
.entry(key)
|
||||
.or_default()
|
||||
.push(format!("seeding failed: {}", text(s, "error"))),
|
||||
}
|
||||
}
|
||||
|
||||
let target_ids: Vec<String> = ids.values().cloned().collect();
|
||||
let runs = wait_for_runs(&agent, &target_ids, &before, timeout).await;
|
||||
|
||||
let report_dir = root.join("target/nightly");
|
||||
let mut report = String::from("# Nightly scan regression\n\n");
|
||||
for t in &selected {
|
||||
let Some(id) = ids.get(&t.key) else { continue };
|
||||
let Some(run) = runs.get(id) else {
|
||||
failures
|
||||
.entry(t.key.clone())
|
||||
.or_default()
|
||||
.push(format!("no finished scan within {}s", timeout.as_secs()));
|
||||
continue;
|
||||
};
|
||||
let got = collect(&agent, id, run).await;
|
||||
write_json(&report_dir.join(format!("{}.json", t.key)), &got.snapshot);
|
||||
|
||||
let mut problems = t.expect.violations(&got.observed);
|
||||
let advisory = t.expect.llm_violations(&got.observed);
|
||||
let path = baseline_path(&root, &t.key);
|
||||
if bless {
|
||||
write_json(&path, &got.snapshot);
|
||||
} else {
|
||||
match std::fs::read_to_string(&path) {
|
||||
Ok(body) => {
|
||||
let blessed: Snapshot = serde_json::from_str(&body).expect("baseline");
|
||||
problems.extend(got.snapshot.diff(&blessed));
|
||||
}
|
||||
Err(_) => problems.push(format!(
|
||||
"no baseline at {}; run with NIGHTLY_BLESS=1",
|
||||
path.display()
|
||||
)),
|
||||
}
|
||||
}
|
||||
report.push_str(&format!(
|
||||
"## {} ({})\n\n{} findings, {} SBOM components, scan {}\n\n",
|
||||
t.key,
|
||||
if problems.is_empty() { "pass" } else { "FAIL" },
|
||||
got.observed.findings,
|
||||
got.observed.sbom_components,
|
||||
got.snapshot.scan_status,
|
||||
));
|
||||
for p in &problems {
|
||||
report.push_str(&format!("- {p}\n"));
|
||||
}
|
||||
if !advisory.is_empty() {
|
||||
report.push_str("\nAdvisory (control refs come from the LLM judge; not gating):\n\n");
|
||||
for a in &advisory {
|
||||
report.push_str(&format!("- {a}\n"));
|
||||
}
|
||||
}
|
||||
report.push('\n');
|
||||
if !problems.is_empty() {
|
||||
failures.entry(t.key.clone()).or_default().extend(problems);
|
||||
}
|
||||
}
|
||||
|
||||
std::fs::create_dir_all(&report_dir).expect("report dir");
|
||||
std::fs::write(report_dir.join("report.md"), &report).expect("report");
|
||||
eprintln!("{report}");
|
||||
assert!(
|
||||
failures.is_empty(),
|
||||
"nightly regression failed:\n{}",
|
||||
failures
|
||||
.iter()
|
||||
.map(|(k, v)| format!("{k}:\n - {}", v.join("\n - ")))
|
||||
.collect::<Vec<_>>()
|
||||
.join("\n")
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod unit {
|
||||
use super::*;
|
||||
|
||||
fn set(items: &[&str]) -> BTreeSet<String> {
|
||||
items.iter().map(|s| s.to_string()).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn exact_sets_report_both_directions_and_at_least_sets_only_losses() {
|
||||
let blessed = Snapshot {
|
||||
scan_status: "completed".into(),
|
||||
skipped_stages: set(&["dast"]),
|
||||
sbom: set(&["cargo:itoa@1.0.15"]),
|
||||
findings: set(&["gitleaks:aws-key a.py:3"]),
|
||||
cves: set(&["CVE-2020-1"]),
|
||||
registry_rules: set(&["python.lang.x"]),
|
||||
};
|
||||
let mut run = blessed.clone();
|
||||
assert!(run.diff(&blessed).is_empty());
|
||||
|
||||
run.sbom = set(&["cargo:itoa@1.0.16"]);
|
||||
run.cves = set(&["CVE-2020-1", "CVE-2026-9"]); // a new CVE is fine
|
||||
run.registry_rules = set(&[]);
|
||||
run.scan_status = "failed".into();
|
||||
let diff = run.diff(&blessed);
|
||||
for needle in [
|
||||
"scan status failed, blessed completed",
|
||||
"missing SBOM component: cargo:itoa@1.0.15",
|
||||
"unexpected SBOM component: cargo:itoa@1.0.16",
|
||||
"missing registry rule: python.lang.x",
|
||||
] {
|
||||
assert!(diff.iter().any(|d| d == needle), "{needle} not in {diff:?}");
|
||||
}
|
||||
assert!(!diff.iter().any(|d| d.contains("CVE")), "{diff:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn our_semgrep_rules_are_recognised_behind_a_config_prefix() {
|
||||
assert_eq!(
|
||||
normalise_rule("semgrep", "tmp.cra_rules.cra-ai-14-python-weak-cipher"),
|
||||
"cra-ai-14-python-weak-cipher"
|
||||
);
|
||||
assert_eq!(
|
||||
normalise_rule("semgrep", "python.lang.security.audit.exec-detected"),
|
||||
"python.lang.security.audit.exec-detected"
|
||||
);
|
||||
assert_eq!(normalise_rule("gitleaks", "cra-ai-x"), "cra-ai-x");
|
||||
}
|
||||
}
|
||||
@@ -83,8 +83,16 @@ pub enum ScanPhase {
|
||||
MobileStatic,
|
||||
ContainerScan,
|
||||
LlmTriage,
|
||||
/// Control refs stamped on findings from the CRA control-map table.
|
||||
ControlTriage,
|
||||
/// The LLM pass that maps findings to master controls.
|
||||
SemanticControlMapping,
|
||||
/// Control checks grounded in the code (text control to code finding).
|
||||
GroundedControlChecks,
|
||||
IssueCreation,
|
||||
DastScanning,
|
||||
/// An ephemeral soft-PLC started to probe the control logic.
|
||||
PlcProvision,
|
||||
IcsProbe,
|
||||
Completed,
|
||||
}
|
||||
@@ -151,6 +159,23 @@ mod skipped_stage_tests {
|
||||
assert_eq!(j["status"], "skipped");
|
||||
}
|
||||
|
||||
/// Every phase the pipeline records must deserialize, or the run drops
|
||||
/// out of `GET /scan-runs` (found by the nightly harness, #188).
|
||||
#[test]
|
||||
fn runs_with_every_recorded_phase_deserialize() {
|
||||
let run = ScanRun::new("repo".into(), ScanTrigger::Manual);
|
||||
let mut j = serde_json::to_value(&run).expect("serialize");
|
||||
j["phases_completed"] = serde_json::json!([
|
||||
"control_triage",
|
||||
"semantic_control_mapping",
|
||||
"grounded_control_checks",
|
||||
"plc_provision"
|
||||
]);
|
||||
j["current_phase"] = serde_json::json!("grounded_control_checks");
|
||||
let back: ScanRun = serde_json::from_value(j).expect("known phases");
|
||||
assert_eq!(back.phases_completed.len(), 4);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scan_runs_without_the_field_deserialize_as_nothing_skipped() {
|
||||
let run = ScanRun::new("repo".into(), ScanTrigger::Manual);
|
||||
|
||||
@@ -61,6 +61,9 @@ pub enum NetGuardError {
|
||||
|
||||
/// Schemes the scanner will fetch over HTTP(S).
|
||||
const HTTP_SCHEMES: &[&str] = &["http", "https"];
|
||||
/// Schemes a live endpoint may use: a web application (DAST) or a PLC the ICS
|
||||
/// probe talks Modbus/TCP or OPC UA to.
|
||||
const LIVE_SCHEMES: &[&str] = &["http", "https", "modbus", "opc.tcp"];
|
||||
/// Schemes accepted for a git remote. `file://` and `git://` are refused: the
|
||||
/// first reads the agent's own disk (including other tenants' checkouts), the
|
||||
/// second is unauthenticated and cleartext. `ssh://` is refused too, because
|
||||
@@ -141,6 +144,13 @@ impl NetGuard {
|
||||
self.check_url_with_schemes(raw, HTTP_SCHEMES)
|
||||
}
|
||||
|
||||
/// Check a live endpoint: an `http(s)` web application or a
|
||||
/// `modbus://` / `opc.tcp://` PLC. The host rules are the same as for
|
||||
/// [`Self::check_url`].
|
||||
pub fn check_live_url(self, raw: &str) -> Result<GuardedUrl, NetGuardError> {
|
||||
self.check_url_with_schemes(raw, LIVE_SCHEMES)
|
||||
}
|
||||
|
||||
/// Check a git remote. Rejects `file://`, `git://` and bare filesystem
|
||||
/// paths; an `ssh://` remote still has to pass the host rules.
|
||||
pub fn check_git_url(self, raw: &str) -> Result<GuardedUrl, NetGuardError> {
|
||||
@@ -456,6 +466,28 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn live_endpoints_accept_plc_protocols_with_the_same_host_rules() {
|
||||
let g = guard();
|
||||
for ok in [
|
||||
"modbus://plc.example.com:502",
|
||||
"opc.tcp://plc.example.com:4840/",
|
||||
"https://hmi.example.com/",
|
||||
] {
|
||||
assert!(g.check_live_url(ok).is_ok(), "{ok}");
|
||||
}
|
||||
for refused in [
|
||||
"modbus://plc-sim:502",
|
||||
"modbus://10.0.0.5:502",
|
||||
"opc.tcp://169.254.169.254/",
|
||||
"ftp://plc.example.com/",
|
||||
] {
|
||||
assert!(g.check_live_url(refused).is_err(), "{refused}");
|
||||
}
|
||||
// Plain HTTP fetches keep refusing PLC schemes.
|
||||
assert!(g.check_url("modbus://plc.example.com:502").is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn git_urls_refuse_file_git_and_ssh_schemes() {
|
||||
assert!(guard()
|
||||
|
||||
@@ -120,7 +120,7 @@
|
||||
],
|
||||
"expect": {
|
||||
"detected_facts": {
|
||||
"build_system": "zephyr"
|
||||
"build_system": "zephyr (west)"
|
||||
},
|
||||
"scans_offered": [
|
||||
"sast"
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
{
|
||||
"scan_status": "completed",
|
||||
"skipped_stages": [
|
||||
"dast"
|
||||
],
|
||||
"sbom": [
|
||||
"github:actions/checkout@v7.0.1",
|
||||
"github:actions/configure-pages@v6.0.0",
|
||||
"github:actions/deploy-pages@v5.0.0",
|
||||
"github:actions/setup-python@v7.0.0",
|
||||
"github:actions/upload-artifact@v7.0.1",
|
||||
"github:actions/upload-pages-artifact@v5.0.0",
|
||||
"github:zephyrproject-rtos/action-dco@v1.0.0",
|
||||
"github:zephyrproject-rtos/action-zephyr-setup@v1.0.15",
|
||||
"toolchain:zephyr-sdk@",
|
||||
"unknown:/tmp/compliance-scanner/repos/dev/Demo___Firmware_RTOS___Zephyr_example-application/.github/workflows/build.yml@unknown",
|
||||
"unknown:/tmp/compliance-scanner/repos/dev/Demo___Firmware_RTOS___Zephyr_example-application/.github/workflows/dco.yml@unknown",
|
||||
"unknown:/tmp/compliance-scanner/repos/dev/Demo___Firmware_RTOS___Zephyr_example-application/.github/workflows/docs.yml@unknown"
|
||||
],
|
||||
"findings": [],
|
||||
"cves": [],
|
||||
"registry_rules": []
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
{
|
||||
"scan_status": "completed",
|
||||
"skipped_stages": [
|
||||
"dast"
|
||||
],
|
||||
"sbom": [],
|
||||
"findings": [
|
||||
"gitleaks:stripe-access-token auth.py:2",
|
||||
"semgrep:cra-ai-14-python-weak-cipher crypto.py:8"
|
||||
],
|
||||
"cves": [],
|
||||
"registry_rules": [
|
||||
"generic.secrets.security.detected-stripe-api-key.detected-stripe-api-key",
|
||||
"python.lang.security.audit.insecure-transport.requests.request-with-http.request-with-http",
|
||||
"python.pycryptodome.security.insecure-cipher-algorithm-des.insecure-cipher-algorithm-des",
|
||||
"python.sqlalchemy.security.sqlalchemy-execute-raw-query.sqlalchemy-execute-raw-query"
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
{
|
||||
"scan_status": "completed",
|
||||
"skipped_stages": [],
|
||||
"sbom": [],
|
||||
"findings": [
|
||||
"plc-control-logic:plc-default-password conveyor.xml:3",
|
||||
"plc-control-logic:plc-hardcoded-credential conveyor.xml:3",
|
||||
"plc-control-logic:plc-hardcoded-credential traffic_light.st:34",
|
||||
"plc-control-logic:plc-insecure-comm conveyor.xml:9",
|
||||
"plc-control-logic:plc-insecure-comm traffic_light.st:45",
|
||||
"plc-control-logic:plc-insecure-protocol-port conveyor.xml:9",
|
||||
"plc-control-logic:plc-insecure-protocol-port traffic_light.st:45",
|
||||
"plc-control-logic:plc-safety-bypass traffic_light.st:59"
|
||||
],
|
||||
"cves": [],
|
||||
"registry_rules": []
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
{
|
||||
"scan_status": "completed",
|
||||
"skipped_stages": [],
|
||||
"sbom": [],
|
||||
"findings": [
|
||||
"plc-control-logic:plc-array-unchecked-index pump_station.st:29",
|
||||
"plc-control-logic:plc-default-password pump_fbd.xml:8",
|
||||
"plc-control-logic:plc-default-password pump_station.st:18",
|
||||
"plc-control-logic:plc-division-by-zero pump_station.st:32",
|
||||
"plc-control-logic:plc-hardcoded-credential pump_fbd.xml:8",
|
||||
"plc-control-logic:plc-hardcoded-credential pump_station.st:18",
|
||||
"plc-control-logic:plc-hardcoded-credential pump_station.st:19",
|
||||
"plc-control-logic:plc-hardcoded-credential pump_station.st:41",
|
||||
"plc-control-logic:plc-insecure-comm pump_fbd.xml:7",
|
||||
"plc-control-logic:plc-insecure-comm pump_station.st:41",
|
||||
"plc-control-logic:plc-insecure-protocol-port pump_fbd.xml:7",
|
||||
"plc-control-logic:plc-insecure-protocol-port pump_station.st:41",
|
||||
"plc-control-logic:plc-safety-bypass pump_fbd.xml:9",
|
||||
"plc-control-logic:plc-safety-bypass pump_station.st:36",
|
||||
"plc-control-logic:plc-safety-bypass pump_station.st:37",
|
||||
"plc-control-logic:plc-unstructured-jump pump_station.st:45"
|
||||
],
|
||||
"cves": [],
|
||||
"registry_rules": []
|
||||
}
|
||||
Reference in new issue
Block a user