Skip to main content

specfold_core/
guards.rs

1//! Guards: named checks over any file in the repository and over commit messages, such as the
2//! gate that keeps internal names out of a public package.
3
4mod cache;
5mod code_spans;
6mod compile;
7mod jslex;
8mod pattern;
9mod prefilter;
10mod prove;
11pub mod range;
12mod scan;
13pub mod secrets;
14pub mod terms;
15
16use crate::check::baseline;
17use crate::check::finding::Finding;
18use crate::config::{Config, GuardDef};
19use anyhow::{Result, anyhow, bail};
20pub use range::GuardRange;
21
22fn select<'a>(cfg: &'a Config, names: &[String]) -> Result<Vec<&'a GuardDef>> {
23    if names.is_empty() {
24        return Ok(cfg.raw.guards.iter().collect());
25    }
26    names
27        .iter()
28        .map(|n| {
29            cfg.raw.guards.iter().find(|g| &g.name == n).ok_or_else(|| {
30                // C216: the built-in check runs as `spec guard secrets` with no guard configured.
31                let mut have: Vec<&str> = cfg.raw.guards.iter().map(|g| g.name.as_str()).collect();
32                have.push("secrets (built-in)");
33                anyhow!("no guard named '{n}' (have: {}); next: spec guard secrets", have.join(", "))
34            })
35        })
36        .collect()
37}
38
39fn scan_one(cfg: &Config, g: &GuardDef, range: Option<&GuardRange>, net: bool) -> Result<scan::Scanned> {
40    let c = compile::compile(cfg, g)?;
41    prove::prove(g, &c)?;
42    let r = range.cloned().unwrap_or_else(|| GuardRange::parse(&g.range));
43    let mut resolved = range::resolve(&cfg.root, &r, &c.bases)?;
44    // F3: `--net` judges a range by its end only; versions a later commit takes back are skipped.
45    if net {
46        resolved.passing.clear();
47    }
48    scan::run(cfg, g, &c, &resolved)
49}
50
51/// Runs the named guards (all of them when `names` is empty). A guard without an explicit range
52/// uses its own default; a guard with a baseline reports only hits the baseline does not hold.
53pub fn run(cfg: &Config, names: &[String], range: Option<&GuardRange>) -> Result<Vec<Finding>> {
54    run_net(cfg, names, range, false)
55}
56
57/// [`run`], with `net` judging a range by its net change: what its end holds, not what an
58/// intermediate commit wrote and a later one took back (F3).
59pub fn run_net(cfg: &Config, names: &[String], range: Option<&GuardRange>, net: bool) -> Result<Vec<Finding>> {
60    let mut out = vec![];
61    for g in select(cfg, names)? {
62        let found = scan_one(cfg, g, range, net)?.findings;
63        match &g.baseline {
64            Some(rel) => match baseline::load_file(&cfg.root, rel)? {
65                Some(b) => out.extend(baseline::hold_with(&b, found, &[]).findings),
66                None => out.extend(found),
67            },
68            None => out.extend(found),
69        }
70    }
71    Ok(out)
72}
73
74/// Measures each named guard over the whole tree and writes its baseline file.
75/// With `write` false, only measures: what `--write-baseline` would record, for its preview.
76pub fn write_baselines(cfg: &Config, names: &[String], write: bool) -> Result<Vec<(String, String, usize)>> {
77    let guards = select(cfg, names)?;
78    // C254: every guard is measured before any baseline is written, and the baseline files of this
79    // run never count as uncommitted, so one guard's new file cannot stop the next half way.
80    let own: Vec<&String> = guards.iter().filter_map(|g| g.baseline.as_ref()).collect();
81    let mut measured = vec![];
82    for g in &guards {
83        let Some(rel) = &g.baseline else {
84            if !names.is_empty() {
85                bail!("guard {} has no baseline file; set baseline = \"…\" on it", g.name);
86            }
87            continue;
88        };
89        let scanned = scan_one(cfg, g, Some(&GuardRange::All), false)?;
90        let b = baseline::measure_with(&cfg.root, &scanned.findings, &[], |p| {
91            !own.iter().any(|o| o.as_str() == p) && scanned.files.iter().any(|f| f == p)
92        })?;
93        measured.push((g.name.clone(), rel.clone(), b));
94    }
95    let mut written = vec![];
96    for (name, rel, b) in measured {
97        if write {
98            baseline::write_file(&cfg.root, &rel, &b)?;
99        }
100        written.push((name, rel, b.counts.values().sum()));
101    }
102    Ok(written)
103}
104
105mod blobs;
106#[cfg(test)]
107mod tests;
108pub use blobs::{builtin_secrets, reads_content, scan_blobs};