Files
pruefwerk/compliance-core/src/models/finding_group.rs
T
sharangandClaude Opus 5.5 6e97a0bf4c
CI / Check (push) Skipped
CI / Agent integration (push) Skipped
CI / Detect Changes (push) Successful in 5s
CI / Deploy Docs (push) Skipped
CI / Deploy MCP (push) Successful in 5m35s
CI / Deploy Dashboard (push) Successful in 7m38s
CI / Deploy Agent (push) Successful in 9m58s
feat(findings): group findings by rule and file, decide a group at once (#951) (#961)
Undecided findings are grouped on read, by target, tool, rule and file,
and by directory when a rule fires in three or more files of one
directory. A stored #464 group stays a group of its own. Nothing about
groups is stored.

- compliance-core: models::finding_group with the pure group_findings
  and members_of, for the findings list and later the Heute inbox.
- GET /api/v1/finding-groups[?target=] lists the groups;
  POST /api/v1/finding-groups/decide gives every undecided member the
  same status through the bulk path (status history, issue sync), so
  VEX and the evidence pack see ordinary per-finding changes.
- Findings list: Gruppiert / Einzeln toggle (default grouped) with group
  cards, the AI's reason, the places, and Fehlalarm / Risiko akzeptiert
  for all places of a group.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-10 16:01:15 +00:00

603 lines
20 KiB
Rust

//! Open findings grouped by rule and place, so that one decision covers
//! every place a rule fired in a file (#951).
//!
//! This is a read-side view: nothing is stored. The grouping (#464) that
//! turns a rule firing all over a repository into one stored finding stays
//! as it is; such a finding is shown here as a group of its own and never
//! merged with others.
//!
//! The rules:
//!
//! * Only undecided findings (open, triaged, needs review) are grouped; a
//! decided one already has its decision.
//! * Findings of one scanner's rule in one file of a target are one group.
//! * When a rule fires in [`DIRECTORY_MIN_FILES`] or more files of one
//! directory, those files are one group for the directory (the files
//! directly in it, not in its subdirectories).
//! * A stored #464 group is a group of its own.
use std::collections::{BTreeMap, HashMap, HashSet};
use bson::oid::ObjectId;
use serde::{Deserialize, Serialize};
use super::finding::{Finding, FindingStatus, Severity};
/// From how many files of one directory a rule's findings are one group
/// for the directory instead of one per file.
pub const DIRECTORY_MIN_FILES: usize = 3;
/// What a group spans.
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[serde(rename_all = "snake_case")]
pub enum GroupScope {
/// The places of a rule in one file.
File,
/// The places of a rule in the files of one directory.
Directory,
/// A finding the scan already grouped for the whole repository (#464).
Repository,
}
/// What identifies a group, from the view to the decision: the decision
/// finds the group's members again from it, so it applies to what is open
/// then, not to what a stale view showed.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct GroupKey {
/// The target (`Finding::repo_id`).
pub repo_id: String,
/// The tool that reported it; rule ids are per tool.
pub scanner: String,
/// The rule id, or the title for a finding without one.
pub rule: String,
pub scope: GroupScope,
/// The file ([`GroupScope::File`]), the directory, `""` for the top
/// level ([`GroupScope::Directory`]), or the stored group's fingerprint
/// ([`GroupScope::Repository`]). `None` for findings without a file
/// (a dependency, a web endpoint).
#[serde(default, skip_serializing_if = "Option::is_none")]
pub place: Option<String>,
}
impl GroupKey {
/// The key as one string, for telling groups apart in a view.
pub fn id(&self) -> String {
let scope = match self.scope {
GroupScope::File => "file",
GroupScope::Directory => "dir",
GroupScope::Repository => "repo",
};
format!(
"{}|{}|{}|{scope}|{}",
self.repo_id,
self.scanner,
self.rule,
self.place.as_deref().unwrap_or_default()
)
}
}
/// What the automated review said about a group's members.
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
pub struct GroupReview {
/// Members the AI dismissed: likely a false alarm.
pub likely_false_alarm: usize,
/// Members the AI was unsure about.
pub unsure: usize,
/// The AI's reason for the first of them (a dismissal first).
#[serde(default, skip_serializing_if = "Option::is_none")]
pub rationale: Option<String>,
}
/// Undecided findings of one rule in one place, decided together.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FindingGroup {
pub key: GroupKey,
/// The title of the first member, as the tool wrote it.
pub title: String,
/// The highest severity among the members.
pub severity: Severity,
/// How many places the members stand for: one each, or every place of
/// a stored #464 group.
pub places: usize,
/// Set when the AI flagged members for review.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub review: Option<GroupReview>,
/// The findings, by file and line.
pub members: Vec<Finding>,
}
impl FindingGroup {
/// The group of `members` (at least one) under `key`.
fn new(key: GroupKey, mut members: Vec<Finding>) -> Self {
// `Option` sorts `None` first; members without a line lead.
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()
.unwrap_or(Severity::Info);
let places = members.iter().map(|f| f.occurrences.len().max(1)).sum();
Self {
title: members.first().map(|f| f.title.clone()).unwrap_or_default(),
review: review_of(&members),
key,
severity,
places,
members,
}
}
/// The ids of the members.
pub fn member_ids(&self) -> Vec<ObjectId> {
self.members.iter().filter_map(|f| f.id).collect()
}
}
/// Whether no person has decided about a finding with `status` yet.
pub fn is_undecided(status: &FindingStatus) -> bool {
match status {
FindingStatus::Open | FindingStatus::Triaged | FindingStatus::NeedsReview => true,
FindingStatus::FalsePositive
| FindingStatus::Resolved
| FindingStatus::Ignored
| FindingStatus::AcceptedRisk
| FindingStatus::WrongMapping => false,
}
}
/// What the AI's review said about one finding.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum AiReview {
/// It dismissed the finding.
LikelyFalseAlarm,
/// It was not confident either way.
Unsure,
}
/// The AI's review of `finding`, when it left the finding for a person.
///
/// Mirrors the predicate PR #958 adds as `Finding::review_reason()`; switch
/// to that once it is merged.
fn ai_review(finding: &Finding) -> Option<AiReview> {
if finding.status != FindingStatus::NeedsReview {
return None;
}
Some(match finding.triage_action.as_deref() {
Some("dismiss") => AiReview::LikelyFalseAlarm,
_ => AiReview::Unsure,
})
}
/// What the AI said about `members`, `None` when it flagged none of them.
fn review_of(members: &[Finding]) -> Option<GroupReview> {
let mut review = GroupReview::default();
let mut unsure_rationale = None;
for finding in members {
let rationale = finding
.triage_rationale
.as_deref()
.map(str::trim)
.filter(|r| !r.is_empty());
match ai_review(finding) {
Some(AiReview::LikelyFalseAlarm) => {
review.likely_false_alarm += 1;
review.rationale = review.rationale.or_else(|| rationale.map(String::from));
}
Some(AiReview::Unsure) => {
review.unsure += 1;
unsure_rationale = unsure_rationale.or(rationale);
}
None => {}
}
}
if review.likely_false_alarm + review.unsure == 0 {
return None;
}
review.rationale = review
.rationale
.or_else(|| unsure_rationale.map(String::from));
Some(review)
}
/// The rule a finding is grouped by: its id, or its title without one.
fn rule_of(finding: &Finding) -> String {
finding
.rule_id
.as_deref()
.filter(|r| !r.is_empty())
.unwrap_or(&finding.title)
.to_string()
}
/// The directory of a repo-relative `path`, `""` at the top level.
fn parent_dir(path: &str) -> &str {
path.rfind(['/', '\\']).map_or("", |i| &path[..i])
}
/// A rule of one tool in one target: (target, scanner, rule).
type RuleInTarget = (String, String, String);
/// Findings by their file (`None`: without one).
type ByFile = BTreeMap<Option<String>, Vec<Finding>>;
/// Group the undecided ones among `findings` (see the module docs); decided
/// findings are left out.
///
/// # Returns
///
/// The groups, most severe first, then the ones with the most places.
///
/// # Examples
///
/// ```
/// use compliance_core::models::finding_group::group_findings;
/// use compliance_core::models::{Finding, ScanType, Severity};
///
/// let at = |line| {
/// let mut f = Finding::new(
/// "repo".into(), format!("fp-{line}"), "gdpr-patterns".into(),
/// ScanType::Sast, "PII data potentially logged".into(), "".into(),
/// Severity::Medium,
/// );
/// f.rule_id = Some("pii-logged".into());
/// f.file_path = Some("src/patterns.rs".into());
/// f.line_number = Some(line);
/// f
/// };
/// let groups = group_findings(vec![at(299), at(302)]);
/// assert_eq!(groups.len(), 1);
/// assert_eq!(groups[0].places, 2);
/// ```
pub fn group_findings(findings: impl IntoIterator<Item = Finding>) -> Vec<FindingGroup> {
let mut groups = Vec::new();
let mut by_rule: HashMap<RuleInTarget, ByFile> = HashMap::new();
for finding in findings.into_iter().filter(|f| is_undecided(&f.status)) {
let rule = rule_of(&finding);
if !finding.occurrences.is_empty() {
let key = GroupKey {
repo_id: finding.repo_id.clone(),
scanner: finding.scanner.clone(),
rule,
scope: GroupScope::Repository,
place: Some(finding.fingerprint.clone()),
};
groups.push(FindingGroup::new(key, vec![finding]));
continue;
}
let file = finding.file_path.clone().filter(|p| !p.is_empty());
by_rule
.entry((finding.repo_id.clone(), finding.scanner.clone(), rule))
.or_default()
.entry(file)
.or_default()
.push(finding);
}
for ((repo_id, scanner, rule), by_file) in by_rule {
let key = |scope, place| GroupKey {
repo_id: repo_id.clone(),
scanner: scanner.clone(),
rule: rule.clone(),
scope,
place,
};
let mut files_per_dir: HashMap<&str, usize> = HashMap::new();
for file in by_file.keys().flatten() {
*files_per_dir.entry(parent_dir(file)).or_default() += 1;
}
let wide_dirs: HashSet<String> = files_per_dir
.into_iter()
.filter(|(_, files)| *files >= DIRECTORY_MIN_FILES)
.map(|(dir, _)| dir.to_string())
.collect();
let mut by_dir: BTreeMap<String, Vec<Finding>> = BTreeMap::new();
for (file, members) in by_file {
match file {
Some(file) if wide_dirs.contains(parent_dir(&file)) => by_dir
.entry(parent_dir(&file).to_string())
.or_default()
.extend(members),
file => groups.push(FindingGroup::new(key(GroupScope::File, file), members)),
}
}
groups.extend(by_dir.into_iter().map(|(dir, members)| {
FindingGroup::new(key(GroupScope::Directory, Some(dir)), members)
}));
}
groups.sort_by(|a, b| {
b.severity
.cmp(&a.severity)
.then(b.places.cmp(&a.places))
.then_with(|| a.key.cmp(&b.key))
});
groups
}
/// The ids of the undecided findings among `findings` that make up the
/// group `key`; empty when there is no such group (any more).
pub fn members_of(findings: impl IntoIterator<Item = Finding>, key: &GroupKey) -> Vec<ObjectId> {
group_findings(findings)
.into_iter()
.find(|g| g.key == *key)
.map(|g| g.member_ids())
.unwrap_or_default()
}
#[cfg(test)]
mod tests {
use super::*;
use crate::models::{Occurrence, ScanType};
fn finding(rule: &str, file: &str, line: u32) -> Finding {
let mut f = Finding::new(
"repo-1".into(),
format!("fp-{file}-{line}"),
"gdpr-patterns".into(),
ScanType::Sast,
"PII data potentially logged".into(),
"d".into(),
Severity::Medium,
);
f.id = Some(ObjectId::new());
f.rule_id = Some(rule.into());
f.file_path = Some(file.into());
f.line_number = Some(line);
f
}
fn scopes(groups: &[FindingGroup]) -> Vec<(GroupScope, Option<&str>, usize)> {
groups
.iter()
.map(|g| (g.key.scope, g.key.place.as_deref(), g.members.len()))
.collect()
}
#[test]
fn one_rule_in_one_file_is_one_group() {
let groups = group_findings(vec![
finding("pii-logged", "src/patterns.rs", 302),
finding("pii-logged", "src/patterns.rs", 299),
finding("pii-logged", "src/patterns.rs", 301),
]);
assert_eq!(
scopes(&groups),
[(GroupScope::File, Some("src/patterns.rs"), 3)]
);
assert_eq!(groups[0].places, 3);
let lines: Vec<_> = groups[0].members.iter().map(|f| f.line_number).collect();
assert_eq!(lines, [Some(299), Some(301), Some(302)]);
}
#[test]
fn other_files_and_other_rules_are_other_groups() {
let groups = group_findings(vec![
finding("pii-logged", "src/a.rs", 1),
finding("pii-logged", "lib/b.rs", 1),
finding("other-rule", "src/a.rs", 2),
]);
assert_eq!(groups.len(), 3);
assert!(groups.iter().all(|g| g.key.scope == GroupScope::File));
}
#[test]
fn the_same_rule_id_of_another_tool_is_another_group() {
let mut other = finding("pii-logged", "src/a.rs", 2);
other.scanner = "semgrep".into();
let groups = group_findings(vec![finding("pii-logged", "src/a.rs", 1), other]);
assert_eq!(groups.len(), 2);
}
#[test]
fn many_files_of_one_directory_are_one_group() {
let groups = group_findings(vec![
finding("pii-logged", "src/api/a.rs", 1),
finding("pii-logged", "src/api/a.rs", 9),
finding("pii-logged", "src/api/b.rs", 1),
finding("pii-logged", "src/api/c.rs", 1),
// A subdirectory and another directory stay apart.
finding("pii-logged", "src/api/v2/d.rs", 1),
finding("pii-logged", "src/e.rs", 1),
]);
let mut found = scopes(&groups);
found.sort();
assert_eq!(
found,
[
(GroupScope::File, Some("src/api/v2/d.rs"), 1),
(GroupScope::File, Some("src/e.rs"), 1),
(GroupScope::Directory, Some("src/api"), 4),
]
);
}
#[test]
fn fewer_files_than_the_directory_needs_stay_one_group_per_file() {
let groups = group_findings(vec![
finding("pii-logged", "src/a.rs", 1),
finding("pii-logged", "src/b.rs", 1),
]);
assert_eq!(groups.len(), DIRECTORY_MIN_FILES - 1);
assert!(groups.iter().all(|g| g.key.scope == GroupScope::File));
}
#[test]
fn top_level_files_group_under_the_empty_directory() {
let groups = group_findings(vec![
finding("pii-logged", "a.rs", 1),
finding("pii-logged", "b.rs", 1),
finding("pii-logged", "c.rs", 1),
]);
assert_eq!(scopes(&groups), [(GroupScope::Directory, Some(""), 3)]);
}
#[test]
fn decided_findings_are_left_out() {
let mut decided = finding("pii-logged", "src/a.rs", 2);
decided.status = FindingStatus::FalsePositive;
let mut accepted = finding("pii-logged", "src/a.rs", 3);
accepted.status = FindingStatus::AcceptedRisk;
let mut triaged = finding("pii-logged", "src/a.rs", 4);
triaged.status = FindingStatus::Triaged;
let groups = group_findings(vec![
finding("pii-logged", "src/a.rs", 1),
decided,
accepted,
triaged,
]);
assert_eq!(scopes(&groups), [(GroupScope::File, Some("src/a.rs"), 2)]);
assert!(group_findings(vec![{
let mut f = finding("r", "x.rs", 1);
f.status = FindingStatus::Resolved;
f
}])
.is_empty());
}
#[test]
fn a_stored_group_stays_a_group_of_its_own() {
let mut stored = finding("pii-logged", "src/a.rs", 1);
stored.fingerprint = "group-fp".into();
stored.occurrences = (1..=7)
.map(|line| Occurrence {
file: "src/a.rs".into(),
line: Some(line),
variant: None,
decision: None,
})
.collect();
let groups = group_findings(vec![stored, finding("pii-logged", "src/a.rs", 20)]);
assert_eq!(
scopes(&groups),
[
(GroupScope::Repository, Some("group-fp"), 1),
(GroupScope::File, Some("src/a.rs"), 1),
]
);
assert_eq!(groups[0].places, 7);
}
#[test]
fn findings_without_a_file_or_rule_still_group() {
let mut no_file = finding("CVE-2024-1", "", 0);
no_file.file_path = None;
let mut no_file_2 = no_file.clone();
no_file_2.id = Some(ObjectId::new());
let mut no_rule = finding("", "src/a.rs", 1);
no_rule.rule_id = None;
let groups = group_findings(vec![no_file, no_file_2, no_rule]);
let mut found: Vec<_> = groups
.iter()
.map(|g| (g.key.rule.as_str(), g.key.place.as_deref(), g.members.len()))
.collect();
found.sort();
assert_eq!(
found,
[
("CVE-2024-1", None, 2),
("PII data potentially logged", Some("src/a.rs"), 1),
]
);
}
#[test]
fn the_most_severe_group_leads() {
let mut critical = finding("hardcoded-key", "src/z.rs", 1);
critical.severity = Severity::Critical;
let groups = group_findings(vec![
finding("pii-logged", "src/a.rs", 1),
finding("pii-logged", "src/a.rs", 2),
critical,
]);
assert_eq!(groups[0].severity, Severity::Critical);
assert_eq!(groups[1].places, 2);
}
#[test]
fn the_group_carries_the_ais_reason() {
let mut dismissed = finding("pii-logged", "src/a.rs", 1);
dismissed.status = FindingStatus::NeedsReview;
dismissed.triage_action = Some("dismiss".into());
dismissed.triage_rationale = Some(" Only a user id, no PII. ".into());
let mut unsure = finding("pii-logged", "src/a.rs", 2);
unsure.status = FindingStatus::NeedsReview;
unsure.triage_action = Some("confirm".into());
unsure.triage_rationale = Some("Unclear".into());
let groups = group_findings(vec![
unsure,
dismissed,
finding("pii-logged", "src/a.rs", 3),
]);
assert_eq!(
groups[0].review,
Some(GroupReview {
likely_false_alarm: 1,
unsure: 1,
rationale: Some("Only a user id, no PII.".into()),
})
);
assert_eq!(
group_findings(vec![finding("r", "a.rs", 1)])[0].review,
None
);
}
#[test]
fn the_members_of_a_key_are_found_again() {
let one = finding("pii-logged", "src/a.rs", 1);
let two = finding("pii-logged", "src/a.rs", 2);
let other = finding("pii-logged", "src/b.rs", 1);
let ids = [one.id, two.id];
let all = vec![one, two, other];
let key = GroupKey {
repo_id: "repo-1".into(),
scanner: "gdpr-patterns".into(),
rule: "pii-logged".into(),
scope: GroupScope::File,
place: Some("src/a.rs".into()),
};
let mut found: Vec<_> = members_of(all.clone(), &key)
.into_iter()
.map(Some)
.collect();
found.sort();
let mut expected = ids.to_vec();
expected.sort();
assert_eq!(found, expected);
let gone = GroupKey {
place: Some("src/c.rs".into()),
..key
};
assert!(members_of(all, &gone).is_empty());
}
#[test]
fn a_key_reads_and_writes_by_its_names() {
let key = GroupKey {
repo_id: "r".into(),
scanner: "s".into(),
rule: "x".into(),
scope: GroupScope::Directory,
place: Some("src".into()),
};
let wire = serde_json::to_value(&key).unwrap_or_default();
assert_eq!(wire["scope"], "directory");
assert_eq!(
serde_json::from_value::<GroupKey>(wire).ok().as_ref(),
Some(&key)
);
assert_ne!(
key.id(),
GroupKey {
scope: GroupScope::File,
..key.clone()
}
.id()
);
}
}