Closes #463. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01DmXxNULoSNPvjF7buKipsB
216 lines
7.6 KiB
Rust
216 lines
7.6 KiB
Rust
//! Rewrites of stored findings that a change to how findings are written
|
|
//! needs, run at every agent start. Each one is idempotent: a finding already
|
|
//! in the new form is left alone, so a second run changes nothing.
|
|
//!
|
|
//! #463: semgrep findings of our own rules were stored with the staging path
|
|
//! in their rule id (`tmp.cra-ai-20-csharp-xxe`), and control-check findings
|
|
//! with the catalog's transliterated titles ("cra-ai-6: Integritaetspruefung").
|
|
//! The fingerprints stay as they are (see [`crate::pipeline::semgrep::fingerprint`]),
|
|
//! so the next scan finds the stored findings again and their triage, status
|
|
//! and tracker issues stay with them.
|
|
|
|
use futures_util::TryStreamExt;
|
|
use mongodb::bson::{doc, Document};
|
|
|
|
use compliance_core::models::oscal::restore_umlauts;
|
|
|
|
use crate::database::{Database, DatabasePool};
|
|
use crate::error::AgentError;
|
|
use crate::pipeline::semgrep;
|
|
|
|
/// What one run of [`migrate_stored_findings`] changed.
|
|
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
|
|
pub struct Migrated {
|
|
/// semgrep findings whose rule id lost its path prefix.
|
|
pub rule_ids: u64,
|
|
/// Of those, findings whose fingerprint was computed from an older
|
|
/// prefix and now matches what a scan computes.
|
|
pub fingerprints: u64,
|
|
/// control-check findings whose title or description got its umlauts.
|
|
pub titles: u64,
|
|
}
|
|
|
|
/// Rewrite the stored findings of every tenant. A tenant that fails is
|
|
/// logged and skipped, so one bad database does not hold up the others.
|
|
///
|
|
/// # Errors
|
|
///
|
|
/// Listing the tenant databases failed.
|
|
pub async fn migrate_stored_findings(pool: &DatabasePool) -> Result<Migrated, AgentError> {
|
|
let mut total = Migrated::default();
|
|
for db in pool.existing_tenant_dbs().await? {
|
|
match migrate_tenant(&db).await {
|
|
Ok(m) => {
|
|
total.rule_ids += m.rule_ids;
|
|
total.fingerprints += m.fingerprints;
|
|
total.titles += m.titles;
|
|
}
|
|
Err(e) => tracing::error!(
|
|
database = db.inner().name(),
|
|
"migrating stored findings failed: {e}"
|
|
),
|
|
}
|
|
}
|
|
Ok(total)
|
|
}
|
|
|
|
/// [`migrate_stored_findings`] for one tenant database.
|
|
///
|
|
/// # Errors
|
|
///
|
|
/// A database error.
|
|
pub async fn migrate_tenant(db: &Database) -> Result<Migrated, AgentError> {
|
|
let mut migrated = Migrated::default();
|
|
let findings = db.findings().clone_with_type::<Document>();
|
|
|
|
// Only ids with a dot can carry a prefix: ours have none.
|
|
let mut cursor = findings
|
|
.find(doc! { "scanner": "semgrep", "rule_id": { "$regex": "\\." } })
|
|
.projection(doc! {
|
|
"rule_id": 1, "fingerprint": 1, "repo_id": 1, "file_path": 1, "line_number": 1,
|
|
})
|
|
.await?;
|
|
while let Some(row) = cursor.try_next().await? {
|
|
let (Ok(id), Ok(rule_id)) = (row.get_object_id("_id"), row.get_str("rule_id")) else {
|
|
continue;
|
|
};
|
|
let Some(bare) = bare_semgrep_rule_id(rule_id) else {
|
|
continue;
|
|
};
|
|
let mut set = doc! { "rule_id": bare };
|
|
if let Some(fingerprint) = scan_fingerprint(&row, bare) {
|
|
// Stored from an older prefix: take the fingerprint a scan
|
|
// computes now, unless a finding already has it (that one is the
|
|
// same finding, stored since; this row is closed by the next scan
|
|
// as before).
|
|
let taken = findings
|
|
.find_one(doc! { "fingerprint": &fingerprint })
|
|
.await?
|
|
.is_some();
|
|
if !taken {
|
|
set.insert("fingerprint", fingerprint);
|
|
migrated.fingerprints += 1;
|
|
}
|
|
}
|
|
findings
|
|
.update_one(doc! { "_id": id }, doc! { "$set": set })
|
|
.await?;
|
|
migrated.rule_ids += 1;
|
|
}
|
|
|
|
let mut cursor = findings
|
|
.find(doc! { "scanner": "control-check" })
|
|
.projection(doc! { "title": 1, "description": 1 })
|
|
.await?;
|
|
while let Some(row) = cursor.try_next().await? {
|
|
let Ok(id) = row.get_object_id("_id") else {
|
|
continue;
|
|
};
|
|
let title = row.get_str("title").unwrap_or_default();
|
|
let description = row.get_str("description").unwrap_or_default();
|
|
let (new_title, new_description) = (restore_umlauts(title), restore_umlauts(description));
|
|
if new_title == title && new_description == description {
|
|
continue;
|
|
}
|
|
findings
|
|
.update_one(
|
|
doc! { "_id": id },
|
|
doc! { "$set": { "title": new_title, "description": new_description } },
|
|
)
|
|
.await?;
|
|
migrated.titles += 1;
|
|
}
|
|
Ok(migrated)
|
|
}
|
|
|
|
/// The bare id of a stored semgrep rule id that still carries a path
|
|
/// prefix; `None` when there is nothing to rewrite.
|
|
fn bare_semgrep_rule_id(stored: &str) -> Option<&str> {
|
|
let bare = semgrep::bare_rule_id(stored);
|
|
(bare != stored).then_some(bare)
|
|
}
|
|
|
|
/// The fingerprint a scan computes for the semgrep finding `row` with rule
|
|
/// `bare`, when it differs from the stored one.
|
|
fn scan_fingerprint(row: &Document, bare: &str) -> Option<String> {
|
|
let line = row
|
|
.get_i32("line_number")
|
|
.ok()
|
|
.and_then(|l| u32::try_from(l).ok())
|
|
.or_else(|| {
|
|
row.get_i64("line_number")
|
|
.ok()
|
|
.and_then(|l| u32::try_from(l).ok())
|
|
})?;
|
|
let fingerprint = semgrep::fingerprint(
|
|
row.get_str("repo_id").ok()?,
|
|
bare,
|
|
row.get_str("file_path").ok()?,
|
|
line,
|
|
);
|
|
(row.get_str("fingerprint").ok() != Some(fingerprint.as_str())).then_some(fingerprint)
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
use crate::pipeline::dedup;
|
|
|
|
#[test]
|
|
fn prefixed_rule_ids_are_rewritten_once() {
|
|
assert_eq!(
|
|
bare_semgrep_rule_id("tmp.cra-ai-20-csharp-xxe"),
|
|
Some("cra-ai-20-csharp-xxe")
|
|
);
|
|
// Already bare, or not ours: nothing to do, so a second run is a no-op.
|
|
assert_eq!(bare_semgrep_rule_id("cra-ai-20-csharp-xxe"), None);
|
|
assert_eq!(bare_semgrep_rule_id("python.lang.exec-detected"), None);
|
|
}
|
|
|
|
fn row(rule_id: &str, fingerprint: &str) -> Document {
|
|
doc! {
|
|
"rule_id": rule_id,
|
|
"fingerprint": fingerprint,
|
|
"repo_id": "repo-1",
|
|
"file_path": "src/Xml.cs",
|
|
"line_number": 7_i32,
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn a_tmp_prefixed_finding_keeps_its_fingerprint() {
|
|
let stored =
|
|
dedup::compute_fingerprint(&["repo-1", "tmp.cra-ai-20-csharp-xxe", "src/Xml.cs", "7"]);
|
|
let r = row("tmp.cra-ai-20-csharp-xxe", &stored);
|
|
assert_eq!(scan_fingerprint(&r, "cra-ai-20-csharp-xxe"), None);
|
|
}
|
|
|
|
#[test]
|
|
fn an_older_prefix_gets_the_fingerprint_a_scan_computes() {
|
|
let old = "tmp.compliance-cra-semgrep-csharp.cra-ai-20-csharp-xxe";
|
|
let stored = dedup::compute_fingerprint(&["repo-1", old, "src/Xml.cs", "7"]);
|
|
let new = scan_fingerprint(&row(old, &stored), "cra-ai-20-csharp-xxe").unwrap();
|
|
assert_eq!(
|
|
new,
|
|
semgrep::fingerprint("repo-1", "cra-ai-20-csharp-xxe", "src/Xml.cs", 7)
|
|
);
|
|
// Rewritten, it is in the new form: nothing left to do.
|
|
assert_eq!(
|
|
scan_fingerprint(&row("cra-ai-20-csharp-xxe", &new), "cra-ai-20-csharp-xxe"),
|
|
None
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn control_titles_get_their_umlauts() {
|
|
assert_eq!(
|
|
restore_umlauts("cra-ai-6: Integritaetspruefung"),
|
|
"cra-ai-6: Integritätsprüfung"
|
|
);
|
|
assert_eq!(
|
|
restore_umlauts("cra-ai-24: Security-Logging"),
|
|
"cra-ai-24: Security-Logging"
|
|
);
|
|
}
|
|
}
|