Skip to main content

surjection_core/diagnostics/
redact.rs

1//! The redaction pass every log line and the diagnostic report go through
2//! (SPEC 4.5): the data folder and the profile folder become placeholders,
3//! and anything that may be a credential is masked.
4
5use 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
12/// What a masked value becomes.
13pub const MASK: &str = "***";
14/// Placeholder of the data folder.
15pub const HOME_PLACEHOLDER: &str = "<SURJECTION_HOME>";
16/// Shortest environment value masked wherever it appears.
17const MIN_ENV_VALUE_LEN: usize = 8;
18/// Shortest word the entropy rule masks.
19const MIN_RANDOM_WORD_LEN: usize = 20;
20
21/// Keyed hashes of every secret value this process resolved, for the
22/// redaction pass; never the values themselves.
23static MEMORY: LazyLock<Option<SecretMemory>> = LazyLock::new(|| SecretMemory::new().ok());
24
25fn memory() -> Option<&'static SecretMemory> {
26    MEMORY.as_ref()
27}
28
29/// Remembers a resolved secret value so no log line or report shows it.
30/// Called by [`SecretMemory::record`].
31pub fn remember(value: &str) {
32    if let Some(memory) = memory() {
33        memory.record_here(value);
34    }
35}
36
37/// Redacts text for the log and the diagnostic report.
38#[derive(Debug, Clone)]
39pub struct Redactor {
40    /// Folder spellings and their placeholder, the data folder first (it
41    /// usually lies inside the profile).
42    roots: Vec<(String, &'static str)>,
43    /// Windows paths compare without case.
44    fold_case: bool,
45    /// Values of environment variables with a sensitive name, longest
46    /// first.
47    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    /// `text` with secrets masked and absolute folders replaced.
85    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
100/// Masks every value [`remember`] saw.
101fn 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
118/// In every `scheme://` URL: the userinfo becomes `***@` and the query
119/// `?***`.
120fn 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
156/// Replaces `form` (a folder) with `placeholder` where it is a whole path
157/// prefix: the next character is a separator or ends the path.
158fn 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
186/// Masks known token formats (`ghp_...`, `sk-...`, JWTs).
187fn 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
199/// Masks long random-looking words with letters and digits; ULIDs stay.
200fn 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
233/// 26 characters of Crockford base32, upper case (apply ids, store ids).
234fn 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}