feat(findings): keyed by the code they flag, not its line number (#491) #497
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
|
||||
|
||||
@@ -0,0 +1,137 @@
|
||||
//! #491: findings are keyed by the code they flag, not its line. A row an
|
||||
//! earlier run stored under the line-based fingerprint is taken over by the
|
||||
//! first scan after the change (same id, so the same tracker issue, status
|
||||
//! and triage), and a line added above a finding later neither closes it nor
|
||||
//! creates a new one. Runs against a live Mongo (`TEST_MONGODB_URI`) and
|
||||
//! skips cleanly without one.
|
||||
|
||||
#![allow(clippy::expect_used, clippy::unwrap_used)]
|
||||
|
||||
use compliance_agent::database::{Database, DatabasePool};
|
||||
use compliance_agent::pipeline::dedup::compute_fingerprint;
|
||||
use compliance_agent::pipeline::finding_store::RunFindings;
|
||||
use compliance_core::models::{Finding, FindingStatus, ScanType, Severity};
|
||||
use mongodb::bson::doc;
|
||||
|
||||
const TARGET: &str = "target-1";
|
||||
|
||||
/// A semgrep finding at `file:line`, fingerprinted by line as before #491.
|
||||
fn semgrep(file: &str, line: u32) -> Finding {
|
||||
let mut f = Finding::new(
|
||||
TARGET.into(),
|
||||
compute_fingerprint(&[
|
||||
TARGET,
|
||||
"cra-ai-20-python-shell-command",
|
||||
file,
|
||||
&line.to_string(),
|
||||
]),
|
||||
"semgrep".into(),
|
||||
ScanType::Sast,
|
||||
"Shell command built from a variable".into(),
|
||||
"d".into(),
|
||||
Severity::High,
|
||||
);
|
||||
f.rule_id = Some("cra-ai-20-python-shell-command".into());
|
||||
f.file_path = Some(file.into());
|
||||
f.line_number = Some(line);
|
||||
f
|
||||
}
|
||||
|
||||
/// One scan of `tree` reporting `findings`, as the pipeline saves it.
|
||||
async fn scan(db: &Database, tree: &std::path::Path, mut findings: Vec<Finding>) -> RunFindings {
|
||||
let mut run = RunFindings::new("run").with_tree(tree.to_path_buf());
|
||||
run.completed("semgrep");
|
||||
run.label(&mut findings);
|
||||
run.save_new(db, &mut findings).await.unwrap();
|
||||
run.write_back(db, &mut findings).await.unwrap();
|
||||
run.resolve_missing(db, TARGET, &[]).await.unwrap();
|
||||
run
|
||||
}
|
||||
|
||||
async fn rows(db: &Database) -> Vec<Finding> {
|
||||
use futures_util::TryStreamExt;
|
||||
let mut rows: Vec<Finding> = db
|
||||
.findings()
|
||||
.find(doc! { "repo_id": TARGET })
|
||||
.await
|
||||
.unwrap()
|
||||
.try_collect()
|
||||
.await
|
||||
.unwrap();
|
||||
rows.sort_by(|a, b| a.file_path.cmp(&b.file_path));
|
||||
rows
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn findings_survive_the_new_fingerprint_and_lines_moving() {
|
||||
let uri = std::env::var("TEST_MONGODB_URI")
|
||||
.unwrap_or_else(|_| "mongodb://root:example@localhost:27017/?authSource=admin".into());
|
||||
let prefix = format!(
|
||||
"contentfp_{}",
|
||||
&uuid::Uuid::new_v4().simple().to_string()[..10]
|
||||
);
|
||||
let Ok(pool) = DatabasePool::connect(&uri, &prefix).await else {
|
||||
eprintln!("SKIP content_fingerprints: no MongoDB reachable at {uri}");
|
||||
return;
|
||||
};
|
||||
let tenant = "content-fingerprints";
|
||||
let Ok(db) = pool.for_tenant_id(tenant).await else {
|
||||
eprintln!("SKIP content_fingerprints: MongoDB at {uri} not usable");
|
||||
return;
|
||||
};
|
||||
let tree = std::env::temp_dir().join(format!("cs-contentfp-{}", uuid::Uuid::new_v4()));
|
||||
std::fs::create_dir_all(&tree).unwrap();
|
||||
std::fs::write(tree.join("a.py"), "import os\nos.system(cmd)\n").unwrap();
|
||||
std::fs::write(tree.join("b.py"), "subprocess.call(cmd, shell=True)\n").unwrap();
|
||||
|
||||
// Arrange: what a scan before #491 stored, line-keyed: one finding a
|
||||
// person marked a false positive, one still open.
|
||||
let mut decided = semgrep("a.py", 2);
|
||||
decided.status = FindingStatus::FalsePositive;
|
||||
let open = semgrep("b.py", 1);
|
||||
db.findings().insert_many([&decided, &open]).await.unwrap();
|
||||
let before = rows(&db).await;
|
||||
|
||||
// Act: the first scan after the change.
|
||||
scan(&db, &tree, vec![semgrep("a.py", 2), semgrep("b.py", 1)]).await;
|
||||
|
||||
// Assert: the same rows (ids, so tracker issues), now content-keyed,
|
||||
// with their status and the old fingerprint on record.
|
||||
let adopted = rows(&db).await;
|
||||
assert_eq!(adopted.len(), 2, "no new rows");
|
||||
for (old, new) in before.iter().zip(&adopted) {
|
||||
assert_eq!(old.id, new.id);
|
||||
assert_eq!(old.status, new.status);
|
||||
assert_ne!(old.fingerprint, new.fingerprint);
|
||||
assert_eq!(
|
||||
new.legacy_fingerprints,
|
||||
std::slice::from_ref(&old.fingerprint)
|
||||
);
|
||||
}
|
||||
|
||||
// Act: lines added above both findings, then another scan.
|
||||
std::fs::write(
|
||||
tree.join("a.py"),
|
||||
"import os\nimport sys\n\nos.system(cmd)\n",
|
||||
)
|
||||
.unwrap();
|
||||
std::fs::write(
|
||||
tree.join("b.py"),
|
||||
"# run it\nsubprocess.call( cmd, shell=True )\n",
|
||||
)
|
||||
.unwrap();
|
||||
let run = scan(&db, &tree, vec![semgrep("a.py", 4), semgrep("b.py", 2)]).await;
|
||||
|
||||
// Assert: nothing new, nothing closed or reopened, the lines follow.
|
||||
let moved = rows(&db).await;
|
||||
assert_eq!(run.new_count(), 0);
|
||||
assert!(run.status_changed().is_empty(), "no close/reopen churn");
|
||||
assert_eq!(moved[0].status, FindingStatus::FalsePositive);
|
||||
assert_eq!(moved[1].status, FindingStatus::Open);
|
||||
assert_eq!(moved[0].line_number, Some(4));
|
||||
assert_eq!(moved[1].line_number, Some(2));
|
||||
assert_eq!(moved[0].fingerprint, adopted[0].fingerprint);
|
||||
|
||||
let _ = std::fs::remove_dir_all(&tree);
|
||||
pool.drop_tenant(tenant).await.ok();
|
||||
}
|
||||
@@ -234,6 +234,15 @@ pub struct Finding {
|
||||
/// 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")]
|
||||
@@ -282,6 +291,8 @@ impl Finding {
|
||||
status_history: Vec::new(),
|
||||
occurrences: Vec::new(),
|
||||
variant: None,
|
||||
legacy_fingerprints: Vec::new(),
|
||||
fingerprint_content: None,
|
||||
created_at: now,
|
||||
updated_at: now,
|
||||
}
|
||||
|
||||
@@ -183,9 +183,14 @@ What the scan never changes:
|
||||
- A scheduled scan that finds no new commits (or unchanged uploaded files) does
|
||||
not scan, so it closes nothing.
|
||||
|
||||
Findings are tied to a file and line. When code moves (lines added above it),
|
||||
the same issue is reported at its new line as a new finding, and the old one
|
||||
is closed as no longer found.
|
||||
Findings are tied to the code they flag, not to its line number: the rule,
|
||||
the file, the flagged line without its whitespace (for a secret, the match),
|
||||
and how many identical lines come before it in the file. When code moves
|
||||
(lines added above it, re-indented), the finding stays the same: its status,
|
||||
assessment and tracker issue stay with it, and it shows the new line. Only
|
||||
a change of the flagged line itself (or a rename of the file) makes it a new
|
||||
finding and closes the old one. Findings stored before this was introduced
|
||||
keep their status and issue on the first scan after it.
|
||||
|
||||
### Recommended Flow
|
||||
|
||||
|
||||
@@ -18,6 +18,7 @@ together on stage in one pass before the next prod promotion.
|
||||
| #465 | Malware stage (ClamAV), committed binaries, unchanged scheduled rescans skipped |
|
||||
| #461 | Transitive NuGet packages of `<PackageReference>` projects resolved from nuget.org |
|
||||
| #467 (follow-up) | npm and Maven licenses from their public registries |
|
||||
| #491 | Findings keyed by the code they flag, not its line number |
|
||||
|
||||
**Customer-visible on the next prod rescan** is marked **[visible]**: these
|
||||
change what a customer sees on their existing targets, without them doing
|
||||
@@ -305,6 +306,31 @@ Unchanged rescans:
|
||||
- **[visible]** npm and Maven components gain licenses in the SBOM and the
|
||||
**Lizenzen** tab (and copyleft warnings where they apply).
|
||||
|
||||
### 18. #491 Content-based fingerprints
|
||||
|
||||
Findings that existed before this deploy must keep their rows; check on a
|
||||
target with history (findings, at least one marked by a person, issues).
|
||||
|
||||
- **Do:** note a target's findings (ids, statuses, tracker issues), deploy,
|
||||
start **Prüfung starten** without changing the code.
|
||||
- **Expect:** no new findings, nothing closed, every status, assessment and
|
||||
issue as before.
|
||||
- **Log:** `findings stored under a line-based fingerprint now keyed by their
|
||||
content` with `adopted=<count of that target's line-based findings>` (once;
|
||||
the next scan logs nothing).
|
||||
- **Do:** in a git target, add a few lines at the top of a file with a finding
|
||||
(or re-indent the flagged line) and push.
|
||||
- **Expect:** the finding keeps its id, status and issue and shows the new line;
|
||||
no "Bei der Prüfung nicht mehr gefunden" comment on its issue, no new issue.
|
||||
- **Log:** `findings whose code moved now point at their new line` with
|
||||
`moved=…`.
|
||||
- **Do:** duplicate a flagged line in the same file.
|
||||
- **Expect:** two findings (the copy is a new one).
|
||||
- **[visible]** on prod after promotion: the first rescan of every target re-keys
|
||||
its findings without changing anything visible; afterwards, edits above a
|
||||
finding no longer close and reopen it and its issue. A change to the flagged
|
||||
line itself still does.
|
||||
|
||||
## After the pass
|
||||
|
||||
- The nightly job on `main` is green with the new mobile targets.
|
||||
|
||||
Reference in new issue
Block a user