//! `control-map` — the deterministic control → scan lookup table (LUT). //! //! The "transcribing" layer: it maps each compliance control to the static-scan //! step(s) that check it, or marks it as needing custom tooling, or as not //! code-checkable at all. The map is **authored and human-reviewed** — no LLM //! decides coverage. The LLM only enters later, downstream, to triage/ground the //! *tool's* findings (that lives in the agent, not here). //! //! This crate is intentionally tiny and standalone: types + an embedded JSON LUT //! + query helpers. use serde::{Deserialize, Serialize}; /// Coverage bucket for a control under static (SAST-family) scanning. #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub enum Coverage { /// An existing tool's scan surfaces findings for this control. Covered, /// Code-checkable, but no existing tool digs it out — we must write tooling. NeedsTooling, /// Process / document control — out of static-scan scope. NotCodeCheckable, } /// One tool binding: a scan step that (at least partially) checks a control. #[derive(Debug, Clone, Serialize, Deserialize)] pub struct ScanBinding { /// Tool name, e.g. `"semgrep"`, `"gitleaks"`, `"syft"`, `"osv"`. pub tool: String, /// Scan family, e.g. `"sast"`, `"secret_detection"`, `"sbom"`, `"cve"`. pub scan_type: String, /// The source languages this binding checks (`"c"`, `"python"`, …), as /// the rules behind it declare them. Empty means language-independent /// (secrets in any file, dependencies from any manifest). #[serde(default)] pub languages: Vec, /// CWEs whose findings map to this control (used to attach findings back). #[serde(default)] pub cwe: Vec, /// 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, /// The binding links its findings to the control but never makes the /// control count as checked: a tool that only looks at some files (the /// committed binaries, #495) says nothing about a tree without them. #[serde(default, skip_serializing_if = "std::ops::Not::not")] pub attach_only: bool, } impl ScanBinding { /// Whether this binding checks code in any of `languages`. pub fn applies_to(&self, languages: &[String]) -> bool { !self.attach_only && (self.languages.is_empty() || self.languages.iter().any(|l| languages.contains(l))) } } /// One control's entry in the LUT. #[derive(Debug, Clone, Serialize, Deserialize)] pub struct ControlEntry { /// Control id, e.g. `"cra-ai-8"`. pub control: String, /// Human-readable title (for the reviewable view). #[serde(default)] pub title: String, /// Coverage bucket. pub status: Coverage, /// Tool bindings (empty unless `status == Covered`). #[serde(default)] pub scans: Vec, /// Reviewer note — why it needs tooling / isn't code-checkable. #[serde(default)] pub note: Option, } impl ControlEntry { /// Whether a scan of code in `languages` checks this control at all: at /// least one of its bindings applies. Only then can "no violation found" /// be claimed for it. pub fn checked_for(&self, languages: &[String]) -> bool { self.scans.iter().any(|s| s.applies_to(languages)) } } /// The control → scan lookup table for one framework. #[derive(Debug, Clone, Serialize, Deserialize)] pub struct ControlMap { pub version: String, pub framework: String, pub controls: Vec, } const CRA_MAP_JSON: &str = include_str!("../data/cra_control_map.json"); /// Whether an authored rule id `bound` matches a scanner's emitted rule id /// `actual`. semgrep prefixes local-rule check_ids with a path /// (`tmp.compliance-cra-semgrep.cra-ai-1-flask-debug-enabled`), so match the final /// id segment rather than requiring exact equality. fn rule_id_matches(bound: &str, actual: &str) -> bool { actual == bound || actual.ends_with(&format!(".{bound}")) } impl ControlMap { /// The built-in CRA control map as authored, for hashing into evidence: /// the hash identifies exactly which mapping produced a report. pub fn cra_source() -> &'static str { CRA_MAP_JSON } /// Load the built-in CRA control map (the embedded, authored LUT). pub fn cra() -> Result { Ok(serde_json::from_str(CRA_MAP_JSON)?) } /// The coverage entry for a control id, if present. pub fn coverage(&self, control_id: &str) -> Option<&ControlEntry> { self.controls.iter().find(|c| c.control == control_id) } /// Controls whose bindings include the given `tool` + `cwe` — used to attach a /// raw tool finding back to the control(s) it's evidence for. pub fn controls_for(&self, tool: &str, cwe: &str) -> Vec<&ControlEntry> { self.controls_for_finding(tool, Some(cwe), None) } /// Controls a tool finding is evidence for, matched by CWE and/or the specific /// rule id that fired. Off-the-shelf findings bind by CWE; our custom detectors /// bind by rule id (precise — a broad CWE would over-attribute and then the /// grounded judge could drop a genuine finding as a control false positive). pub fn controls_for_finding( &self, tool: &str, 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_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() } /// Controls any tool binds to `cwe`. For findings a person verified (a /// penetration test), where the tool that would have found it does not /// matter: the weakness is the same one a scanner's rule for it covers. /// Controls bound only by rule id are never matched this way. pub fn controls_for_cwe(&self, cwe: &str) -> Vec<&ControlEntry> { self.controls .iter() .filter(|c| c.scans.iter().any(|s| s.cwe.iter().any(|x| x == cwe))) .collect() } /// Count of controls in each coverage bucket. pub fn summary(&self) -> CoverageSummary { let mut s = CoverageSummary::default(); for c in &self.controls { match c.status { Coverage::Covered => s.covered += 1, Coverage::NeedsTooling => s.needs_tooling += 1, Coverage::NotCodeCheckable => s.not_code_checkable += 1, } } s } } /// Coverage bucket counts. #[derive(Debug, Default, Clone, Copy, PartialEq, Eq)] pub struct CoverageSummary { pub covered: usize, pub needs_tooling: usize, pub not_code_checkable: usize, } impl CoverageSummary { pub fn total(&self) -> usize { self.covered + self.needs_tooling + self.not_code_checkable } } /// Errors loading a control map. #[derive(Debug, thiserror::Error)] pub enum MapError { #[error("failed to parse control map: {0}")] Parse(#[from] serde_json::Error), } #[cfg(test)] mod tests { use super::*; #[test] fn a_cwe_maps_whatever_tool_found_it() { let map = ControlMap::cra().expect("map"); let ids: Vec<&str> = map .controls_for_cwe("CWE-798") .iter() .map(|c| c.control.as_str()) .collect(); assert!(ids.contains(&"cra-ai-8"), "{ids:?}"); assert!(map.controls_for_cwe("CWE-0").is_empty()); } #[test] fn a_missing_content_security_policy_is_evidence_for_secure_defaults() { // DAST reports a missing CSP as CWE-16 and a missing protection // mechanism as CWE-693 (#998). Neither makes the control count as // checked: the DAST checks look at what one URL serves. let map = ControlMap::cra().expect("map"); for cwe in ["CWE-16", "CWE-693"] { let ids: Vec<&str> = map .controls_for_cwe(cwe) .iter() .map(|c| c.control.as_str()) .collect(); assert_eq!(ids, ["cra-ai-1"], "{cwe}"); } let dast = map .coverage("cra-ai-1") .and_then(|c| c.scans.iter().find(|s| s.tool == "dast")) .expect("a dast binding"); assert!(dast.attach_only); // So the CRA status never reads "checked" because of it. assert!(!dast.applies_to(&["python".to_string()])); } #[test] fn cra_map_loads_all_40_controls() { let map = ControlMap::cra().expect("CRA map should parse"); assert_eq!(map.framework, "cra"); assert_eq!(map.controls.len(), 40); assert_eq!(map.summary().total(), 40); } #[test] fn a_control_is_checked_only_for_the_languages_its_rules_cover() { let map = ControlMap::cra().expect("map"); let c_only = ["c".to_string()]; let python = ["python".to_string()]; let secure_defaults = map.coverage("cra-ai-1").expect("cra-ai-1"); let memory_safety = map.coverage("cra-ai-20").expect("cra-ai-20"); let secrets = map.coverage("cra-ai-9").expect("cra-ai-9"); // Only Python/JS rules check secure defaults. assert!(!secure_defaults.checked_for(&c_only)); assert!(secure_defaults.checked_for(&python)); // Our C rules and cppcheck check memory safety in C, and in C++. assert!(memory_safety.checked_for(&c_only)); assert!(memory_safety.checked_for(&["cpp".to_string()])); // gitleaks reads any file, so no language is needed. assert!(secrets.checked_for(&[])); // C# is checked for secure defaults by its own rules and the .NET // configuration checks. assert!(secure_defaults.checked_for(&["csharp".to_string()])); assert!(memory_safety.checked_for(&["csharp".to_string()])); } #[test] fn dotnet_findings_attach_to_their_controls() { let map = ControlMap::cra().expect("map"); let controls = |tool: &str, rule: &str| -> Vec { map.controls_for_finding(tool, None, Some(rule)) .iter() .map(|c| c.control.clone()) .collect() }; assert_eq!( controls( "semgrep", "tmp.compliance-cra-semgrep-csharp.cra-ai-20-csharp-sql-string" ), ["cra-ai-20"] ); assert_eq!( controls("dotnet-config", "dotnet-config-cleartext-password"), ["cra-ai-9"] ); assert_eq!( controls("dotnet-config", "dotnet-config-wcf-insecure-binding"), ["cra-ai-15"] ); assert_eq!( controls("secret-files", "secret-file-private-key"), ["cra-ai-16"] ); assert_eq!( controls("dotnet-lifecycle", "dotnet-framework-end-of-support"), ["cra-ai-22"] ); assert_eq!( controls("yocto-release", "yocto-release-eol"), ["cra-ai-22"] ); assert_eq!( controls("yocto-release", "yocto-release-eol-soon"), ["cra-ai-22"] ); } #[test] fn every_code_binding_names_its_languages() { // Only tools that do not read source code may be language-independent // (DAST tests the running application); a rule binding without // languages would claim every language. let map = ControlMap::cra().expect("map"); for control in &map.controls { for scan in &control.scans { let reads_code = !matches!( scan.tool.as_str(), "gitleaks" | "secret-files" | "syft" | "osv" | "binary-inventory" | "dast" ); assert_eq!( reads_code, !scan.languages.is_empty(), "{} / {}", control.control, scan.tool ); } } } #[test] fn binary_findings_attach_without_claiming_coverage() { let map = ControlMap::cra().expect("map"); let controls = |rule: &str| -> Vec<&str> { map.controls_for_finding("binary-inventory", None, Some(rule)) .into_iter() .map(|c| c.control.as_str()) .collect() }; assert_eq!(controls("binary-no-aslr"), ["cra-ai-1"]); assert_eq!(controls("binary-hex-invalid"), ["cra-ai-6"]); assert!(controls("binary-unsigned").is_empty()); assert!(controls("binary-no-cfg").is_empty()); // A Go tree without binaries does not make cra-ai-1 checked. let c = map.coverage("cra-ai-1").expect("cra-ai-1"); assert!(!c.checked_for(&["go".to_string()])); assert!(c.checked_for(&["python".to_string()])); } #[test] fn yocto_recipe_findings_attach_to_their_controls() { let map = ControlMap::cra().expect("map"); let controls = |tool: &str, rule: &str| -> Vec<&str> { map.controls_for_finding(tool, None, Some(rule)) .into_iter() .map(|c| c.control.as_str()) .collect() }; let debug = "oelint.var.badimagefeature.debug-tweaks"; assert_eq!(controls("oelint-adv", debug), ["cra-ai-1", "cra-ai-8"]); assert_eq!( controls("oelint-adv", "oelint.var.badimagefeature.tools-debug"), ["cra-ai-1"] ); for rule in [ "oelint.vars.srcurichecksum", "oelint.vars.autorev", "oelint.vars.srcurigittag", ] { assert_eq!(controls("oelint-adv", rule), ["cra-ai-6"], "{rule}"); } // The attack-surface rules. assert_eq!(controls("oelint-adv", "oelint.task.network"), ["cra-ai-2"]); assert!(controls("oelint-adv", "oelint.vars.insaneskip").is_empty()); assert_eq!( controls("yocto-config", "yocto-extrausers-password"), ["cra-ai-8"] ); assert_eq!(controls("yocto-config", "yocto-src-uri-http"), ["cra-ai-2"]); assert_eq!( controls("yocto-config", "yocto-sshd-root-login"), ["cra-ai-1"] ); assert!(controls("yocto-config", "yocto-files-certificate").is_empty()); // A rule id of one tool does not attach a finding of another. assert!(controls("semgrep", debug).is_empty()); // A layer tree is checked for these controls. let bitbake = ["bitbake".to_string()]; for id in ["cra-ai-1", "cra-ai-2", "cra-ai-6", "cra-ai-8"] { assert!(map.coverage(id).expect(id).checked_for(&bitbake), "{id}"); } } #[test] fn hardcoded_password_control_is_tool_covered() { let map = ControlMap::cra().unwrap(); let c = map.coverage("cra-ai-8").expect("cra-ai-8 present"); assert_eq!(c.status, Coverage::Covered); assert!(c.scans.iter().any(|s| s.tool == "semgrep")); assert!(c.scans.iter().any(|s| s.tool == "gitleaks")); } #[test] fn finding_attaches_back_to_control_via_tool_and_cwe() { let map = ControlMap::cra().unwrap(); let hits = map.controls_for("semgrep", "CWE-798"); assert!(hits.iter().any(|c| c.control == "cra-ai-8")); } #[test] fn covered_and_not_checkable_are_populated() { let s = ControlMap::cra().unwrap().summary(); assert!(s.covered > 0); assert!(s.not_code_checkable > 0); // needs_tooling is empty: every code-checkable control is either // covered by our own rules and tools or by the grounded surface pass. assert_eq!(s.needs_tooling, 0); } #[test] fn rule_id_matching_handles_semgrep_path_prefix() { let bound = "cra-ai-1-flask-debug-enabled"; assert!(rule_id_matches(bound, bound)); // exact assert!(rule_id_matches( bound, "tmp.compliance-cra-semgrep.cra-ai-1-flask-debug-enabled" )); // semgrep path prefix assert!(!rule_id_matches( bound, "cra-ai-1-flask-debug-enabled-extra" )); // not a suffix segment assert!(!rule_id_matches( bound, "python.lang.security.exec-detected" )); // unrelated } #[test] fn custom_rule_finding_attaches_to_control_by_rule_id() { let map = ControlMap::cra().unwrap(); // cra-ai-1 is now tool-covered by custom rules. assert_eq!(map.coverage("cra-ai-1").unwrap().status, Coverage::Covered); // A prefixed check_id still maps back to cra-ai-1 by rule id. let hits = map.controls_for_finding("semgrep", None, Some("tmp.x.cra-ai-1-tls-verify-disabled")); assert!(hits.iter().any(|c| c.control == "cra-ai-1")); } #[test] fn coverage_after_grounded_promotion() { let s = ControlMap::cra().unwrap().summary(); // Our own semgrep rules, gitleaks, cppcheck, syft/OSV and 8 grounded // surface controls (promoted after the grounded path was validated // live). assert_eq!(s.covered, 21); // Nothing left as needs_tooling — every code-checkable control is covered. assert_eq!(s.needs_tooling, 0); // The 4 pure-architectural controls remain not code-checkable. assert_eq!(s.not_code_checkable, 19); assert_eq!(s.total(), 40); } #[test] fn architectural_controls_are_not_code_checkable() { let map = ControlMap::cra().unwrap(); for id in ["cra-ai-2", "cra-ai-3", "cra-ai-4", "cra-ai-5"] { let c = map.coverage(id).unwrap(); assert_eq!(c.status, Coverage::NotCodeCheckable, "{id}"); // Only cra-ai-2 carries bindings, and only the Yocto recipe // lint's attack-surface rules: no other code is checked for it. let bound: Vec<(&str, &str, &[String])> = c .scans .iter() .flat_map(|s| { s.rules .iter() .map(move |r| (s.tool.as_str(), r.as_str(), s.languages.as_slice())) }) .collect(); let bitbake = ["bitbake".to_string()]; let expected: Vec<(&str, &str, &[String])> = if id == "cra-ai-2" { vec![ ("oelint-adv", "oelint.task.network", &bitbake), ("yocto-config", "yocto-src-uri-http", &bitbake), ] } else { Vec::new() }; assert_eq!(bound, expected, "{id}"); assert!(c .scans .iter() .all(|s| s.scan_type == "recipe_lint" && s.cwe.is_empty())); } } #[test] fn custom_rule_controls_do_not_bind_by_broad_cwe() { let map = ControlMap::cra().unwrap(); // cra-ai-1 rules emit CWE-489 in metadata, but the LUT binds by rule id // only (cwe: []) — so a stray CWE-489 finding must NOT attach to it. assert!(map.controls_for("semgrep", "CWE-489").is_empty()); // The CWE path for off-the-shelf findings is unchanged. assert!(map .controls_for("semgrep", "CWE-798") .iter() .any(|c| c.control == "cra-ai-8")); } }