surjection_core/diagnostics/
redact.rs1use std::path::Path;
6use std::sync::LazyLock;
7
8use crate::env::{Env, Os};
9use crate::secrets::classify::{find_tokens, is_high_entropy, is_sensitive_key};
10use crate::secrets::scanner::SecretMemory;
11
12pub const MASK: &str = "***";
14pub const HOME_PLACEHOLDER: &str = "<SURJECTION_HOME>";
16const MIN_ENV_VALUE_LEN: usize = 8;
18const MIN_RANDOM_WORD_LEN: usize = 20;
20
21static MEMORY: LazyLock<Option<SecretMemory>> = LazyLock::new(|| SecretMemory::new().ok());
24
25fn memory() -> Option<&'static SecretMemory> {
26 MEMORY.as_ref()
27}
28
29pub fn remember(value: &str) {
32 if let Some(memory) = memory() {
33 memory.record_here(value);
34 }
35}
36
37#[derive(Debug, Clone)]
39pub struct Redactor {
40 roots: Vec<(String, &'static str)>,
43 fold_case: bool,
45 values: Vec<String>,
48}
49
50impl Redactor {
51 pub fn new(env: &Env, surjection_home: &Path) -> Self {
52 let mut roots = Vec::new();
53 for (root, placeholder) in [(surjection_home, HOME_PLACEHOLDER), (env.home(), "~")] {
54 let native = root.to_string_lossy().into_owned();
55 let native = native.trim_end_matches(['/', '\\']).to_owned();
56 if native.is_empty() {
57 continue;
58 }
59 let forward = native.replace('\\', "/");
60 let doubled = native.replace('\\', "\\\\");
61 for form in [doubled, native, forward] {
62 if !roots.iter().any(|(known, _)| *known == form) {
63 roots.push((form, placeholder));
64 }
65 }
66 }
67 let mut values: Vec<String> = env
68 .vars()
69 .filter(|(name, _)| is_sensitive_key(name))
70 .filter_map(|(_, value)| value.to_str())
71 .map(str::trim)
72 .filter(|value| value.len() >= MIN_ENV_VALUE_LEN)
73 .map(str::to_owned)
74 .collect();
75 values.sort_by_key(|value| std::cmp::Reverse(value.len()));
76 values.dedup();
77 Self {
78 roots,
79 fold_case: env.os() == Os::Windows,
80 values,
81 }
82 }
83
84 pub fn redact(&self, text: &str) -> String {
86 let mut out = text.to_owned();
87 for value in &self.values {
88 out = out.replace(value.as_str(), MASK);
89 }
90 out = mask_remembered(&out);
91 out = redact_urls(&out);
92 for (form, placeholder) in &self.roots {
93 out = replace_root(&out, form, placeholder, self.fold_case);
94 }
95 out = mask_tokens(&out);
96 mask_random_words(&out)
97 }
98}
99
100fn mask_remembered(text: &str) -> String {
102 let Some(memory) = memory() else {
103 return text.to_owned();
104 };
105 if memory.is_empty() {
106 return text.to_owned();
107 }
108 let mut out = text.to_owned();
109 while let Some(range) = memory.find(out.as_bytes()) {
110 if !out.is_char_boundary(range.start) || !out.is_char_boundary(range.end) {
111 break;
112 }
113 out.replace_range(range, MASK);
114 }
115 out
116}
117
118fn redact_urls(text: &str) -> String {
121 let mut out = String::with_capacity(text.len());
122 let mut rest = text;
123 while let Some(sep) = rest.find("://") {
124 let (head, tail) = rest.split_at(sep + 3);
125 out.push_str(head);
126 let end = tail
127 .find(|c: char| c.is_whitespace() || "\"'<>`".contains(c))
128 .unwrap_or(tail.len());
129 let (url, after) = tail.split_at(end);
130 let authority_end = url.find(['/', '?', '#']).unwrap_or(url.len());
131 let (authority, path) = url.split_at(authority_end);
132 match authority.rfind('@') {
133 Some(at) => {
134 out.push_str(MASK);
135 out.push_str(&authority[at..]);
136 }
137 None => out.push_str(authority),
138 }
139 match path.find('?') {
140 Some(query) => {
141 out.push_str(&path[..query]);
142 out.push('?');
143 out.push_str(MASK);
144 if let Some(fragment) = path[query..].find('#') {
145 out.push_str(&path[query + fragment..]);
146 }
147 }
148 None => out.push_str(path),
149 }
150 rest = after;
151 }
152 out.push_str(rest);
153 out
154}
155
156fn replace_root(text: &str, form: &str, placeholder: &str, fold_case: bool) -> String {
159 let bytes = text.as_bytes();
160 let needle = form.as_bytes();
161 let mut out = String::with_capacity(text.len());
162 let mut copied = 0;
163 let mut i = 0;
164 while i + needle.len() <= bytes.len() {
165 let candidate = &bytes[i..i + needle.len()];
166 let matches = if fold_case {
167 candidate.eq_ignore_ascii_case(needle)
168 } else {
169 candidate == needle
170 };
171 let next = bytes.get(i + needle.len()).copied();
172 let whole = !next.is_some_and(|b| b.is_ascii_alphanumeric() || b"_-.".contains(&b));
173 if matches && whole && text.is_char_boundary(i) {
174 out.push_str(&text[copied..i]);
175 out.push_str(placeholder);
176 i += needle.len();
177 copied = i;
178 } else {
179 i += 1;
180 }
181 }
182 out.push_str(&text[copied..]);
183 out
184}
185
186fn mask_tokens(text: &str) -> String {
188 let mut out = text.to_owned();
189 for hit in find_tokens(text).into_iter().rev() {
190 out.replace_range(hit.range, MASK);
191 }
192 out
193}
194
195fn is_word_byte(b: u8) -> bool {
196 b.is_ascii_alphanumeric() || b"_-+".contains(&b)
197}
198
199fn mask_random_words(text: &str) -> String {
201 let bytes = text.as_bytes();
202 let mut out = String::with_capacity(text.len());
203 let mut copied = 0;
204 let mut i = 0;
205 while i < bytes.len() {
206 if !is_word_byte(bytes[i]) {
207 i += 1;
208 continue;
209 }
210 let start = i;
211 while i < bytes.len() && is_word_byte(bytes[i]) {
212 i += 1;
213 }
214 let word = &text[start..i];
215 if looks_random(word) {
216 out.push_str(&text[copied..start]);
217 out.push_str(MASK);
218 copied = i;
219 }
220 }
221 out.push_str(&text[copied..]);
222 out
223}
224
225fn looks_random(word: &str) -> bool {
226 word.len() >= MIN_RANDOM_WORD_LEN
227 && word.bytes().any(|b| b.is_ascii_digit())
228 && word.bytes().any(|b| b.is_ascii_alphabetic())
229 && !is_ulid(word)
230 && is_high_entropy(word)
231}
232
233fn is_ulid(word: &str) -> bool {
235 word.len() == 26
236 && word
237 .bytes()
238 .all(|b| b.is_ascii_digit() || (b.is_ascii_uppercase() && !b"ILOU".contains(&b)))
239}
240
241#[cfg(test)]
242mod tests {
243 use super::*;
244
245 #[test]
246 fn url_userinfo_and_query_are_masked() {
247 assert_eq!(
248 redact_urls("got https://me:pw@example.com/a/b?token=x&q=y#top end"),
249 "got https://***@example.com/a/b?***#top end"
250 );
251 assert_eq!(
252 redact_urls("https://example.com/a"),
253 "https://example.com/a"
254 );
255 }
256
257 #[test]
258 fn roots_match_whole_folders_only() {
259 assert_eq!(
260 replace_root("C:\\Users\\me\\x", "C:\\Users\\me", "~", true),
261 "~\\x"
262 );
263 assert_eq!(
264 replace_root("C:\\Users\\me2\\x", "C:\\Users\\me", "~", true),
265 "C:\\Users\\me2\\x"
266 );
267 assert_eq!(
268 replace_root("c:/users/ME/x", "C:/Users/me", "~", true),
269 "~/x"
270 );
271 assert_eq!(
272 replace_root("/home/ME/x", "/home/me", "~", false),
273 "/home/ME/x"
274 );
275 }
276
277 #[test]
278 fn random_words_are_masked_but_ulids_and_codes_stay() {
279 assert_eq!(mask_random_words("k=Zx81Qa9vLr02mWq7TbYc"), "k=***");
280 assert_eq!(
281 mask_random_words("id=01JDKQ7Z8M3N4P5Q6R7S8T9V0W code=scanner_download_failed"),
282 "id=01JDKQ7Z8M3N4P5Q6R7S8T9V0W code=scanner_download_failed"
283 );
284 }
285}