//! 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/.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, } impl Agent { async fn call(&self, method: reqwest::Method, path: &str, body: Option) -> 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 { 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)>, String> { let mut files: Vec = 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, 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, 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(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 { 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, 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 = 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, /// The stages the run's notes are about (code left out by design, /// suppressed findings), compared exactly. #[serde(default, skip_serializing_if = "BTreeSet::is_empty")] notes: BTreeSet, /// `package_manager:name@version`, with ` [in image: ]` for a /// component an image declares, compared exactly. sbom: BTreeSet, /// Deterministic findings as `scanner:rule file:line`, compared exactly. findings: BTreeSet, /// CVE and advisory ids; the run must contain at least these. cves: BTreeSet, /// A Yocto target's layer pins as `source name branch@commit` (`-` for /// what is not pinned), compared exactly. #[serde(default, skip_serializing_if = "BTreeSet::is_empty")] layer_pins: BTreeSet, /// The Yocto release read from them, compared exactly. #[serde(default, skip_serializing_if = "String::is_empty")] yocto_release: String, } impl Snapshot { /// Differences between this run (`self`) and the blessed `baseline`. fn diff(&self, baseline: &Snapshot) -> Vec { 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, want: &BTreeSet| { let mut lines: Vec = 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, want: &BTreeSet| { want.difference(got) .map(|m| format!("missing {what}: {m}")) .collect::>() }; out.extend(exact( "skipped stage", &self.skipped_stages, &baseline.skipped_stages, )); out.extend(exact("note", &self.notes, &baseline.notes)); 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(exact("layer pin", &self.layer_pins, &baseline.layer_pins)); if self.yocto_release != baseline.yocto_release { out.push(format!( "Yocto release \"{}\", blessed \"{}\"", self.yocto_release, baseline.yocto_release )); } 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, } /// The `stage` of every entry of a run's `skipped_stages` or `notes`. fn stages(entries: &Value) -> BTreeSet { entries .as_array() .into_iter() .flatten() .map(|s| text(s, "stage")) .collect() } 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: stages(&run["skipped_stages"]), notes: stages(&run["notes"]), ..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 = 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 { let in_image = e["in_image"]["images"] .as_array() .map(|images| { let names: Vec<&str> = images.iter().filter_map(Value::as_str).collect(); format!(" [in image: {}]", names.join(", ")) }) .unwrap_or_default(); snapshot.sbom.insert(format!( "{}:{}@{}{in_image}", text(e, "package_manager"), text(e, "name"), blessed_version(&text(e, "package_manager"), &text(e, "version")) )); for v in e["known_vulnerabilities"].as_array().into_iter().flatten() { snapshot.cves.insert(text(v, "id")); } } let pins = &target["layer_pins"]; for pin in pins["pins"].as_array().into_iter().flatten() { let or_dash = |key: &str| pin[key].as_str().unwrap_or("-").to_string(); snapshot.layer_pins.insert(format!( "{} {} {}@{}", text(pin, "source"), text(pin, "name"), or_dash("branch"), or_dash("commit") )); } snapshot.yocto_release = text(&pins["release"], "codename"); 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 queued or running /// at the deadline are left out. async fn wait_for_runs( agent: &Agent, targets: &[String], before: &BTreeSet, timeout: Duration, ) -> BTreeMap { 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)) // Still waiting for a slot (t84) or scanning: not finished. || matches!(text(&run, "status").as_str(), "queued" | "running") { continue; } done.insert(repo, run); } } done } /// The version a snapshot keeps of a component. A GitHub Action is named by /// a moving tag (`actions/deploy-pages@v5`), which the scan resolves to the /// release it points to today (`v5.0.1`): the snapshot keeps the major /// version, so an upstream patch release does not break the baseline (#573). /// A commit SHA has no dot and stays whole. fn blessed_version(package_manager: &str, version: &str) -> String { if package_manager == "github" { if let Some((major, _)) = version.split_once('.') { return major.to_string(); } } version.to_string() } fn baseline_path(root: &Path, key: &str) -> PathBuf { root.join("fixtures/nightly/baselines") .join(format!("{key}.json")) } fn write_json(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 = 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 = agent .all("/api/v1/scan-runs") .await .iter() .map(oid) .collect(); let mut failures: BTreeMap> = BTreeMap::new(); let mut skipped: Vec = Vec::new(); let mut ids: BTreeMap = 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 = 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::>() .join("\n") ); } #[cfg(test)] mod unit { use super::*; fn set(items: &[&str]) -> BTreeSet { items.iter().map(|s| s.to_string()).collect() } #[test] fn a_github_action_keeps_its_major_version_only() { assert_eq!(blessed_version("github", "v5.0.1"), "v5"); assert_eq!(blessed_version("github", "v1"), "v1"); let sha = "38a6d9b276ed434454900130cacc87d058d3ac62"; assert_eq!(blessed_version("github", sha), sha); assert_eq!(blessed_version("cargo", "1.0.15"), "1.0.15"); } #[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"]), notes: set(&["sast_vendor_code"]), sbom: set(&["cargo:itoa@1.0.15"]), findings: set(&["gitleaks:aws-key a.py:3"]), cves: set(&["CVE-2020-1", "GHSA-xxxx-yyyy-zzzz"]), ..Default::default() }; 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(); run.notes = set(&["recipe_lint_suppressed"]); run.layer_pins = set(&["kas poky dunfell@-"]); let diff = run.diff(&blessed); for needle in [ "unexpected layer pin: kas poky dunfell@-", "scan status failed, blessed completed", "missing note: sast_vendor_code", "unexpected note: recipe_lint_suppressed", "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"); } }