1use std::collections::BTreeMap;
21use std::sync::OnceLock;
22
23use regex::Regex;
24
25#[derive(Debug, Clone, Copy)]
29pub struct RedactionClass {
30 pub name: &'static str,
31 pub pattern: &'static str,
32 pub keeps_leading_group: bool,
35}
36
37pub 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
66pub 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
88pub 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: ®ex::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#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
118pub struct RedactionCount {
119 pub class: String,
120 pub count: usize,
121}
122
123pub 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 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 #[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 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}