Files
pruefwerk/compliance-agent/tests/nightly.rs
T
sharangandClaude Opus 5.5 d406741907
CI / Check (push) Skipped
CI / Detect Changes (push) Successful in 4s
CI / Deploy Dashboard (push) Skipped
CI / Deploy MCP (push) Skipped
CI / Deploy Docs (push) Successful in 1m13s
CI / Deploy Agent (push) Successful in 6m21s
feat(sast): vendored MIT semgrep packs and a guard against registry rules (#492) (#504)
Our ~35 own rules left whole languages without SAST findings. Three
permissively licensed community packs now run next to them, on the same
semgrep invocation (--metrics=off, local files only):

- GitLab sast-rules v2.10.1 (53bf5cf6): 148 rules for C#, Java,
  JavaScript/TypeScript, Python and one Go rule; only files whose header says
  "License: MIT (c) GitLab Inc.". Not vendored: c/ (every file GPL-2.0,
  generated from flawfinder), go/ apart from one file (Apache-2.0 gosec
  ports), scala/, rules/lgpl, rules/lgpl-cc (Commons Clause), rules/gitlab (EE).
- 0xdea semgrep-rules (dae50da6, MIT): 35 C/C++ rules.
- elttam semgrep-rules (24426856, MIT; its LICENSE carries the Semgrep
  template's copyright line): 34 rules for Java, Go and Struts/Spring XML.

Each pack lives in compliance-agent/rules/vendor/<source>/ with LICENSE,
NOTICE (provenance, what was left out and why) and UPSTREAM (pinned commit):
upstream/ holds the selected files unchanged with their tests, pack.yaml the
rules the agent runs, ids prefixed per source (gitlab-, 0xdea-, elttam-),
rules.json an index for the tests. scripts/vendor-semgrep-rules.py
regenerates all of it deterministically.

Provenance: every candidate rule was compared with the Semgrep registry
(semgrep/semgrep-rules, read only for the comparison). Eight GitLab Python/JS
rules with the same message or the same patterns are not vendored, nor are
elttam's Kubernetes rules (registry-derived). Also left out: elttam's
entrypoint enumerators, its ORM-leak hints, three files whose upstream
tests fail on semgrep 1.177 and a join-mode rule.

Noise budget: run over the nightly fixtures, the public samples and
FreeRTOS-Kernel, lwIP, OpenRA, eShopOnWeb, requests, express and
spring-petclinic. 15 rules that flood real code (0xdea missing-return 1514
hits, typos 989, interesting-api-calls 718, signed-unsigned-conversion 221,
suspicious-assert 176, format-string-bugs 61 ...; GitLab assert-used) are
dropped from the pack, each listed with its reason in NOTICE. CPU time of
the semgrep run roughly doubles on C-heavy trees (FreeRTOS-Kernel 70 s ->
136 s, lwIP 18 s -> 68 s), well inside the 10-minute stage timeout.

Ids stay bare (#473 logic covers the vendored ids, fingerprint() unchanged).
The control map gets one vendored semgrep binding per control, by CWE (by
rule id for the few elttam rules without one), with exactly the languages of
the rules behind it; a test checks every vendored rule maps to a control
that claims its languages.

Guard: semgrep_args() builds the one invocation; a test fails if any
--config is not a staged local pack, or is auto, p/, r/ or a URL, and
another scans the agent source, scripts, docker/, CI and Dockerfile.agent for
a registry config.

Nightly baselines with C, Python, C# or JS code change and need a bless run
after the image is deployed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DmXxNULoSNPvjF7buKipsB
2026-10-06 12:22:50 +00:00

789 lines
28 KiB
Rust

//! Nightly scan regression (#188).
//!
//! Seeds two corpora 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 demo targets (`fixtures/demo-targets/targets.json`), which the agent
//! seeds itself (`POST /targets/demo-seed`, as the dashboard does), and
//! - the nightly-only fixtures (`fixtures/nightly/targets.json`, same schema),
//! which the harness onboards through the public API the way a customer does:
//! create, upload, detect, scan.
//!
//! The baselines:
//!
//! - the hand-written `expect` block in the manifest: 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 and the vendored `gitlab-`, `0xdea-` and
//! `elttam-` ones, #492);
//! - **at least**: CVE and advisory ids, 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 from either manifest),
//! `NIGHTLY_TIMEOUT_SECS` (default 1500), and the env vars an optional fixture
//! names (e.g. `NIGHTLY_CODESYS_SAMPLE`; the target is skipped without it). 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::{DemoArtifact, DemoTarget, DemoTargets, Observed, Pack};
/// 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}");
if text.trim().is_empty() {
return Value::Null;
}
serde_json::from_str(&text).unwrap_or_else(|e| panic!("{method} {path}: {e}: {text}"))
}
async fn post(&self, path: &str, body: Value) -> Value {
self.call(reqwest::Method::POST, path, Some(body)).await
}
/// Upload one file artifact the way the dashboard does (multipart). A
/// directory is packed first (zip, or tar.gz when the fixture says so), so
/// source-tree fixtures stay reviewable as plain files in the repository.
async fn upload(&self, target_id: &str, a: &DemoArtifact, path: &Path) -> Result<(), String> {
let name = path
.file_name()
.map(|n| n.to_string_lossy().into_owned())
.unwrap_or_default();
let (bytes, filename) = if path.is_dir() {
match a.pack {
Pack::Zip => (zip_dir(path)?, format!("{name}.zip")),
Pack::TarGz => (tar_gz_dir(path)?, format!("{name}.tar.gz")),
}
} else {
let bytes = tokio::fs::read(path)
.await
.map_err(|e| format!("reading {}: {e}", path.display()))?;
(bytes, name)
};
let mut form = reqwest::multipart::Form::new()
.text("kind", serde_name(&a.kind))
.part(
"file",
reqwest::multipart::Part::bytes(bytes).file_name(filename),
);
if let Some(format) = &a.plc_format {
form = form.text("plc_format", serde_name(format));
}
let url = format!("{}/api/v1/targets/{target_id}/artifacts/upload", self.base);
let mut req = self.http.post(url).multipart(form);
if let Some(t) = &self.token {
req = req.bearer_auth(t);
}
let resp = req.send().await.map_err(|e| format!("upload: {e}"))?;
if !resp.status().is_success() {
return Err(format!("upload {} -> {}", path.display(), resp.status()));
}
Ok(())
}
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()
}
/// The files under a fixture directory as `(relative path, contents)`, in a
/// stable order.
fn dir_files(dir: &Path) -> Result<Vec<(String, Vec<u8>)>, String> {
let mut files: Vec<PathBuf> = walkdir::WalkDir::new(dir)
.into_iter()
.filter_map(Result::ok)
.filter(|e| e.file_type().is_file())
.map(|e| e.into_path())
.collect();
files.sort();
files
.into_iter()
.map(|file| {
let rel = file
.strip_prefix(dir)
.map_err(|e| e.to_string())?
.to_string_lossy()
.replace('\\', "/");
let body = std::fs::read(&file).map_err(|e| format!("{}: {e}", file.display()))?;
Ok((rel, body))
})
.collect()
}
/// Zip a fixture directory in memory.
fn zip_dir(dir: &Path) -> Result<Vec<u8>, String> {
use std::io::Write;
let mut zip = zip::ZipWriter::new(std::io::Cursor::new(Vec::new()));
let options: zip::write::SimpleFileOptions = Default::default();
for (rel, body) in dir_files(dir)? {
zip.start_file(rel, options).map_err(|e| e.to_string())?;
zip.write_all(&body).map_err(|e| e.to_string())?;
}
Ok(zip.finish().map_err(|e| e.to_string())?.into_inner())
}
/// Pack a fixture directory as a tar.gz in memory, the way `tar czf` would.
fn tar_gz_dir(dir: &Path) -> Result<Vec<u8>, String> {
let gz = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::default());
let mut tar = tar::Builder::new(gz);
for (rel, body) in dir_files(dir)? {
let mut header = tar::Header::new_gnu();
header.set_size(body.len() as u64);
header.set_mode(0o644);
tar.append_data(&mut header, rel, body.as_slice())
.map_err(|e| e.to_string())?;
}
let gz = tar.into_inner().map_err(|e| e.to_string())?;
gz.finish().map_err(|e| e.to_string())
}
/// The wire name of a snake_case enum (`plc_project`, `project_archive`).
fn serde_name<T: Serialize>(value: &T) -> String {
serde_json::to_value(value)
.ok()
.and_then(|v| v.as_str().map(str::to_string))
.unwrap_or_default()
}
/// The keys of `manifest` that this run covers (all of them when `only` is
/// empty).
fn keys_in(manifest: &DemoTargets, only: &[String]) -> Vec<String> {
manifest
.targets
.iter()
.map(|t| t.key.clone())
.filter(|k| only.is_empty() || only.contains(k))
.collect()
}
/// Onboard one nightly-only fixture through the public API, as a customer
/// would, and start its scan; an existing target of the same name is only
/// rescanned. `Ok(None)` when an optional file is missing and nothing is left
/// to scan.
async fn seed_nightly(
agent: &Agent,
root: &Path,
manifest: &DemoTargets,
t: &DemoTarget,
) -> Result<Option<String>, String> {
let name = manifest.full_name(t);
let mut uploads = Vec::new();
for a in t.artifacts.iter().filter(|a| a.is_upload()) {
match a.upload_path(root) {
Some(path) => uploads.push((a, path)),
None if a.optional => {}
None => return Err(format!("{:?} artifact has no file", a.kind)),
}
}
let references: Vec<Value> = t
.artifacts
.iter()
.filter(|a| !a.is_upload())
.filter_map(|a| {
a.resolved_source_ref().map(|source_ref| {
json!({
"kind": a.kind,
"source_ref": source_ref,
"branch": a.branch,
"plc_format": a.plc_format,
})
})
})
.collect();
if uploads.is_empty() && references.is_empty() {
return Ok(None);
}
let existing = agent
.all("/api/v1/targets")
.await
.into_iter()
.find(|v| text(v, "name") == name);
let id = match existing {
Some(target) => oid(&target),
None => {
let created = agent
.post(
"/api/v1/targets",
json!({
"name": name,
"target_type": t.target_type,
"description": t.description,
"artifacts": references,
}),
)
.await;
let id = oid(&created["data"]);
for (a, path) in &uploads {
agent.upload(&id, a, path).await?;
}
if !t.enabled_scans.is_empty() {
agent
.call(
reqwest::Method::PATCH,
&format!("/api/v1/targets/{id}"),
Some(json!({ "scan_config": { "enabled_scans": t.enabled_scans } })),
)
.await;
}
agent
.post(&format!("/api/v1/targets/{id}/detect"), json!({}))
.await;
id
}
};
agent
.post(&format!("/api/v1/targets/{id}/scan"), json!({}))
.await;
Ok(Some(id))
}
/// 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. (The agent
/// has stored bare ids since #473, the vendored ones included.)
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,
/// The run's error message, for fixtures that must fail cleanly.
#[serde(default, skip_serializing_if = "String::is_empty")]
error: 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>,
}
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
));
}
if self.error != baseline.error {
out.push(format!(
"error \"{}\", blessed \"{}\"",
self.error, baseline.error
));
}
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
}
}
/// A target's heading and one-line summary in the report: what it found,
/// including the CVEs it matched (NVD answers change daily, so the baseline
/// holds a lower bound; the count shows what a run actually saw).
fn summary(key: &str, pass: bool, got: &Collected) -> String {
format!(
"## {key} ({})\n\n{} findings, {} SBOM components, {} CVEs, scan {}\n\n",
if pass { "pass" } else { "FAIL" },
got.observed.findings,
got.observed.sbom_components,
got.snapshot.cves.len(),
got.snapshot.scan_status,
)
}
/// 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 graph = agent.get(&format!("/api/v1/graph/{target_id}")).await["data"].clone();
let mut snapshot = Snapshot {
scan_status: text(run, "status"),
error: text(run, "error_message"),
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 {
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);
// The app variant tells apart the same file in a phone and a
// tablet app, which the file name alone does not.
let variant = f["variant"]
.as_str()
.map(|v| format!(" [{v}]"))
.unwrap_or_default();
snapshot
.findings
.insert(format!("{scanner}:{rule} {file}:{line}{variant}"));
}
}
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();
observed.graph_nodes = graph["total_nodes"].as_u64().unwrap_or(0);
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 demo = DemoTargets::load().expect("demo manifest");
let nightly = DemoTargets::load_from(&root.join("fixtures/nightly/targets.json"))
.expect("nightly manifest");
let demo_keys = keys_in(&demo, &only);
let nightly_keys = keys_in(&nightly, &only);
let selected: Vec<&DemoTarget> = demo
.targets
.iter()
.filter(|t| demo_keys.contains(&t.key))
.chain(
nightly
.targets
.iter()
.filter(|t| nightly_keys.contains(&t.key)),
)
.collect();
// 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 mut failures: BTreeMap<String, Vec<String>> = BTreeMap::new();
let mut skipped: Vec<String> = Vec::new();
let mut ids: BTreeMap<String, String> = BTreeMap::new();
// An empty name list would seed every demo target, so skip the call when
// this run covers none of them.
if !demo_keys.is_empty() {
let seeded = agent
.post(
"/api/v1/targets/demo-seed",
json!({ "names": demo_keys, "rescan": true }),
)
.await;
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"))),
}
}
}
for t in nightly
.targets
.iter()
.filter(|t| nightly_keys.contains(&t.key))
{
match seed_nightly(&agent, &root, &nightly, t).await {
Ok(Some(id)) => {
ids.insert(t.key.clone(), id);
}
Ok(None) => skipped.push(t.key.clone()),
Err(e) => failures
.entry(t.key.clone())
.or_default()
.push(format!("seeding failed: {e}")),
}
}
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 key in &skipped {
report.push_str(&format!(
"## {key} (skipped)\n\nAn optional fixture file is not available here.\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(&summary(&t.key, problems.is_empty(), &got));
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(),
error: String::new(),
skipped_stages: set(&["dast"]),
sbom: set(&["cargo:itoa@1.0.15"]),
findings: set(&["gitleaks:aws-key a.py:3"]),
cves: set(&["CVE-2020-1", "GHSA-xxxx-yyyy-zzzz"]),
};
let mut run = blessed.clone();
assert!(run.diff(&blessed).is_empty());
run.sbom = set(&["cargo:itoa@1.0.16"]);
// A new CVE is fine, a lost one is not.
run.cves = set(&["CVE-2020-1", "CVE-2026-9"]);
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 CVE: GHSA-xxxx-yyyy-zzzz",
] {
assert!(diff.iter().any(|d| d == needle), "{needle} not in {diff:?}");
}
assert!(!diff.iter().any(|d| d.contains("CVE-2026-9")), "{diff:?}");
}
#[test]
fn the_summary_shows_the_cves_a_run_matched() {
let got = Collected {
snapshot: Snapshot {
scan_status: "completed".into(),
cves: set(&["CVE-2020-22283", "CVE-2020-22284"]),
..Default::default()
},
observed: Observed {
findings: 3,
sbom_components: 5,
..Default::default()
},
};
assert_eq!(
summary("fw-embedded-libs", true, &got),
"## fw-embedded-libs (pass)\n\n3 findings, 5 SBOM components, 2 CVEs, scan completed\n\n"
);
}
#[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");
}
}