CI / Check (push) Skipped
CI / Agent integration (push) Skipped
CI / Detect Changes (push) Successful in 6s
CI / Deploy Docs (push) Skipped
CI / Deploy MCP (push) Successful in 4m6s
CI / Deploy Dashboard (push) Successful in 5m38s
CI / Deploy Agent (push) Successful in 6m19s
"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>
453 lines
17 KiB
Rust
453 lines
17 KiB
Rust
//! Scan-pipeline integration for control triage.
|
|
//!
|
|
//! After the deterministic tools have produced findings, this stamps each finding
|
|
//! with the compliance control(s) it's evidence for and marks control-level false
|
|
//! positives — using the ingested OSCAL catalog for control text, the
|
|
//! `control-map` LUT for the finding→control link, and the grounded LLM judge to
|
|
//! confirm. Skipped entirely unless breakpilot is configured.
|
|
|
|
use std::collections::HashMap;
|
|
use std::path::Path;
|
|
use std::sync::Arc;
|
|
|
|
use futures_util::StreamExt;
|
|
|
|
use compliance_core::control_check::{CandidateRegion, ControlCheckSpec};
|
|
use compliance_core::models::finding::{Finding, FindingStatus, Severity};
|
|
use compliance_core::models::onboarding::ComplianceFramework;
|
|
use compliance_core::traits::Control;
|
|
use compliance_core::AgentConfig;
|
|
use control_map::ControlMap;
|
|
|
|
use super::surface;
|
|
use super::{
|
|
ControlIndex, ControlTriage, GroundedControlChecker, LlmControlJudge, OscalControlsProvider,
|
|
SemanticControlChecker, TriageOutcome,
|
|
};
|
|
use crate::llm::LlmClient;
|
|
|
|
/// Nearest master controls judged per code region in the semantic pass.
|
|
const SEMANTIC_TOP_K: usize = 5;
|
|
/// Control-triage judge calls in flight at once.
|
|
const CONTROL_TRIAGE_CONCURRENCY: usize = 8;
|
|
/// Most findings one scan maps semantically: each costs an embedding and up
|
|
/// to [`SEMANTIC_TOP_K`] judge calls, so an uncapped pass would add tens of
|
|
/// minutes to a large scan. The most severe unmapped ones go first.
|
|
const SEMANTIC_MAX_FINDINGS: usize = 40;
|
|
/// Findings judged at the same time.
|
|
const SEMANTIC_CONCURRENCY: usize = 4;
|
|
|
|
/// Lines of context to read on each side of a finding's line.
|
|
const REGION_WINDOW: usize = 6;
|
|
|
|
/// Triage every finding in `findings` against the CRA control map: stamp
|
|
/// `control_refs` on confirmed findings and flag control false positives. Returns
|
|
/// the number of findings tagged with at least one control.
|
|
pub async fn triage_repo_findings(
|
|
config: &AgentConfig,
|
|
llm: Arc<LlmClient>,
|
|
repo_path: &Path,
|
|
findings: &mut [Finding],
|
|
) -> usize {
|
|
let Some(provider) = provider_for(config) else {
|
|
return 0; // control triage is opt-in via BREAKPILOT_BASE_URL or a snapshot
|
|
};
|
|
let specs = build_specs(&provider).await;
|
|
if specs.is_empty() {
|
|
return 0;
|
|
}
|
|
let map = match ControlMap::cra() {
|
|
Ok(m) => m,
|
|
Err(e) => {
|
|
tracing::warn!(error = %e, "control map failed to load; skipping control triage");
|
|
return 0;
|
|
}
|
|
};
|
|
let triage = ControlTriage::new(LlmControlJudge::new(llm), map, specs);
|
|
|
|
// The judge reads each finding's code; its calls run a few at a time, and
|
|
// the outcomes are applied once all are in.
|
|
let candidates: Vec<(usize, CandidateRegion)> = findings
|
|
.iter()
|
|
.enumerate()
|
|
.filter_map(|(i, f)| {
|
|
let region = fetch_region(repo_path, f.file_path.as_deref()?, f.line_number?)?;
|
|
Some((i, region))
|
|
})
|
|
.collect();
|
|
let mut outcomes = Vec::with_capacity(candidates.len());
|
|
{
|
|
let read: &[Finding] = findings;
|
|
for group in candidates.chunks(CONTROL_TRIAGE_CONCURRENCY) {
|
|
let calls = group
|
|
.iter()
|
|
.map(|(i, region)| triage.triage(&read[*i], region));
|
|
outcomes.extend(futures_util::future::join_all(calls).await);
|
|
}
|
|
}
|
|
|
|
let mut tagged = 0;
|
|
for ((i, _), outcome) in candidates.iter().zip(outcomes) {
|
|
let finding = &mut findings[*i];
|
|
match outcome {
|
|
TriageOutcome::Confirmed(controls) => {
|
|
finding.control_refs = controls;
|
|
tagged += 1;
|
|
}
|
|
// The judge refuted the mapping: the finding stays, for a person
|
|
// to decide.
|
|
TriageOutcome::NeedsReview => {
|
|
finding.status = FindingStatus::NeedsReview;
|
|
finding.triage_action = Some(
|
|
compliance_core::models::finding::TRIAGE_CONTROL_NOT_CONFIRMED.to_string(),
|
|
);
|
|
finding.triage_rationale.get_or_insert_with(|| {
|
|
"The control check did not confirm the CRA requirements this \
|
|
finding maps to. Please review whether it is a real issue."
|
|
.to_string()
|
|
});
|
|
}
|
|
TriageOutcome::Undecided | TriageOutcome::Unmapped => {}
|
|
}
|
|
}
|
|
tagged
|
|
}
|
|
|
|
/// Build the control requirement specs (by id) from the ingested OSCAL catalog.
|
|
/// The catalog source for this agent: the breakpilot backend when
|
|
/// `BREAKPILOT_BASE_URL` is set, else the baked/previously written snapshots
|
|
/// under `BREAKPILOT_SNAPSHOT_DIR`. `None` = control triage is off.
|
|
pub(super) fn provider_for(config: &AgentConfig) -> Option<OscalControlsProvider> {
|
|
let snapshot_dir = Path::new(&config.breakpilot.snapshot_dir);
|
|
if config.breakpilot.base_url.is_none() && !OscalControlsProvider::has_snapshots(snapshot_dir) {
|
|
return None;
|
|
}
|
|
Some(OscalControlsProvider::new(
|
|
reqwest::Client::new(),
|
|
config.breakpilot.base_url.clone(),
|
|
config.breakpilot.token.clone(),
|
|
snapshot_dir,
|
|
))
|
|
}
|
|
|
|
/// The CRA catalog's controls by id (from the backend or the baked snapshot),
|
|
/// for the ratings the CRA status shows. Empty when no catalog is available.
|
|
pub async fn cra_catalog(config: &AgentConfig) -> HashMap<String, Control> {
|
|
let Some(provider) = provider_for(config) else {
|
|
return HashMap::new();
|
|
};
|
|
match provider.load(ComplianceFramework::Cra).await {
|
|
Ok(doc) => doc
|
|
.to_controls()
|
|
.into_iter()
|
|
.map(|c| (c.id.clone(), c))
|
|
.collect(),
|
|
Err(e) => {
|
|
tracing::warn!(error = %e, "could not load the CRA catalog");
|
|
HashMap::new()
|
|
}
|
|
}
|
|
}
|
|
|
|
async fn build_specs(provider: &OscalControlsProvider) -> HashMap<String, ControlCheckSpec> {
|
|
let mut specs = HashMap::new();
|
|
match provider.load(ComplianceFramework::Cra).await {
|
|
Ok(doc) => {
|
|
for control in doc.to_controls() {
|
|
specs.insert(
|
|
control.id.clone(),
|
|
ControlCheckSpec {
|
|
control_id: control.id,
|
|
title: control.title,
|
|
requirement: control.text,
|
|
default_cwe: None,
|
|
// The catalog's rating; Medium where it has none.
|
|
severity: control.severity.unwrap_or(Severity::Medium),
|
|
},
|
|
);
|
|
}
|
|
}
|
|
Err(e) => tracing::warn!(error = %e, "could not load control catalog for triage"),
|
|
}
|
|
specs
|
|
}
|
|
|
|
/// Absence-based control pass (the grounded half of the hybrid coverage): for each
|
|
/// control with a [`surface`] definition, deterministically retrieve the code
|
|
/// surfaces it governs (login routes, logging setup, update/download code) and have
|
|
/// the grounded judge decide whether the control holds there. Returns net-new
|
|
/// findings, each already tagged with its control and grounded to a real snippet.
|
|
///
|
|
/// The orchestrator runs this when `breakpilot.grounded_control_checks` is set
|
|
/// (on by default). Validated live; it covers the 8 absence-based CRA controls
|
|
/// (the judge decides presence/absence, grounded to a real snippet).
|
|
pub async fn grounded_surface_findings(
|
|
config: &AgentConfig,
|
|
llm: Arc<LlmClient>,
|
|
repo_path: &Path,
|
|
repo_id: &str,
|
|
) -> Vec<Finding> {
|
|
let Some(provider) = provider_for(config) else {
|
|
return Vec::new();
|
|
};
|
|
let specs = build_specs(&provider).await;
|
|
if specs.is_empty() {
|
|
return Vec::new();
|
|
}
|
|
let checker = GroundedControlChecker::new(LlmControlJudge::new(llm));
|
|
// The vendor SDK is not the customer's code: its surfaces are left out.
|
|
let tree = repo_path.to_path_buf();
|
|
let vendor = tokio::task::spawn_blocking(move || crate::pipeline::vendor::vendor_dirs(&tree))
|
|
.await
|
|
.unwrap_or_default();
|
|
|
|
let mut out = Vec::new();
|
|
for surf in surface::SURFACES {
|
|
let Some(spec) = specs.get(surf.control_id) else {
|
|
continue; // catalog doesn't carry this control
|
|
};
|
|
let regions = surface::retrieve(repo_path, surf.terms, &vendor);
|
|
if regions.is_empty() {
|
|
continue;
|
|
}
|
|
out.extend(checker.check(spec, ®ions, repo_id).await);
|
|
}
|
|
out
|
|
}
|
|
|
|
/// Read a window of lines around `line` (1-based) from `repo_path/file`.
|
|
fn fetch_region(repo_path: &Path, file: &str, line: u32) -> Option<CandidateRegion> {
|
|
let content = compliance_core::encoding::read_source(&repo_path.join(file)).ok()?;
|
|
let lines: Vec<&str> = content.lines().collect();
|
|
if lines.is_empty() {
|
|
return None;
|
|
}
|
|
let center = (line.saturating_sub(1) as usize).min(lines.len() - 1);
|
|
let start = center.saturating_sub(REGION_WINDOW);
|
|
let end = (center + REGION_WINDOW + 1).min(lines.len());
|
|
Some(CandidateRegion {
|
|
file: file.to_string(),
|
|
start_line: (start as u32) + 1,
|
|
content: lines[start..end].join("\n"),
|
|
})
|
|
}
|
|
|
|
/// Master-controls **semantic** pass: for each finding's code region, retrieve the
|
|
/// top-K nearest master controls by embedding, have the grounded judge confirm,
|
|
/// and stamp the confirmed control ids onto the finding — the scale path for the
|
|
/// ~13.6k master-control corpus (which has no CWE to LUT on). Returns the number
|
|
/// of findings that gained a master-control ref.
|
|
///
|
|
/// The orchestrator runs this when `breakpilot.semantic_mapping` is set (on by
|
|
/// default). The control embedding index is built once and cached to
|
|
/// `snapshot_dir` keyed by corpus hash ([`ControlIndex::load_or_build`]), so only
|
|
/// the first scan after a catalog change pays the embedding cost.
|
|
pub async fn semantic_stamp_findings(
|
|
config: &AgentConfig,
|
|
llm: Arc<LlmClient>,
|
|
repo_path: &Path,
|
|
findings: &mut [Finding],
|
|
) -> usize {
|
|
let Some(provider) = provider_for(config) else {
|
|
return 0;
|
|
};
|
|
let doc = match provider.load_master_controls().await {
|
|
Ok(d) => d,
|
|
Err(e) => {
|
|
tracing::warn!(error = %e, "master-controls catalog unavailable; skipping semantic pass");
|
|
return 0;
|
|
}
|
|
};
|
|
let specs: Vec<ControlCheckSpec> = doc
|
|
.to_controls()
|
|
.into_iter()
|
|
.map(|c| ControlCheckSpec {
|
|
control_id: c.id,
|
|
title: c.title,
|
|
requirement: c.text,
|
|
default_cwe: None,
|
|
severity: Severity::Medium,
|
|
})
|
|
.collect();
|
|
let cache_path =
|
|
Path::new(&config.breakpilot.snapshot_dir).join("control-index-master-controls.json");
|
|
let index = match ControlIndex::load_or_build(&llm, specs, &cache_path).await {
|
|
Ok(i) if !i.is_empty() => i,
|
|
Ok(_) => return 0,
|
|
Err(e) => {
|
|
tracing::warn!(error = %e, "failed to embed master-controls corpus");
|
|
return 0;
|
|
}
|
|
};
|
|
let checker = SemanticControlChecker::new(LlmControlJudge::new(llm.clone()));
|
|
|
|
let candidates = semantic_candidates(findings);
|
|
let considered = findings
|
|
.iter()
|
|
.filter(|f| {
|
|
!matches!(
|
|
f.status,
|
|
FindingStatus::FalsePositive | FindingStatus::WrongMapping
|
|
) && f.control_refs.is_empty()
|
|
})
|
|
.count();
|
|
if candidates.len() < considered {
|
|
tracing::info!(
|
|
"semantic pass: the {} most severe of {considered} unmapped findings",
|
|
candidates.len()
|
|
);
|
|
}
|
|
|
|
// Judged a few at a time: each finding costs an embedding and up to
|
|
// SEMANTIC_TOP_K judge calls.
|
|
let results: Vec<(usize, Vec<String>)> = {
|
|
let (index, checker, llm) = (&index, &checker, &llm);
|
|
let findings: &[Finding] = findings;
|
|
futures_util::stream::iter(candidates)
|
|
.map(|i| async move {
|
|
let refs = semantic_refs(llm, checker, index, repo_path, &findings[i]).await;
|
|
(i, refs)
|
|
})
|
|
.buffer_unordered(SEMANTIC_CONCURRENCY)
|
|
.collect()
|
|
.await
|
|
};
|
|
|
|
let mut tagged = 0;
|
|
for (i, refs) in results {
|
|
let Some(finding) = findings.get_mut(i) else {
|
|
continue;
|
|
};
|
|
let before = finding.control_refs.len();
|
|
for cref in refs {
|
|
if !finding.control_refs.contains(&cref) {
|
|
finding.control_refs.push(cref);
|
|
}
|
|
}
|
|
if finding.control_refs.len() > before {
|
|
tagged += 1;
|
|
}
|
|
}
|
|
tagged
|
|
}
|
|
|
|
/// The findings the semantic pass looks at, by index: not false positives,
|
|
/// not already mapped by the CRA triage, with a code location, most severe
|
|
/// first, at most [`SEMANTIC_MAX_FINDINGS`].
|
|
fn semantic_candidates(findings: &[Finding]) -> Vec<usize> {
|
|
let mut candidates: Vec<usize> = findings
|
|
.iter()
|
|
.enumerate()
|
|
.filter(|(_, f)| {
|
|
!matches!(
|
|
f.status,
|
|
FindingStatus::FalsePositive | FindingStatus::WrongMapping
|
|
) && f.control_refs.is_empty()
|
|
&& f.file_path.is_some()
|
|
&& f.line_number.is_some()
|
|
})
|
|
.map(|(i, _)| i)
|
|
.collect();
|
|
// Stable, so equally severe findings keep their scan order.
|
|
candidates.sort_by(|a, b| findings[*b].severity.cmp(&findings[*a].severity));
|
|
candidates.truncate(SEMANTIC_MAX_FINDINGS);
|
|
candidates
|
|
}
|
|
|
|
/// The master-control ids the judge confirms for one finding; empty when its
|
|
/// region cannot be read or embedded.
|
|
async fn semantic_refs(
|
|
llm: &LlmClient,
|
|
checker: &SemanticControlChecker<LlmControlJudge>,
|
|
index: &ControlIndex,
|
|
repo_path: &Path,
|
|
finding: &Finding,
|
|
) -> Vec<String> {
|
|
let (Some(file), Some(line)) = (finding.file_path.as_deref(), finding.line_number) else {
|
|
return Vec::new();
|
|
};
|
|
let Some(region) = fetch_region(repo_path, file, line) else {
|
|
return Vec::new();
|
|
};
|
|
// Retrieve on the finding's intent + the code, not the region alone: two
|
|
// findings in one file share overlapping windows and otherwise embed alike,
|
|
// collapsing onto the same controls. The finding's title/description carry
|
|
// the discriminating signal (e.g. "brute-force protection" vs "weak hash").
|
|
// The raw `region` still goes to the judge for snippet grounding.
|
|
let query = format!(
|
|
"{}\n{}\n\n{}",
|
|
finding.title, finding.description, region.content
|
|
);
|
|
let query_emb = match llm.embed(vec![query]).await {
|
|
Ok(mut embs) => match embs.pop() {
|
|
Some(v) => v,
|
|
None => return Vec::new(),
|
|
},
|
|
Err(e) => {
|
|
tracing::warn!(error = %e, "query embed failed; skipping finding");
|
|
return Vec::new();
|
|
}
|
|
};
|
|
checker
|
|
.check(index, ®ion, &query_emb, SEMANTIC_TOP_K, &finding.repo_id)
|
|
.await
|
|
.into_iter()
|
|
.flat_map(|f| f.control_refs)
|
|
.collect()
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
|
|
#[test]
|
|
fn the_semantic_pass_takes_the_most_severe_unmapped_findings() {
|
|
let mk = |severity: Severity, refs: &[&str], status: FindingStatus| {
|
|
let mut f = Finding::new(
|
|
"t".into(),
|
|
format!("fp-{severity}-{}", refs.len()),
|
|
"plc-control-logic".into(),
|
|
compliance_core::models::scan::ScanType::Sast,
|
|
"x".into(),
|
|
"d".into(),
|
|
severity,
|
|
);
|
|
f.file_path = Some("pump.st".into());
|
|
f.line_number = Some(3);
|
|
f.control_refs = refs.iter().map(|r| r.to_string()).collect();
|
|
f.status = status;
|
|
f
|
|
};
|
|
let findings = vec![
|
|
mk(Severity::Low, &[], FindingStatus::Open),
|
|
mk(Severity::Critical, &[], FindingStatus::Open),
|
|
mk(Severity::High, &["cra-ai-8"], FindingStatus::Open), // mapped already
|
|
mk(Severity::High, &[], FindingStatus::FalsePositive),
|
|
mk(Severity::High, &[], FindingStatus::NeedsReview),
|
|
];
|
|
assert_eq!(semantic_candidates(&findings), [1, 4, 0]);
|
|
|
|
let many: Vec<Finding> = (0..SEMANTIC_MAX_FINDINGS + 5)
|
|
.map(|_| mk(Severity::Medium, &[], FindingStatus::Open))
|
|
.collect();
|
|
assert_eq!(semantic_candidates(&many).len(), SEMANTIC_MAX_FINDINGS);
|
|
}
|
|
|
|
#[test]
|
|
fn fetch_region_windows_around_the_line() {
|
|
let dir = std::env::temp_dir().join(format!("triage-region-{}", uuid::Uuid::new_v4()));
|
|
std::fs::create_dir_all(&dir).unwrap();
|
|
let file = "a.py";
|
|
std::fs::write(dir.join(file), "l1\nl2\nl3\nSECRET=1\nl5\nl6\n").unwrap();
|
|
let r = fetch_region(&dir, file, 4).unwrap();
|
|
assert!(r.content.contains("SECRET=1"));
|
|
assert_eq!(r.start_line, 1); // window clamps to file start
|
|
let _ = std::fs::remove_dir_all(&dir);
|
|
}
|
|
|
|
#[test]
|
|
fn fetch_region_missing_file_is_none() {
|
|
assert!(fetch_region(Path::new("/nonexistent"), "nope.py", 1).is_none());
|
|
}
|
|
}
|