diff --git a/compliance-agent/src/api/handlers/evidence.rs b/compliance-agent/src/api/handlers/evidence.rs index cd85cca..3d8d92a 100644 --- a/compliance-agent/src/api/handlers/evidence.rs +++ b/compliance-agent/src/api/handlers/evidence.rs @@ -12,6 +12,7 @@ use compliance_core::tenant_ctx::TenantCtx; use super::dto::{collect_cursor_async, tenant_db, AgentExt}; use super::sbom::MAX_EXPORT_COMPONENTS; +use crate::agent::ComplianceAgent; use crate::database::Database; use crate::evidence::compliance::ControlState; use crate::evidence::{build_pack, compliance_of, EvidenceInputs}; @@ -21,7 +22,11 @@ const MAX_PACK_FINDINGS: u64 = 50_000; /// Everything stored about target `id`: 404 for an unknown target, 413 when it /// is too large to build in memory. -async fn load_inputs(db: &Database, id: &str) -> Result { +async fn load_inputs( + agent: &ComplianceAgent, + db: &Database, + id: &str, +) -> Result { let oid = ObjectId::parse_str(id).map_err(|_| StatusCode::BAD_REQUEST)?; let target = db .onboarded_targets() @@ -77,6 +82,7 @@ async fn load_inputs(db: &Database, id: &str) -> Result, ) -> Result, StatusCode> { let db = tenant_db(&agent, &tenant).await?; - let inputs = load_inputs(&db, &id).await?; + let inputs = load_inputs(&agent, &db, &id).await?; let controls = compliance_of(&inputs); let count = |state: ControlState| controls.iter().filter(|c| c.state == state).count(); Ok(Json(serde_json::json!({ @@ -120,7 +126,7 @@ pub async fn evidence_pack( Path(id): Path, ) -> Result { let db = tenant_db(&agent, &tenant).await?; - let inputs = load_inputs(&db, &id).await?; + let inputs = load_inputs(&agent, &db, &id).await?; let now = chrono::Utc::now(); let (zip, _files) = tokio::task::spawn_blocking(move || build_pack(&inputs, now)) diff --git a/compliance-agent/src/controls/mod.rs b/compliance-agent/src/controls/mod.rs index f14cee0..f08ffd7 100644 --- a/compliance-agent/src/controls/mod.rs +++ b/compliance-agent/src/controls/mod.rs @@ -18,6 +18,8 @@ pub use checker::GroundedControlChecker; pub use index::ControlIndex; pub use judge::{ControlJudge, JudgeError, LlmControlJudge, PROMPT_VERSION}; pub use oscal_provider::OscalControlsProvider; -pub use scan_triage::{grounded_surface_findings, semantic_stamp_findings, triage_repo_findings}; +pub use scan_triage::{ + cra_catalog, grounded_surface_findings, semantic_stamp_findings, triage_repo_findings, +}; pub use semantic::SemanticControlChecker; pub use triage::{ControlTriage, TriageOutcome}; diff --git a/compliance-agent/src/controls/oscal_provider.rs b/compliance-agent/src/controls/oscal_provider.rs index 4777771..27903e0 100644 --- a/compliance-agent/src/controls/oscal_provider.rs +++ b/compliance-agent/src/controls/oscal_provider.rs @@ -231,6 +231,8 @@ mod tests { title: title.into(), text: String::new(), source: None, + severity: None, + evidence_type: None, }; let controls = vec![ mk("a", "logging policy"), @@ -267,6 +269,20 @@ mod tests { assert_eq!(doc.to_controls().len(), 40); } + #[test] + fn the_control_map_and_the_shipped_catalog_name_the_same_controls() { + // The map is ours, the catalog breakpilot-compliance's: a control one + // has and the other lacks would never be triaged or never be shown. + const SHIPPED: &str = include_str!("../../controls/snapshot/oscal-catalog-cra.json"); + let doc: OscalDocument = serde_json::from_str(SHIPPED).unwrap(); + let mut catalog: Vec = doc.to_controls().into_iter().map(|c| c.id).collect(); + let map = control_map::ControlMap::cra().unwrap(); + let mut mapped: Vec = map.controls.into_iter().map(|c| c.control).collect(); + catalog.sort(); + mapped.sort(); + assert_eq!(catalog, mapped); + } + #[tokio::test] async fn snapshot_only_mode_serves_baked_catalog() { let dir = std::env::temp_dir().join(format!("oscal-test-{}", uuid::Uuid::new_v4())); diff --git a/compliance-agent/src/controls/scan_triage.rs b/compliance-agent/src/controls/scan_triage.rs index 0169d75..6f86334 100644 --- a/compliance-agent/src/controls/scan_triage.rs +++ b/compliance-agent/src/controls/scan_triage.rs @@ -13,6 +13,7 @@ use std::sync::Arc; use compliance_core::control_check::{CandidateRegion, ControlCheckSpec}; use compliance_core::models::finding::{Finding, FindingStatus, Severity}; use compliance_core::models::onboarding::ComplianceFramework; +use compliance_core::traits::Control; use compliance_core::AgentConfig; use control_map::ControlMap; @@ -101,6 +102,25 @@ fn provider_for(config: &AgentConfig) -> Option { )) } +/// The CRA catalog's controls by id (from the backend or the baked snapshot), +/// for the ratings the CRA status shows. Empty when no catalog is available. +pub async fn cra_catalog(config: &AgentConfig) -> HashMap { + let Some(provider) = provider_for(config) else { + return HashMap::new(); + }; + match provider.load(ComplianceFramework::Cra).await { + Ok(doc) => doc + .to_controls() + .into_iter() + .map(|c| (c.id.clone(), c)) + .collect(), + Err(e) => { + tracing::warn!(error = %e, "could not load the CRA catalog"); + HashMap::new() + } + } +} + async fn build_specs(provider: &OscalControlsProvider) -> HashMap { let mut specs = HashMap::new(); match provider.load(ComplianceFramework::Cra).await { @@ -113,7 +133,8 @@ async fn build_specs(provider: &OscalControlsProvider) -> HashMap ControlTriage { // Match by CWE (off-the-shelf findings) and/or rule id (our custom // detectors, which carry no LUT-bound CWE). A finding with neither is // simply unmapped. - let mapped = self.map.controls_for_finding( + let mapped = self.map.bindings_for_finding( &finding.scanner, finding.cwe.as_deref(), finding.rule_id.as_deref(), @@ -66,14 +67,23 @@ impl ControlTriage { let mut confirmed = Vec::new(); let mut refuted = 0_usize; let mut undecided = 0_usize; - for entry in mapped { + for (entry, binding) in mapped { let Some(spec) = self.specs.get(&entry.control) else { undecided += 1; continue; }; - match self.judge.judge(spec, region).await { + // The binding's own check text, where it has one: what this + // tool's finding means for the control, not the control's prose. + let spec = match &binding.check { + Some(check) => Cow::Owned(ControlCheckSpec { + requirement: check.clone(), + ..spec.clone() + }), + None => Cow::Borrowed(spec), + }; + match self.judge.judge(&spec, region).await { // The verdict only counts if it grounds to real code in the region. - Ok(verdict) if ground(spec, region, &verdict, &finding.repo_id).is_some() => { + Ok(verdict) if ground(&spec, region, &verdict, &finding.repo_id).is_some() => { confirmed.push(entry.control.clone()); } Ok(_) => refuted += 1, @@ -120,6 +130,24 @@ mod tests { } } + /// A judge that remembers the requirement text it was asked about. + #[derive(Default)] + struct RecordingJudge { + asked: std::sync::Mutex>, + } + impl ControlJudge for RecordingJudge { + async fn judge( + &self, + spec: &ControlCheckSpec, + _r: &CandidateRegion, + ) -> Result { + if let Ok(mut asked) = self.asked.lock() { + asked.push(spec.requirement.clone()); + } + Err(JudgeError::Unavailable("recording only".into())) + } + } + /// A judge that never answers, as when the model is down. struct DownJudge; impl ControlJudge for DownJudge { @@ -246,6 +274,33 @@ mod tests { assert_eq!(out, TriageOutcome::Undecided); } + #[tokio::test] + async fn the_judge_reads_the_bindings_check_not_the_controls_prose() { + // cra-ai-16's catalog prose is about key storage; a rand() finding is + // judged against what that finding means instead. + let mut specs = HashMap::new(); + specs.insert( + "cra-ai-16".to_string(), + ControlCheckSpec { + control_id: "cra-ai-16".into(), + title: "Key management".into(), + requirement: "Keys in an HSM or vault".into(), + default_cwe: None, + severity: Severity::High, + }, + ); + let triage = + ControlTriage::new(RecordingJudge::default(), ControlMap::cra().unwrap(), specs); + let mut f = semgrep_finding("CWE-338"); + f.rule_id = Some("cra-ai-16-c-predictable-random".into()); + + let _ = triage.triage(&f, ®ion()).await; + + let asked = triage.judge.asked.lock().unwrap().clone(); + assert_eq!(asked.len(), 1, "{asked:?}"); + assert!(asked[0].contains("rand()"), "{asked:?}"); + } + #[test] fn one_missing_verdict_keeps_a_refutation_undecided() { assert_eq!(outcome(vec![], 2, 0), TriageOutcome::NeedsReview); diff --git a/compliance-agent/src/evidence/compliance.rs b/compliance-agent/src/evidence/compliance.rs index 4e1903c..5723a0c 100644 --- a/compliance-agent/src/evidence/compliance.rs +++ b/compliance-agent/src/evidence/compliance.rs @@ -75,6 +75,13 @@ pub struct ControlStatus { /// Why a checkable control was not assessed; set only in that state. #[serde(skip_serializing_if = "Option::is_none")] pub reason: Option, + /// How severe a violation is, as the catalog rates it. + #[serde(skip_serializing_if = "Option::is_none")] + pub severity: Option, + /// How the control is evidenced, as the catalog says (`code`, `process`, + /// `hybrid`, `document`). + #[serde(skip_serializing_if = "Option::is_none")] + pub evidence_type: Option, pub findings: Vec, } @@ -168,6 +175,8 @@ pub fn control_statuses( state, note: entry.note.clone(), reason, + severity: None, + evidence_type: None, findings: against, } }) diff --git a/compliance-agent/src/evidence/mod.rs b/compliance-agent/src/evidence/mod.rs index 326c88b..99cab4f 100644 --- a/compliance-agent/src/evidence/mod.rs +++ b/compliance-agent/src/evidence/mod.rs @@ -32,6 +32,8 @@ pub struct EvidenceInputs { pub cves: Vec, /// The newest scan run, if the target was ever scanned. pub last_run: Option, + /// The CRA catalog's controls by id, for their ratings; empty without one. + pub catalog: std::collections::HashMap, } /// One file of the pack, as `manifest.json` lists it. @@ -176,12 +178,20 @@ pub fn failed_tools(inputs: &EvidenceInputs) -> Vec<&'static str> { pub fn compliance_of(inputs: &EvidenceInputs) -> Vec { control_map::ControlMap::cra() .map(|map| { - compliance::control_statuses( + let mut statuses = compliance::control_statuses( &map, &inputs.findings, scanned_languages(inputs), &failed_tools(inputs), - ) + ); + // The catalog's own ratings, next to our state. + for status in &mut statuses { + if let Some(control) = inputs.catalog.get(&status.control) { + status.severity = control.severity.as_ref().map(ToString::to_string); + status.evidence_type = control.evidence_type.clone(); + } + } + statuses }) .unwrap_or_default() } @@ -268,6 +278,7 @@ mod tests { )], cves: vec![], last_run: None, + catalog: Default::default(), } } diff --git a/compliance-core/src/models/oscal.rs b/compliance-core/src/models/oscal.rs index d65e6d5..8677a82 100644 --- a/compliance-core/src/models/oscal.rs +++ b/compliance-core/src/models/oscal.rs @@ -204,6 +204,10 @@ fn collect_control( title: control.title.clone(), text: control.statement().unwrap_or_default().to_string(), source, + severity: control.prop("severity").and_then(|s| { + serde_json::from_value(serde_json::Value::String(s.to_ascii_lowercase())).ok() + }), + evidence_type: control.prop("evidence-type").map(str::to_owned), }); for enhancement in &control.controls { collect_control(enhancement, framework, source_label, out); @@ -238,6 +242,9 @@ mod tests { let c8 = controls.iter().find(|c| c.id == "cra-ai-8").unwrap(); assert_eq!(c8.framework, ComplianceFramework::Cra); + // The catalog's own ratings come along. + assert_eq!(c8.severity, Some(crate::models::Severity::Critical)); + assert_eq!(c8.evidence_type.as_deref(), Some("code")); assert!(!c8.title.is_empty()); assert!(!c8.text.is_empty(), "statement prose should map into text"); assert!(c8.source.as_deref().unwrap_or_default().contains("Annex I")); diff --git a/compliance-core/src/traits/controls.rs b/compliance-core/src/traits/controls.rs index 8580de6..9923863 100644 --- a/compliance-core/src/traits/controls.rs +++ b/compliance-core/src/traits/controls.rs @@ -22,6 +22,11 @@ pub struct Control { pub text: String, /// Free-form source reference (catalog name, law citation, ...). pub source: Option, + /// How severe a violation is, as the catalog rates it. + pub severity: Option, + /// How the control is evidenced, as the catalog says (`code`, `process`, + /// `hybrid`, `document`). + pub evidence_type: Option, } /// A query for relevant controls. diff --git a/compliance-dashboard/src/i18n/texts.rs b/compliance-dashboard/src/i18n/texts.rs index d5ea330..e25b310 100644 --- a/compliance-dashboard/src/i18n/texts.rs +++ b/compliance-dashboard/src/i18n/texts.rs @@ -1760,6 +1760,40 @@ pub mod compliance { en: "The CRA status could not be loaded.", }; + /// How a control is evidenced, from the catalog's `evidence-type`. + pub fn evidence_type(code: &str) -> Option { + Some(match code { + "code" => Text { + de: "Nachweis im Code", + en: "Evidenced in code", + }, + "process" => Text { + de: "Nachweis im Prozess", + en: "Evidenced by process", + }, + "hybrid" => Text { + de: "Nachweis in Code und Prozess", + en: "Evidenced in code and process", + }, + "document" => Text { + de: "Nachweis durch Dokumente", + en: "Evidenced by documents", + }, + _ => return None, + }) + } + + /// A catalog severity (`critical`, `high`, …) in words. + pub fn severity(code: &str) -> Option { + Some(match code { + "critical" => super::common::CRITICAL, + "high" => super::common::HIGH, + "medium" => super::common::MEDIUM, + "low" => super::common::LOW, + _ => return None, + }) + } + /// A language code from the scan (`c`, `cpp`, `python`, …) as people /// write it; an unknown code is shown as it is. pub fn language_name(code: &str) -> &str { @@ -1843,6 +1877,19 @@ pub mod compliance { ); } + #[test] + fn catalog_ratings_read_in_both_languages() { + assert_eq!( + evidence_type("code").map(|t| t.get(Lang::De)), + Some("Nachweis im Code") + ); + assert_eq!( + severity("critical").map(|t| t.get(Lang::En)), + Some("Critical") + ); + assert!(evidence_type("unknown").is_none()); + } + #[test] fn the_reason_names_the_languages_no_rule_covers() { let reason = serde_json::json!({ diff --git a/compliance-dashboard/src/pages/compliance.rs b/compliance-dashboard/src/pages/compliance.rs index 0d89679..8c892fa 100644 --- a/compliance-dashboard/src/pages/compliance.rs +++ b/compliance-dashboard/src/pages/compliance.rs @@ -118,11 +118,27 @@ pub fn CompliancePage(id: String) -> Element { let findings = control["findings"].as_array().cloned().unwrap_or_default(); let note = control["note"].as_str().map(String::from); let reason = tx::not_assessed_reason(&control["reason"], lang); + let severity = control["severity"].as_str().unwrap_or_default().to_string(); + let severity_label = tx::severity(&severity).map(|t| t.get(lang)); + let evidence = control["evidence_type"] + .as_str() + .and_then(tx::evidence_type) + .map(|t| t.get(lang)); rsx! { tr { td { div { style: "font-family: monospace; font-size: 0.85em; opacity: 0.7;", "{control[\"control\"].as_str().unwrap_or_default()}" } div { "{control[\"title\"].as_str().unwrap_or_default()}" } + if severity_label.is_some() || evidence.is_some() { + div { style: "display: flex; gap: 6px; align-items: center; margin-top: 3px; font-size: 0.8em; opacity: 0.8;", + if let Some(label) = severity_label { + span { class: "badge badge-{severity}", "{label}" } + } + if let Some(evidence) = evidence { + span { "{evidence}" } + } + } + } } td { match shown { diff --git a/control-map/data/cra_control_map.json b/control-map/data/cra_control_map.json index e46eb2b..4add688 100644 --- a/control-map/data/cra_control_map.json +++ b/control-map/data/cra_control_map.json @@ -95,7 +95,8 @@ "cwe": [], "rules": [ "cra-ai-7-weak-password-hash" - ] + ], + "check": "Passwords must be stored with a slow, salted password hash (bcrypt, scrypt, Argon2id, PBKDF2); a fast or unsalted hash (MD5, SHA-1, SHA-256) of a password violates it." } ], "note": null, @@ -110,7 +111,8 @@ "scan_type": "secret_detection", "languages": [], "cwe": [], - "rules": [] + "rules": [], + "check": "No credential (password, key, token) may be written into the product's source or configuration: every installation would ship the same secret." }, { "tool": "semgrep", @@ -134,7 +136,8 @@ ], "rules": [ "cra-ai-8-c-hardcoded-credential" - ] + ], + "check": "No credential (password, key, token) may be written into the product's source, as a variable or a #define: every device would ship the same secret. A placeholder or an empty value does not violate it." } ], "note": null, @@ -149,7 +152,8 @@ "scan_type": "secret_detection", "languages": [], "cwe": [], - "rules": [] + "rules": [], + "check": "Credentials must not be kept in plain text in the source or configuration; a real secret committed to the repository violates it." }, { "tool": "semgrep", @@ -169,7 +173,8 @@ "CWE-798", "CWE-522" ], - "rules": [] + "rules": [], + "check": "Credentials must not be kept or compared in plain text; a hard-coded or plain-text stored secret violates it." } ], "note": null, @@ -191,7 +196,8 @@ "rules": [ "cra-ai-10-session-cookie-insecure", "cra-ai-10-express-cookie-insecure" - ] + ], + "check": "Session cookies must be protected: set Secure and HttpOnly (and SameSite). A session cookie configured without them violates it." } ], "note": null, @@ -279,7 +285,8 @@ ], "rules": [ "cra-ai-13-c-broken-hash-or-cipher" - ] + ], + "check": "Data must not be protected with a broken algorithm: MD5, SHA-1 or DES used for integrity or confidentiality violates it. A non-security use (a cache key, a checksum of public data) does not." } ], "note": null, @@ -301,7 +308,8 @@ "rules": [ "cra-ai-14-python-weak-cipher", "cra-ai-14-node-weak-cipher" - ] + ], + "check": "Stored data must be encrypted with a current cipher and mode (AES-GCM, ChaCha20-Poly1305); DES, RC4, ECB mode or a hard-coded key violates it." } ], "note": null, @@ -329,7 +337,8 @@ "CWE-319", "CWE-311" ], - "rules": [] + "rules": [], + "check": "Network traffic must use TLS 1.2 or newer with certificate checking; plain HTTP for sensitive data, disabled verification or old protocol versions violate it." } ], "note": null, @@ -344,7 +353,8 @@ "scan_type": "secret_detection", "languages": [], "cwe": [], - "rules": [] + "rules": [], + "check": "Keys must not be committed to the source: a private key or secret key in the repository violates it." }, { "tool": "semgrep", @@ -368,7 +378,8 @@ ], "rules": [ "cra-ai-16-c-predictable-random" - ] + ], + "check": "Keys, nonces, tokens and session ids must come from a cryptographically secure random source (the MCU's hardware RNG, a DRBG); rand() used for them violates it." } ], "note": null, @@ -425,7 +436,8 @@ "cra-ai-20-c-unbounded-string-function", "cra-ai-20-c-scanf-unbounded-string", "cra-ai-20-c-non-literal-format-string" - ] + ], + "check": "The code must not write past a buffer or let input control a format string: strcpy, strcat, sprintf, gets, scanf(\"%s\") or a non-literal format argument violates it." }, { "tool": "cppcheck", @@ -454,7 +466,8 @@ "CWE-787", "CWE-788" ], - "rules": [] + "rules": [], + "check": "The code must be free of memory-safety defects: out-of-bounds access, use of uninitialised memory, leaks, null dereferences and similar defects violate it." } ], "note": null, diff --git a/control-map/src/lib.rs b/control-map/src/lib.rs index df4306a..5963673 100644 --- a/control-map/src/lib.rs +++ b/control-map/src/lib.rs @@ -41,6 +41,11 @@ pub struct ScanBinding { /// Optional specific rule ids this control keys on. #[serde(default)] pub rules: Vec, + /// What a finding of this binding means for the control, for the judge. + /// The catalog's prose is written for the whole control ("SAST in the + /// CI/CD pipeline"); a buffer overflow is judged against this instead. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub check: Option, } impl ScanBinding { @@ -128,15 +133,32 @@ impl ControlMap { cwe: Option<&str>, rule_id: Option<&str>, ) -> Vec<&ControlEntry> { + self.bindings_for_finding(tool, cwe, rule_id) + .into_iter() + .map(|(control, _)| control) + .collect() + } + + /// Like [`Self::controls_for_finding`], with the binding that matched each + /// control (for its [`ScanBinding::check`] text). + pub fn bindings_for_finding( + &self, + tool: &str, + cwe: Option<&str>, + rule_id: Option<&str>, + ) -> Vec<(&ControlEntry, &ScanBinding)> { self.controls .iter() - .filter(|c| { - c.scans.iter().any(|s| { - s.tool == tool - && (cwe.is_some_and(|w| s.cwe.iter().any(|x| x == w)) - || rule_id - .is_some_and(|r| s.rules.iter().any(|b| rule_id_matches(b, r)))) - }) + .filter_map(|c| { + c.scans + .iter() + .find(|s| { + s.tool == tool + && (cwe.is_some_and(|w| s.cwe.iter().any(|x| x == w)) + || rule_id + .is_some_and(|r| s.rules.iter().any(|b| rule_id_matches(b, r)))) + }) + .map(|s| (c, s)) }) .collect() }