feat(controls): ship the master-controls snapshot; semantic mapping capped #403
No files matched your search
File diff suppressed because it is too large.
Load diff
@@ -269,6 +269,25 @@ mod tests {
|
||||
assert_eq!(doc.to_controls().len(), 40);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shipped_master_controls_snapshot_parses_with_its_declared_count() {
|
||||
// Taken once from breakpilot-compliance (#382); the semantic pass reads
|
||||
// it in snapshot-only mode, where the backend is not reachable.
|
||||
const SHIPPED: &str =
|
||||
include_str!("../../controls/snapshot/oscal-catalog-master-controls.json");
|
||||
let doc: OscalDocument = serde_json::from_str(SHIPPED).unwrap();
|
||||
let declared: usize = doc
|
||||
.catalog
|
||||
.metadata
|
||||
.props
|
||||
.iter()
|
||||
.find(|p| p.name == "control-count")
|
||||
.and_then(|p| p.value.parse().ok())
|
||||
.unwrap();
|
||||
assert_eq!(doc.to_controls().len(), declared);
|
||||
assert!(declared > 2_000, "{declared}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_control_map_and_the_shipped_catalog_name_the_same_controls() {
|
||||
// The map is ours, the catalog breakpilot-compliance's: a control one
|
||||
|
||||
@@ -10,6 +10,8 @@ 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;
|
||||
@@ -26,6 +28,12 @@ use crate::llm::LlmClient;
|
||||
|
||||
/// Nearest master controls judged per code region in the semantic pass.
|
||||
const SEMANTIC_TOP_K: usize = 5;
|
||||
/// 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;
|
||||
@@ -253,51 +261,42 @@ pub async fn semantic_stamp_findings(
|
||||
};
|
||||
let checker = SemanticControlChecker::new(LlmControlJudge::new(llm.clone()));
|
||||
|
||||
let mut tagged = 0;
|
||||
for finding in findings.iter_mut() {
|
||||
if finding.status == FindingStatus::FalsePositive {
|
||||
continue;
|
||||
}
|
||||
let (Some(file), Some(line)) = (finding.file_path.clone(), finding.line_number) else {
|
||||
continue;
|
||||
};
|
||||
let Some(region) = fetch_region(repo_path, &file, line) else {
|
||||
continue;
|
||||
};
|
||||
// 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 candidates = semantic_candidates(findings);
|
||||
let considered = findings
|
||||
.iter()
|
||||
.filter(|f| f.status != FindingStatus::FalsePositive && f.control_refs.is_empty())
|
||||
.count();
|
||||
if candidates.len() < considered {
|
||||
tracing::info!(
|
||||
"semantic pass: the {} most severe of {considered} unmapped findings",
|
||||
candidates.len()
|
||||
);
|
||||
let query_emb = match llm.embed(vec![query]).await {
|
||||
Ok(mut embs) => match embs.pop() {
|
||||
Some(v) => v,
|
||||
None => continue,
|
||||
},
|
||||
Err(e) => {
|
||||
tracing::warn!(error = %e, "query embed failed; skipping finding");
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
// 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 confirmed = checker
|
||||
.check(
|
||||
&index,
|
||||
®ion,
|
||||
&query_emb,
|
||||
SEMANTIC_TOP_K,
|
||||
&finding.repo_id,
|
||||
)
|
||||
.await;
|
||||
let before = finding.control_refs.len();
|
||||
for f in confirmed {
|
||||
for cref in f.control_refs {
|
||||
if !finding.control_refs.contains(&cref) {
|
||||
finding.control_refs.push(cref);
|
||||
}
|
||||
for cref in refs {
|
||||
if !finding.control_refs.contains(&cref) {
|
||||
finding.control_refs.push(cref);
|
||||
}
|
||||
}
|
||||
if finding.control_refs.len() > before {
|
||||
@@ -307,10 +306,106 @@ pub async fn semantic_stamp_findings(
|
||||
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)| {
|
||||
f.status != FindingStatus::FalsePositive
|
||||
&& 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()));
|
||||
|
||||
Reference in new issue
Block a user