Files
pruefwerk/compliance-core/src/models/finding.rs
T
Sharang ParnerkarandClaude Opus 5.5 0e9077181c
CI / Check (push) Skipped
CI / Detect Changes (pull_request) Skipped
CI / Agent integration (pull_request) Successful in 4m5s
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 17m45s
feat(findings): say why a finding needs review — AI false alarm or AI unsure (#954)
"Zu prüfen" now says which of the two cases put it there: the LLM triage
dismissed the finding as a likely false alarm ("KI: wohl Fehlalarm"), or it
confirmed it with too little confidence ("KI: unsicher"). The reason is read
from the verdict already stored on the finding (triage_action, confidence),
so findings from before this change get it too; the wire status stays
needs_review.

- core: ReviewReason, ReviewReason::of_verdict and Finding::review_reason;
  the triage's confidence threshold and its action markers move to core.
- agent: apply_action decides through ReviewReason::of_verdict, so the
  triage and the label cannot drift apart.
- dashboard: the list and the finding page show the reason instead of the
  bare status, the list with the AI's rationale on hover; the finding page
  confirms ("Fehlalarm bestätigen", false positive with the rationale as
  reason) or rejects ("Doch prüfen", triaged) the AI's guess in one click,
  for roles that may change a status.

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

448 lines
16 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,
/// Its file now lies in test data (`fixtures/`, `testdata/`), which is
/// left out of the scan.
NowTestData,
/// Its file now lies in a path the target's settings exclude from the
/// scan (`scan_config.exclude_paths`).
NowExcluded,
/// 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,
}
}
}
/// `triage_action` of a finding the LLM triage judged a false alarm.
pub const TRIAGE_DISMISS: &str = "dismiss";
/// `triage_action` of a finding the LLM triage gave no verdict; the reason is
/// in `triage_rationale`, which starts with `skipped: <reason>`.
pub const TRIAGE_SKIPPED: &str = "skipped";
/// `triage_action` of a finding the control check did not confirm against the
/// CRA requirements it maps to.
pub const TRIAGE_CONTROL_NOT_CONFIRMED: &str = "control_not_confirmed";
/// Least confidence (0-10, as stored in `confidence`) at which the LLM triage
/// takes a confirmed finding as triaged; below it the finding needs review.
pub const TRIAGE_CONFIDENCE_THRESHOLD: f64 = 3.0;
/// Why the LLM triage left a finding to a person ([`FindingStatus::NeedsReview`]).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ReviewReason {
/// The model dismissed the finding as a likely false alarm.
LikelyFalseAlarm,
/// The model confirmed the finding, but with too little confidence.
Unsure,
}
impl ReviewReason {
/// Why a verdict of the model leaves a finding to a person; `None` when
/// the verdict decides it (confirmed, downgraded or upgraded).
///
/// # Arguments
///
/// * `action` - the model's action (`confirm`, `dismiss`, ...); an unknown
/// one counts as `confirm`
/// * `confidence` - the model's confidence, as stored in `confidence`
pub fn of_verdict(action: &str, confidence: f64) -> Option<Self> {
match action {
TRIAGE_DISMISS => Some(Self::LikelyFalseAlarm),
"downgrade" | "upgrade" => None,
_ if confidence < TRIAGE_CONFIDENCE_THRESHOLD => Some(Self::Unsure),
_ => None,
}
}
}
impl Finding {
/// Why the LLM triage left this finding to a person, read from its stored
/// verdict (`triage_action`, `confidence`); `None` unless it needs review
/// because of that verdict (also when the triage skipped it or the control
/// check put it there).
pub fn review_reason(&self) -> Option<ReviewReason> {
if self.status != FindingStatus::NeedsReview {
return None;
}
match self.triage_action.as_deref()? {
TRIAGE_SKIPPED | TRIAGE_CONTROL_NOT_CONFIRMED => None,
action => ReviewReason::of_verdict(action, self.confidence?),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
/// A finding as the LLM triage leaves it.
fn reviewed(status: FindingStatus, action: &str, confidence: Option<f64>) -> Finding {
let mut finding = Finding::new(
"repo".to_string(),
"fp".to_string(),
"semgrep".to_string(),
ScanType::Sast,
"title".to_string(),
"description".to_string(),
Severity::High,
);
finding.status = status;
finding.triage_action = Some(action.to_string());
finding.confidence = confidence;
finding
}
#[test]
fn a_dismissed_finding_needs_review_as_a_likely_false_alarm() {
let finding = reviewed(FindingStatus::NeedsReview, TRIAGE_DISMISS, Some(9.0));
assert_eq!(
finding.review_reason(),
Some(ReviewReason::LikelyFalseAlarm)
);
}
#[test]
fn a_confirmation_below_the_threshold_is_unsure() {
let unsure = reviewed(FindingStatus::NeedsReview, "confirm", Some(2.9));
assert_eq!(unsure.review_reason(), Some(ReviewReason::Unsure));
// An unknown action counts as a confirmation, as in the triage.
let unknown = reviewed(FindingStatus::NeedsReview, "keep", Some(1.0));
assert_eq!(unknown.review_reason(), Some(ReviewReason::Unsure));
let sure = reviewed(FindingStatus::NeedsReview, "confirm", Some(3.0));
assert_eq!(sure.review_reason(), None);
}
#[test]
fn only_a_finding_that_needs_review_has_a_reason() {
let decided = reviewed(FindingStatus::FalsePositive, TRIAGE_DISMISS, Some(9.0));
assert_eq!(decided.review_reason(), None);
let triaged = reviewed(FindingStatus::Triaged, "confirm", Some(1.0));
assert_eq!(triaged.review_reason(), None);
}
#[test]
fn a_finding_the_model_did_not_put_up_for_review_has_no_reason() {
let mut untriaged = reviewed(FindingStatus::NeedsReview, "confirm", Some(1.0));
untriaged.triage_action = None;
assert_eq!(untriaged.review_reason(), None);
// The control check keeps the model's confidence: it is not the reason.
let control = reviewed(
FindingStatus::NeedsReview,
TRIAGE_CONTROL_NOT_CONFIRMED,
Some(1.0),
);
assert_eq!(control.review_reason(), None);
let skipped = reviewed(FindingStatus::NeedsReview, TRIAGE_SKIPPED, Some(0.5));
assert_eq!(skipped.review_reason(), None);
let no_confidence = reviewed(FindingStatus::NeedsReview, "confirm", None);
assert_eq!(no_confidence.review_reason(), None);
}
#[test]
fn a_change_of_severity_decides_the_finding() {
assert_eq!(ReviewReason::of_verdict("downgrade", 0.0), None);
assert_eq!(ReviewReason::of_verdict("upgrade", 0.0), None);
}
#[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)
));
}
}