From 64f5a810dd9e8eff534c095f2d1a6bc9306d0937 Mon Sep 17 00:00:00 2001 From: Sharang Parnerkar Date: Fri, 9 Oct 2026 18:21:28 +0000 Subject: [PATCH] feat(scans): a scan run lists informational notes apart from skipped stages (#556) --- compliance-agent/src/api/handlers/health.rs | 7 +- .../src/api/handlers/onboarding.rs | 4 +- compliance-agent/src/api/handlers/scans.rs | 7 +- compliance-agent/src/evidence/mod.rs | 70 ++++++- compliance-agent/src/pipeline/orchestrator.rs | 21 +- compliance-agent/tests/nightly.rs | 27 ++- compliance-core/src/models/mod.rs | 3 +- compliance-core/src/models/scan.rs | 190 +++++++++++++++++- .../src/components/scan_runs.rs | 75 +++++-- compliance-dashboard/src/i18n/texts.rs | 6 + compliance-mcp/src/server.rs | 2 +- compliance-mcp/src/tools/targets.rs | 9 +- .../nightly/baselines/dotnet-framework48.json | 4 +- .../nightly/baselines/fw-c-sensor-node.json | 4 +- .../nightly/baselines/fw-embedded-libs.json | 4 +- .../nightly/baselines/fw-yocto-layer.json | 4 +- .../baselines/mobile-unity-mobile.json | 4 +- 17 files changed, 391 insertions(+), 50 deletions(-) diff --git a/compliance-agent/src/api/handlers/health.rs b/compliance-agent/src/api/handlers/health.rs index 24f7977..3148ddc 100644 --- a/compliance-agent/src/api/handlers/health.rs +++ b/compliance-agent/src/api/handlers/health.rs @@ -99,7 +99,12 @@ pub async fn stats_overview( .limit(10) .await { - Ok(cursor) => collect_cursor_async(cursor).await, + Ok(cursor) => { + let mut runs: Vec = collect_cursor_async(cursor).await; + // Runs recorded before notes existed list them among their skips. + runs.iter_mut().for_each(ScanRun::split_notes); + runs + } Err(e) => { tracing::warn!("Failed to fetch recent scans: {e}"); Vec::new() diff --git a/compliance-agent/src/api/handlers/onboarding.rs b/compliance-agent/src/api/handlers/onboarding.rs index bc4074d..9cd82a4 100644 --- a/compliance-agent/src/api/handlers/onboarding.rs +++ b/compliance-agent/src/api/handlers/onboarding.rs @@ -200,7 +200,9 @@ pub(crate) async fn latest_scan_runs( cursor .filter_map(|row| async move { let run = row.ok()?.get_document("run").ok()?.clone(); - let run: ScanRun = mongodb::bson::from_document(run).ok()?; + let mut run: ScanRun = mongodb::bson::from_document(run).ok()?; + // Runs recorded before notes existed list them among their skips. + run.split_notes(); Some((run.repo_id.clone(), run)) }) .collect() diff --git a/compliance-agent/src/api/handlers/scans.rs b/compliance-agent/src/api/handlers/scans.rs index b7f5e79..9652884 100644 --- a/compliance-agent/src/api/handlers/scans.rs +++ b/compliance-agent/src/api/handlers/scans.rs @@ -51,7 +51,12 @@ pub async fn list_scan_runs( .limit(params.limit) .await { - Ok(cursor) => collect_cursor_async(cursor).await, + Ok(cursor) => { + let mut runs: Vec = collect_cursor_async(cursor).await; + // Runs recorded before notes existed list them among their skips. + runs.iter_mut().for_each(ScanRun::split_notes); + runs + } Err(e) => { tracing::warn!("Failed to fetch scan runs: {e}"); Vec::new() diff --git a/compliance-agent/src/evidence/mod.rs b/compliance-agent/src/evidence/mod.rs index 2d63a86..17758e3 100644 --- a/compliance-agent/src/evidence/mod.rs +++ b/compliance-agent/src/evidence/mod.rs @@ -158,12 +158,16 @@ pub fn build_pack( "type": inputs.target.target_type.to_string(), }), last_scan_run: inputs.last_run.as_ref().map(|run| { + // A run recorded before notes existed lists them among its skips. + let mut run = run.clone(); + run.split_notes(); serde_json::json!({ "id": run.id.map(|id| id.to_hex()), "status": run.status, "started_at": run.started_at, "completed_at": run.completed_at, "skipped_stages": run.skipped_stages, + "notes": run.notes, }) }), tool_versions: std::fs::read(TOOL_VERSIONS_PATH) @@ -215,12 +219,13 @@ pub fn scanned_languages(inputs: &EvidenceInputs) -> Option<&[String]> { } /// The tools that did not complete in the target's last scan (a skipped -/// stage a control relies on: semgrep, cppcheck, the CVE lookup). +/// stage a control relies on: semgrep, cppcheck, the CVE lookup). Notes never +/// count: the stage they inform about ran. pub fn failed_tools(inputs: &EvidenceInputs) -> Vec<&'static str> { inputs .last_run .iter() - .flat_map(|run| &run.skipped_stages) + .flat_map(ScanRun::skips) .filter_map(|s| compliance::tool_of_stage(&s.stage)) .collect() } @@ -232,7 +237,7 @@ pub fn sbom_coverage(inputs: &EvidenceInputs) -> compliance::SbomCoverage { let unresolved: Vec = inputs .last_run .iter() - .flat_map(|run| &run.skipped_stages) + .flat_map(ScanRun::skips) .filter(|s| s.code == Some(SkipCode::DependenciesUnlocked)) .filter_map(|s| s.subject.clone()) .collect(); @@ -343,7 +348,7 @@ fn csv_cell(value: &str) -> String { #[allow(clippy::expect_used)] mod tests { use super::*; - use compliance_core::models::{ScanType, Severity, TargetType}; + use compliance_core::models::{ScanType, Severity, SkippedStage, TargetType}; use std::io::Read; fn inputs() -> EvidenceInputs { @@ -416,6 +421,63 @@ mod tests { assert!(listed.iter().all(|f| f.name != "enisa-drafts.json")); } + /// The last run of `inputs()` with these skipped stages and notes, as a + /// completed run. + fn with_run(skipped: Vec, notes: Vec) -> EvidenceInputs { + let mut run = ScanRun::new("t1".into(), compliance_core::models::ScanTrigger::Manual); + run.completed_at = Some(Utc::now()); + run.languages = vec!["c".into()]; + run.skipped_stages = skipped; + run.notes = notes; + EvidenceInputs { + last_run: Some(run), + ..inputs() + } + } + + fn vendor_note() -> SkippedStage { + SkippedStage::new("sast_vendor_code", SkipCode::VendorCode, "vendor").about("Drivers") + } + + #[test] + fn notes_leave_the_control_status_alone() { + let without = with_run(Vec::new(), Vec::new()); + let noted = with_run(Vec::new(), vec![vendor_note()]); + // A run recorded before notes existed, the note among its skips. + let mut old_note = vendor_note(); + old_note.status = SkippedStage::SKIPPED.to_string(); + let old = with_run(vec![old_note], Vec::new()); + assert!(failed_tools(¬ed).is_empty()); + assert!(failed_tools(&old).is_empty()); + assert_eq!(compliance_of(¬ed), compliance_of(&without)); + assert_eq!(compliance_of(&old), compliance_of(&without)); + } + + #[test] + fn the_manifest_lists_the_last_runs_notes_apart_from_its_skips() { + let mut old_note = vendor_note(); + old_note.status = SkippedStage::SKIPPED.to_string(); + let semgrep = SkippedStage::new("sast", SkipCode::ToolFailed, "semgrep did not complete"); + let pack = with_run(vec![old_note, semgrep], Vec::new()); + assert_eq!(failed_tools(&pack), ["semgrep"]); + + let (zip_bytes, _) = build_pack(&pack, Utc::now()).expect("pack"); + let mut archive = + zip::ZipArchive::new(std::io::Cursor::new(zip_bytes)).expect("a valid zip"); + let mut manifest = String::new(); + archive + .by_name("manifest.json") + .expect("manifest") + .read_to_string(&mut manifest) + .expect("read"); + let manifest: serde_json::Value = serde_json::from_str(&manifest).expect("json"); + let run = &manifest["last_scan_run"]; + assert_eq!(run["skipped_stages"].as_array().map(Vec::len), Some(1)); + assert_eq!(run["skipped_stages"][0]["stage"], "sast"); + assert_eq!(run["notes"][0]["stage"], "sast_vendor_code"); + assert_eq!(run["notes"][0]["status"], "note"); + } + #[test] fn the_pack_holds_every_file_and_the_manifest_hashes_match() { let (zip_bytes, listed) = build_pack(&inputs(), Utc::now()).expect("pack"); diff --git a/compliance-agent/src/pipeline/orchestrator.rs b/compliance-agent/src/pipeline/orchestrator.rs index c980b27..103d0bc 100644 --- a/compliance-agent/src/pipeline/orchestrator.rs +++ b/compliance-agent/src/pipeline/orchestrator.rs @@ -2219,13 +2219,20 @@ impl PipelineOrchestrator { /// Record a stage the pipeline deliberately did not run. A skipped stage is /// not an error: the scan completes, and the dashboard shows it as skipped - /// rather than failed. + /// rather than failed. An informational entry (a stage that ran, with + /// context) goes to the run's notes instead. pub(super) async fn skip_stage(&self, scan_run_id: &str, skipped: SkippedStage) { + let field = if skipped.is_note() { + "notes" + } else { + "skipped_stages" + }; tracing::info!( scan_run_id, stage = %skipped.stage, reason = %skipped.reason, - "pipeline stage skipped" + field, + "pipeline stage skipped or noted" ); let Ok(oid) = mongodb::bson::oid::ObjectId::parse_str(scan_run_id) else { return; @@ -2236,17 +2243,15 @@ impl PipelineOrchestrator { let _ = self .db .scan_runs() - .update_one( - doc! { "_id": oid }, - doc! { "$push": { "skipped_stages": entry } }, - ) + .update_one(doc! { "_id": oid }, doc! { "$push": { field: entry } }) .await; } /// The recipe lint of a tree whose `languages` include BitBake, outside /// the `vendor` directories: the findings, and the scanners that - /// completed. Upstream layers left out and an oelint-adv run that did not - /// complete are recorded as skipped stages. + /// completed. Upstream layers left out and findings suppressed in the + /// recipes are recorded as notes, an oelint-adv run that did not complete + /// as a skipped stage. async fn lint_recipes( &self, tree: &std::path::Path, diff --git a/compliance-agent/tests/nightly.rs b/compliance-agent/tests/nightly.rs index 91a54d5..ce2bbde 100644 --- a/compliance-agent/tests/nightly.rs +++ b/compliance-agent/tests/nightly.rs @@ -331,6 +331,10 @@ struct Snapshot { #[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, @@ -377,6 +381,7 @@ impl Snapshot { &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)); @@ -404,6 +409,16 @@ struct Collected { 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}")) @@ -421,12 +436,8 @@ async fn collect(agent: &Agent, target_id: &str, run: &Value) -> Collected { 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(), + skipped_stages: stages(&run["skipped_stages"]), + notes: stages(&run["notes"]), ..Default::default() }; let mut observed = Observed { @@ -738,6 +749,7 @@ mod unit { 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"]), @@ -749,9 +761,12 @@ mod unit { // 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"]); let diff = run.diff(&blessed); for needle in [ "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", diff --git a/compliance-core/src/models/mod.rs b/compliance-core/src/models/mod.rs index acba099..a0949c4 100644 --- a/compliance-core/src/models/mod.rs +++ b/compliance-core/src/models/mod.rs @@ -68,7 +68,8 @@ pub use sbom::{ SbomQualityProfile, VulnRef, YOCTO_RECIPE_MANAGER, YOCTO_RECIPE_SOURCE, }; pub use scan::{ - RunErrorCode, ScanPhase, ScanRun, ScanRunStatus, ScanStep, ScanType, SkipCode, SkippedStage, + RunErrorCode, RunNote, ScanPhase, ScanRun, ScanRunStatus, ScanStep, ScanType, SkipCode, + SkippedStage, }; pub use vex::{VexAssessment, VexError, VexJustification, VexStatus}; pub use webhook_delivery::{DeliveryResult, WebhookDelivery, DELIVERIES_SHOWN}; diff --git a/compliance-core/src/models/scan.rs b/compliance-core/src/models/scan.rs index 1445ff5..c870457 100644 --- a/compliance-core/src/models/scan.rs +++ b/compliance-core/src/models/scan.rs @@ -160,9 +160,16 @@ pub struct ScanRun { pub completed_at: Option>, /// Stages the pipeline deliberately did not run (e.g. a deployment /// feature flag turned them off). Distinct from `error_message`: a - /// skipped stage is not a failure. + /// skipped stage is not a failure. Runs recorded before `notes` existed + /// also hold informational entries here; [`ScanRun::skips`] leaves them + /// out. #[serde(default)] pub skipped_stages: Vec, + /// Informational entries about stages that ran: code left out of the + /// analysis by design, findings suppressed in the sources. Never a gap in + /// what was checked. + #[serde(default)] + pub notes: Vec, /// The source languages the static analysis found outside vendor code /// (`"c"`, `"python"`, …). A control counts as checked only if one of its /// rules covers one of them. Empty in runs from before it was recorded. @@ -179,8 +186,9 @@ pub struct ScanRun { pub sbom_quality: Option, } -/// Why a stage was skipped, stable for the dashboard to word in the reader's -/// language. The stage's `reason` next to it is English prose for API +/// Why a stage was skipped, or what a run note is about +/// ([`SkipCode::is_informational`]), stable for the dashboard to word in the +/// reader's language. The stage's `reason` next to it is English prose for API /// readers; neither ever carries a server path or a raw error (those go to /// the log). #[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)] @@ -247,6 +255,36 @@ pub enum SkipCode { NotInTree, } +impl SkipCode { + /// Whether an entry with this code only informs about a stage that ran + /// (a run note) rather than recording something that did not run, failed + /// or is not analysed yet (a skipped stage). + pub fn is_informational(self) -> bool { + // An exhaustive match, so a new code has to be classified here. + match self { + Self::VendorCode | Self::SuppressedInSource | Self::NotInTree => true, + Self::FeatureDisabled + | Self::SubmodulesNotFetched + | Self::ToolFailed + | Self::DependenciesUnlocked + | Self::NotAnalysedYet + | Self::ArchiveUnreadable + | Self::ArtifactNotIngested + | Self::ArchivePasswordRequired + | Self::ArchivePasswordWrong + | Self::FirmwareSbomFailed + | Self::FirmwareBuildUnknown + | Self::FirmwareUnresolved + | Self::CveLookupIncomplete + | Self::LfsNotFetched + | Self::NoNewCommits + | Self::PlatformProjectGenerated + | Self::UploadUnchanged + | Self::TooLargeToScan => false, + } + } +} + /// Why a scan run failed, stable for the dashboard to word. #[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)] #[serde(rename_all = "snake_case")] @@ -268,7 +306,8 @@ pub enum RunErrorCode { pub struct SkippedStage { /// Stage id (`dast`, `pentest`, `ics_probe`, `plc_runtime`, …). pub stage: String, - /// Always `skipped` — present so the entry reads like a stage result. + /// `skipped`, or `note` for an informational entry (a [`RunNote`]) — + /// present so the entry reads like a stage result. pub status: String, /// Why it was skipped, in English (`feature disabled`, …). pub reason: String, @@ -280,15 +319,29 @@ pub struct SkippedStage { pub subject: Option, } +/// An informational entry of a scan run: the same shape as a skipped stage, +/// with status `note` and an informational [`SkipCode`]. +pub type RunNote = SkippedStage; + impl SkippedStage { /// The reason recorded when a deployment feature flag disables a stage. pub const FEATURE_DISABLED: &'static str = "feature disabled"; + /// The status of a stage that did not run. + pub const SKIPPED: &'static str = "skipped"; + /// The status of an informational entry (a [`RunNote`]). + pub const NOTE: &'static str = "note"; - /// A skipped `stage`, why (`code`), and the English `reason`. + /// A skipped `stage`, why (`code`), and the English `reason`; a note + /// when `code` is informational. pub fn new(stage: impl Into, code: SkipCode, reason: impl Into) -> Self { + let status = if code.is_informational() { + Self::NOTE + } else { + Self::SKIPPED + }; Self { stage: stage.into(), - status: "skipped".to_string(), + status: status.to_string(), reason: reason.into(), code: Some(code), subject: None, @@ -304,6 +357,12 @@ impl SkippedStage { pub fn feature_disabled(stage: impl Into) -> Self { Self::new(stage, SkipCode::FeatureDisabled, Self::FEATURE_DISABLED) } + + /// Whether this entry is a note: its code is informational. Entries + /// without a code predate the informational codes, so they are skips. + pub fn is_note(&self) -> bool { + self.code.is_some_and(SkipCode::is_informational) + } } impl ScanRun { @@ -323,6 +382,7 @@ impl ScanRun { started_at: Utc::now(), completed_at: None, skipped_stages: Vec::new(), + notes: Vec::new(), languages: Vec::new(), planned_phases: Vec::new(), sbom_quality: None, @@ -330,9 +390,125 @@ impl ScanRun { } } +impl ScanRun { + /// The stages that did not run, without the informational entries older + /// runs recorded among them. + pub fn skips(&self) -> impl Iterator { + self.skipped_stages.iter().filter(|s| !s.is_note()) + } + + /// The run's notes, including the informational entries older runs + /// recorded among the skipped stages. + pub fn all_notes(&self) -> impl Iterator { + self.notes + .iter() + .chain(self.skipped_stages.iter().filter(|s| s.is_note())) + } + + /// Move the informational entries older runs recorded among the skipped + /// stages into `notes`, as status `note`, so a run read back exports + /// both lists the way new runs record them. + pub fn split_notes(&mut self) { + let (notes, skips) = std::mem::take(&mut self.skipped_stages) + .into_iter() + .partition::, _>(SkippedStage::is_note); + self.skipped_stages = skips; + self.notes.extend(notes.into_iter().map(|mut note| { + note.status = SkippedStage::NOTE.to_string(); + note + })); + } +} + #[cfg(test)] mod skipped_stage_tests { - use super::{ScanRun, ScanStep, ScanTrigger, SkippedStage}; + use super::{ScanRun, ScanStep, ScanTrigger, SkipCode, SkippedStage}; + + #[test] + fn only_code_exclusions_and_suppressions_are_informational() { + let notes = [ + SkipCode::VendorCode, + SkipCode::SuppressedInSource, + SkipCode::NotInTree, + ]; + let skips = [ + SkipCode::FeatureDisabled, + SkipCode::SubmodulesNotFetched, + SkipCode::ToolFailed, + SkipCode::DependenciesUnlocked, + SkipCode::NotAnalysedYet, + SkipCode::ArchiveUnreadable, + SkipCode::ArtifactNotIngested, + SkipCode::ArchivePasswordRequired, + SkipCode::ArchivePasswordWrong, + SkipCode::FirmwareSbomFailed, + SkipCode::FirmwareBuildUnknown, + SkipCode::FirmwareUnresolved, + SkipCode::CveLookupIncomplete, + SkipCode::LfsNotFetched, + SkipCode::NoNewCommits, + SkipCode::PlatformProjectGenerated, + SkipCode::UploadUnchanged, + SkipCode::TooLargeToScan, + ]; + assert!(notes.iter().all(|c| c.is_informational())); + assert!(skips.iter().all(|c| !c.is_informational())); + } + + #[test] + fn an_informational_entry_is_recorded_as_a_note() { + let note = SkippedStage::new("sast_vendor_code", SkipCode::VendorCode, "vendor"); + assert_eq!(note.status, SkippedStage::NOTE); + assert!(note.is_note()); + let skip = SkippedStage::new("sast", SkipCode::ToolFailed, "semgrep did not complete"); + assert_eq!(skip.status, SkippedStage::SKIPPED); + assert!(!skip.is_note()); + } + + /// A run recorded before notes existed, with an informational entry among + /// its skipped stages, lists it as a note and keeps the real skips. + #[test] + fn an_old_run_lists_its_informational_skips_as_notes() { + let mut run = ScanRun::new("repo".into(), ScanTrigger::Manual); + let mut old = + SkippedStage::new("recipe_lint_suppressed", SkipCode::SuppressedInSource, "2"); + old.status = SkippedStage::SKIPPED.to_string(); + run.skipped_stages = vec![ + SkippedStage::feature_disabled("dast"), + old, + SkippedStage::new("sast", SkipCode::ToolFailed, "semgrep did not complete"), + ]; + let stages = |it: Vec<&SkippedStage>| -> Vec { + it.into_iter().map(|s| s.stage.clone()).collect() + }; + assert_eq!(stages(run.skips().collect()), ["dast", "sast"]); + assert_eq!( + stages(run.all_notes().collect()), + ["recipe_lint_suppressed"] + ); + + run.split_notes(); + assert_eq!( + stages(run.skipped_stages.iter().collect()), + ["dast", "sast"] + ); + assert_eq!( + stages(run.notes.iter().collect()), + ["recipe_lint_suppressed"] + ); + assert_eq!(run.notes[0].status, SkippedStage::NOTE); + let j = serde_json::to_value(&run).expect("serialize"); + assert_eq!(j["notes"][0]["code"], "suppressed_in_source"); + } + + #[test] + fn scan_runs_without_notes_deserialize_with_none() { + let run = ScanRun::new("repo".into(), ScanTrigger::Manual); + let mut j = serde_json::to_value(&run).expect("serialize"); + j.as_object_mut().expect("object").remove("notes"); + let back: ScanRun = serde_json::from_value(j).expect("older document"); + assert!(back.notes.is_empty()); + } #[test] fn feature_disabled_reads_like_a_stage_result() { diff --git a/compliance-dashboard/src/components/scan_runs.rs b/compliance-dashboard/src/components/scan_runs.rs index 378f8dc..65103ba 100644 --- a/compliance-dashboard/src/components/scan_runs.rs +++ b/compliance-dashboard/src/components/scan_runs.rs @@ -1,5 +1,6 @@ //! A target's scan history: status, the step a running scan is at, when it -//! started and finished, why it failed, and which stages it did not run. +//! started and finished, why it failed, which stages it did not run, and its +//! notes (informational entries about stages that ran). //! //! A running scan shows its planned stages as a stepper with the elapsed //! time; one that finishes while the page is open reveals what it found. @@ -8,7 +9,7 @@ use std::collections::HashSet; use dioxus::prelude::*; -use compliance_core::models::{ScanPhase, ScanRun, ScanRunStatus, ScanStep}; +use compliance_core::models::{ScanPhase, ScanRun, ScanRunStatus, ScanStep, SkippedStage}; use crate::app::Route; use crate::i18n::texts::{common, scans}; @@ -223,16 +224,43 @@ fn scan_run_card(run: &ScanRun, lang: Lang) -> Element { {scans::ERROR.get(lang)} ": {error}" } } - if !run.skipped_stages.is_empty() { - div { style: "font-size: 0.85em; margin-top: 4px;", - div { style: "opacity: 0.8;", {scans::SKIPPED.get(lang)} ":" } - ul { style: "margin: 2px 0 0 18px; padding: 0;", - for skipped in run.skipped_stages.iter() { - li { - strong { {stage_name(&skipped.stage, lang)} } - " — {scans::skipped_reason(skipped, lang)}" - } - } + {entry_list(scans::SKIPPED, &entry_lines(run.skips(), lang), "", lang)} + // Notes inform about stages that ran: neutral, and after the skips. + {entry_list(scans::NOTES, &entry_lines(run.all_notes(), lang), "opacity: 0.75;", lang)} + } + } +} + +/// Skipped stages or notes as (stage name, reason) lines in the reader's +/// language. Notes and skips share the shape and the wording of their codes. +fn entry_lines<'a>( + entries: impl Iterator, + lang: Lang, +) -> Vec<(String, String)> { + entries + .map(|entry| { + ( + stage_name(&entry.stage, lang), + scans::skipped_reason(entry, lang), + ) + }) + .collect() +} + +/// A titled list of `lines` under a run, nothing when there are none; +/// `style` sets the list apart (the notes are muted). +fn entry_list(title: Text, lines: &[(String, String)], style: &str, lang: Lang) -> Element { + if lines.is_empty() { + return rsx! {}; + } + rsx! { + div { style: "font-size: 0.85em; margin-top: 4px; {style}", + div { style: "opacity: 0.8;", {title.get(lang)} ":" } + ul { style: "margin: 2px 0 0 18px; padding: 0;", + for (stage, reason) in lines.iter() { + li { + strong { "{stage}" } + " — {reason}" } } } @@ -547,6 +575,29 @@ mod tests { assert_eq!(text.get(Lang::En), "Fetching submodules"); } + /// A run recorded before notes existed, with an informational entry + /// among its skipped stages, shows it under the notes. + #[test] + fn an_old_runs_informational_skip_is_listed_as_a_note() { + use compliance_core::models::SkipCode; + let mut run = ScanRun::new("t".into(), compliance_core::models::ScanTrigger::Manual); + let mut old = SkippedStage::new( + "recipe_lint_suppressed", + SkipCode::SuppressedInSource, + "2 findings suppressed by recipe comments (# nooelint)", + ) + .about("2"); + old.status = SkippedStage::SKIPPED.to_string(); + run.skipped_stages = vec![old, SkippedStage::feature_disabled("dast")]; + + let skips = entry_lines(run.skips(), Lang::En); + assert_eq!(skips.len(), 1); + assert_eq!(skips[0].1, "Not enabled in this environment."); + let notes = entry_lines(run.all_notes(), Lang::De); + assert_eq!(notes.len(), 1); + assert!(notes[0].1.contains("# nooelint"), "{}", notes[0].1); + } + #[test] fn unknown_stages_are_shown_by_id() { assert_eq!( diff --git a/compliance-dashboard/src/i18n/texts.rs b/compliance-dashboard/src/i18n/texts.rs index 0a51808..3203997 100644 --- a/compliance-dashboard/src/i18n/texts.rs +++ b/compliance-dashboard/src/i18n/texts.rs @@ -412,6 +412,12 @@ pub mod scans { de: "Nicht ausgeführt", en: "Not run", }; + /// Informational entries about stages that ran (code left out by design, + /// findings suppressed in the sources), apart from the skipped stages. + pub const NOTES: Text = Text { + de: "Hinweise", + en: "Notes", + }; pub const LOAD_FAILED: Text = Text { de: "Der Prüfverlauf konnte nicht geladen werden.", en: "The scan history could not be loaded.", diff --git a/compliance-mcp/src/server.rs b/compliance-mcp/src/server.rs index 3e91a5b..16cd0dc 100644 --- a/compliance-mcp/src/server.rs +++ b/compliance-mcp/src/server.rs @@ -100,7 +100,7 @@ impl ComplianceMcpServer { } #[tool( - description = "Get a target's scan runs, newest first: status, start and finish, new findings, error, and the stages that were not run with their reasons" + description = "Get a target's scan runs, newest first: status, start and finish, new findings, error, the stages that were not run with their reasons (skipped_stages), and informational notes about stages that ran (notes)" )] async fn get_scan_results( &self, diff --git a/compliance-mcp/src/tools/targets.rs b/compliance-mcp/src/tools/targets.rs index 62e313a..172b92b 100644 --- a/compliance-mcp/src/tools/targets.rs +++ b/compliance-mcp/src/tools/targets.rs @@ -6,7 +6,7 @@ use rmcp::{model::*, ErrorData as McpError}; use schemars::JsonSchema; use serde::{Deserialize, Serialize}; -use compliance_core::models::{Credentials, OnboardedTarget}; +use compliance_core::models::{Credentials, OnboardedTarget, ScanRun}; use super::{collect, db_error, json_result}; use crate::database::Database; @@ -81,13 +81,14 @@ pub struct GetScanResultsParams { } /// `get_scan_results`: a target's scan runs, newest first, with their status, -/// new-finding count, error and the stages they did not run. +/// new-finding count, error, the stages they did not run (`skipped_stages`) +/// and informational notes about stages that ran (`notes`). pub async fn get_scan_results( db: &Database, params: GetScanResultsParams, ) -> Result { let limit = params.limit.unwrap_or(DEFAULT_RUNS).clamp(1, MAX_RUNS); - let runs = collect( + let mut runs = collect( db.scan_runs() .find(doc! { "repo_id": ¶ms.target_id }) .sort(doc! { "started_at": -1 }) @@ -96,6 +97,8 @@ pub async fn get_scan_results( .map_err(db_error)?, ) .await?; + // Runs recorded before notes existed list them among their skips. + runs.iter_mut().for_each(ScanRun::split_notes); json_result(&runs) } diff --git a/fixtures/nightly/baselines/dotnet-framework48.json b/fixtures/nightly/baselines/dotnet-framework48.json index 08fb445..e15f886 100644 --- a/fixtures/nightly/baselines/dotnet-framework48.json +++ b/fixtures/nightly/baselines/dotnet-framework48.json @@ -1,7 +1,9 @@ { "scan_status": "completed", "skipped_stages": [ - "malware", + "malware" + ], + "notes": [ "sast_vendor_code" ], "sbom": [ diff --git a/fixtures/nightly/baselines/fw-c-sensor-node.json b/fixtures/nightly/baselines/fw-c-sensor-node.json index c9ec0eb..02c676b 100644 --- a/fixtures/nightly/baselines/fw-c-sensor-node.json +++ b/fixtures/nightly/baselines/fw-c-sensor-node.json @@ -1,7 +1,9 @@ { "scan_status": "completed", "skipped_stages": [ - "malware", + "malware" + ], + "notes": [ "sast_vendor_code" ], "sbom": [ diff --git a/fixtures/nightly/baselines/fw-embedded-libs.json b/fixtures/nightly/baselines/fw-embedded-libs.json index 726055b..b15fba8 100644 --- a/fixtures/nightly/baselines/fw-embedded-libs.json +++ b/fixtures/nightly/baselines/fw-embedded-libs.json @@ -1,7 +1,9 @@ { "scan_status": "completed", "skipped_stages": [ - "malware", + "malware" + ], + "notes": [ "sast_vendor_code" ], "sbom": [ diff --git a/fixtures/nightly/baselines/fw-yocto-layer.json b/fixtures/nightly/baselines/fw-yocto-layer.json index bc76036..027d08c 100644 --- a/fixtures/nightly/baselines/fw-yocto-layer.json +++ b/fixtures/nightly/baselines/fw-yocto-layer.json @@ -2,9 +2,11 @@ "scan_status": "completed", "skipped_stages": [ "firmware_sbom", - "image_install", "malware" ], + "notes": [ + "image_install" + ], "sbom": [ "yocto-recipe:busybox@1.35.0 [in image: pump-image]", "yocto-recipe:libmodbus@3.1.6 [in image: pump-image]", diff --git a/fixtures/nightly/baselines/mobile-unity-mobile.json b/fixtures/nightly/baselines/mobile-unity-mobile.json index ce7c270..2e9741c 100644 --- a/fixtures/nightly/baselines/mobile-unity-mobile.json +++ b/fixtures/nightly/baselines/mobile-unity-mobile.json @@ -3,7 +3,9 @@ "skipped_stages": [ "cve_lookup", "malware", - "platform_project", + "platform_project" + ], + "notes": [ "sast_vendor_code" ], "sbom": [