Skip to main content

memstead_base/ops/
redaction.rs

1//! Private-pattern redaction for portable authoring provenance.
2//!
3//! `memstead export --format mem` ships each entity's latest mutation
4//! rationale in the archive's `.memstead/provenance.json`. Those notes are
5//! written inside the private workspace and name what the public tree must
6//! never carry: internal `dev/` plan paths, the legacy domain, absolute
7//! user paths, and the rest of the classes `scripts/leak-scan.sh` refuses
8//! on the public repo. The export redacts every matched span to
9//! `[redacted:<class>]` and never strips the record (the decision on
10//! published anchors: a stripped note is indistinguishable from one never
11//! written, a sentinel keeps the rationale readable while naming nothing).
12//!
13//! One vocabulary. The classes below are the leak scan's `scan` lines,
14//! label and pattern verbatim; the test at the bottom reads the script and
15//! holds the two equal, so a class added to one without the other fails
16//! naming the class. Entity bodies are not touched here: the leak scan
17//! keeps guarding them, and an archive whose bodies carry a private string
18//! still refuses at the seal gate.
19
20use std::collections::BTreeMap;
21use std::sync::OnceLock;
22
23use regex::Regex;
24
25/// One redaction class: the leak scan's label, its extended-regex pattern
26/// verbatim, and whether the pattern's first capture group is a boundary
27/// prefix (a space, quote or line start) that must survive the redaction.
28#[derive(Debug, Clone, Copy)]
29pub struct RedactionClass {
30    pub name: &'static str,
31    pub pattern: &'static str,
32    /// The pattern opens with `(^|<boundary chars>)` so the match includes
33    /// one character that is not private; that group is kept.
34    pub keeps_leading_group: bool,
35}
36
37/// The redaction vocabulary, in the leak scan's order.
38pub const REDACTION_CLASSES: &[RedactionClass] = &[
39    RedactionClass {
40        name: "absolute-user-paths",
41        pattern: r"/Users/(dasboe|bjornbosenberg)",
42        keeps_leading_group: false,
43    },
44    RedactionClass {
45        name: "secrets",
46        pattern: r"(-----BEGIN [A-Z]+ PRIVATE KEY|ghp_[A-Za-z0-9]{30,}|github_pat_[A-Za-z0-9_]{30,}|gho_[A-Za-z0-9]{30,}|xox[baprs]-[A-Za-z0-9-]{10,}|AKIA[0-9A-Z]{16}|sk-ant-[A-Za-z0-9_-]{24,}|sk-[A-Za-z0-9]{24,})",
47        keeps_leading_group: false,
48    },
49    RedactionClass {
50        name: "private-infra",
51        pattern: r"(railway\.app|\.up\.railway\.app|railway\.json)",
52        keeps_leading_group: false,
53    },
54    RedactionClass {
55        name: "internal-refs",
56        pattern: r"(dev/plans|dev/strategy|dev/ci|LAUNCH\.md)",
57        keeps_leading_group: false,
58    },
59    RedactionClass {
60        name: "excluded-private-dirs",
61        pattern: r#"(^|[[:space:]"'`(:,])(macos|websites|graph|inspector|local-ai)/"#,
62        keeps_leading_group: true,
63    },
64];
65
66/// The sentinel a redacted span becomes.
67pub fn sentinel(class: &str) -> String {
68    format!("[redacted:{class}]")
69}
70
71fn compiled() -> &'static [(RedactionClass, Regex)] {
72    static COMPILED: OnceLock<Vec<(RedactionClass, Regex)>> = OnceLock::new();
73    COMPILED.get_or_init(|| {
74        REDACTION_CLASSES
75            .iter()
76            .map(|c| {
77                (
78                    *c,
79                    Regex::new(c.pattern).unwrap_or_else(|e| {
80                        panic!("redaction class {} has an invalid pattern: {e}", c.name)
81                    }),
82                )
83            })
84            .collect()
85    })
86}
87
88/// Redact every private span in `text`, class by class in vocabulary
89/// order; returns the redacted text and the per-class count of spans
90/// replaced (classes with no match are absent).
91pub fn redact(text: &str) -> (String, BTreeMap<&'static str, usize>) {
92    let mut out = text.to_string();
93    let mut counts: BTreeMap<&'static str, usize> = BTreeMap::new();
94    for (class, re) in compiled() {
95        let mut n = 0usize;
96        let replaced = re.replace_all(&out, |caps: &regex::Captures| {
97            n += 1;
98            if class.keeps_leading_group {
99                format!(
100                    "{}{}",
101                    caps.get(1).map(|m| m.as_str()).unwrap_or(""),
102                    sentinel(class.name)
103                )
104            } else {
105                sentinel(class.name)
106            }
107        });
108        if n > 0 {
109            out = replaced.into_owned();
110            counts.insert(class.name, n);
111        }
112    }
113    (out, counts)
114}
115
116/// Per-class redaction counts as the export result carries them.
117#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
118pub struct RedactionCount {
119    pub class: String,
120    pub count: usize,
121}
122
123/// Fold per-string counts into the export result's list, in vocabulary
124/// order.
125pub fn tally(into: &mut BTreeMap<&'static str, usize>, counts: BTreeMap<&'static str, usize>) {
126    for (k, v) in counts {
127        *into.entry(k).or_insert(0) += v;
128    }
129}
130
131pub fn counts_to_list(counts: &BTreeMap<&'static str, usize>) -> Vec<RedactionCount> {
132    REDACTION_CLASSES
133        .iter()
134        .filter_map(|c| {
135            counts.get(c.name).map(|n| RedactionCount {
136                class: c.name.to_string(),
137                count: *n,
138            })
139        })
140        .collect()
141}
142
143#[cfg(test)]
144mod tests {
145    use super::*;
146
147    #[test]
148    fn redacts_each_class_to_its_sentinel_and_keeps_the_rest() {
149        // Assembled at runtime: this file is exempt from the leak scan for
150        // its patterns, but the scan's file-type-scoped class still reads
151        // it, so no literal below may match a class.
152        let input = format!(
153            "see {}/x.md from {}/w; reads a {}/ path prefix",
154            ["dev", "plans"].join("/"),
155            ["/Users", "bjornbosenberg"].join("/"),
156            "graph"
157        );
158        let (out, counts) = redact(&input);
159        assert_eq!(
160            out,
161            "see [redacted:internal-refs]/x.md from [redacted:absolute-user-paths]/w; reads a [redacted:excluded-private-dirs] path prefix"
162        );
163        let list = counts_to_list(&counts);
164        assert_eq!(
165            list.iter()
166                .map(|c| (c.class.as_str(), c.count))
167                .collect::<Vec<_>>(),
168            vec![
169                ("absolute-user-paths", 1),
170                ("internal-refs", 1),
171                ("excluded-private-dirs", 1),
172            ]
173        );
174        let (clean, none) = redact("an ordinary note about engine-graph/ and memstead.com");
175        assert_eq!(
176            clean,
177            "an ordinary note about engine-graph/ and memstead.com"
178        );
179        assert!(none.is_empty());
180    }
181
182    /// One vocabulary: the classes here equal the leak scan's `scan` lines,
183    /// label and pattern verbatim. A class added to either side alone
184    /// fails naming it.
185    #[test]
186    fn vocabulary_equals_the_leak_scan_classes() {
187        let script =
188            std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../scripts/leak-scan.sh");
189        let text = std::fs::read_to_string(&script)
190            .unwrap_or_else(|e| panic!("read {}: {e}", script.display()));
191        // `scan "label" '<pattern>'` — the pattern is a single-quoted shell
192        // word; the one class whose pattern carries a literal quote spells
193        // it as '"'"' and is folded back here.
194        let re = Regex::new(r#"(?m)^scan\s+"([a-z-]+)"\s+'((?:[^']|'"'"')+)'"#).unwrap();
195        let scanned: Vec<(String, String)> = re
196            .captures_iter(&text)
197            .map(|c| (c[1].to_string(), c[2].replace("'\"'\"'", "'")))
198            .collect();
199        assert!(
200            !scanned.is_empty(),
201            "no scan lines parsed from {}",
202            script.display()
203        );
204        let ours: Vec<(String, String)> = REDACTION_CLASSES
205            .iter()
206            .map(|c| (c.name.to_string(), c.pattern.to_string()))
207            .collect();
208        for (name, pattern) in &scanned {
209            let mine = ours.iter().find(|(n, _)| n == name).unwrap_or_else(|| {
210                panic!(
211                    "leak-scan class `{name}` is not in the engine's redaction vocabulary (ops/redaction.rs)"
212                )
213            });
214            assert_eq!(
215                &mine.1, pattern,
216                "class `{name}`: the engine's pattern differs from the leak scan's"
217            );
218        }
219        for (name, _) in &ours {
220            assert!(
221                scanned.iter().any(|(n, _)| n == name),
222                "engine redaction class `{name}` has no leak-scan `scan` line"
223            );
224        }
225        assert_eq!(scanned.len(), ours.len());
226    }
227}