fix(scan): findings in test data and excluded paths close, whichever scanner stored them #904

Merged
sharang merged 1 commits from fix/left-out-findings-resolve into main 2026-11-05 17:56:01 +00:00
3 changed files with 119 additions and 18 deletions

No files matched your search

+35 -12
View File
@@ -782,12 +782,24 @@ impl RunFindings {
Ok(closed)
}
/// Close the undecided findings of `scanner` on target `target_id` whose
/// file lies in the excluded paths or the test data this run left out
/// Close the undecided findings on target `target_id` whose file lies in
/// the excluded paths or the test data this run left out
/// ([`Self::with_excluded`], [`Self::with_test_data`]), each with its
/// reason. For a stage that stores its findings without this object (the
/// PLC analysis), so nothing it no longer sees is closed as fixed; only
/// what was left out.
/// reason. Nothing is closed as fixed; only what was left out.
///
/// [`Self::resolve_missing`] only closes what a scanner that completed no
/// longer reports. A scanner that did not run cannot close its findings in
/// a left-out path, although nothing can see them any more: cppcheck runs
/// only on a tree with C, so once a fixture held the tree's only C, its
/// findings would stay open for good. This closes them, whichever scanner
/// stored them. A finding this run reported again is kept.
///
/// # Arguments
///
/// * `db` - the tenant database
/// * `target_id` - the scanned target (`Finding::repo_id`)
/// * `scanner` - only this scanner's findings (a stage that stores its
/// findings without this object, the PLC analysis), or `None` for all
///
/// # Returns
///
@@ -800,20 +812,23 @@ impl RunFindings {
&mut self,
db: &Database,
target_id: &str,
scanner: &str,
scanner: Option<&str>,
) -> Result<u32, AgentError> {
if self.excluded.is_empty() && self.test_data.is_empty() {
return Ok(0);
}
let mut filter = doc! {
"repo_id": target_id,
"status": { "$in": UNDECIDED.to_vec() },
};
if let Some(scanner) = scanner {
filter.insert("scanner", scanner);
}
let rows: Vec<Document> = db
.findings()
.clone_with_type::<Document>()
.find(doc! {
"repo_id": target_id,
"scanner": scanner,
"status": { "$in": UNDECIDED.to_vec() },
})
.projection(doc! { "file_path": 1 })
.find(filter)
.projection(doc! { "fingerprint": 1, "file_path": 1 })
.await?
.try_collect()
.await?;
@@ -822,6 +837,14 @@ impl RunFindings {
let (Ok(id), Ok(file)) = (row.get_object_id("_id"), row.get_str("file_path")) else {
continue;
};
// Something in this run still reports it, so it is not left out:
// closing it would only see it reopened by the next run.
let reported = row
.get_str("fingerprint")
.is_ok_and(|fp| self.inserted.contains_key(fp) || self.earlier.contains(fp));
if reported {
continue;
}
if crate::pipeline::vendor::in_vendor_dir(file, &self.excluded) {
excluded.push(id);
} else if crate::pipeline::vendor::in_vendor_dir(file, &self.test_data) {
+20 -5
View File
@@ -255,6 +255,14 @@ impl PipelineOrchestrator {
tokio::task::spawn_blocking(move || crate::pipeline::variants::app_variants(&tree))
.await
.unwrap_or_default();
// Left out of the tree, but a scanner that walks the git history
// (gitleaks) still sees what was committed there.
let left_out_dirs: Vec<String> = left_out
.excluded
.iter()
.chain(&left_out.test_data)
.cloned()
.collect();
let mut run_findings = crate::pipeline::finding_store::RunFindings::new(scan_run_id)
.with_variants(variants)
.with_tree(repo_path.clone())
@@ -293,12 +301,14 @@ impl PipelineOrchestrator {
.await;
}
// The same vendor code is left out of every code scanner's findings:
// the pattern, secret and lint scanners walk the whole tree.
// the pattern, secret and lint scanners walk the whole tree. So are the
// left-out paths, for the secret scanner, which reads the history.
let outside_vendor = |findings: &mut Vec<Finding>| {
findings.retain(|f| {
!f.file_path
.as_deref()
.is_some_and(|p| crate::pipeline::vendor::in_vendor_dir(p, &vendor))
!f.file_path.as_deref().is_some_and(|p| {
crate::pipeline::vendor::in_vendor_dir(p, &vendor)
|| crate::pipeline::vendor::in_vendor_dir(p, &left_out_dirs)
})
})
};
match SemgrepScanner::new(vendor.clone())
@@ -997,6 +1007,11 @@ impl PipelineOrchestrator {
run_findings
.resolve_missing(&self.db, &repo_id, &vendor)
.await?;
// And what an earlier scan stored in a left-out path, also of a scanner
// that did not run this time.
run_findings
.resolve_left_out(&self.db, &repo_id, None)
.await?;
// Their issues follow: closed with a comment, or reopened.
crate::pipeline::issue_sync::IssueSync {
db: self.db.clone(),
@@ -1594,7 +1609,7 @@ impl PipelineOrchestrator {
.with_excluded(left_out.excluded)
.with_test_data(left_out.test_data);
let closed = left_out_run
.resolve_left_out(&self.db, target_id, "plc-control-logic")
.resolve_left_out(&self.db, target_id, Some("plc-control-logic"))
.await?;
if closed > 0 {
tracing::info!(target_id, closed, "PLC findings in left-out paths resolved");
+64 -1
View File
@@ -196,7 +196,7 @@ async fn only_what_was_left_out_is_closed_for_a_stage_without_a_seen_set() {
.with_excluded(vec!["legacy".to_string()])
.with_test_data(vec!["fixtures".to_string()]);
let closed = run
.resolve_left_out(&db, TARGET, "plc-control-logic")
.resolve_left_out(&db, TARGET, Some("plc-control-logic"))
.await
.unwrap();
@@ -228,3 +228,66 @@ async fn only_what_was_left_out_is_closed_for_a_stage_without_a_seen_set() {
pool.drop_tenant(TENANT).await.ok();
}
#[tokio::test]
async fn left_out_findings_close_whichever_scanner_stored_them() {
let uri = std::env::var("TEST_MONGODB_URI")
.unwrap_or_else(|_| "mongodb://root:example@localhost:27017/?authSource=admin".into());
let prefix = format!(
"leftoutall_{}",
&uuid::Uuid::new_v4().simple().to_string()[..10]
);
let Ok(pool) = DatabasePool::connect(&uri, &prefix).await else {
eprintln!("SKIP resolve_findings: no MongoDB reachable at {uri}");
return;
};
let db = pool.for_tenant_id(TENANT).await.unwrap();
// Arrange: an earlier scan stored findings of scanners that do not run
// now (no C, no BitBake left in the tree), one in the test data that this
// run still reports, and one outside the left-out paths.
db.findings()
.insert_many([
finding("fp-cppcheck", "cppcheck", "fixtures/firmware/sensors.c"),
finding("fp-recipe", "yocto-config", "legacy/image.bb"),
finding("fp-reported", "gitleaks", "fixtures/app/.env.local"),
finding("fp-kept", "cppcheck", "src/main.c"),
])
.await
.unwrap();
// Act: only gitleaks completes, and it reports fp-reported again.
let mut run = RunFindings::new("run-all")
.with_excluded(vec!["legacy".to_string()])
.with_test_data(vec!["fixtures".to_string()]);
run.completed("gitleaks");
let mut seen = vec![finding(
"fp-reported",
"gitleaks",
"fixtures/app/.env.local",
)];
run.write_back(&db, &mut seen).await.unwrap();
run.resolve_missing(&db, TARGET, &[]).await.unwrap();
let closed = run.resolve_left_out(&db, TARGET, None).await.unwrap();
// Assert: the left-out findings close with their reason, although their
// scanner did not run; one this run reported, and one outside, stay.
assert_eq!(closed, 2);
let cppcheck = row(&db, "fp-cppcheck").await;
assert_eq!(cppcheck.status, FindingStatus::Resolved);
assert_eq!(
last_scan_change(&cppcheck),
Some(ScanChangeKind::NowTestData)
);
let recipe = row(&db, "fp-recipe").await;
assert_eq!(recipe.status, FindingStatus::Resolved);
assert_eq!(last_scan_change(&recipe), Some(ScanChangeKind::NowExcluded));
assert_eq!(
row(&db, "fp-reported").await.status,
FindingStatus::Open,
"a finding this run reported is not closed"
);
assert_eq!(row(&db, "fp-kept").await.status, FindingStatus::Open);
pool.drop_tenant(TENANT).await.ok();
}