This commit was merged in pull request #497.
This commit is contained in:
1 parent
bdf7fa4268
commit
ece992da32
8 files changed
+531
-8
No files matched your search
@@ -15,6 +15,7 @@
|
||||
//! findings ([`crate::pipeline::grouping`]) is closed as grouped.
|
||||
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use futures_util::TryStreamExt;
|
||||
use mongodb::bson::{doc, oid::ObjectId, to_bson, Bson, Document};
|
||||
@@ -42,6 +43,8 @@ pub struct RunFindings {
|
||||
grouped: HashSet<GroupedPlace>,
|
||||
/// The app variants of the scanned tree, which label each finding.
|
||||
variants: AppVariants,
|
||||
/// The scanned tree: the flagged lines fingerprints are made of (#491).
|
||||
tree: Option<PathBuf>,
|
||||
}
|
||||
|
||||
/// One place a group lists: scanner, rule, file, line.
|
||||
@@ -71,9 +74,17 @@ impl RunFindings {
|
||||
status_changed: Vec::new(),
|
||||
grouped: HashSet::new(),
|
||||
variants: AppVariants::default(),
|
||||
tree: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Key the findings of this run by the content of the code they flag in
|
||||
/// the tree under `tree`, not by its line number (#491).
|
||||
pub fn with_tree(mut self, tree: PathBuf) -> Self {
|
||||
self.tree = Some(tree);
|
||||
self
|
||||
}
|
||||
|
||||
/// Label the findings this run saves with the app variant holding them
|
||||
/// (see [`crate::pipeline::variants`]).
|
||||
pub fn with_variants(mut self, variants: AppVariants) -> Self {
|
||||
@@ -81,9 +92,13 @@ impl RunFindings {
|
||||
self
|
||||
}
|
||||
|
||||
/// Label `findings` with their app variant. Called before grouping too,
|
||||
/// so a group's list of places names each place's variant.
|
||||
/// Key `findings` by the content they flag (see [`content_fingerprints`])
|
||||
/// and label them with their app variant. Called before grouping too, so
|
||||
/// a group's list of places names each place's variant.
|
||||
pub fn label(&self, findings: &mut [Finding]) {
|
||||
if let Some(tree) = &self.tree {
|
||||
content_fingerprints(tree, findings);
|
||||
}
|
||||
self.variants.label(findings);
|
||||
}
|
||||
|
||||
@@ -133,10 +148,16 @@ impl RunFindings {
|
||||
.findings()
|
||||
.clone_with_type::<Document>()
|
||||
.find(doc! { "fingerprint": { "$in": unknown.iter().collect::<Vec<_>>() } })
|
||||
.projection(doc! { "fingerprint": 1, "status": 1, "scanner": 1 })
|
||||
.projection(doc! { "fingerprint": 1, "status": 1, "scanner": 1, "line_number": 1 })
|
||||
.await?
|
||||
.try_collect()
|
||||
.await?;
|
||||
let mut stored_rows = stored_rows;
|
||||
stored_rows.extend(
|
||||
self.adopt_legacy_rows(db, findings, &unknown, &stored_rows)
|
||||
.await?,
|
||||
);
|
||||
self.update_moved(db, findings, &stored_rows).await?;
|
||||
let stored: HashSet<String> = stored_rows
|
||||
.iter()
|
||||
.filter_map(|d| d.get_str("fingerprint").ok().map(str::to_owned))
|
||||
@@ -201,6 +222,147 @@ impl RunFindings {
|
||||
Ok(saved)
|
||||
}
|
||||
|
||||
/// Give the rows an earlier run stored under a finding's line-based
|
||||
/// fingerprint (#491) its content fingerprint, once: the row keeps its id,
|
||||
/// status, triage and tracker issue, and records the old fingerprint.
|
||||
///
|
||||
/// # Returns
|
||||
///
|
||||
/// The adopted rows as [`Self::save_new`] reads stored rows (with the new
|
||||
/// fingerprint), so they count as stored and a resolved one is reopened.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// A database error.
|
||||
async fn adopt_legacy_rows(
|
||||
&mut self,
|
||||
db: &Database,
|
||||
findings: &[Finding],
|
||||
unknown: &HashSet<String>,
|
||||
stored_rows: &[Document],
|
||||
) -> Result<Vec<Document>, AgentError> {
|
||||
let already: HashSet<&str> = stored_rows
|
||||
.iter()
|
||||
.filter_map(|d| d.get_str("fingerprint").ok())
|
||||
.collect();
|
||||
let mut by_legacy: HashMap<&str, &Finding> = HashMap::new();
|
||||
for finding in findings {
|
||||
let fp = finding.fingerprint.as_str();
|
||||
if unknown.contains(fp) && !already.contains(fp) {
|
||||
for old in &finding.legacy_fingerprints {
|
||||
by_legacy.entry(old.as_str()).or_insert(finding);
|
||||
}
|
||||
}
|
||||
}
|
||||
if by_legacy.is_empty() {
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
let rows: Vec<Document> = db
|
||||
.findings()
|
||||
.clone_with_type::<Document>()
|
||||
.find(doc! { "fingerprint": { "$in": by_legacy.keys().copied().collect::<Vec<_>>() } })
|
||||
.projection(doc! { "fingerprint": 1, "status": 1, "scanner": 1, "line_number": 1 })
|
||||
.await?
|
||||
.try_collect()
|
||||
.await?;
|
||||
let mut adopted = Vec::with_capacity(rows.len());
|
||||
let mut taken: HashSet<String> = HashSet::new();
|
||||
for mut row in rows {
|
||||
let (Ok(id), Ok(old)) = (row.get_object_id("_id"), row.get_str("fingerprint")) else {
|
||||
continue;
|
||||
};
|
||||
let Some(finding) = by_legacy.get(old).copied() else {
|
||||
continue;
|
||||
};
|
||||
// One row per content fingerprint (two old rows never map to one).
|
||||
if !taken.insert(finding.fingerprint.clone()) {
|
||||
continue;
|
||||
}
|
||||
let old = old.to_string();
|
||||
db.findings()
|
||||
.update_one(
|
||||
doc! { "_id": id },
|
||||
doc! {
|
||||
"$set": {
|
||||
"fingerprint": &finding.fingerprint,
|
||||
"line_number": finding.line_number,
|
||||
"code_snippet": finding.code_snippet.clone(),
|
||||
"updated_at": mongodb::bson::DateTime::now(),
|
||||
},
|
||||
"$addToSet": { "legacy_fingerprints": &old },
|
||||
},
|
||||
)
|
||||
.await?;
|
||||
row.insert("fingerprint", finding.fingerprint.clone());
|
||||
row.insert("line_number", finding.line_number);
|
||||
adopted.push(row);
|
||||
}
|
||||
if !adopted.is_empty() {
|
||||
tracing::info!(
|
||||
scan_run_id = %self.scan_run_id,
|
||||
adopted = adopted.len(),
|
||||
"findings stored under a line-based fingerprint now keyed by their content"
|
||||
);
|
||||
}
|
||||
Ok(adopted)
|
||||
}
|
||||
|
||||
/// Move the stored rows of findings whose code moved (same content
|
||||
/// fingerprint, another line) to the line this run found them at.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// A database error.
|
||||
async fn update_moved(
|
||||
&self,
|
||||
db: &Database,
|
||||
findings: &[Finding],
|
||||
stored_rows: &[Document],
|
||||
) -> Result<(), AgentError> {
|
||||
let lines: HashMap<&str, (Option<u32>, Option<&String>)> = findings
|
||||
.iter()
|
||||
.filter(|f| f.occurrences.is_empty())
|
||||
.map(|f| {
|
||||
(
|
||||
f.fingerprint.as_str(),
|
||||
(f.line_number, f.code_snippet.as_ref()),
|
||||
)
|
||||
})
|
||||
.collect();
|
||||
let mut moved = 0usize;
|
||||
for row in stored_rows {
|
||||
let (Ok(id), Ok(fp)) = (row.get_object_id("_id"), row.get_str("fingerprint")) else {
|
||||
continue;
|
||||
};
|
||||
let Some((Some(line), snippet)) = lines.get(fp).copied() else {
|
||||
continue;
|
||||
};
|
||||
let (_, _, _, stored_line) = stored_place(row);
|
||||
if stored_line == Some(line) {
|
||||
continue;
|
||||
}
|
||||
db.findings()
|
||||
.update_one(
|
||||
doc! { "_id": id },
|
||||
doc! { "$set": {
|
||||
"line_number": line,
|
||||
"code_snippet": snippet.cloned(),
|
||||
"updated_at": mongodb::bson::DateTime::now(),
|
||||
} },
|
||||
)
|
||||
.await?;
|
||||
moved += 1;
|
||||
}
|
||||
if moved > 0 {
|
||||
tracing::info!(
|
||||
scan_run_id = %self.scan_run_id,
|
||||
moved,
|
||||
"findings whose code moved now point at their new line"
|
||||
);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Store what triage changed on the findings this run saved and on those
|
||||
/// an earlier run stored (see [`row_writes`]). Findings no stage has saved
|
||||
/// yet (the grounded surface checks) are saved first.
|
||||
@@ -532,6 +694,90 @@ fn unanimous<'a>(
|
||||
decisions.all(|d| d == Some(first)).then(|| first.clone())
|
||||
}
|
||||
|
||||
/// The version tag in every content fingerprint, so a later change of what
|
||||
/// it hashes can tell its own fingerprints apart.
|
||||
const CONTENT_FINGERPRINT: &str = "content-v1";
|
||||
|
||||
/// A line as fingerprints compare it: without any whitespace, so
|
||||
/// re-indenting or re-wrapping spaces does not change it.
|
||||
fn normalised(line: &str) -> String {
|
||||
line.chars().filter(|c| !c.is_whitespace()).collect()
|
||||
}
|
||||
|
||||
/// Key every finding at one place in a file by what it flags instead of
|
||||
/// where (#491): repository, scanner, rule, file, the flagged line without
|
||||
/// whitespace (or the content the scanner gave, a secret's match), and how
|
||||
/// many identical lines come before it in the file, so two identical lines
|
||||
/// stay two findings. A line added above it no longer changes it, and the
|
||||
/// auto-close (#443) and issue sync (#451) stop closing and reopening it.
|
||||
///
|
||||
/// The line-based fingerprint it replaces is kept in
|
||||
/// `legacy_fingerprints`, through which [`RunFindings::save_new`] finds the
|
||||
/// row an earlier run stored. A finding without a file and line, a group
|
||||
/// (#464, keyed without places already), one already keyed, and one whose
|
||||
/// line is empty or gone keep the fingerprint they have.
|
||||
fn content_fingerprints(tree: &Path, findings: &mut [Finding]) {
|
||||
let mut files: HashMap<String, Option<Vec<String>>> = HashMap::new();
|
||||
for finding in findings.iter_mut() {
|
||||
if !finding.occurrences.is_empty() || !finding.legacy_fingerprints.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let (Some(path), Some(line)) = (finding.file_path.clone(), finding.line_number) else {
|
||||
continue;
|
||||
};
|
||||
let lines = files.entry(path.clone()).or_insert_with(|| {
|
||||
std::fs::read_to_string(tree.join(&path))
|
||||
.ok()
|
||||
.map(|text| text.lines().map(normalised).collect())
|
||||
});
|
||||
let index = usize::try_from(line).unwrap_or(0).checked_sub(1);
|
||||
let at_line = lines.as_ref().zip(index).and_then(|(l, i)| l.get(i));
|
||||
let given = finding.fingerprint_content.is_some();
|
||||
let content = match &finding.fingerprint_content {
|
||||
Some(content) => normalised(content),
|
||||
None => at_line.cloned().unwrap_or_default(),
|
||||
};
|
||||
if content.is_empty() {
|
||||
continue;
|
||||
}
|
||||
// Identical lines before this one: the same content further down is
|
||||
// another finding. Content no longer on its line (a secret from the
|
||||
// history) has no place to count from.
|
||||
let on_its_line = at_line.is_some_and(|l| l.contains(content.as_str()));
|
||||
let occurrence = match (lines.as_ref(), index) {
|
||||
(Some(lines), Some(i)) if on_its_line => lines
|
||||
.iter()
|
||||
.take(i)
|
||||
// A whole line counts when equal; a scanner's content (a
|
||||
// secret) wherever it appears in a line.
|
||||
.filter(|l| {
|
||||
if given {
|
||||
l.contains(content.as_str())
|
||||
} else {
|
||||
**l == content
|
||||
}
|
||||
})
|
||||
.count(),
|
||||
_ => 0,
|
||||
};
|
||||
let rule = finding
|
||||
.rule_id
|
||||
.clone()
|
||||
.unwrap_or_else(|| finding.title.clone());
|
||||
let fingerprint = crate::pipeline::dedup::compute_fingerprint(&[
|
||||
CONTENT_FINGERPRINT,
|
||||
&finding.repo_id,
|
||||
&finding.scanner,
|
||||
&rule,
|
||||
&path,
|
||||
&content,
|
||||
&occurrence.to_string(),
|
||||
]);
|
||||
let old = std::mem::replace(&mut finding.fingerprint, fingerprint);
|
||||
finding.legacy_fingerprints.push(old);
|
||||
}
|
||||
}
|
||||
|
||||
/// The place of a stored finding, to compare with [`RunFindings::grouped`].
|
||||
fn stored_place(row: &Document) -> GroupedPlace {
|
||||
let text = |key: &str| row.get_str(key).unwrap_or_default().to_string();
|
||||
@@ -692,6 +938,97 @@ mod tests {
|
||||
|
||||
use super::*;
|
||||
|
||||
/// A finding of `rule` at `file:line`, fingerprinted by line as the
|
||||
/// scanners do.
|
||||
fn at(file: &str, line: u32) -> Finding {
|
||||
let mut f = Finding::new(
|
||||
"repo-1".into(),
|
||||
crate::pipeline::dedup::compute_fingerprint(&[
|
||||
"repo-1",
|
||||
"rule",
|
||||
file,
|
||||
&line.to_string(),
|
||||
]),
|
||||
"semgrep".into(),
|
||||
ScanType::Sast,
|
||||
"t".into(),
|
||||
"d".into(),
|
||||
Severity::Medium,
|
||||
);
|
||||
f.rule_id = Some("rule".into());
|
||||
f.file_path = Some(file.into());
|
||||
f.line_number = Some(line);
|
||||
f
|
||||
}
|
||||
|
||||
fn keyed(tree: &Path, mut findings: Vec<Finding>) -> Vec<Finding> {
|
||||
content_fingerprints(tree, &mut findings);
|
||||
findings
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_line_added_above_keeps_the_fingerprint_and_twins_stay_apart() {
|
||||
let dir = std::env::temp_dir().join(format!("cs-fp-{}", uuid::Uuid::new_v4()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
std::fs::write(
|
||||
dir.join("a.py"),
|
||||
"import os\nos.system(cmd)\nx = 1\nos.system(cmd)\n",
|
||||
)
|
||||
.unwrap();
|
||||
let before = keyed(&dir, vec![at("a.py", 2), at("a.py", 4)]);
|
||||
// Re-indented and moved down by a new line above.
|
||||
std::fs::write(
|
||||
dir.join("a.py"),
|
||||
"import os\nimport sys\n os.system( cmd )\nx = 1\nos.system(cmd)\n",
|
||||
)
|
||||
.unwrap();
|
||||
let after = keyed(&dir, vec![at("a.py", 3), at("a.py", 5)]);
|
||||
let missing = keyed(&dir, vec![at("gone.py", 3)]);
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
assert_eq!(before[0].fingerprint, after[0].fingerprint);
|
||||
assert_eq!(before[1].fingerprint, after[1].fingerprint);
|
||||
assert_ne!(
|
||||
before[0].fingerprint, before[1].fingerprint,
|
||||
"identical lines stay two"
|
||||
);
|
||||
// The line-based fingerprint is kept to find the row stored under it.
|
||||
assert_eq!(
|
||||
before[0].legacy_fingerprints,
|
||||
[crate::pipeline::dedup::compute_fingerprint(&[
|
||||
"repo-1", "rule", "a.py", "2"
|
||||
])]
|
||||
);
|
||||
// Without the file nothing changes.
|
||||
assert!(missing[0].legacy_fingerprints.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_scanners_own_content_and_groups_are_respected() {
|
||||
let dir = std::env::temp_dir().join(format!("cs-fp-{}", uuid::Uuid::new_v4()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
std::fs::write(dir.join("cfg.ini"), "token=abc123\n").unwrap();
|
||||
// A secret from the history: line 9 of a file that is shorter now.
|
||||
let mut secret = at("cfg.ini", 9);
|
||||
secret.fingerprint_content = Some("token=abc123".into());
|
||||
let mut moved = at("cfg.ini", 1);
|
||||
moved.fingerprint_content = Some("token=abc123".into());
|
||||
let mut group = at("cfg.ini", 1);
|
||||
group.occurrences = vec![compliance_core::models::Occurrence {
|
||||
file: "cfg.ini".into(),
|
||||
line: Some(1),
|
||||
variant: None,
|
||||
decision: None,
|
||||
}];
|
||||
let group_fp = group.fingerprint.clone();
|
||||
let found = keyed(&dir, vec![secret, moved, group]);
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
assert_eq!(
|
||||
found[0].fingerprint, found[1].fingerprint,
|
||||
"the match, not the line"
|
||||
);
|
||||
assert_eq!(found[2].fingerprint, group_fp, "groups keep their key");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_one_decision_on_every_place_is_taken_over() {
|
||||
let fp = FindingStatus::FalsePositive;
|
||||
|
||||
@@ -188,6 +188,9 @@ impl Scanner for GitleaksScanner {
|
||||
finding.rule_id = Some(r.rule_id);
|
||||
finding.file_path = Some(r.file);
|
||||
finding.line_number = Some(r.start_line);
|
||||
// A secret found in the history may not be on that line of the
|
||||
// tree any more: the match itself identifies it (#491).
|
||||
finding.fingerprint_content = Some(r.r#match.clone());
|
||||
finding.code_snippet = Some(r.r#match);
|
||||
finding
|
||||
})
|
||||
|
||||
@@ -226,6 +226,9 @@ fn group(mut members: Vec<Finding>) -> Option<Finding> {
|
||||
let mut first = members.into_iter().next()?;
|
||||
let rule = first.rule_id.clone().unwrap_or_default();
|
||||
first.fingerprint = group_fingerprint(&first.repo_id, &first.scanner, &rule);
|
||||
// The member's former fingerprints are not the group's: adopting them
|
||||
// would turn that member's stored row into the group (#491).
|
||||
first.legacy_fingerprints.clear();
|
||||
first.severity = severity;
|
||||
first.description = describe(&first.description, &occurrences);
|
||||
first.occurrences = occurrences;
|
||||
|
||||
@@ -178,8 +178,9 @@ impl PipelineOrchestrator {
|
||||
tokio::task::spawn_blocking(move || crate::pipeline::variants::app_variants(&tree))
|
||||
.await
|
||||
.unwrap_or_default();
|
||||
let mut run_findings =
|
||||
crate::pipeline::finding_store::RunFindings::new(scan_run_id).with_variants(variants);
|
||||
let mut run_findings = crate::pipeline::finding_store::RunFindings::new(scan_run_id)
|
||||
.with_variants(variants)
|
||||
.with_tree(repo_path.clone());
|
||||
|
||||
// Stage 1: SAST. Vendor SDK code (HAL, CMSIS, third-party middleware) is
|
||||
// not the customer's to fix, so both analysers skip it and the run says
|
||||
|
||||
Reference in new issue
Block a user