From fc099d07c1199e04fb4ea5ecd1540668c79ee62d Mon Sep 17 00:00:00 2001 From: Sharang Parnerkar Date: Mon, 5 Oct 2026 23:07:14 +0000 Subject: [PATCH] fix(findings): bare semgrep rule ids, real umlauts in control titles (#463) (#473) Closes #463. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01DmXxNULoSNPvjF7buKipsB --- .../controls/snapshot/oscal-catalog-cra.json | 76 +++---- .../src/controls/oscal_provider.rs | 53 +++++ compliance-agent/src/finding_migrations.rs | 215 ++++++++++++++++++ compliance-agent/src/lib.rs | 1 + compliance-agent/src/main.rs | 17 +- compliance-agent/src/pipeline/semgrep.rs | 141 ++++++++++-- compliance-agent/tests/finding_migrations.rs | 161 +++++++++++++ compliance-core/src/models/oscal.rs | 180 +++++++++++++++ 8 files changed, 792 insertions(+), 52 deletions(-) create mode 100644 compliance-agent/src/finding_migrations.rs create mode 100644 compliance-agent/tests/finding_migrations.rs diff --git a/compliance-agent/controls/snapshot/oscal-catalog-cra.json b/compliance-agent/controls/snapshot/oscal-catalog-cra.json index e603caa..0d0b18a 100644 --- a/compliance-agent/controls/snapshot/oscal-catalog-cra.json +++ b/compliance-agent/controls/snapshot/oscal-catalog-cra.json @@ -78,7 +78,7 @@ { "id": "cra-ai-1_smt", "name": "statement", - "prose": "Produkte muessen mit sicheren Standardeinstellungen ausgeliefert werden. Keine offenen Ports, keine aktivierten Debug-Schnittstellen, keine unnoetig laufenden Dienste." + "prose": "Produkte müssen mit sicheren Standardeinstellungen ausgeliefert werden. Keine offenen Ports, keine aktivierten Debug-Schnittstellen, keine unnötig laufenden Dienste." } ], "links": [ @@ -91,7 +91,7 @@ { "id": "cra-ai-2", "class": "cra-annex-i", - "title": "Minimale Angriffsflaeche", + "title": "Minimale Angriffsfläche", "props": [ { "name": "label", @@ -199,7 +199,7 @@ { "id": "cra-ai-3_smt", "name": "statement", - "prose": "Sicherheitskritische Komponenten muessen isoliert werden (Sandboxing, Containerisierung, Privilege Separation)." + "prose": "Sicherheitskritische Komponenten müssen isoliert werden (Sandboxing, Containerisierung, Privilege Separation)." } ], "links": [ @@ -262,7 +262,7 @@ { "id": "cra-ai-4_smt", "name": "statement", - "prose": "Jede Komponente, jeder Prozess und jeder Benutzer erhaelt nur die minimal notwendigen Berechtigungen." + "prose": "Jede Komponente, jeder Prozess und jeder Benutzer erhält nur die minimal notwendigen Berechtigungen." } ], "links": [ @@ -320,7 +320,7 @@ { "id": "cra-ai-5_smt", "name": "statement", - "prose": "Schutz vor unautorisierter Aenderung von Software und Konfiguration (Code Signing, Secure Boot, TPM)." + "prose": "Schutz vor unautorisierter Änderung von Software und Konfiguration (Code Signing, Secure Boot, TPM)." } ], "links": [ @@ -333,7 +333,7 @@ { "id": "cra-ai-6", "class": "cra-annex-i", - "title": "Integritaetspruefung", + "title": "Integritätsprüfung", "props": [ { "name": "label", @@ -378,7 +378,7 @@ { "id": "cra-ai-6_smt", "name": "statement", - "prose": "Automatische Ueberpruefung der Integritaet von Software, Firmware und Konfigurationsdaten bei Start und Laufzeit." + "prose": "Automatische Überprüfung der Integrität von Software, Firmware und Konfigurationsdaten bei Start und Laufzeit." } ], "links": [ @@ -443,7 +443,7 @@ { "id": "cra-ai-7_smt", "name": "statement", - "prose": "Sichere Authentifizierungsmechanismen, MFA fuer administrative Zugriffe, FIDO2/WebAuthn." + "prose": "Sichere Authentifizierungsmechanismen, MFA für administrative Zugriffe, FIDO2/WebAuthn." } ], "links": [ @@ -456,7 +456,7 @@ { "id": "cra-ai-8", "class": "cra-annex-i", - "title": "Keine Default-Passwoerter", + "title": "Keine Default-Passwörter", "props": [ { "name": "label", @@ -501,7 +501,7 @@ { "id": "cra-ai-8_smt", "name": "statement", - "prose": "Produkte duerfen keine universellen Standardpasswoerter verwenden. Aenderung bei Ersteinrichtung erzwingen." + "prose": "Produkte dürfen keine universellen Standardpasswörter verwenden. Änderung bei Ersteinrichtung erzwingen." } ], "links": [ @@ -559,7 +559,7 @@ { "id": "cra-ai-9_smt", "name": "statement", - "prose": "Zugangsdaten verschluesselt speichern (bcrypt, Argon2id). Keine Klartextspeicherung. Tokens rotieren." + "prose": "Zugangsdaten verschlüsselt speichern (bcrypt, Argon2id). Keine Klartextspeicherung. Tokens rotieren." } ], "links": [ @@ -767,7 +767,7 @@ { "id": "cra-ai-13", "class": "cra-annex-i", - "title": "Verschluesselung sensibler Daten", + "title": "Verschlüsselung sensibler Daten", "props": [ { "name": "label", @@ -812,7 +812,7 @@ { "id": "cra-ai-13_smt", "name": "statement", - "prose": "Sensible Daten at rest (AES-256) und in transit (TLS 1.2+) verschluesseln." + "prose": "Sensible Daten at rest (AES-256) und in transit (TLS 1.2+) verschlüsseln." } ], "links": [ @@ -870,7 +870,7 @@ { "id": "cra-ai-14_smt", "name": "statement", - "prose": "Verschluesselung von Festplatten, Datenbanken, Backups. Schluessel getrennt von Daten." + "prose": "Verschlüsselung von Festplatten, Datenbanken, Backups. Schlüssel getrennt von Daten." } ], "links": [ @@ -928,7 +928,7 @@ { "id": "cra-ai-15_smt", "name": "statement", - "prose": "TLS 1.2+ fuer alle Netzwerkkommunikation. SSL/TLS 1.0/1.1 deaktivieren. Certificate Pinning." + "prose": "TLS 1.2+ für alle Netzwerkkommunikation. SSL/TLS 1.0/1.1 deaktivieren. Certificate Pinning." } ], "links": [ @@ -941,7 +941,7 @@ { "id": "cra-ai-16", "class": "cra-annex-i", - "title": "Sicheres Schluesselmanagement", + "title": "Sicheres Schlüsselmanagement", "props": [ { "name": "label", @@ -986,7 +986,7 @@ { "id": "cra-ai-16_smt", "name": "statement", - "prose": "Schluessel in HSM/Vault. Mind. jaehrliche Rotation. Dokumentation der Lebenszyklen." + "prose": "Schlüssel in HSM/Vault. Mind. jährliche Rotation. Dokumentation der Lebenszyklen." } ], "links": [ @@ -1049,7 +1049,7 @@ { "id": "cra-ai-17_smt", "name": "statement", - "prose": "Nur Daten erfassen, die fuer die Produktfunktion erforderlich sind. DSGVO-Grundsaetze beachten." + "prose": "Nur Daten erfassen, die für die Produktfunktion erforderlich sind. DSGVO-Grundsätze beachten." } ], "links": [ @@ -1177,7 +1177,7 @@ { "id": "cra-ai-19_smt", "name": "statement", - "prose": "Peer Reviews mit Security-Fokus fuer jeden Commit. OWASP Top 10 + CWE Top 25 Checklisten." + "prose": "Peer Reviews mit Security-Fokus für jeden Commit. OWASP Top 10 + CWE Top 25 Checklisten." } ], "links": [ @@ -1305,7 +1305,7 @@ { "id": "cra-ai-21_smt", "name": "statement", - "prose": "Drittanbieter-Komponenten systematisch auf Schwachstellen und Lizenz-Compliance pruefen." + "prose": "Drittanbieter-Komponenten systematisch auf Schwachstellen und Lizenz-Compliance prüfen." } ], "links": [ @@ -1368,7 +1368,7 @@ { "id": "cra-ai-22_smt", "name": "statement", - "prose": "Kontinuierliche CVE-Ueberwachung aller Abhaengigkeiten. Automatische Benachrichtigungen." + "prose": "Kontinuierliche CVE-Überwachung aller Abhängigkeiten. Automatische Benachrichtigungen." } ], "links": [ @@ -1426,7 +1426,7 @@ { "id": "cra-ai-23_smt", "name": "statement", - "prose": "Maschinenlesbares SBOM (CycloneDX oder SPDX). Top-Level-Abhaengigkeiten mit Name, Version, Lizenz. Bei jedem Release aktualisieren." + "prose": "Maschinenlesbares SBOM (CycloneDX oder SPDX). Top-Level-Abhängigkeiten mit Name, Version, Lizenz. Bei jedem Release aktualisieren." } ], "links": [ @@ -1553,7 +1553,7 @@ { "id": "cra-ai-25_smt", "name": "statement", - "prose": "Zentrale Sammlung und Echtzeit-Ueberwachung. SIEM oder vergleichbares. Event-Korrelation." + "prose": "Zentrale Sammlung und Echtzeit-Überwachung. SIEM oder vergleichbares. Event-Korrelation." } ], "links": [ @@ -1624,7 +1624,7 @@ { "id": "cra-ai-27", "class": "cra-annex-i", - "title": "Log-Integritaet und -Aufbewahrung", + "title": "Log-Integrität und -Aufbewahrung", "props": [ { "name": "label", @@ -1739,7 +1739,7 @@ { "id": "cra-ai-28_smt", "name": "statement", - "prose": "Updates ueber sichere Kanaele (HTTPS, signiert). Automatische oder einfach zugaengliche Update-Moeglichkeit. Rollback-Faehigkeit." + "prose": "Updates über sichere Kanäle (HTTPS, signiert). Automatische oder einfach zugängliche Update-Möglichkeit. Rollback-Fähigkeit." } ], "links": [ @@ -1756,7 +1756,7 @@ { "id": "cra-ai-29", "class": "cra-annex-i", - "title": "Update-Authentizitaet", + "title": "Update-Authentizität", "props": [ { "name": "label", @@ -1801,7 +1801,7 @@ { "id": "cra-ai-29_smt", "name": "statement", - "prose": "Updates digital signiert. Signaturpruefung vor Installation. Dokumentierte Key Ceremony." + "prose": "Updates digital signiert. Signaturprüfung vor Installation. Dokumentierte Key Ceremony." } ], "links": [ @@ -1814,7 +1814,7 @@ { "id": "cra-ai-30", "class": "cra-annex-i", - "title": "Update-Integritaet", + "title": "Update-Integrität", "props": [ { "name": "label", @@ -1859,7 +1859,7 @@ { "id": "cra-ai-30_smt", "name": "statement", - "prose": "Integritaetspruefung jedes Update-Pakets (Hash, Signatur). Manipulationen waehrend Uebertragung erkennen." + "prose": "Integritätsprüfung jedes Update-Pakets (Hash, Signatur). Manipulationen während Übertragung erkennen." } ], "links": [ @@ -1917,7 +1917,7 @@ { "id": "cra-ai-31_smt", "name": "statement", - "prose": "Security-Updates fuer mind. 5 Jahre ab Inverkehrbringen oder erwartete Nutzungsdauer. End-of-Life klar kommunizieren." + "prose": "Security-Updates für mind. 5 Jahre ab Inverkehrbringen oder erwartete Nutzungsdauer. End-of-Life klar kommunizieren." } ], "links": [ @@ -2045,7 +2045,7 @@ { "id": "cra-ai-33_smt", "name": "statement", - "prose": "SBOM aktuell halten und kontinuierlich gegen CVE-Datenbanken pruefen. Auto-Alarmierung bei neuen CVEs." + "prose": "SBOM aktuell halten und kontinuierlich gegen CVE-Datenbanken prüfen. Auto-Alarmierung bei neuen CVEs." } ], "links": [ @@ -2103,7 +2103,7 @@ { "id": "cra-ai-34_smt", "name": "statement", - "prose": "CVSS-basierte Priorisierung. SLAs: Kritisch 24-72h, Hoch 7 Tage, Mittel 30 Tage, Niedrig naechster Zyklus." + "prose": "CVSS-basierte Priorisierung. SLAs: Kritisch 24-72h, Hoch 7 Tage, Mittel 30 Tage, Niedrig nächster Zyklus." } ], "links": [ @@ -2166,7 +2166,7 @@ { "id": "cra-ai-35_smt", "name": "statement", - "prose": "CVD-Policy mit Meldeprozess. Kontaktadresse fuer Forscher. Eingangsbestaetigung innerhalb 5 Werktagen." + "prose": "CVD-Policy mit Meldeprozess. Kontaktadresse für Forscher. Eingangsbestätigung innerhalb 5 Werktagen." } ], "links": [ @@ -2247,7 +2247,7 @@ { "id": "cra-ai-37", "class": "cra-annex-i", - "title": "Fruehwarnung (24h)", + "title": "Frühwarnung (24h)", "props": [ { "name": "label", @@ -2297,7 +2297,7 @@ { "id": "cra-ai-37_smt", "name": "statement", - "prose": "Bei aktiv ausgenutzten Schwachstellen oder schweren Vorfaellen: Fruehwarnung an ENISA/CSIRT innerhalb 24 Stunden." + "prose": "Bei aktiv ausgenutzten Schwachstellen oder schweren Vorfällen: Frühwarnung an ENISA/CSIRT innerhalb 24 Stunden." } ], "links": [ @@ -2360,7 +2360,7 @@ { "id": "cra-ai-38_smt", "name": "statement", - "prose": "72h: Detaillierter Bericht mit Umfang, Auswirkung, Ursachenanalyse, Gegenmassnahmen. Bei personenbezogenen Daten zusaetzlich DSGVO Art. 33/34." + "prose": "72h: Detaillierter Bericht mit Umfang, Auswirkung, Ursachenanalyse, Gegenmaßnahmen. Bei personenbezogenen Daten zusätzlich DSGVO Art. 33/34." } ], "links": [ @@ -2418,7 +2418,7 @@ { "id": "cra-ai-39_smt", "name": "statement", - "prose": "Patches fuer gemeldete Schwachstellen so schnell wie moeglich. Security Advisories (CSAF-Format empfohlen)." + "prose": "Patches für gemeldete Schwachstellen so schnell wie möglich. Security Advisories (CSAF-Format empfohlen)." } ], "links": [ @@ -2476,7 +2476,7 @@ { "id": "cra-ai-40_smt", "name": "statement", - "prose": "Lueckenlose Dokumentation aller Schwachstellen + Vorfaelle, mind. 10 Jahre Aufbewahrung. Lessons-Learned-Prozess." + "prose": "Lückenlose Dokumentation aller Schwachstellen + Vorfälle, mind. 10 Jahre Aufbewahrung. Lessons-Learned-Prozess." } ], "links": [ diff --git a/compliance-agent/src/controls/oscal_provider.rs b/compliance-agent/src/controls/oscal_provider.rs index 78582e6..e56bacc 100644 --- a/compliance-agent/src/controls/oscal_provider.rs +++ b/compliance-agent/src/controls/oscal_provider.rs @@ -122,7 +122,17 @@ impl OscalControlsProvider { /// Load the catalog for a framework token: fetch fresh + snapshot the exact /// bytes; on network failure, fall back to the last snapshot so scans run. + /// + /// Either way its titles and prose are spelled with real umlauts: the + /// catalog spells them out, and its titles reach customers (#463). async fn load_token(&self, framework: &str) -> Result { + let mut doc = self.load_token_as_served(framework).await?; + doc.restore_umlauts(); + Ok(doc) + } + + /// [`Self::load_token`] without the spelling fix. + async fn load_token_as_served(&self, framework: &str) -> Result { match self.fetch_raw(framework).await { Ok(raw) => { let doc: OscalDocument = serde_json::from_slice(&raw)?; @@ -319,4 +329,47 @@ mod tests { assert!(offline.load_master_controls().await.is_err()); let _ = std::fs::remove_dir_all(&dir); } + + #[tokio::test] + async fn a_snapshot_written_before_the_spelling_fix_is_served_with_umlauts() { + // Prod keeps the snapshot it was seeded with (copy-if-absent), so the + // fix cannot rely on a corrected file. + let dir = std::env::temp_dir().join(format!("oscal-test-{}", uuid::Uuid::new_v4())); + let old = MINI_CATALOG + .replace("\"MFA\"", "\"Integritaetspruefung\"") + .replace("require mfa", "Updates muessen signiert sein"); + provider(&dir) + .write_snapshot("cra", old.as_bytes()) + .await + .unwrap(); + let offline = OscalControlsProvider::new(reqwest::Client::new(), None, None, &dir); + let controls = offline + .load(ComplianceFramework::Cra) + .await + .unwrap() + .to_controls(); + assert_eq!(controls[0].title, "Integritätsprüfung"); + assert_eq!(controls[0].text, "Updates müssen signiert sein"); + let _ = std::fs::remove_dir_all(&dir); + } + + #[test] + fn the_shipped_cra_snapshot_has_real_umlauts() { + const SHIPPED: &str = include_str!("../../controls/snapshot/oscal-catalog-cra.json"); + let doc: OscalDocument = serde_json::from_str(SHIPPED).unwrap(); + let controls = doc.to_controls(); + let c6 = controls.iter().find(|c| c.id == "cra-ai-6").unwrap(); + assert_eq!(c6.title, "Integritätsprüfung"); + // Already right, so the load-time fix changes nothing. + let mut restored = doc.clone(); + restored.restore_umlauts(); + let again: Vec<(String, String)> = restored + .to_controls() + .into_iter() + .map(|c| (c.title, c.text)) + .collect(); + let shipped: Vec<(String, String)> = + controls.into_iter().map(|c| (c.title, c.text)).collect(); + assert_eq!(again, shipped); + } } diff --git a/compliance-agent/src/finding_migrations.rs b/compliance-agent/src/finding_migrations.rs new file mode 100644 index 0000000..2806639 --- /dev/null +++ b/compliance-agent/src/finding_migrations.rs @@ -0,0 +1,215 @@ +//! 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 { + 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 { + 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; + } + 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 { + 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" + ); + } +} diff --git a/compliance-agent/src/lib.rs b/compliance-agent/src/lib.rs index 71bf4ff..3752894 100644 --- a/compliance-agent/src/lib.rs +++ b/compliance-agent/src/lib.rs @@ -9,6 +9,7 @@ pub mod database; pub mod demo_seed; pub mod error; pub mod evidence; +pub mod finding_migrations; pub mod fixtures; pub mod git_source; pub mod import; diff --git a/compliance-agent/src/main.rs b/compliance-agent/src/main.rs index 7aac538..4c0f8e8 100644 --- a/compliance-agent/src/main.rs +++ b/compliance-agent/src/main.rs @@ -1,4 +1,6 @@ -use compliance_agent::{agent, api, config, database, lifecycle, scheduler, secrets, webhooks}; +use compliance_agent::{ + agent, api, config, database, finding_migrations, lifecycle, scheduler, secrets, webhooks, +}; use compliance_core::shutdown; #[tokio::main] @@ -28,6 +30,19 @@ async fn main() -> Result<(), Box> { let agent = agent::ComplianceAgent::new(config.clone(), db_pool); + // Stored findings in the form the scans now write them (#463), before a + // scan (a resumed one included) can compare against them. + match finding_migrations::migrate_stored_findings(&agent.db_pool).await { + Ok(m) if m == finding_migrations::Migrated::default() => {} + Ok(m) => tracing::info!( + rule_ids = m.rule_ids, + fingerprints = m.fingerprints, + titles = m.titles, + "migrated stored findings" + ), + Err(e) => tracing::error!("migrating stored findings failed: {e}"), + } + // Before anything can start a new run, close the runs the previous agent // process left open when it stopped. let started_at = chrono::Utc::now(); diff --git a/compliance-agent/src/pipeline/semgrep.rs b/compliance-agent/src/pipeline/semgrep.rs index b117389..d27dde4 100644 --- a/compliance-agent/src/pipeline/semgrep.rs +++ b/compliance-agent/src/pipeline/semgrep.rs @@ -18,9 +18,10 @@ const REDACTED_LINES: &str = "requires login"; /// run without sending metrics to Semgrep. Each rule id is keyed back to its /// control by the `control-map` LUT. /// -/// Each pack is staged under its own fixed name: semgrep prefixes a rule's -/// check_id with the config path, and the check_id is part of a finding's -/// fingerprint, so the first pack keeps the name it always had. +/// Each pack is staged under its own fixed name. semgrep prefixes a rule's +/// check_id with the config's directory; [`bare_rule_id`] takes it off again +/// and [`fingerprint`] hashes a fixed prefix instead, so neither the staged +/// name nor the temp directory reaches a finding. const RULE_PACKS: &[(&str, &str)] = &[ ( "compliance-cra-semgrep.yaml", @@ -32,6 +33,59 @@ const RULE_PACKS: &[(&str, &str)] = &[ ), ]; +/// What a finding's fingerprint hashes in front of our rule id. +/// +/// semgrep prefixes a rule's id with the directory of its config file, +/// relative to its working directory: the packs are staged in the temp +/// directory, so the agent stored ids like `tmp.cra-ai-20-csharp-xxe`, and +/// fingerprints computed from them. The rule id is now stored bare +/// ([`bare_rule_id`]); the fingerprint keeps hashing this prefix so the +/// findings already stored keep theirs and a rescan finds nothing new (#463). +/// It is fixed here, no longer taken from wherever the temp directory is. +const FINGERPRINT_RULE_PREFIX: &str = "tmp."; + +/// The ids of the rules in our packs, as written after `- id:`. +pub fn bundled_rule_ids() -> &'static [&'static str] { + static IDS: std::sync::LazyLock> = std::sync::LazyLock::new(|| { + RULE_PACKS + .iter() + .flat_map(|(_, rules)| rules.lines()) + .filter_map(|line| line.trim().strip_prefix("- id:")) + .map(str::trim) + .collect() + }); + &IDS +} + +/// Our rule id without the path semgrep puts in front of it +/// (`tmp.cra-ai-8-csharp-hardcoded-credential` → `cra-ai-8-csharp-hardcoded-credential`, +/// also the older `tmp.compliance-cra-semgrep.cra-ai-1-…` form). An id that is +/// not one of ours is returned unchanged. +pub fn bare_rule_id(check_id: &str) -> &str { + bundled_rule_ids() + .iter() + .copied() + .find(|id| { + check_id == *id + || check_id + .strip_suffix(id) + .is_some_and(|prefix| prefix.ends_with('.')) + }) + .unwrap_or(check_id) +} + +/// The fingerprint of a semgrep finding for `rule` (bare or not) at +/// `path:line`: the same one the agent stored before the ids were made bare. +pub fn fingerprint(repo_id: &str, rule: &str, path: &str, line: u32) -> String { + let rule = bare_rule_id(rule); + let hashed = if bundled_rule_ids().contains(&rule) { + format!("{FINGERPRINT_RULE_PREFIX}{rule}") + } else { + rule.to_string() + }; + dedup::compute_fingerprint(&[repo_id, &hashed, path, &line.to_string()]) +} + /// Write the bundled rule packs to stable temp paths (atomic: unique tmp + /// rename). The tmp name is unique per call, not per process: scans run /// concurrently in one agent, and a shared tmp file let one scan rename it @@ -150,12 +204,7 @@ impl Scanner for SemgrepScanner { // which means nothing to a customer and changes when an archive // is uploaded again. let path = relative_path(repo_path, &r.path); - let fingerprint = dedup::compute_fingerprint(&[ - repo_id, - &r.check_id, - &path, - &r.start.line.to_string(), - ]); + let fingerprint = fingerprint(repo_id, &r.check_id, &path, r.start.line); let end_line = r.end.as_ref().map_or(r.start.line, |e| e.line); let snippet = read_lines(repo_path, &path, r.start.line, end_line) .or_else(|| (r.extra.lines != REDACTED_LINES).then(|| r.extra.lines.clone())); @@ -169,7 +218,7 @@ impl Scanner for SemgrepScanner { r.extra.message, severity, ); - finding.rule_id = Some(r.check_id); + finding.rule_id = Some(bare_rule_id(&r.check_id).to_string()); finding.file_path = Some(path); finding.line_number = Some(r.start.line); finding.code_snippet = snippet; @@ -322,9 +371,75 @@ mod tests { .collect(); bundled.sort(); assert_eq!(on_disk, bundled); - // The first pack keeps its staged name: check_ids, and with them the - // fingerprints of existing findings, depend on it. - assert_eq!(RULE_PACKS[0].0, "compliance-cra-semgrep.yaml"); + } + + #[test] + fn rule_ids_are_stored_without_the_staging_path() { + for id in [ + "tmp.cra-ai-20-csharp-xxe", + "tmp.compliance-cra-semgrep-csharp.cra-ai-20-csharp-xxe", + "var.tmp.cra-ai-20-csharp-xxe", + "cra-ai-20-csharp-xxe", + ] { + assert_eq!(bare_rule_id(id), "cra-ai-20-csharp-xxe", "{id}"); + } + assert_eq!( + bare_rule_id("tmp.cra-ai-20-c-unbounded-string-function"), + "cra-ai-20-c-unbounded-string-function" + ); + // Not ours: left as semgrep reported it. + assert_eq!( + bare_rule_id("python.lang.security.audit.exec-detected"), + "python.lang.security.audit.exec-detected" + ); + // A suffix that is not a whole id segment is not a match. + assert_eq!( + bare_rule_id("tmp.xcra-ai-20-csharp-xxe"), + "tmp.xcra-ai-20-csharp-xxe" + ); + // Our ids have no dots, so a bare one can never look prefixed. + assert!(bundled_rule_ids().iter().all(|id| !id.contains('.'))); + assert!(bundled_rule_ids().len() > 20); + } + + #[test] + fn a_rescan_keeps_the_fingerprints_stored_with_the_prefixed_ids() { + // What the agent stored before #463, from the check_id semgrep + // reported with the packs staged in /tmp. + let stored = dedup::compute_fingerprint(&[ + "repo-1", + "tmp.cra-ai-8-csharp-hardcoded-credential", + "src/Settings.cs", + "12", + ]); + // A rescan computes the same one, whatever directory semgrep put in + // front of the id this time, or none. + for reported in [ + "tmp.cra-ai-8-csharp-hardcoded-credential", + "cra-ai-8-csharp-hardcoded-credential", + "srv.scratch.cra-ai-8-csharp-hardcoded-credential", + ] { + assert_eq!( + fingerprint("repo-1", reported, "src/Settings.cs", 12), + stored, + "{reported}" + ); + } + // Different location, different finding. + assert_ne!( + fingerprint( + "repo-1", + "cra-ai-8-csharp-hardcoded-credential", + "src/Settings.cs", + 13 + ), + stored + ); + // An id that is not ours hashes as reported. + assert_eq!( + fingerprint("repo-1", "rule-x", "a.py", 1), + dedup::compute_fingerprint(&["repo-1", "rule-x", "a.py", "1"]) + ); } #[test] diff --git a/compliance-agent/tests/finding_migrations.rs b/compliance-agent/tests/finding_migrations.rs new file mode 100644 index 0000000..7f222c0 --- /dev/null +++ b/compliance-agent/tests/finding_migrations.rs @@ -0,0 +1,161 @@ +//! #463: stored findings are rewritten in place, and a rescan of the same +//! tree afterwards finds nothing new. 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::finding_migrations::{migrate_tenant, Migrated}; +use compliance_agent::pipeline::dedup::compute_fingerprint; +use compliance_agent::pipeline::finding_store::RunFindings; +use compliance_agent::pipeline::semgrep; +use compliance_core::models::{Finding, ScanType, Severity}; +use mongodb::bson::doc; + +const TENANT: &str = "finding-migrations"; +const TARGET: &str = "target-1"; + +/// A semgrep finding as the scanner writes it for `rule` (as reported) at +/// `path:line`, with the given fingerprint. +fn semgrep_finding(rule: &str, fingerprint: String, path: &str, line: u32) -> Finding { + let mut f = Finding::new( + TARGET.into(), + fingerprint, + "semgrep".into(), + ScanType::Sast, + "XML parser resolves external entities".into(), + "XML parser resolves external entities".into(), + Severity::High, + ); + f.rule_id = Some(rule.into()); + f.file_path = Some(path.into()); + f.line_number = Some(line); + f +} + +async fn by_fingerprint(db: &Database, fingerprint: &str) -> Finding { + db.findings() + .find_one(doc! { "fingerprint": fingerprint }) + .await + .unwrap() + .unwrap() +} + +#[tokio::test] +async fn stored_findings_are_migrated_and_a_rescan_finds_nothing_new() { + let uri = std::env::var("TEST_MONGODB_URI") + .unwrap_or_else(|_| "mongodb://root:example@localhost:27017/?authSource=admin".into()); + let prefix = format!( + "migrate_{}", + &uuid::Uuid::new_v4().simple().to_string()[..10] + ); + let Ok(pool) = DatabasePool::connect(&uri, &prefix).await else { + eprintln!("SKIP finding_migrations: no MongoDB reachable at {uri}"); + return; + }; + let Ok(db) = pool.for_tenant_id(TENANT).await else { + eprintln!("SKIP finding_migrations: MongoDB at {uri} not usable"); + return; + }; + + // Arrange: what the agent stored before #463. + let legacy = |rule: &str, path: &str, line: u32| { + let fp = compute_fingerprint(&[TARGET, rule, path, &line.to_string()]); + semgrep_finding(rule, fp, path, line) + }; + let xxe = legacy("tmp.cra-ai-20-csharp-xxe", "src/Xml.cs", 7); + let cred = legacy( + "tmp.cra-ai-8-csharp-hardcoded-credential", + "src/Settings.cs", + 12, + ); + let older = legacy( + "tmp.compliance-cra-semgrep.cra-ai-1-flask-debug-enabled", + "app.py", + 3, + ); + let mut control = Finding::new( + TARGET.into(), + "fp-control".into(), + "control-check".into(), + ScanType::CodeReview, + "cra-ai-6: Integritaetspruefung".into(), + "Control cra-ai-6 appears violated (Updates muessen signiert sein) at a.c:1".into(), + Severity::Medium, + ); + control.file_path = Some("a.c".into()); + db.findings() + .insert_many([xxe.clone(), cred.clone(), older.clone(), control]) + .await + .unwrap(); + + // Act + let first = migrate_tenant(&db).await.unwrap(); + + // Assert: ids bare, the tmp. fingerprints untouched, the older one moved + // to what a scan computes, the title spelled right. + assert_eq!( + first, + Migrated { + rule_ids: 3, + fingerprints: 1, + titles: 1 + } + ); + let row = by_fingerprint(&db, &xxe.fingerprint).await; + assert_eq!(row.rule_id.as_deref(), Some("cra-ai-20-csharp-xxe")); + let row = by_fingerprint(&db, &cred.fingerprint).await; + assert_eq!( + row.rule_id.as_deref(), + Some("cra-ai-8-csharp-hardcoded-credential") + ); + let moved = semgrep::fingerprint(TARGET, "cra-ai-1-flask-debug-enabled", "app.py", 3); + let row = by_fingerprint(&db, &moved).await; + assert_eq!(row.rule_id.as_deref(), Some("cra-ai-1-flask-debug-enabled")); + let row = by_fingerprint(&db, "fp-control").await; + assert_eq!(row.title, "cra-ai-6: Integritätsprüfung"); + assert!(row.description.contains("Updates müssen")); + + // A second start changes nothing. + assert_eq!(migrate_tenant(&db).await.unwrap(), Migrated::default()); + + // A rescan of the unchanged tree reports the same findings, with bare ids + // and whatever prefix semgrep puts in front this time: none is new. + let mut rescan: Vec = [ + ("tmp.cra-ai-20-csharp-xxe", "src/Xml.cs", 7), + ( + "cra-ai-8-csharp-hardcoded-credential", + "src/Settings.cs", + 12, + ), + ( + "tmp.compliance-cra-semgrep.cra-ai-1-flask-debug-enabled", + "app.py", + 3, + ), + ] + .into_iter() + .map(|(rule, path, line)| { + let mut f = semgrep_finding( + semgrep::bare_rule_id(rule), + semgrep::fingerprint(TARGET, rule, path, line), + path, + line, + ); + f.rule_id = Some(semgrep::bare_rule_id(rule).to_string()); + f + }) + .collect(); + let mut run = RunFindings::new("run-rescan"); + run.completed("semgrep"); + assert_eq!(run.save_new(&db, &mut rescan).await.unwrap(), 0); + assert_eq!( + db.findings() + .count_documents(doc! { "scanner": "semgrep" }) + .await + .unwrap(), + 3 + ); + + pool.drop_tenant(TENANT).await.ok(); +} diff --git a/compliance-core/src/models/oscal.rs b/compliance-core/src/models/oscal.rs index 8677a82..72d8b4e 100644 --- a/compliance-core/src/models/oscal.rs +++ b/compliance-core/src/models/oscal.rs @@ -156,6 +156,16 @@ impl OscalDocument { self.catalog.metadata.prop("content-hash") } + /// Spell the catalog's group and control titles and statement prose with + /// real umlauts where the catalog transliterated them + /// ("Integritaetspruefung" → "Integritätsprüfung"). The titles reach + /// customers in findings and reports; see [`restore_umlauts`]. + pub fn restore_umlauts(&mut self) { + for group in &mut self.catalog.groups { + restore_group(group); + } + } + /// Flatten the catalog into the corpus controls the mapping engine consumes. pub fn to_controls(&self) -> Vec { let framework = self.framework().unwrap_or(ComplianceFramework::Cra); @@ -168,6 +178,125 @@ impl OscalDocument { } } +/// Transliterated German words in the CRA catalog and their real spelling. +/// A word list and not a rule: `ae`/`oe`/`ue`/`ss` stand for an umlaut or +/// `ß` only in some words ("aktuell", "neue", "Quelle", "Prozess" are spelled +/// right). Lower-case entries also match a capitalised word ("Fuer"). +const TRANSLITERATED: &[(&str, &str)] = &[ + ("Abhaengigkeiten", "Abhängigkeiten"), + ("Aenderung", "Änderung"), + ("Aenderungen", "Änderungen"), + ("Angriffsflaeche", "Angriffsfläche"), + ("Authentizitaet", "Authentizität"), + ("Eingangsbestaetigung", "Eingangsbestätigung"), + ("Faehigkeit", "Fähigkeit"), + ("Fruehwarnung", "Frühwarnung"), + ("Gegenmassnahmen", "Gegenmaßnahmen"), + ("Grundsaetze", "Grundsätze"), + ("Integritaet", "Integrität"), + ("Integritaetspruefung", "Integritätsprüfung"), + ("Kanaele", "Kanäle"), + ("Lueckenlose", "Lückenlose"), + ("Massnahmen", "Maßnahmen"), + ("Moeglichkeit", "Möglichkeit"), + ("Passwoerter", "Passwörter"), + ("Pruefung", "Prüfung"), + ("Schluessel", "Schlüssel"), + ("Schluesselmanagement", "Schlüsselmanagement"), + ("Signaturpruefung", "Signaturprüfung"), + ("Standardpasswoerter", "Standardpasswörter"), + ("Ueberpruefung", "Überprüfung"), + ("Uebertragung", "Übertragung"), + ("Ueberwachung", "Überwachung"), + ("Verschluesselung", "Verschlüsselung"), + ("Vorfaelle", "Vorfälle"), + ("Vorfaellen", "Vorfällen"), + ("duerfen", "dürfen"), + ("erhaelt", "erhält"), + ("fuer", "für"), + ("jaehrliche", "jährliche"), + ("moeglich", "möglich"), + ("muessen", "müssen"), + ("naechster", "nächster"), + ("pruefen", "prüfen"), + ("ueber", "über"), + ("unnoetig", "unnötig"), + ("verschluesseln", "verschlüsseln"), + ("verschluesselt", "verschlüsselt"), + ("waehrend", "während"), + ("zugaengliche", "zugängliche"), + ("zusaetzlich", "zusätzlich"), +]; + +/// The real spelling of one transliterated word, if it is one. +fn umlaut_word(word: &str) -> Option { + if let Some((_, real)) = TRANSLITERATED.iter().find(|(t, _)| *t == word) { + return Some((*real).to_string()); + } + // "Fuer" at the start of a sentence: the lower-case entry, capitalised. + let mut chars = word.chars(); + let first = chars.next().filter(char::is_ascii_uppercase)?; + let lowered = format!("{}{}", first.to_ascii_lowercase(), chars.as_str()); + let (_, real) = TRANSLITERATED.iter().find(|(t, _)| *t == lowered)?; + let mut real_chars = real.chars(); + let head = real_chars.next()?; + Some(head.to_uppercase().chain(real_chars).collect()) +} + +/// `text` with every transliterated word of [`TRANSLITERATED`] spelled with +/// its umlauts. Words are runs of letters, so "Log-Integritaet" and +/// "CVE-Ueberwachung" are covered; anything else is left as it is. +pub fn restore_umlauts(text: &str) -> String { + let mut out = String::with_capacity(text.len() + 8); + let mut word = String::new(); + let flush = |word: &mut String, out: &mut String| { + match umlaut_word(word) { + Some(real) => out.push_str(&real), + None => out.push_str(word), + } + word.clear(); + }; + for c in text.chars() { + if c.is_alphabetic() { + word.push(c); + } else { + flush(&mut word, &mut out); + out.push(c); + } + } + flush(&mut word, &mut out); + out +} + +fn restore_group(group: &mut Group) { + group.title = restore_umlauts(&group.title); + for control in &mut group.controls { + restore_control(control); + } + for sub in &mut group.groups { + restore_group(sub); + } +} + +fn restore_control(control: &mut Control) { + control.title = restore_umlauts(&control.title); + for part in &mut control.parts { + restore_part(part); + } + for enhancement in &mut control.controls { + restore_control(enhancement); + } +} + +fn restore_part(part: &mut Part) { + if let Some(prose) = &part.prose { + part.prose = Some(restore_umlauts(prose)); + } + for sub in &mut part.parts { + restore_part(sub); + } +} + /// Map an OSCAL framework token (e.g. `"cra"`) to [`ComplianceFramework`] via its /// serde snake_case representation. fn framework_from_str(raw: &str) -> Option { @@ -250,6 +379,57 @@ mod tests { assert!(c8.source.as_deref().unwrap_or_default().contains("Annex I")); } + #[test] + fn umlauts_are_restored_in_titles_and_prose() { + // The catalog as breakpilot-compliance serves it spells umlauts out. + let mut doc = parse(); + doc.restore_umlauts(); + let controls = doc.to_controls(); + let title = |id: &str| { + controls + .iter() + .find(|c| c.id == id) + .map(|c| c.title.clone()) + .unwrap() + }; + assert_eq!(title("cra-ai-6"), "Integritätsprüfung"); + assert_eq!(title("cra-ai-8"), "Keine Default-Passwörter"); + assert_eq!(title("cra-ai-24"), "Security-Logging"); + for c in &controls { + for word in [ + "Integritaet", + "pruef", + "Schluessel", + "Passwoerter", + " fuer ", + ] { + assert!(!c.title.contains(word), "{}: {}", c.id, c.title); + assert!(!c.text.contains(word), "{}: {}", c.id, c.text); + } + } + } + + #[test] + fn restoring_umlauts_leaves_other_words_alone() { + assert_eq!( + restore_umlauts("Log-Integritaet und -Aufbewahrung"), + "Log-Integrität und -Aufbewahrung" + ); + assert_eq!(restore_umlauts("Fuer neue Quellen"), "Für neue Quellen"); + assert_eq!( + restore_umlauts("aktuell, Prozess, Dauer, Request, Queue, issue"), + "aktuell, Prozess, Dauer, Request, Queue, issue" + ); + assert_eq!( + restore_umlauts("CVE-Ueberwachung (24h)"), + "CVE-Überwachung (24h)" + ); + // Already right: nothing to do, and doing it twice changes nothing. + let once = restore_umlauts("Integritaetspruefung fuer Schluessel"); + assert_eq!(once, "Integritätsprüfung für Schlüssel"); + assert_eq!(restore_umlauts(&once), once); + } + #[test] fn exposes_content_hash_for_snapshotting() { assert_eq!(parse().content_hash().map(str::len), Some(64));