//! 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"). //! A1: semgrep findings were stored with the rule's whole message as their //! title, pages of Markdown for the vendored GitLab rules; the title becomes //! the rule's short description or the message's first sentence. //! //! 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, /// semgrep findings whose title was the rule's whole message. pub semgrep_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 { 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; total.semgrep_titles += m.semgrep_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 { let mut migrated = Migrated::default(); let findings = db.findings().clone_with_type::(); // 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; } // Only titles a scan would now write shorter: a long or multi-line one. let mut cursor = findings .find(doc! { "scanner": "semgrep", "$or": [ { "title": { "$regex": "\n" } }, { "$expr": { "$gt": [{ "$strLenCP": "$title" }, MAX_STORED_TITLE_CHARS] } }, ], }) .projection(doc! { "title": 1, "rule_id": 1 }) .await?; while let Some(row) = cursor.try_next().await? { let (Ok(id), Ok(title)) = (row.get_object_id("_id"), row.get_str("title")) else { continue; }; let new_title = semgrep_title(row.get_str("rule_id").ok(), title); if new_title == title { continue; } findings .update_one(doc! { "_id": id }, doc! { "$set": { "title": new_title } }) .await?; migrated.semgrep_titles += 1; } Ok(migrated) } /// A stored semgrep title longer than this was the rule's whole message: a /// scan writes at most [`semgrep::headline`]'s length. const MAX_STORED_TITLE_CHARS: i32 = 160; /// The title a scan now gives a semgrep finding of `rule_id` whose stored /// title is the rule's message: the bundled rule's short description, else /// the message's first sentence. fn semgrep_title(rule_id: Option<&str>, stored: &str) -> String { rule_id .and_then(|rule| { semgrep::bundled_short_descriptions() .get(semgrep::bare_rule_id(rule)) .copied() }) .map_or_else(|| semgrep::headline(stored), str::to_string) } /// 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 { 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" ); } }