Files
pruefwerk/compliance-core/src/models/finding.rs
T
Sharang ParnerkarandClaude Opus 5.5 223db85f2a
CI / Check (push) Skipped
CI / Detect Changes (pull_request) Skipped
CI / Deploy Agent (pull_request) Skipped
CI / Deploy Dashboard (pull_request) Skipped
CI / Deploy Docs (pull_request) Skipped
CI / Deploy MCP (pull_request) Skipped
CI / Check (pull_request) Successful in 8m19s
feat(findings): keyed by the code they flag, not its line number (#491)
Closes #491. Fingerprints hashed repository/rule/file/line, so since the
auto-close (#443) and issue sync (#451) every line added above a finding
closed it and its tracker issue, reported it anew and lost its triage.

- RunFindings keys every finding at one place in a file by content
  (finding_store::content_fingerprints, applied with the variant labels
  before grouping and on save): repository, scanner, rule, file, the
  flagged line without whitespace, and the number of identical lines
  above it (two identical lines stay two findings). The idea of CodeQL's
  primaryLocationLineHash and CodeChecker's context-free-v2. Version-tagged
  ("content-v1").
- Per tool: gitleaks gives the matched secret as the content
  (Finding::fingerprint_content, never stored), as a hit from the history
  may not be on that line of the tree any more.
- One-time alias: the replaced line-based fingerprint is kept
  (Finding::legacy_fingerprints); the first scan after deploy finds the
  row stored under it and takes it over (fingerprint rewritten, old one
  recorded) instead of inserting, so the row keeps its id (tracker issue),
  status (a person's decisions included) and triage. Idempotent: later
  scans find the new fingerprint directly.
- A stored finding whose code moved is updated to its new line and snippet.
- Groups (#464/#477) keep their line-free key and never take over a
  member's former fingerprint.
- Unchanged: findings without file and line (CVE, malware, binaries,
  DAST), and the PLC path, which does not save through RunFindings.
- Tests: a line added above and re-indentation keep the fingerprint,
  twins stay distinct, a secret is keyed by its match, groups untouched;
  Mongo: pre-change rows are adopted with id/status kept, a later line
  shift gives no new row and no close/reopen, the line follows.
- Docs (findings guide); staging test plan: check 18.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EYKjxacrr6K88DruUmP48p
2026-10-06 12:25:29 +02:00

317 lines
11 KiB
Rust
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use super::scan::ScanType;
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)]
#[serde(rename_all = "lowercase")]
pub enum Severity {
Info,
Low,
Medium,
High,
Critical,
}
impl std::fmt::Display for Severity {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Info => write!(f, "info"),
Self::Low => write!(f, "low"),
Self::Medium => write!(f, "medium"),
Self::High => write!(f, "high"),
Self::Critical => write!(f, "critical"),
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[serde(rename_all = "snake_case")]
pub enum FindingStatus {
Open,
Triaged,
/// A person decided the rule fired wrongly: the finding is not real
/// ("Fehlalarm – Regel").
FalsePositive,
Resolved,
Ignored,
/// Known and deliberately not fixed; the reason is in the status history.
AcceptedRisk,
/// Flagged by the automated review (the LLM triage or the control judge)
/// as possibly not a real issue. It stays open until a person decides; no
/// finding is ever hidden automatically.
NeedsReview,
/// A person decided the finding does not violate the CRA requirement it
/// was mapped to ("Fehlalarm – Zuordnung"). The code issue may be real;
/// the finding keeps its control refs, so which mapping was wrong stays
/// on record, but it no longer counts against them.
WrongMapping,
}
impl FindingStatus {
/// Whether setting this status needs a reason from the person setting
/// it (recorded in the status history).
pub fn needs_reason(&self) -> bool {
matches!(self, Self::AcceptedRisk | Self::WrongMapping)
}
}
impl std::fmt::Display for FindingStatus {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Open => write!(f, "open"),
Self::Triaged => write!(f, "triaged"),
Self::FalsePositive => write!(f, "false_positive"),
Self::Resolved => write!(f, "resolved"),
Self::Ignored => write!(f, "ignored"),
Self::AcceptedRisk => write!(f, "accepted_risk"),
Self::NeedsReview => write!(f, "needs_review"),
Self::WrongMapping => write!(f, "wrong_mapping"),
}
}
}
/// One change of a finding's status: who made it, when, and why.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct StatusChange {
pub status: FindingStatus,
/// The user id of whoever changed it.
pub by: String,
/// How the customer reads who it was: a name, or "BreakPilot-Support
/// (name)"; absent in changes from before it was recorded.
#[serde(default)]
pub by_name: Option<String>,
/// Made by BreakPilot support rather than one of the tenant's users.
#[serde(default)]
pub support: bool,
#[serde(with = "super::serde_helpers::bson_datetime")]
pub at: DateTime<Utc>,
/// Why; required when a risk is accepted.
#[serde(default)]
pub reason: Option<String>,
/// Set when a scan changed the status rather than a person: why, and
/// which run.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub scan: Option<ScanStatusChange>,
}
impl StatusChange {
/// The `by` of every change a scan made.
pub const SCAN_ACTOR: &'static str = "pruefwerk-scan";
/// A change the scan run `scan_run_id` made, for the reason `kind`.
///
/// # Arguments
///
/// * `status` - the status the finding moves to
/// * `kind` - why the scan changed it
/// * `scan_run_id` - the run that changed it
pub fn by_scan(status: FindingStatus, kind: ScanChangeKind, scan_run_id: &str) -> Self {
Self {
status,
by: Self::SCAN_ACTOR.to_string(),
by_name: None,
support: false,
at: Utc::now(),
reason: None,
scan: Some(ScanStatusChange {
kind,
scan_run_id: scan_run_id.to_string(),
}),
}
}
}
/// Why a scan changed a finding's status.
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum ScanChangeKind {
/// The scanner that reported it completed and did not report it again:
/// the code was fixed or removed (or moved, which reports it anew).
NoLongerFound,
/// Its file now lies in vendor code, which is left out of the findings.
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,
/// 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`].
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct ScanStatusChange {
pub kind: ScanChangeKind,
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<u32>,
/// The app variant whose files hold this place (`Tablet App`), when the
/// repository has several.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub variant: Option<String>,
/// 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<FindingStatus>,
}
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)?,
}
if let Some(variant) = &self.variant {
write!(f, " ({variant})")?;
}
match &self.decision {
Some(decision) => write!(f, " [marked {decision}]"),
None => Ok(()),
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Finding {
#[serde(rename = "_id", skip_serializing_if = "Option::is_none")]
pub id: Option<bson::oid::ObjectId>,
pub repo_id: String,
pub fingerprint: String,
pub scanner: String,
pub scan_type: ScanType,
pub rule_id: Option<String>,
pub title: String,
pub description: String,
pub severity: Severity,
pub confidence: Option<f64>,
pub cwe: Option<String>,
pub cve: Option<String>,
pub cvss_score: Option<f64>,
pub file_path: Option<String>,
pub line_number: Option<u32>,
pub code_snippet: Option<String>,
pub remediation: Option<String>,
pub suggested_fix: Option<String>,
pub status: FindingStatus,
pub tracker_issue_url: Option<String>,
pub scan_run_id: Option<String>,
/// LLM triage action and reasoning
pub triage_action: Option<String>,
pub triage_rationale: Option<String>,
/// Developer feedback on finding quality
pub developer_feedback: Option<String>,
/// Compliance control ids this finding is evidence for (stamped by control
/// triage against the `control-map` LUT). Empty when unmapped.
#[serde(default)]
pub control_refs: Vec<String>,
/// Who entered or imported this finding by hand (a user id); `None` for
/// findings a scanner produced.
#[serde(default)]
pub reported_by: Option<String>,
/// How to reproduce the finding, for findings from a manual test.
#[serde(default)]
pub reproduction: Option<String>,
/// Every status change, oldest first: those made by a person, and those
/// a scan made ([`StatusChange::scan`]).
#[serde(default)]
pub status_history: Vec<StatusChange>,
/// 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<Occurrence>,
/// The app variant whose files hold the finding (`Tablet App`), when the
/// repository has several; for a group, the variant all its places share.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub variant: Option<String>,
/// Fingerprints this finding was stored under before (the line-based ones
/// before #491), so a later scan still recognises it.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub legacy_fingerprints: Vec<String>,
/// What identifies the flagged code when the scanner knows it better than
/// the line in the tree does (the matched secret of a finding from the
/// git history); never stored.
#[serde(skip)]
pub fingerprint_content: Option<String>,
#[serde(with = "super::serde_helpers::bson_datetime")]
pub created_at: DateTime<Utc>,
#[serde(with = "super::serde_helpers::bson_datetime")]
pub updated_at: DateTime<Utc>,
}
impl Finding {
pub fn new(
repo_id: String,
fingerprint: String,
scanner: String,
scan_type: ScanType,
title: String,
description: String,
severity: Severity,
) -> Self {
let now = Utc::now();
Self {
id: None,
repo_id,
fingerprint,
scanner,
scan_type,
rule_id: None,
title,
description,
severity,
confidence: None,
cwe: None,
cve: None,
cvss_score: None,
file_path: None,
line_number: None,
code_snippet: None,
remediation: None,
suggested_fix: None,
status: FindingStatus::Open,
tracker_issue_url: None,
scan_run_id: None,
triage_action: None,
triage_rationale: None,
developer_feedback: None,
control_refs: Vec::new(),
reported_by: None,
reproduction: None,
status_history: Vec::new(),
occurrences: Vec::new(),
variant: None,
legacy_fingerprints: Vec::new(),
fingerprint_content: None,
created_at: now,
updated_at: now,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn needs_review_reads_and_writes_as_needs_review() {
let wire = serde_json::to_string(&FindingStatus::NeedsReview).unwrap_or_default();
assert_eq!(wire, "\"needs_review\"");
assert_eq!(FindingStatus::NeedsReview.to_string(), "needs_review");
assert!(matches!(
serde_json::from_str::<FindingStatus>("\"needs_review\""),
Ok(FindingStatus::NeedsReview)
));
}
}