diff --git a/.env.example b/.env.example index cbefa3f..8c31667 100644 --- a/.env.example +++ b/.env.example @@ -44,6 +44,12 @@ CVE_MONITOR_SCHEDULE=0 0 0 * * * # GIT_SOURCE_HOST_PATTERN=^[a-z0-9-]+\.code(-stage)?\.breakpilot\.com$ # GIT_SOURCE_SYNC_MINUTES=30 # WEBHOOK_PUBLIC_URL=https://pruefwerk-hooks.example.com +# Grouping (#464): more than this many low/info findings of one scanner's rule +# in one repository become one finding listing every place (`off`: never). +# Per scanner as `scanner=N` or `scanner=off`; the severities that are grouped. +# FINDING_GROUP_THRESHOLD=5 +# FINDING_GROUP_SCANNERS=mobsfscan=5,gitleaks=off +# FINDING_GROUP_SEVERITIES=low,info GIT_CLONE_BASE_PATH=/tmp/compliance-scanner/repos # NuGet licenses (#467): look up licenses the tree's .nuspec files do not give # on api.nuget.org (package id and version only; never for ids a nuget.config diff --git a/compliance-agent/src/config.rs b/compliance-agent/src/config.rs index 0f5fd23..98ba561 100644 --- a/compliance-agent/src/config.rs +++ b/compliance-agent/src/config.rs @@ -27,6 +27,8 @@ pub fn load_config() -> Result { // Same for the managed git source settings: a bad host pattern must not // leave every host (or none) allowed. crate::git_source::Settings::from_env().map_err(AgentError::Config)?; + // And for how findings are grouped (#464). + crate::pipeline::grouping::GroupingPolicy::from_env().map_err(AgentError::Config)?; if let Err(problems) = config.validate_deployment() { return Err(AgentError::Config(format!( "refusing to start in {}:\n - {}", diff --git a/compliance-agent/src/pipeline/finding_store.rs b/compliance-agent/src/pipeline/finding_store.rs index d278518..4b0bc9f 100644 --- a/compliance-agent/src/pipeline/finding_store.rs +++ b/compliance-agent/src/pipeline/finding_store.rs @@ -11,7 +11,8 @@ //! [`RunFindings::save_new`] reopens a resolved finding that is reported //! again. Only scanners whose run is known to have completed count (see //! [`RunFindings::completed`]): a tool that failed quietly must not close -//! everything it found before. +//! everything it found before. A finding now listed by a group of one rule's +//! findings ([`crate::pipeline::grouping`]) is closed as grouped. use std::collections::{HashMap, HashSet}; @@ -35,8 +36,14 @@ pub struct RunFindings { completed: HashSet, /// Findings this run closed or reopened, for their issues. status_changed: Vec, + /// The places listed by the groups this run reported (scanner, rule, + /// file, line): a finding stored at one of them was grouped, not fixed. + grouped: HashSet, } +/// One place a group lists: scanner, rule, file, line. +type GroupedPlace = (String, String, String, Option); + /// Statuses a scan may close: nobody has decided about the finding yet. A /// false positive, an accepted risk, an ignored finding and a wrong mapping /// are a person's decision and stay as they are. @@ -55,6 +62,7 @@ impl RunFindings { earlier: HashSet::new(), completed: HashSet::new(), status_changed: Vec::new(), + grouped: HashSet::new(), } } @@ -86,6 +94,7 @@ impl RunFindings { db: &Database, findings: &mut [Finding], ) -> Result { + self.note_groups(findings); let unknown: HashSet = findings .iter() .map(|f| f.fingerprint.as_str()) @@ -247,7 +256,14 @@ impl RunFindings { target_id: &str, vendor: &[String], ) -> Result { - if self.completed.is_empty() { + // A finding a group of this run lists was grouped, whether or not its + // scanner counts as completed (lint never does). + let scanners: HashSet<&String> = self + .completed + .iter() + .chain(self.grouped.iter().map(|(scanner, ..)| scanner)) + .collect(); + if scanners.is_empty() { return Ok(0); } let candidates: Vec = db @@ -255,14 +271,16 @@ impl RunFindings { .clone_with_type::() .find(doc! { "repo_id": target_id, - "scanner": { "$in": self.completed.iter().collect::>() }, + "scanner": { "$in": scanners.into_iter().collect::>() }, "status": { "$in": UNDECIDED.to_vec() }, }) - .projection(doc! { "fingerprint": 1, "file_path": 1 }) + .projection(doc! { + "fingerprint": 1, "file_path": 1, "scanner": 1, "rule_id": 1, "line_number": 1, + }) .await? .try_collect() .await?; - let (mut fixed, mut vendored) = (Vec::new(), Vec::new()); + let (mut fixed, mut vendored, mut grouped) = (Vec::new(), Vec::new(), Vec::new()); for row in &candidates { let (Ok(id), Ok(fingerprint)) = (row.get_object_id("_id"), row.get_str("fingerprint")) else { @@ -274,7 +292,14 @@ impl RunFindings { let in_vendor = row .get_str("file_path") .is_ok_and(|file| crate::pipeline::vendor::in_vendor_dir(file, vendor)); - if in_vendor { + let completed = row + .get_str("scanner") + .is_ok_and(|scanner| self.completed.contains(scanner)); + if self.grouped.contains(&stored_place(row)) { + grouped.push(id); + } else if !completed { + continue; + } else if in_vendor { vendored.push(id); } else { fixed.push(id); @@ -283,16 +308,19 @@ impl RunFindings { for (ids, kind) in [ (&fixed, ScanChangeKind::NoLongerFound), (&vendored, ScanChangeKind::NowVendorCode), + (&grouped, ScanChangeKind::Grouped), ] { self.set_status(db, ids, &UNDECIDED, FindingStatus::Resolved, kind) .await?; } - let closed = u32::try_from(fixed.len() + vendored.len()).unwrap_or(u32::MAX); + let closed = + u32::try_from(fixed.len() + vendored.len() + grouped.len()).unwrap_or(u32::MAX); if closed > 0 { tracing::info!( scan_run_id = %self.scan_run_id, fixed = fixed.len(), vendored = vendored.len(), + grouped = grouped.len(), "resolved findings the scan no longer reports" ); } @@ -335,6 +363,18 @@ impl RunFindings { &self.status_changed } + /// Remember the places the groups among `findings` list. + fn note_groups(&mut self, findings: &[Finding]) { + for f in findings.iter().filter(|f| !f.occurrences.is_empty()) { + let rule = f.rule_id.clone().unwrap_or_default(); + self.grouped.extend( + f.occurrences + .iter() + .map(|o| (f.scanner.clone(), rule.clone(), o.file.clone(), o.line)), + ); + } + } + /// Give each finding this run saved its row id. fn stamp_ids(&self, findings: &mut [Finding]) { for finding in findings.iter_mut() { @@ -346,6 +386,17 @@ impl RunFindings { } } +/// 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(); + let line = match row.get("line_number") { + Some(Bson::Int32(l)) => u32::try_from(*l).ok(), + Some(Bson::Int64(l)) => u32::try_from(*l).ok(), + _ => None, + }; + (text("scanner"), text("rule_id"), text("file_path"), line) +} + /// `value` as BSON. fn bson_of(value: &T) -> Result { to_bson(value).map_err(|e| AgentError::Other(format!("encode finding field: {e}"))) @@ -364,6 +415,8 @@ enum WriteKind { EarlierStatus, /// The control refs of a row an earlier run stored. EarlierControlRefs, + /// The places of a group an earlier run stored (#464). + EarlierPlaces, } /// One update of a finding's stored row. @@ -437,6 +490,21 @@ fn row_writes(finding: &Finding, inserted: Option) -> Result bool { rule_id == "gcp-api-key" && FIREBASE_CONFIGS.contains(&name.as_str()) } +/// gitleaks' catch-all rule for anything that looks like a key. +const GENERIC_API_KEY: &str = "generic-api-key"; + +/// Whether a result is the catch-all rule firing on an Eclipse launch +/// configuration (`*.launch`, the debugger setup of embedded IDEs). Those +/// hold hex ids of probes, targets and memory regions, which the rule takes +/// for keys: every hit in the firmware repositories of the pilot was one. +/// gitleaks' specific rules (private keys, tokens) still apply there. +fn launch_config_id(rule_id: &str, file: &str) -> bool { + rule_id == GENERIC_API_KEY && file.to_ascii_lowercase().ends_with(".launch") +} + +/// Whether a result is reported: not in an example or test file, not a +/// repeat of the Firebase rule, not an id in a launch configuration. +fn reportable(r: &GitleaksResult) -> bool { + !is_allowlisted(&r.file) + && !repeats_firebase_rule(&r.rule_id, &r.file) + && !launch_config_id(&r.rule_id, &r.file) +} + /// The configuration of one run, in a temporary directory of its own (a /// shared file would let concurrent scans pull it from under each other), /// removed on drop. @@ -117,8 +137,7 @@ impl Scanner for GitleaksScanner { let findings = results .into_iter() - .filter(|r| !is_allowlisted(&r.file)) - .filter(|r| !repeats_firebase_rule(&r.rule_id, &r.file)) + .filter(reportable) .map(|r| { let severity = match r.rule_id.as_str() { // It identifies the app; the risk is a key left @@ -215,6 +234,45 @@ struct GitleaksResult { mod tests { use super::*; + #[test] + fn hex_ids_in_eclipse_launch_files_are_not_keys() { + assert!(launch_config_id( + "generic-api-key", + "Firmware/Debug/board-a Debug.launch" + )); + assert!(launch_config_id("generic-api-key", "tools/PROBE.LAUNCH")); + // Other rules still fire in a launch file, and the generic rule + // everywhere else. + assert!(!launch_config_id( + "private-key", + "Firmware/Debug/board-a Debug.launch" + )); + assert!(!launch_config_id("aws-access-token", "x.launch")); + assert!(!launch_config_id("generic-api-key", "src/config.xml")); + assert!(!launch_config_id("generic-api-key", "src/launch.c")); + } + + #[test] + fn launch_file_hits_are_dropped_from_the_results() { + // What gitleaks reports for a debugger configuration: the id of a + // memory region, made up. + let json = r#"[ + {"Description": "Generic API Key", "RuleID": "generic-api-key", + "File": "Firmware/.settings/board-a Debug.launch", "StartLine": 12, + "Match": "value=\"0123456789abcdef0123456789abcdef\""}, + {"Description": "Generic API Key", "RuleID": "generic-api-key", + "File": "src/settings.ini", "StartLine": 3, + "Match": "api_key=0123456789abcdef0123456789abcdef"} + ]"#; + let results: Vec = serde_json::from_str(json).unwrap(); + let kept: Vec<&str> = results + .iter() + .filter(|r| reportable(r)) + .map(|r| r.file.as_str()) + .collect(); + assert_eq!(kept, ["src/settings.ini"]); + } + #[test] fn the_firebase_key_is_reported_once() { assert!(repeats_firebase_rule( diff --git a/compliance-agent/src/pipeline/grouping.rs b/compliance-agent/src/pipeline/grouping.rs new file mode 100644 index 0000000..32f8127 --- /dev/null +++ b/compliance-agent/src/pipeline/grouping.rs @@ -0,0 +1,456 @@ +//! One finding for a rule that fires all over a repository (#464). +//! +//! A rule that matches dozens of times in one repository (every `Log.d` call +//! of an Android app) buried the findings that matter and opened an issue +//! for each match. Above a threshold, the low and info findings of one +//! scanner's rule in one repository become a single finding listing every +//! place it fired. +//! +//! The group's fingerprint comes from (scanner, rule, repository), not from +//! a place, so it stays the same from scan to scan however the places +//! change, and a person's triage and status stay with it. + +use std::collections::{BTreeSet, HashMap}; + +use compliance_core::models::{Finding, Occurrence, Severity}; + +use crate::pipeline::dedup; + +/// How many findings of one rule a repository may have before they are +/// grouped: more than this many become one. +pub const DEFAULT_THRESHOLD: usize = 5; + +/// How many places a group's description lists; the occurrence list on the +/// finding has all of them. +const LISTED: usize = 50; + +/// When findings are grouped. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct GroupingPolicy { + /// More findings of a rule than this are grouped; `None`: never. + pub threshold: Option, + /// Per scanner (`Finding::scanner`), in place of `threshold`. + pub per_scanner: HashMap>, + /// The severities that are grouped; findings of other severities stay + /// one per place. + pub severities: BTreeSet, +} + +impl Default for GroupingPolicy { + fn default() -> Self { + Self { + threshold: Some(DEFAULT_THRESHOLD), + per_scanner: HashMap::new(), + severities: BTreeSet::from([Severity::Low, Severity::Info]), + } + } +} + +impl GroupingPolicy { + /// The policy from the environment: + /// + /// * `FINDING_GROUP_THRESHOLD`: a number, or `off` (default 5) + /// * `FINDING_GROUP_SCANNERS`: per scanner, `mobsfscan=3,gitleaks=off` + /// * `FINDING_GROUP_SEVERITIES`: `low,info` (default) + /// + /// # Errors + /// + /// A malformed value: startup refuses it rather than group differently + /// than configured. + pub fn from_env() -> Result { + let var = |k: &str| std::env::var(k).ok().filter(|v| !v.trim().is_empty()); + Self::parse( + var("FINDING_GROUP_THRESHOLD").as_deref(), + var("FINDING_GROUP_SCANNERS").as_deref(), + var("FINDING_GROUP_SEVERITIES").as_deref(), + ) + } + + /// Build the policy from raw values (`None` = default). + /// + /// # Errors + /// + /// See [`Self::from_env`]. + pub fn parse( + threshold: Option<&str>, + per_scanner: Option<&str>, + severities: Option<&str>, + ) -> Result { + let mut policy = Self::default(); + if let Some(t) = threshold { + policy.threshold = + parse_threshold(t).map_err(|e| format!("FINDING_GROUP_THRESHOLD: {e}"))?; + } + for entry in per_scanner + .unwrap_or_default() + .split(',') + .map(str::trim) + .filter(|e| !e.is_empty()) + { + let (scanner, value) = entry + .split_once('=') + .map(|(s, v)| (s.trim(), v)) + .filter(|(s, _)| !s.is_empty()) + .ok_or_else(|| { + format!("FINDING_GROUP_SCANNERS: `{entry}` is not `scanner=number` or `scanner=off`") + })?; + let value = parse_threshold(value) + .map_err(|e| format!("FINDING_GROUP_SCANNERS: {scanner}: {e}"))?; + policy.per_scanner.insert(scanner.to_string(), value); + } + if let Some(list) = severities { + policy.severities = list + .split(',') + .map(str::trim) + .filter(|s| !s.is_empty()) + .map(|s| { + serde_json::from_value(serde_json::Value::String(s.to_ascii_lowercase())) + .map_err(|_| format!("FINDING_GROUP_SEVERITIES: `{s}` is not a severity")) + }) + .collect::>()?; + } + Ok(policy) + } + + /// The threshold for `scanner`'s findings, `None` when they are never + /// grouped. + pub fn threshold_for(&self, scanner: &str) -> Option { + self.per_scanner + .get(scanner) + .copied() + .unwrap_or(self.threshold) + } +} + +fn parse_threshold(raw: &str) -> Result, String> { + let raw = raw.trim(); + if raw.eq_ignore_ascii_case("off") { + return Ok(None); + } + raw.parse::() + .map(Some) + .map_err(|_| format!("`{raw}` is not a number or `off`")) +} + +/// The fingerprint of the group of `scanner`'s findings for `rule` in +/// `repo_id`. +pub fn group_fingerprint(repo_id: &str, scanner: &str, rule: &str) -> String { + dedup::compute_fingerprint(&["group", repo_id, scanner, rule]) +} + +/// Replace, in `findings`, the findings of each (scanner, rule, repository) +/// with more of them than the policy allows by one finding for all of them. +/// Findings of a severity the policy does not group, findings without a rule, +/// and groups made by an earlier call are left as they are, so calling it +/// again changes nothing. +/// +/// # Returns +/// +/// How many groups were made. +pub fn group_repetitive(findings: &mut Vec, policy: &GroupingPolicy) -> usize { + let key = |f: &Finding| -> Option<(String, String, String)> { + let rule = f.rule_id.as_deref()?; + let eligible = f.occurrences.is_empty() + && policy.severities.contains(&f.severity) + && policy.threshold_for(&f.scanner).is_some(); + eligible.then(|| (f.repo_id.clone(), f.scanner.clone(), rule.to_string())) + }; + let mut counts: HashMap<(String, String, String), usize> = HashMap::new(); + for f in findings.iter() { + if let Some(k) = key(f) { + *counts.entry(k).or_default() += 1; + } + } + let grouped: HashMap<_, _> = counts + .into_iter() + .filter(|((_, scanner, _), n)| policy.threshold_for(scanner).is_some_and(|t| *n > t)) + .map(|(k, _)| (k, Vec::new())) + .collect(); + if grouped.is_empty() { + return 0; + } + + let mut members = grouped; + let mut kept = Vec::with_capacity(findings.len()); + // Where each group goes: in place of its first member. + let mut order: Vec> = Vec::with_capacity(findings.len()); + for f in findings.drain(..) { + match key(&f).filter(|k| members.contains_key(k)) { + Some(k) => { + let list = members.get_mut(&k); + if list.as_ref().is_some_and(|l| l.is_empty()) { + order.push(Some(k.clone())); + } + if let Some(list) = list { + list.push(f); + } + } + None => { + order.push(None); + kept.push(f); + } + } + } + let made = members.len(); + let mut kept = kept.into_iter(); + for slot in order { + match slot { + None => findings.extend(kept.next()), + Some(k) => { + if let Some(list) = members.remove(&k) { + findings.extend(group(list)); + } + } + } + } + made +} + +/// One finding for `members` (one scanner's findings of one rule in one +/// repository, at least one). +fn group(mut members: Vec) -> Option { + members.sort_by(|a, b| { + (a.file_path.as_deref(), a.line_number).cmp(&(b.file_path.as_deref(), b.line_number)) + }); + let severity = members.iter().map(|f| f.severity.clone()).max()?; + let mut occurrences: Vec = members + .iter() + .map(|f| Occurrence { + file: f.file_path.clone().unwrap_or_default(), + line: f.line_number, + }) + .collect(); + occurrences.dedup(); + let mut first = members.into_iter().next()?; + let rule = first.rule_id.clone().unwrap_or_default(); + first.fingerprint = group_fingerprint(&first.repo_id, &first.scanner, &rule); + first.severity = severity; + first.description = describe(&first.description, &occurrences); + first.occurrences = occurrences; + Some(first) +} + +/// 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", + occurrences.len() + ); + for o in occurrences.iter().take(LISTED) { + text.push_str(&format!("- {o}\n")); + } + if occurrences.len() > LISTED { + text.push_str(&format!("- and {} more\n", occurrences.len() - LISTED)); + } + text +} + +#[cfg(test)] +mod tests { + use super::*; + use compliance_core::models::ScanType; + + fn finding(scanner: &str, rule: &str, file: &str, line: u32, severity: Severity) -> Finding { + let mut f = Finding::new( + "repo-1".into(), + dedup::compute_fingerprint(&["repo-1", rule, file, &line.to_string()]), + scanner.into(), + ScanType::Sast, + "Logging of sensitive data".into(), + "The app logs information.".into(), + severity, + ); + f.rule_id = Some(rule.into()); + f.file_path = Some(file.into()); + f.line_number = Some(line); + f + } + + fn logging(n: u32) -> Vec { + (1..=n) + .map(|i| { + finding( + "mobsfscan", + "android_logging", + &format!("app/src/main/java/A{}.java", i % 7), + i, + Severity::Low, + ) + }) + .collect() + } + + #[test] + fn many_low_findings_of_one_rule_become_one() { + let mut findings = logging(38); + findings.push(finding( + "mobsfscan", + "android_ssl_pinning", + "a.java", + 1, + Severity::High, + )); + assert_eq!( + group_repetitive(&mut findings, &GroupingPolicy::default()), + 1 + ); + assert_eq!(findings.len(), 2); + let g = &findings[0]; + assert_eq!(g.occurrences.len(), 38); + assert_eq!( + g.fingerprint, + group_fingerprint("repo-1", "mobsfscan", "android_logging") + ); + assert_eq!(g.severity, Severity::Low); + assert_eq!(g.title, "Logging of sensitive data"); + assert!(g.description.contains("38 places")); + assert!(g.description.contains("- app/src/main/java/A0.java:7\n")); + // The first place is the finding's location. + assert_eq!(g.file_path.as_deref(), Some(g.occurrences[0].file.as_str())); + assert_eq!(g.line_number, g.occurrences[0].line); + // The high one stays where it was. + assert_eq!(findings[1].rule_id.as_deref(), Some("android_ssl_pinning")); + } + + #[test] + fn the_threshold_is_more_than_five() { + let mut five = logging(5); + assert_eq!(group_repetitive(&mut five, &GroupingPolicy::default()), 0); + assert_eq!(five.len(), 5); + let mut six = logging(6); + assert_eq!(group_repetitive(&mut six, &GroupingPolicy::default()), 1); + assert_eq!(six.len(), 1); + } + + #[test] + fn the_group_fingerprint_does_not_depend_on_the_places() { + // Same rule, the places moved: the same finding, so its triage and + // status stay. + let mut before = logging(8); + let mut after = logging(12); + for f in &mut after { + f.line_number = f.line_number.map(|l| l + 100); + } + let policy = GroupingPolicy::default(); + group_repetitive(&mut before, &policy); + group_repetitive(&mut after, &policy); + assert_eq!(before[0].fingerprint, after[0].fingerprint); + // Another repository, scanner or rule: another group. + assert_ne!( + group_fingerprint("repo-1", "mobsfscan", "android_logging"), + group_fingerprint("repo-2", "mobsfscan", "android_logging") + ); + assert_ne!( + group_fingerprint("repo-1", "mobsfscan", "android_logging"), + group_fingerprint("repo-1", "semgrep", "android_logging") + ); + } + + #[test] + fn grouping_twice_changes_nothing() { + let mut findings = logging(9); + let policy = GroupingPolicy::default(); + group_repetitive(&mut findings, &policy); + let once: Vec = findings.iter().map(|f| f.fingerprint.clone()).collect(); + assert_eq!(group_repetitive(&mut findings, &policy), 0); + let twice: Vec = findings.iter().map(|f| f.fingerprint.clone()).collect(); + assert_eq!(once, twice); + } + + #[test] + fn only_the_configured_severities_are_grouped() { + let mut findings: Vec = (1..=9) + .map(|i| finding("semgrep", "rule-a", "a.c", i, Severity::Medium)) + .collect(); + assert_eq!( + group_repetitive(&mut findings, &GroupingPolicy::default()), + 0 + ); + assert_eq!(findings.len(), 9); + let policy = GroupingPolicy::parse(None, None, Some("medium")).unwrap(); + assert_eq!(group_repetitive(&mut findings, &policy), 1); + assert_eq!(findings.len(), 1); + } + + #[test] + fn mixed_severities_group_only_the_eligible_ones() { + let mut findings = logging(7); + findings.push(finding( + "mobsfscan", + "android_logging", + "b.java", + 1, + Severity::Medium, + )); + group_repetitive(&mut findings, &GroupingPolicy::default()); + assert_eq!(findings.len(), 2); + assert_eq!(findings[0].occurrences.len(), 7); + assert!(findings[1].occurrences.is_empty()); + } + + #[test] + fn findings_without_a_rule_are_not_grouped() { + let mut findings = logging(8); + for f in &mut findings { + f.rule_id = None; + } + assert_eq!( + group_repetitive(&mut findings, &GroupingPolicy::default()), + 0 + ); + assert_eq!(findings.len(), 8); + } + + #[test] + fn the_threshold_is_configurable_per_scanner() { + let policy = + GroupingPolicy::parse(Some("10"), Some("mobsfscan=3, gitleaks=off"), None).unwrap(); + assert_eq!(policy.threshold_for("mobsfscan"), Some(3)); + assert_eq!(policy.threshold_for("gitleaks"), None); + assert_eq!(policy.threshold_for("semgrep"), Some(10)); + let mut findings = logging(4); + assert_eq!(group_repetitive(&mut findings, &policy), 1); + + let off = GroupingPolicy::parse(Some("off"), None, None).unwrap(); + let mut findings = logging(40); + assert_eq!(group_repetitive(&mut findings, &off), 0); + assert_eq!(findings.len(), 40); + } + + #[test] + fn a_bad_policy_is_refused() { + assert!(GroupingPolicy::parse(Some("many"), None, None).is_err()); + assert!(GroupingPolicy::parse(None, Some("mobsfscan"), None).is_err()); + assert!(GroupingPolicy::parse(None, Some("=3"), None).is_err()); + assert!(GroupingPolicy::parse(None, Some("mobsfscan=x"), None).is_err()); + assert!(GroupingPolicy::parse(None, None, Some("loud")).is_err()); + assert_eq!( + GroupingPolicy::parse(None, None, None).unwrap(), + GroupingPolicy::default() + ); + } + + #[test] + fn the_description_lists_at_most_fifty_places() { + let places: Vec = (1..=60) + .map(|i| Occurrence { + file: "a.java".into(), + line: Some(i), + }) + .collect(); + let text = describe("Rule.", &places); + assert!(text.starts_with("Rule.\n\nThis rule fired at 60 places")); + assert_eq!(text.matches("\n- a.java:").count(), 50); + assert!(text.ends_with("- and 10 more\n")); + } + + #[test] + fn order_of_the_other_findings_is_kept() { + let mut findings = vec![finding("semgrep", "x", "a.c", 1, Severity::High)]; + findings.extend(logging(6)); + findings.push(finding("semgrep", "y", "b.c", 2, Severity::High)); + group_repetitive(&mut findings, &GroupingPolicy::default()); + let rules: Vec<_> = findings.iter().filter_map(|f| f.rule_id.clone()).collect(); + assert_eq!(rules, ["x", "android_logging", "y"]); + } +} diff --git a/compliance-agent/src/pipeline/issue_creation.rs b/compliance-agent/src/pipeline/issue_creation.rs index bb4d2e8..070a903 100644 --- a/compliance-agent/src/pipeline/issue_creation.rs +++ b/compliance-agent/src/pipeline/issue_creation.rs @@ -340,7 +340,14 @@ pub(super) fn format_issue_body(finding: &Finding) -> String { body.push_str(&format!("\n### Description\n\n{}\n", finding.description)); - if let Some(file_path) = &finding.file_path { + if finding.occurrences.len() > 1 { + // A group (#464): its description lists the places. + body.push_str(&format!( + "\n### Location\n\n{} places, listed above; the first is `{}`.\n", + finding.occurrences.len(), + finding.occurrences[0] + )); + } else if let Some(file_path) = &finding.file_path { body.push_str(&format!("\n### Location\n\n**File:** `{}`", file_path)); if let Some(line) = finding.line_number { body.push_str(&format!(" (line {})", line)); @@ -441,6 +448,35 @@ mod tests { assert!(body.contains("`fp1`")); } + #[test] + fn a_group_has_one_issue_listing_its_places() { + let mut findings: Vec = (1..=8) + .map(|i| { + let mut f = Finding::new( + "r".into(), + format!("fp{i}"), + "mobsfscan".into(), + ScanType::Sast, + "Logging".into(), + "The app logs.".into(), + Severity::Low, + ); + f.rule_id = Some("android_logging".into()); + f.file_path = Some("app/Main.java".into()); + f.line_number = Some(i * 10); + f + }) + .collect(); + let policy = crate::pipeline::grouping::GroupingPolicy::default(); + crate::pipeline::grouping::group_repetitive(&mut findings, &policy); + assert_eq!(findings.len(), 1, "one finding, so one issue"); + let body = format_issue_body(&findings[0]); + assert!(body.contains("- app/Main.java:10\n")); + assert!(body.contains("- app/Main.java:80\n")); + assert!(body.contains("8 places, listed above; the first is `app/Main.java:10`.")); + assert!(body.contains(&format!("`{}`", findings[0].fingerprint))); + } + #[test] fn links_only_to_an_https_dashboard() { assert_eq!( diff --git a/compliance-agent/src/pipeline/issue_sync.rs b/compliance-agent/src/pipeline/issue_sync.rs index 1f636f0..b7ec83d 100644 --- a/compliance-agent/src/pipeline/issue_sync.rs +++ b/compliance-agent/src/pipeline/issue_sync.rs @@ -196,6 +196,10 @@ fn comment(status: &FindingStatus, change: Option<&StatusChange>) -> String { "Bei der Prüfung nicht mehr gefunden, daher als behoben markiert.", "No longer found by the scan, so marked resolved.", ), + (FindingStatus::Resolved, Some(ScanChangeKind::Grouped)) => ( + "Diese Regel schlägt im Repository an vielen Stellen an; alle Stellen sind jetzt ein Befund mit eigenem Ticket, das diese Stelle aufführt.", + "This rule fires at many places in the repository; they are now one finding with an issue of its own, which lists this place.", + ), (FindingStatus::Resolved, Some(ScanChangeKind::NowVendorCode)) => ( "Die Datei gilt jetzt als Herstellercode und ist von den Befunden ausgenommen.", "The file now counts as vendor code, which is left out of the findings.", @@ -469,6 +473,13 @@ mod tests { ); assert!(fixed.contains("nicht mehr gefunden") && fixed.contains("No longer found")); + let grouped = comment( + &FindingStatus::Resolved, + Some(&by_scan(FindingStatus::Resolved, ScanChangeKind::Grouped)), + ); + assert!(grouped.contains("ein Befund") && grouped.contains("now one finding")); + assert!(!grouped.contains("behoben"), "grouped is not fixed"); + let back = comment( &FindingStatus::Open, Some(&by_scan(FindingStatus::Open, ScanChangeKind::FoundAgain)), diff --git a/compliance-agent/src/pipeline/mod.rs b/compliance-agent/src/pipeline/mod.rs index dbfdc11..f84025f 100644 --- a/compliance-agent/src/pipeline/mod.rs +++ b/compliance-agent/src/pipeline/mod.rs @@ -12,6 +12,7 @@ pub mod git; pub mod git_submodules; pub mod gitleaks; mod graph_build; +pub mod grouping; mod issue_creation; pub(crate) mod issue_sync; pub mod languages; diff --git a/compliance-agent/src/pipeline/orchestrator.rs b/compliance-agent/src/pipeline/orchestrator.rs index 8c6bef7..5a097bc 100644 --- a/compliance-agent/src/pipeline/orchestrator.rs +++ b/compliance-agent/src/pipeline/orchestrator.rs @@ -14,6 +14,7 @@ use crate::pipeline::cppcheck::CppcheckScanner; use crate::pipeline::cve::CveScanner; use crate::pipeline::git::GitOps; use crate::pipeline::gitleaks::GitleaksScanner; +use crate::pipeline::grouping::{group_repetitive, GroupingPolicy}; use crate::pipeline::lint::LintScanner; use crate::pipeline::mobsfscan::MobsfscanScanner; use crate::pipeline::patterns::{GdprPatternScanner, OAuthPatternScanner}; @@ -166,6 +167,9 @@ impl PipelineOrchestrator { repo: &RepoView, scan_run_id: &str, ) -> Result { + // Checked at startup (`load_config`); one rule's many low findings + // are one finding (#464). + let grouping = GroupingPolicy::from_env().unwrap_or_default(); let repo_id = repo.id.as_ref().map(|id| id.to_hex()).unwrap_or_default(); let repo_path = tree.to_path_buf(); @@ -288,6 +292,7 @@ impl PipelineOrchestrator { } } } + group_repetitive(&mut all_findings, &grouping); run_findings.save_new(&self.db, &mut all_findings).await?; // Stage 2: SBOM Generation @@ -514,6 +519,7 @@ impl PipelineOrchestrator { outside_vendor(&mut pattern_findings); all_findings.extend(pattern_findings); } + group_repetitive(&mut all_findings, &grouping); run_findings.save_new(&self.db, &mut all_findings).await?; // Stage 4a: Secret Detection (Gitleaks) @@ -534,6 +540,7 @@ impl PipelineOrchestrator { } Err(e) => tracing::warn!("[{repo_id}] Gitleaks failed: {e}"), } + group_repetitive(&mut all_findings, &grouping); run_findings.save_new(&self.db, &mut all_findings).await?; // Stage 4b: Lint Scanning @@ -553,6 +560,7 @@ impl PipelineOrchestrator { } Err(e) => tracing::warn!("[{repo_id}] Lint scanning failed: {e}"), } + group_repetitive(&mut all_findings, &grouping); run_findings.save_new(&self.db, &mut all_findings).await?; // Stage 4.5: Graph Building diff --git a/compliance-agent/tests/group_findings.rs b/compliance-agent/tests/group_findings.rs new file mode 100644 index 0000000..b17e418 --- /dev/null +++ b/compliance-agent/tests/group_findings.rs @@ -0,0 +1,139 @@ +//! #464: one rule's many low findings become one; the findings stored one +//! per place are closed as grouped, and the group stays the same finding +//! from scan to scan. 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_fingerprint, group_repetitive, GroupingPolicy}; +use compliance_core::models::{ + Finding, FindingStatus, ScanChangeKind, ScanType, Severity, StatusChange, +}; +use mongodb::bson::doc; + +const TENANT: &str = "group-findings"; +const TARGET: &str = "target-1"; + +fn logging(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 +} + +/// What a scan reports for `lines`, grouped as the pipeline does. +fn scan(lines: impl Iterator) -> Vec { + let mut findings: Vec = lines.map(logging).collect(); + group_repetitive(&mut findings, &GroupingPolicy::default()); + findings +} + +async fn row(db: &Database, fingerprint: &str) -> Finding { + db.findings() + .find_one(doc! { "fingerprint": fingerprint }) + .await + .unwrap() + .unwrap() +} + +#[tokio::test] +async fn a_rule_firing_everywhere_is_one_finding_across_scans() { + let uri = std::env::var("TEST_MONGODB_URI") + .unwrap_or_else(|_| "mongodb://root:example@localhost:27017/?authSource=admin".into()); + let prefix = format!("group_{}", &uuid::Uuid::new_v4().simple().to_string()[..10]); + let Ok(pool) = DatabasePool::connect(&uri, &prefix).await else { + eprintln!("SKIP group_findings: no MongoDB reachable at {uri}"); + return; + }; + let Ok(db) = pool.for_tenant_id(TENANT).await else { + eprintln!("SKIP group_findings: MongoDB at {uri} not usable"); + return; + }; + + // Arrange: a scan before grouping stored 38 findings, one per place; a + // person decided one of them. + let mut stored: Vec = (1..=38).map(logging).collect(); + stored[0].status = FindingStatus::FalsePositive; + db.findings().insert_many(&stored).await.unwrap(); + + // Act: a scan with grouping. + let mut first = scan(1..=38); + assert_eq!(first.len(), 1); + let mut run = RunFindings::new("run-1"); + run.completed("mobsfscan"); + assert_eq!(run.save_new(&db, &mut first).await.unwrap(), 1); + run.write_back(&db, &mut first).await.unwrap(); + let closed = run.resolve_missing(&db, TARGET, &[]).await.unwrap(); + + // Assert: the 37 undecided ones are closed as grouped (not as fixed), + // the decided one is left alone. + assert_eq!(closed, 37); + let single = row(&db, &stored[1].fingerprint).await; + assert_eq!(single.status, FindingStatus::Resolved); + let change = single + .status_history + .last() + .filter(|c| c.by == StatusChange::SCAN_ACTOR) + .and_then(|c| c.scan.as_ref()) + .map(|s| s.kind); + assert_eq!(change, Some(ScanChangeKind::Grouped)); + assert_eq!( + row(&db, &stored[0].fingerprint).await.status, + FindingStatus::FalsePositive + ); + let fp = group_fingerprint(TARGET, "mobsfscan", "android_logging"); + let group = row(&db, &fp).await; + assert_eq!(group.occurrences.len(), 38); + + // A person triages the group. + db.findings() + .update_one( + doc! { "fingerprint": &fp }, + doc! { "$set": { "status": "accepted_risk" } }, + ) + .await + .unwrap(); + + // Act: a rescan of the same tree finds nothing new. + let mut again = scan(1..=38); + let mut run = RunFindings::new("run-2"); + run.completed("mobsfscan"); + assert_eq!(run.save_new(&db, &mut again).await.unwrap(), 0); + + // Act: the places change (two more, one gone): still the same finding, + // its decision kept, its places updated. + let mut moved = scan(2..=40); + let mut run = RunFindings::new("run-3"); + run.completed("mobsfscan"); + assert_eq!(run.save_new(&db, &mut moved).await.unwrap(), 0); + run.write_back(&db, &mut moved).await.unwrap(); + run.resolve_missing(&db, TARGET, &[]).await.unwrap(); + let group = row(&db, &fp).await; + assert_eq!(group.status, FindingStatus::AcceptedRisk); + assert_eq!(group.occurrences.len(), 39); + assert_eq!(group.line_number, Some(2)); + assert!(group.description.contains("39 places")); + assert_eq!( + db.findings() + .count_documents(doc! { "repo_id": TARGET }) + .await + .unwrap(), + 39, + "38 single findings and one group, nothing else" + ); + + pool.drop_tenant(TENANT).await.ok(); +} diff --git a/compliance-core/src/models/finding.rs b/compliance-core/src/models/finding.rs index 631b41c..796e8db 100644 --- a/compliance-core/src/models/finding.rs +++ b/compliance-core/src/models/finding.rs @@ -133,6 +133,9 @@ pub enum ScanChangeKind { NowVendorCode, /// A finding marked resolved was reported again. FoundAgain, + /// Its rule fired often enough in the repository that its occurrences + /// are now one finding, which lists this one's place (#464). + Grouped, } /// The scan behind a [`StatusChange`]. @@ -142,6 +145,24 @@ pub struct ScanStatusChange { pub scan_run_id: String, } +/// One place a rule fired, in a finding that groups its occurrences. +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub struct Occurrence { + /// Repo-relative path. + pub file: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub line: Option, +} + +impl std::fmt::Display for Occurrence { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self.line { + Some(line) => write!(f, "{}:{line}", self.file), + None => write!(f, "{}", self.file), + } + } +} + #[derive(Debug, Clone, Serialize, Deserialize)] pub struct Finding { #[serde(rename = "_id", skip_serializing_if = "Option::is_none")] @@ -186,6 +207,11 @@ pub struct Finding { /// a scan made ([`StatusChange::scan`]). #[serde(default)] pub status_history: Vec, + /// Every place the rule fired, for a finding that stands for all + /// occurrences of one rule in the repository (#464); empty for a finding + /// at one place. `file_path`/`line_number` name the first of them. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub occurrences: Vec, #[serde(with = "super::serde_helpers::bson_datetime")] pub created_at: DateTime, #[serde(with = "super::serde_helpers::bson_datetime")] @@ -232,6 +258,7 @@ impl Finding { reported_by: None, reproduction: None, status_history: Vec::new(), + occurrences: Vec::new(), created_at: now, updated_at: now, } diff --git a/compliance-core/src/models/mod.rs b/compliance-core/src/models/mod.rs index 3613fe7..f301174 100644 --- a/compliance-core/src/models/mod.rs +++ b/compliance-core/src/models/mod.rs @@ -32,7 +32,7 @@ pub use dast::{ }; pub use embedding::{CodeEmbedding, EmbeddingBuildRun, EmbeddingBuildStatus}; pub use finding::{ - Finding, FindingStatus, ScanChangeKind, ScanStatusChange, Severity, StatusChange, + Finding, FindingStatus, Occurrence, ScanChangeKind, ScanStatusChange, Severity, StatusChange, }; pub use git_source::{GitSource, GitSourceView, SourceRepo, GIT_SOURCE_ID}; pub use graph::{ diff --git a/compliance-dashboard/src/i18n/texts.rs b/compliance-dashboard/src/i18n/texts.rs index 5093d14..ee7310f 100644 --- a/compliance-dashboard/src/i18n/texts.rs +++ b/compliance-dashboard/src/i18n/texts.rs @@ -1695,6 +1695,10 @@ pub mod findings { de: "Bei der Prüfung erneut gefunden.", en: "Found again by the scan.", }, + ScanChangeKind::Grouped => Text { + de: "Mit den anderen Stellen derselben Regel zu einem Befund zusammengefasst.", + en: "Combined with the other places of the same rule into one finding.", + }, } }