diff --git a/compliance-agent/src/pipeline/finding_store.rs b/compliance-agent/src/pipeline/finding_store.rs index 00c9590..981ae20 100644 --- a/compliance-agent/src/pipeline/finding_store.rs +++ b/compliance-agent/src/pipeline/finding_store.rs @@ -52,6 +52,10 @@ type GroupedPlace = (String, String, String, Option); /// are a person's decision and stay as they are. const UNDECIDED: [&str; 3] = ["open", "triaged", "needs_review"]; +/// A person's decisions about a single finding that a group of its rule's +/// places takes over when every place carries the same one (#483). +const INHERITABLE: [&str; 3] = ["false_positive", "accepted_risk", "ignored"]; + /// How many findings one update names: keeps each query small however many a /// scan closes. const UPDATE_CHUNK: usize = 500; @@ -215,6 +219,7 @@ impl RunFindings { findings: &mut [Finding], ) -> Result, AgentError> { self.save_new(db, findings).await?; + self.inherit_decisions(db, findings).await?; let mut new_findings = Vec::new(); let mut written: HashSet<&str> = HashSet::new(); @@ -246,6 +251,121 @@ impl RunFindings { Ok(new_findings) } + /// Give each group among `findings` what a person decided about the single + /// findings stored for its places (#483). Each place is listed with its + /// decision; when every place carries the same one (false positive, + /// accepted risk, ignored), the group takes it, with a history entry, + /// unless a person has already decided about the group itself. + /// + /// # Errors + /// + /// A database error. + async fn inherit_decisions( + &mut self, + db: &Database, + findings: &mut [Finding], + ) -> Result<(), AgentError> { + for group in findings.iter_mut().filter(|f| !f.occurrences.is_empty()) { + let Some(rule) = group.rule_id.clone() else { + continue; + }; + let decided: Vec = db + .findings() + .clone_with_type::() + .find(doc! { + "repo_id": &group.repo_id, + "scanner": &group.scanner, + "rule_id": &rule, + "fingerprint": { "$ne": &group.fingerprint }, + "occurrences.0": { "$exists": false }, + "status": { "$in": INHERITABLE.to_vec() }, + }) + .projection(doc! { "file_path": 1, "line_number": 1, "status": 1 }) + .await? + .try_collect() + .await?; + if decided.is_empty() { + continue; + } + let decisions: HashMap<(String, Option), FindingStatus> = decided + .iter() + .filter_map(|row| { + let (_, _, file, line) = stored_place(row); + let status = mongodb::bson::from_bson(row.get("status")?.clone()).ok()?; + Some(((file, line), status)) + }) + .collect(); + for occurrence in &mut group.occurrences { + occurrence.decision = decisions + .get(&(occurrence.file.clone(), occurrence.line)) + .cloned(); + } + let rule_text = + crate::pipeline::grouping::rule_description(&group.description).to_string(); + group.description = crate::pipeline::grouping::describe(&rule_text, &group.occurrences); + let places = group.occurrences.len(); + let inherited = unanimous(group.occurrences.iter().map(|o| o.decision.as_ref())); + let mut update = doc! { "$set": { + "occurrences": bson_of(&group.occurrences)?, + "description": group.description.clone(), + } }; + let mut filter = doc! { "fingerprint": &group.fingerprint }; + if let Some(status) = &inherited { + let mut change = StatusChange::by_scan( + status.clone(), + ScanChangeKind::Inherited, + &self.scan_run_id, + ); + change.reason = Some(format!("inherited from {places} grouped findings")); + update.insert("$push", doc! { "status_history": bson_of(&change)? }); + if let Ok(set) = update.get_document_mut("$set") { + set.insert("status", bson_of(status)?); + set.insert("updated_at", mongodb::bson::DateTime::now()); + } + // A person's own decision about the group stays. + filter.insert("status", doc! { "$in": UNDECIDED.to_vec() }); + group.status = status.clone(); + group.status_history.push(change); + } + let before = db + .findings() + .clone_with_type::() + .find_one_and_update(filter.clone(), update) + .projection(doc! { "_id": 1 }) + .await?; + match ( + before.and_then(|row| row.get_object_id("_id").ok()), + &inherited, + ) { + (Some(id), Some(status)) => { + self.status_changed.push(id); + tracing::info!( + scan_run_id = %self.scan_run_id, + group = %id, + %status, + places, + "group inherited the decision on all its places" + ); + } + (None, Some(_)) => { + // Decided on the group already: keep its places listed. + filter.remove("status"); + db.findings() + .update_one( + filter, + doc! { "$set": { + "occurrences": bson_of(&group.occurrences)?, + "description": group.description.clone(), + } }, + ) + .await?; + } + _ => {} + } + } + Ok(()) + } + /// Mark resolved the findings of `target_id` that a scanner which /// completed in this run stored earlier but did not report this time. /// Call it once, after [`Self::write_back`] succeeded: a run that fails @@ -404,6 +524,14 @@ impl RunFindings { } } +/// The decision every place carries, when all carry the same one. +fn unanimous<'a>( + mut decisions: impl Iterator>, +) -> Option { + let first = decisions.next().flatten()?; + decisions.all(|d| d == Some(first)).then(|| first.clone()) +} + /// The place of a stored finding, to compare with [`RunFindings::grouped`]. fn stored_place(row: &Document) -> GroupedPlace { let text = |key: &str| row.get_str(key).unwrap_or_default().to_string(); @@ -564,6 +692,19 @@ mod tests { use super::*; + #[test] + fn only_one_decision_on_every_place_is_taken_over() { + let fp = FindingStatus::FalsePositive; + let risk = FindingStatus::AcceptedRisk; + assert_eq!( + unanimous([Some(&fp), Some(&fp)].into_iter()), + Some(fp.clone()) + ); + assert_eq!(unanimous([Some(&fp), Some(&risk)].into_iter()), None); + assert_eq!(unanimous([Some(&fp), None].into_iter()), None); + assert_eq!(unanimous([None, Some(&fp)].into_iter()), None); + } + fn triaged(action: &str, status: FindingStatus) -> Finding { let mut f = Finding::new( "repo".into(), diff --git a/compliance-agent/src/pipeline/grouping.rs b/compliance-agent/src/pipeline/grouping.rs index 09ade89..55c05ec 100644 --- a/compliance-agent/src/pipeline/grouping.rs +++ b/compliance-agent/src/pipeline/grouping.rs @@ -219,6 +219,7 @@ fn group(mut members: Vec) -> Option { file: f.file_path.clone().unwrap_or_default(), line: f.line_number, variant: f.variant.clone(), + decision: None, }) .collect(); occurrences.dedup(); @@ -231,10 +232,13 @@ fn group(mut members: Vec) -> Option { Some(first) } +/// What [`describe`] puts between the rule's description and the places. +const PLACES_HEADING: &str = "\n\nThis rule fired at "; + /// A group's description: the rule's own, then where it fired. pub fn describe(rule_description: &str, occurrences: &[Occurrence]) -> String { let mut text = format!( - "{rule_description}\n\nThis rule fired at {} places in the repository; they are one finding:\n", + "{rule_description}{PLACES_HEADING}{} places in the repository; they are one finding:\n", occurrences.len() ); for o in occurrences.iter().take(LISTED) { @@ -246,6 +250,13 @@ pub fn describe(rule_description: &str, occurrences: &[Occurrence]) -> String { text } +/// The rule's own description inside a group's, as [`describe`] wrote it. +pub fn rule_description(group_description: &str) -> &str { + group_description + .split_once(PLACES_HEADING) + .map_or(group_description, |(rule, _)| rule) +} + #[cfg(test)] mod tests { use super::*; @@ -431,6 +442,28 @@ mod tests { ); } + #[test] + fn the_rule_text_is_recovered_and_places_show_their_decision() { + let places = vec![ + Occurrence { + file: "a.java".into(), + line: Some(3), + variant: Some("Tablet".into()), + decision: Some(compliance_core::models::FindingStatus::FalsePositive), + }, + Occurrence { + file: "b.java".into(), + line: None, + variant: None, + decision: None, + }, + ]; + let text = describe("Logs data.", &places); + assert_eq!(rule_description(&text), "Logs data."); + assert_eq!(rule_description("Plain."), "Plain."); + assert!(text.contains("- a.java:3 (Tablet) [marked false_positive]\n- b.java\n")); + } + #[test] fn the_description_lists_at_most_fifty_places() { let places: Vec = (1..=60) @@ -438,6 +471,7 @@ mod tests { file: "a.java".into(), line: Some(i), variant: None, + decision: None, }) .collect(); let text = describe("Rule.", &places); diff --git a/compliance-agent/src/pipeline/issue_creation.rs b/compliance-agent/src/pipeline/issue_creation.rs index 84c1d69..c9b6637 100644 --- a/compliance-agent/src/pipeline/issue_creation.rs +++ b/compliance-agent/src/pipeline/issue_creation.rs @@ -86,13 +86,17 @@ impl PipelineOrchestrator { } }; - // Only create issues for medium+ severity findings + // Only create issues for medium+ severity findings nobody has decided + // about (a group can take over its places' decision, #483). let actionable: Vec<&Finding> = new_findings .iter() .filter(|f| { matches!( f.severity, Severity::Medium | Severity::High | Severity::Critical + ) && matches!( + f.status, + FindingStatus::Open | FindingStatus::Triaged | FindingStatus::NeedsReview ) }) .collect(); diff --git a/compliance-agent/src/pipeline/issue_sync.rs b/compliance-agent/src/pipeline/issue_sync.rs index b7ec83d..515a939 100644 --- a/compliance-agent/src/pipeline/issue_sync.rs +++ b/compliance-agent/src/pipeline/issue_sync.rs @@ -208,6 +208,13 @@ fn comment(status: &FindingStatus, change: Option<&StatusChange>) -> String { "In Prüfwerk als behoben markiert.", "Marked resolved in Prüfwerk.", ), + ( + FindingStatus::FalsePositive | FindingStatus::AcceptedRisk | FindingStatus::Ignored, + Some(ScanChangeKind::Inherited), + ) => ( + "Alle Stellen dieses Befunds waren zuvor einzeln gleich bewertet; der zusammengefasste Befund übernimmt diese Entscheidung.", + "Every place of this finding had been decided the same way one by one; the combined finding takes over that decision.", + ), (FindingStatus::FalsePositive, _) => ( "In Prüfwerk als Fehlalarm (Regel) markiert.", "Marked a false positive (rule) in Prüfwerk.", @@ -480,6 +487,12 @@ mod tests { assert!(grouped.contains("ein Befund") && grouped.contains("now one finding")); assert!(!grouped.contains("behoben"), "grouped is not fixed"); + let mut taken_over = by_scan(FindingStatus::FalsePositive, ScanChangeKind::Inherited); + taken_over.reason = Some("inherited from 38 grouped findings".into()); + let inherited = comment(&FindingStatus::FalsePositive, Some(&taken_over)); + assert!(inherited.contains("einzeln gleich bewertet") && inherited.contains("takes over")); + assert!(inherited.contains("> inherited from 38 grouped findings")); + let back = comment( &FindingStatus::Open, Some(&by_scan(FindingStatus::Open, ScanChangeKind::FoundAgain)), diff --git a/compliance-agent/src/pipeline/variants.rs b/compliance-agent/src/pipeline/variants.rs index cb487d3..0807605 100644 --- a/compliance-agent/src/pipeline/variants.rs +++ b/compliance-agent/src/pipeline/variants.rs @@ -394,6 +394,7 @@ mod tests { file: file.into(), line: Some(1), variant: None, + decision: None, }; let mut mixed = finding("app/src/phone/A.kt"); mixed.occurrences = vec![place("app/src/phone/A.kt"), place("app/src/tablet/A.kt")]; diff --git a/compliance-agent/tests/group_decisions.rs b/compliance-agent/tests/group_decisions.rs new file mode 100644 index 0000000..0e6cb84 --- /dev/null +++ b/compliance-agent/tests/group_decisions.rs @@ -0,0 +1,152 @@ +//! #483: a group takes over what a person decided about its places one by +//! one, when they all carry the same decision; mixed decisions are listed per +//! place and leave the group open; a decision on the group itself is never +//! overridden. Runs against a live Mongo (`TEST_MONGODB_URI`) and skips +//! cleanly without one. + +#![allow(clippy::expect_used, clippy::unwrap_used)] + +use compliance_agent::database::{Database, DatabasePool}; +use compliance_agent::pipeline::dedup::compute_fingerprint; +use compliance_agent::pipeline::finding_store::RunFindings; +use compliance_agent::pipeline::grouping::{group_repetitive, GroupingPolicy}; +use compliance_core::models::{Finding, FindingStatus, ScanChangeKind, ScanType, Severity}; +use mongodb::bson::doc; + +const PLACES: u32 = 6; + +fn logging(target: &str, line: u32) -> Finding { + let file = "app/src/main/java/Main.java"; + let mut f = Finding::new( + target.into(), + compute_fingerprint(&[target, "android_logging", file, &line.to_string()]), + "mobsfscan".into(), + ScanType::Sast, + "The app logs information".into(), + "The app logs information.".into(), + Severity::Low, + ); + f.rule_id = Some("android_logging".into()); + f.file_path = Some(file.into()); + f.line_number = Some(line); + f +} + +/// Store the single findings of `target` with the status `decide` gives each +/// line, then run a scan that groups them; the stored group. +async fn scan_after( + db: &Database, + target: &str, + decide: impl Fn(u32) -> FindingStatus, +) -> (Finding, RunFindings) { + let stored: Vec = (1..=PLACES) + .map(|line| { + let mut f = logging(target, line); + f.status = decide(line); + f + }) + .collect(); + db.findings().insert_many(&stored).await.unwrap(); + let mut findings: Vec = (1..=PLACES).map(|line| logging(target, line)).collect(); + group_repetitive(&mut findings, &GroupingPolicy::default()); + let mut run = RunFindings::new("run-1"); + run.completed("mobsfscan"); + run.save_new(db, &mut findings).await.unwrap(); + run.write_back(db, &mut findings).await.unwrap(); + run.resolve_missing(db, target, &[]).await.unwrap(); + let group = db + .findings() + .find_one(doc! { "repo_id": target, "occurrences.0": { "$exists": true } }) + .await + .unwrap() + .unwrap(); + (group, run) +} + +#[tokio::test] +async fn groups_take_over_their_places_decisions() { + let uri = std::env::var("TEST_MONGODB_URI") + .unwrap_or_else(|_| "mongodb://root:example@localhost:27017/?authSource=admin".into()); + let prefix = format!( + "groupdec_{}", + &uuid::Uuid::new_v4().simple().to_string()[..10] + ); + let Ok(pool) = DatabasePool::connect(&uri, &prefix).await else { + eprintln!("SKIP group_decisions: no MongoDB reachable at {uri}"); + return; + }; + let tenant = "group-decisions"; + let Ok(db) = pool.for_tenant_id(tenant).await else { + eprintln!("SKIP group_decisions: MongoDB at {uri} not usable"); + return; + }; + + // Every place marked a false positive: the group is one too, and its + // issue follows. + let (group, run) = scan_after(&db, "all-same", |_| FindingStatus::FalsePositive).await; + assert_eq!(group.status, FindingStatus::FalsePositive); + let change = group.status_history.last().expect("history"); + assert_eq!( + change.scan.as_ref().map(|s| s.kind), + Some(ScanChangeKind::Inherited) + ); + assert_eq!( + change.reason.as_deref(), + Some("inherited from 6 grouped findings") + ); + assert!(run.status_changed().contains(&group.id.unwrap())); + assert!(group + .description + .contains("Main.java:1 [marked false_positive]")); + + // Mixed: the group stays open and lists each place's decision. + let (group, _) = scan_after(&db, "mixed", |line| { + if line <= 3 { + FindingStatus::AcceptedRisk + } else { + FindingStatus::Open + } + }) + .await; + assert_eq!(group.status, FindingStatus::Open); + let decisions: Vec> = group + .occurrences + .iter() + .map(|o| o.decision.clone()) + .collect(); + assert_eq!( + decisions, + [ + Some(FindingStatus::AcceptedRisk), + Some(FindingStatus::AcceptedRisk), + Some(FindingStatus::AcceptedRisk), + None, + None, + None + ] + ); + + // A group stored before (#477) is set right on the next scan, but a + // person's decision about the group itself stays. + for (target, stored_status, expected) in [ + ("earlier-open", FindingStatus::Open, FindingStatus::Ignored), + ( + "earlier-decided", + FindingStatus::AcceptedRisk, + FindingStatus::AcceptedRisk, + ), + ] { + let mut earlier: Vec = (1..=PLACES).map(|line| logging(target, line)).collect(); + group_repetitive(&mut earlier, &GroupingPolicy::default()); + earlier[0].status = stored_status; + db.findings().insert_many(&earlier).await.unwrap(); + let (group, _) = scan_after(&db, target, |_| FindingStatus::Ignored).await; + assert_eq!(group.status, expected, "{target}"); + assert!(group + .occurrences + .iter() + .all(|o| o.decision == Some(FindingStatus::Ignored))); + } + + pool.drop_tenant(tenant).await.ok(); +} diff --git a/compliance-core/src/models/finding.rs b/compliance-core/src/models/finding.rs index e799212..2362116 100644 --- a/compliance-core/src/models/finding.rs +++ b/compliance-core/src/models/finding.rs @@ -25,7 +25,7 @@ impl std::fmt::Display for Severity { } } -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord, Hash)] #[serde(rename_all = "snake_case")] pub enum FindingStatus { Open, @@ -136,6 +136,9 @@ pub enum ScanChangeKind { /// Its rule fired often enough in the repository that its occurrences /// are now one finding, which lists this one's place (#464). Grouped, + /// A group whose places a person had all decided the same way, one by + /// one, before they were grouped: the group takes that decision (#483). + Inherited, } /// The scan behind a [`StatusChange`]. @@ -156,6 +159,10 @@ pub struct Occurrence { /// repository has several. #[serde(default, skip_serializing_if = "Option::is_none")] pub variant: Option, + /// What a person decided about the single finding stored for this place + /// before it was grouped (`false_positive`, `accepted_risk`, `ignored`). + #[serde(default, skip_serializing_if = "Option::is_none")] + pub decision: Option, } impl std::fmt::Display for Occurrence { @@ -164,8 +171,11 @@ impl std::fmt::Display for Occurrence { Some(line) => write!(f, "{}:{line}", self.file)?, None => write!(f, "{}", self.file)?, } - match &self.variant { - Some(variant) => write!(f, " ({variant})"), + if let Some(variant) = &self.variant { + write!(f, " ({variant})")?; + } + match &self.decision { + Some(decision) => write!(f, " [marked {decision}]"), None => Ok(()), } } diff --git a/compliance-dashboard/src/i18n/texts.rs b/compliance-dashboard/src/i18n/texts.rs index a46428d..4c94e89 100644 --- a/compliance-dashboard/src/i18n/texts.rs +++ b/compliance-dashboard/src/i18n/texts.rs @@ -1724,6 +1724,10 @@ pub mod findings { de: "Mit den anderen Stellen derselben Regel zu einem Befund zusammengefasst.", en: "Combined with the other places of the same rule into one finding.", }, + ScanChangeKind::Inherited => Text { + de: "Von den einzeln bewerteten Stellen übernommen: Alle waren gleich markiert.", + en: "Taken over from its places, which a person had all marked the same way.", + }, } }