diff --git a/compliance-agent/src/pipeline/finding_store.rs b/compliance-agent/src/pipeline/finding_store.rs new file mode 100644 index 0000000..c074949 --- /dev/null +++ b/compliance-agent/src/pipeline/finding_store.rs @@ -0,0 +1,218 @@ +//! Findings saved as a scan finds them (#372). +//! +//! Each scanner stage saves its first-seen findings at once, so the dashboard +//! shows them while the scan is still running. The triage stages that follow +//! change them (severity, status, rationale, control refs); +//! [`RunFindings::write_back`] stores those changes on the rows already saved, +//! without undoing a status a person set in the meantime. + +use std::collections::{HashMap, HashSet}; + +use futures_util::TryStreamExt; +use mongodb::bson::{doc, oid::ObjectId, to_bson, Bson, Document}; + +use compliance_core::models::{Finding, FindingStatus}; + +use crate::database::Database; +use crate::error::AgentError; + +/// The findings one scan run has saved so far, by fingerprint. +pub struct RunFindings { + scan_run_id: String, + /// First seen in this run, and saved: fingerprint → row id. + inserted: HashMap, + /// Already stored by an earlier run; never saved again. + earlier: HashSet, +} + +impl RunFindings { + /// Nothing saved yet for the run `scan_run_id`. + pub fn new(scan_run_id: &str) -> Self { + Self { + scan_run_id: scan_run_id.to_string(), + inserted: HashMap::new(), + earlier: HashSet::new(), + } + } + + /// How many findings this run saw first. + pub fn new_count(&self) -> u32 { + u32::try_from(self.inserted.len()).unwrap_or(u32::MAX) + } + + /// Save the findings in `findings` that no run has stored yet, in one + /// query and one insert, and count them on the scan run. Findings handled + /// by an earlier call are skipped; those this run saved get their row id. + /// + /// # Returns + /// + /// How many findings were saved by this call. + /// + /// # Errors + /// + /// A database error, as the pipeline's final save used to return. + pub async fn save_new( + &mut self, + db: &Database, + findings: &mut [Finding], + ) -> Result { + let unknown: HashSet = findings + .iter() + .map(|f| f.fingerprint.as_str()) + .filter(|fp| !self.inserted.contains_key(*fp) && !self.earlier.contains(*fp)) + .map(str::to_owned) + .collect(); + if unknown.is_empty() { + self.stamp_ids(findings); + return Ok(0); + } + + // Which of them an earlier run already stored (fingerprints only). + let stored: HashSet = db + .findings() + .clone_with_type::() + .find(doc! { "fingerprint": { "$in": unknown.iter().collect::>() } }) + .projection(doc! { "fingerprint": 1 }) + .await? + .try_collect::>() + .await? + .into_iter() + .filter_map(|d| d.get_str("fingerprint").ok().map(str::to_owned)) + .collect(); + + // The first finding of each new fingerprint (a scan can report the + // same one twice). + let mut batch: Vec = Vec::new(); + let mut queued: HashSet<&str> = HashSet::new(); + for finding in findings.iter() { + let fp = finding.fingerprint.as_str(); + if unknown.contains(fp) && !stored.contains(fp) && queued.insert(fp) { + let mut row = finding.clone(); + row.scan_run_id = Some(self.scan_run_id.clone()); + batch.push(row); + } + } + self.earlier.extend(stored); + + let saved = if batch.is_empty() { + 0 + } else { + let result = db.findings().insert_many(&batch).await?; + for (index, id) in result.inserted_ids { + if let (Some(row), Bson::ObjectId(id)) = (batch.get(index), id) { + self.inserted.insert(row.fingerprint.clone(), id); + } + } + batch.len() + }; + self.stamp_ids(findings); + + let saved = u32::try_from(saved).unwrap_or(u32::MAX); + if saved > 0 { + if let Ok(run) = ObjectId::parse_str(&self.scan_run_id) { + db.scan_runs() + .update_one( + doc! { "_id": run }, + doc! { "$inc": { "new_findings_count": i64::from(saved) } }, + ) + .await?; + } + } + Ok(saved) + } + + /// Store what triage changed on the findings this run saved, and the + /// control refs of findings an earlier run stored. Findings no stage has + /// saved yet (the grounded surface checks) are saved first. + /// + /// A status is written only onto a row still `open`: a person who marked + /// a finding while the scan ran keeps their choice. + /// + /// # Returns + /// + /// This run's new findings in their final state, once each (for issue + /// creation). + /// + /// # Errors + /// + /// A database error. + pub async fn write_back( + &mut self, + db: &Database, + findings: &mut [Finding], + ) -> Result, AgentError> { + self.save_new(db, findings).await?; + + let mut new_findings = Vec::new(); + let mut written: HashSet<&str> = HashSet::new(); + let mut refreshed = 0_u32; + for finding in findings.iter() { + if !written.insert(finding.fingerprint.as_str()) { + continue; + } + match self.inserted.get(&finding.fingerprint) { + Some(id) => { + db.findings() + .update_one(doc! { "_id": id }, triage_update(finding)?) + .await?; + if finding.status != FindingStatus::Open { + db.findings() + .update_one( + doc! { "_id": id, "status": "open" }, + doc! { "$set": { "status": bson_of(&finding.status)? } }, + ) + .await?; + } + new_findings.push(finding.clone()); + } + // A mapping pass (newly enabled or tuned) computed refs for a + // finding first stored before it ran. + None if !finding.control_refs.is_empty() => { + db.findings() + .update_one( + doc! { "fingerprint": &finding.fingerprint }, + doc! { "$set": { "control_refs": finding.control_refs.clone() } }, + ) + .await?; + refreshed += 1; + } + None => {} + } + } + if refreshed > 0 { + tracing::info!( + scan_run_id = %self.scan_run_id, + "refreshed control_refs on {refreshed} existing findings" + ); + } + Ok(new_findings) + } + + /// Give each finding this run saved its row id. + fn stamp_ids(&self, findings: &mut [Finding]) { + for finding in findings.iter_mut() { + if let Some(id) = self.inserted.get(&finding.fingerprint) { + finding.id = Some(*id); + finding.scan_run_id = Some(self.scan_run_id.clone()); + } + } + } +} + +/// `value` as BSON. +fn bson_of(value: &T) -> Result { + to_bson(value).map_err(|e| AgentError::Other(format!("encode finding field: {e}"))) +} + +/// The fields the triage stages set, as an update. +fn triage_update(finding: &Finding) -> Result { + Ok(doc! { "$set": { + "severity": bson_of(&finding.severity)?, + "confidence": finding.confidence, + "triage_action": finding.triage_action.clone(), + "triage_rationale": finding.triage_rationale.clone(), + "remediation": finding.remediation.clone(), + "control_refs": finding.control_refs.clone(), + "updated_at": mongodb::bson::DateTime::now(), + } }) +} diff --git a/compliance-agent/src/pipeline/mod.rs b/compliance-agent/src/pipeline/mod.rs index 98e1562..d15b675 100644 --- a/compliance-agent/src/pipeline/mod.rs +++ b/compliance-agent/src/pipeline/mod.rs @@ -3,6 +3,7 @@ pub mod cppcheck; pub mod cve; pub mod dedup; pub mod embedded_versions; +pub mod finding_store; pub mod firmware_sbom; pub mod git; pub mod git_submodules; diff --git a/compliance-agent/src/pipeline/orchestrator.rs b/compliance-agent/src/pipeline/orchestrator.rs index eca948b..af1ddef 100644 --- a/compliance-agent/src/pipeline/orchestrator.rs +++ b/compliance-agent/src/pipeline/orchestrator.rs @@ -117,6 +117,9 @@ impl PipelineOrchestrator { let repo_path = tree.to_path_buf(); let mut all_findings: Vec = Vec::new(); + // Each scanner stage saves its new findings at once, so they show while + // the scan runs (#372); triage updates them at the end. + let mut run_findings = crate::pipeline::finding_store::RunFindings::new(scan_run_id); // Stage 1: SAST. Vendor SDK code (HAL, CMSIS, third-party middleware) is // not the customer's to fix, so both analysers skip it and the run says @@ -182,6 +185,7 @@ impl PipelineOrchestrator { } } } + run_findings.save_new(&self.db, &mut all_findings).await?; // Stage 2: SBOM Generation tracing::info!("[{repo_id}] Stage 2: SBOM Generation"); @@ -319,6 +323,7 @@ impl PipelineOrchestrator { .await; all_findings.extend(pattern_findings); } + run_findings.save_new(&self.db, &mut all_findings).await?; // Stage 4a: Secret Detection (Gitleaks) tracing::info!("[{repo_id}] Stage 4a: Secret Detection"); @@ -334,6 +339,7 @@ impl PipelineOrchestrator { Ok(output) => all_findings.extend(output.findings), Err(e) => tracing::warn!("[{repo_id}] Gitleaks failed: {e}"), } + run_findings.save_new(&self.db, &mut all_findings).await?; // Stage 4b: Lint Scanning tracing::info!("[{repo_id}] Stage 4b: Lint Scanning"); @@ -349,6 +355,7 @@ impl PipelineOrchestrator { Ok(output) => all_findings.extend(output.findings), Err(e) => tracing::warn!("[{repo_id}] Lint scanning failed: {e}"), } + run_findings.save_new(&self.db, &mut all_findings).await?; // Stage 4.5: Graph Building tracing::info!("[{repo_id}] Stage 4.5: Graph Building"); @@ -445,43 +452,11 @@ impl PipelineOrchestrator { } } - // Dedup against existing findings: insert first-seen ones, and refresh the - // control mappings on ones we've seen before. - let mut new_count = 0u32; - let mut refreshed_count = 0u32; - let mut new_findings: Vec = Vec::new(); - for mut finding in all_findings { - finding.scan_run_id = Some(scan_run_id.to_string()); - // Check if fingerprint already exists - let existing = self - .db - .findings() - .find_one(doc! { "fingerprint": &finding.fingerprint }) - .await?; - if existing.is_none() { - let result = self.db.findings().insert_one(&finding).await?; - finding.id = result.inserted_id.as_object_id(); - new_findings.push(finding); - new_count += 1; - } else if !finding.control_refs.is_empty() { - // Re-scan refresh: a mapping pass (newly enabled or tuned) computed - // control_refs for a finding first seen before mapping ran. Persist - // them onto the existing row — the insert path alone never would. - self.db - .findings() - .update_one( - doc! { "fingerprint": &finding.fingerprint }, - doc! { "$set": { "control_refs": finding.control_refs.clone() } }, - ) - .await?; - refreshed_count += 1; - } - } - if refreshed_count > 0 { - tracing::info!( - "[{repo_id}] Refreshed control_refs on {refreshed_count} existing findings" - ); - } + // Store what triage changed on the findings saved along the way, save + // those no stage saved yet, and refresh the control mappings of findings + // an earlier run stored. + let new_findings = run_findings.write_back(&self.db, &mut all_findings).await?; + let new_count = run_findings.new_count(); // 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 diff --git a/compliance-agent/tests/live_findings.rs b/compliance-agent/tests/live_findings.rs new file mode 100644 index 0000000..4f5f74f --- /dev/null +++ b/compliance-agent/tests/live_findings.rs @@ -0,0 +1,128 @@ +//! Findings saved stage by stage (#372): a finding shows as soon as its stage +//! ends, triage later updates the same row, and a status a person set while +//! the scan ran is kept. Runs against a live Mongo (`TEST_MONGODB_URI`) and +//! skips cleanly without one. + +#![allow(clippy::expect_used, clippy::unwrap_used)] + +use compliance_agent::database::DatabasePool; +use compliance_agent::pipeline::finding_store::RunFindings; +use compliance_core::models::{Finding, FindingStatus, ScanRun, ScanTrigger, ScanType, Severity}; +use mongodb::bson::doc; + +const TENANT: &str = "live-findings"; + +fn finding(fingerprint: &str, title: &str) -> Finding { + Finding::new( + "target-1".into(), + fingerprint.into(), + "semgrep".into(), + ScanType::Sast, + title.into(), + "desc".into(), + Severity::High, + ) +} + +#[tokio::test] +async fn findings_show_per_stage_and_triage_updates_them_in_place() { + let uri = std::env::var("TEST_MONGODB_URI") + .unwrap_or_else(|_| "mongodb://root:example@localhost:27017/?authSource=admin".into()); + let prefix = format!("live_{}", &uuid::Uuid::new_v4().simple().to_string()[..10]); + let Ok(pool) = DatabasePool::connect(&uri, &prefix).await else { + eprintln!("SKIP live_findings: no MongoDB reachable at {uri}"); + return; + }; + let db = pool.for_tenant_id(TENANT).await.unwrap(); + let run = db + .scan_runs() + .insert_one(ScanRun::new("target-1".into(), ScanTrigger::Manual)) + .await + .unwrap(); + let run_id = run.inserted_id.as_object_id().unwrap().to_hex(); + // A finding an earlier run stored: never saved twice. + db.findings() + .insert_one(finding("fp-old", "seen before")) + .await + .unwrap(); + + let mut store = RunFindings::new(&run_id); + let mut all = vec![ + finding("fp-sast", "strcpy"), + finding("fp-old", "seen before"), + ]; + + // Act 1: SAST ends. Its new finding is visible at once, and counted. + assert_eq!(store.save_new(&db, &mut all).await.unwrap(), 1); + let saved = db + .findings() + .find_one(doc! { "fingerprint": "fp-sast" }) + .await + .unwrap() + .expect("visible while the scan runs"); + assert_eq!(saved.scan_run_id.as_deref(), Some(run_id.as_str())); + let counted = db + .scan_runs() + .find_one(doc! { "_id": run.inserted_id.clone() }) + .await + .unwrap() + .unwrap(); + assert_eq!(counted.new_findings_count, 1); + + // A person marks it while the scan still runs; the same stage output + // again (a later stage) saves nothing twice. + db.findings() + .update_one( + doc! { "fingerprint": "fp-sast" }, + doc! { "$set": { "status": "accepted_risk" } }, + ) + .await + .unwrap(); + assert_eq!(store.save_new(&db, &mut all).await.unwrap(), 0); + + // Act 2: triage refutes it and adds a rationale; a grounded check adds one. + all[0].status = FindingStatus::NeedsReview; + all[0].triage_rationale = Some("vendor-style bounded copy".into()); + all[0].control_refs = vec!["cra-ai-20".into()]; + let mut grounded = finding("fp-grounded", "no update signature"); + grounded.status = FindingStatus::NeedsReview; + all.push(grounded); + let new_findings = store.write_back(&db, &mut all).await.unwrap(); + + // Assert: triage landed on the row, the person's status stayed. + let row = db + .findings() + .find_one(doc! { "fingerprint": "fp-sast" }) + .await + .unwrap() + .unwrap(); + assert_eq!(row.status, FindingStatus::AcceptedRisk); + assert_eq!( + row.triage_rationale.as_deref(), + Some("vendor-style bounded copy") + ); + assert_eq!(row.control_refs, ["cra-ai-20"]); + // Untouched by a person, triage's status lands. + let grounded = db + .findings() + .find_one(doc! { "fingerprint": "fp-grounded" }) + .await + .unwrap() + .unwrap(); + assert_eq!(grounded.status, FindingStatus::NeedsReview); + assert_eq!(store.new_count(), 2); + assert_eq!( + new_findings.len(), + 2, + "sast + grounded, not the earlier one" + ); + assert_eq!( + db.findings() + .count_documents(doc! { "fingerprint": "fp-old" }) + .await + .unwrap(), + 1 + ); + + pool.drop_tenant(TENANT).await.ok(); +} diff --git a/compliance-dashboard/src/components/scan_runs.rs b/compliance-dashboard/src/components/scan_runs.rs index e7646a4..6bf5192 100644 --- a/compliance-dashboard/src/components/scan_runs.rs +++ b/compliance-dashboard/src/components/scan_runs.rs @@ -127,6 +127,9 @@ fn scan_run_card(run: &ScanRun, lang: Lang) -> Element { {scans::PHASE.get(lang)} ": " strong { {phase(&run.current_phase).get(lang)} } } Elapsed { started_at: run.started_at } + span { style: "font-size: 0.9em;", + {scans::NEW_FINDINGS.get(lang)} ": {run.new_findings_count}" + } } else { span { style: "font-size: 0.9em;", {scans::NEW_FINDINGS.get(lang)} ": {run.new_findings_count}" @@ -135,6 +138,10 @@ fn scan_run_card(run: &ScanRun, lang: Lang) -> Element { } if running { {stepper(run, lang)} + LiveFindings { + target_id: run.repo_id.clone(), + run_id: run.id.map(|id| id.to_hex()).unwrap_or_default(), + } } if run.status == ScanRunStatus::Interrupted { div { style: "font-size: 0.85em; opacity: 0.8; margin-top: 4px;", @@ -249,6 +256,44 @@ fn Elapsed(started_at: chrono::DateTime) -> Element { } } +/// The newest findings of a running scan, refreshed while it runs. Each is +/// saved as its stage ends (#372); new rows fade in, and every row says it is +/// still being assessed until triage has run. +#[component] +fn LiveFindings(target_id: String, run_id: String) -> Element { + let lang = use_lang()(); + let ids = use_signal(|| (target_id.clone(), run_id.clone())); + #[cfg_attr(not(feature = "web"), allow(unused_mut))] + let mut found = use_resource(move || async move { + let (target, run) = ids(); + fetch_run_findings(target, run, REVEAL_LIMIT) + .await + .unwrap_or_default() + }); + use_future(move || async move { + #[cfg(feature = "web")] + loop { + gloo_timers::future::TimeoutFuture::new(POLL_MS).await; + found.restart(); + } + }); + let list = found().unwrap_or_default(); + rsx! { + if !list.is_empty() { + ul { class: "run-reveal-list", + for f in list { + // Keyed by id: rows already shown stay, new ones fade in. + li { key: "{f.id}", class: "run-reveal-item", + span { class: "badge badge-{f.severity}", "{f.severity}" } + Link { to: Route::FindingDetailPage { id: f.id.clone() }, "{f.title}" } + span { class: "badge badge-neutral", {scans::BEING_ASSESSED.get(lang)} } + } + } + } + } + } +} + /// A scan that just finished: its new-findings count rises to `count`, and /// its first findings appear one after another. #[component] diff --git a/compliance-dashboard/src/i18n/texts.rs b/compliance-dashboard/src/i18n/texts.rs index e25b310..6fd75f3 100644 --- a/compliance-dashboard/src/i18n/texts.rs +++ b/compliance-dashboard/src/i18n/texts.rs @@ -256,6 +256,10 @@ pub mod scans { de: "Schritte erledigt", en: "Steps done", }; + pub const BEING_ASSESSED: Text = Text { + de: "wird bewertet", + en: "being assessed", + }; pub const JUST_FINISHED: Text = Text { de: "Prüfung abgeschlossen", en: "Scan finished",