Skip to main content

subspace_core/diagnostics/
redact.rs

1use std::{fmt, sync::LazyLock};
2
3use regex::Regex;
4
5use super::home::Home;
6
7const MASK: &str = "[redacted]";
8const MAX_FIELD_CHARS: usize = 4_096;
9const MAX_SHORT_ENVIRONMENT_CHARS: usize = 3;
10const PATTERNS: [&str; 5] = [
11    r#"(?i)\b[a-z][a-z0-9+.-]*://[^\s<>\"'`]+|\bwww\.[^\s<>\"'`]+|//[^\s<>\"'`]*@[^\s<>\"'`]+"#,
12    r#"\b[A-Za-z_][A-Za-z0-9_]*\s*=\s*(?:\"(?:\\.|[^\"])*\"|'(?:\\.|[^'])*'|[^\s,;]+)"#,
13    r##"(?i)\b[a-z0-9_-]*(?:token|secret|password|passwd|pwd|pat|api[_-]?key|apikey|private[_-]?key|signature)["']?\s*[:=]\s*(?:"(?:\\.|[^"])*"|'(?:\\.|[^'])*')"##,
14    r"(?s)-----BEGIN [A-Z ]*PRIVATE KEY-----.*?(?:-----END [A-Z ]*PRIVATE KEY-----|$)",
15    r#"(?:/(?:[^\s:\"'`;]+):)+/[^\s\"'`;]+|(?:[A-Za-z]:[\\/][^;\r\n\"'`]+;)+[A-Za-z]:[\\/][^;\r\n\"'`]+"#,
16];
17
18static RULES: LazyLock<Vec<Regex>> = LazyLock::new(|| {
19    PATTERNS
20        .iter()
21        .map(|pattern| Regex::new(pattern).expect("constant diagnostics pattern"))
22        .collect()
23});
24
25/// Private inputs used only to remove values, never serialized or printed.
26/// The shell supplies environment values without collecting them on copy.
27/// Text removes literal values, while HOME becomes `~`. Registered identities
28/// and the named executable, shell and Azure CLI paths remain explicit
29/// exceptions, so common environment values cannot corrupt versions or paths.
30#[derive(Clone, Default)]
31pub struct RedactionContext {
32    home: Option<Home>,
33    environment_values: Vec<String>,
34}
35
36impl fmt::Debug for RedactionContext {
37    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
38        formatter.write_str("RedactionContext { private inputs omitted }")
39    }
40}
41
42impl RedactionContext {
43    /// Empty values are ignored; longer values are removed before their parts.
44    pub fn new(home: Option<String>, environment_values: impl IntoIterator<Item = String>) -> Self {
45        let home = home.and_then(Home::new);
46        let mut environment_values: Vec<_> = environment_values
47            .into_iter()
48            .filter(|value| {
49                !value.is_empty() && !home.as_ref().is_some_and(|home| home.matches(value))
50            })
51            .map(|value| match &home {
52                Some(home) => home.replace(&value),
53                None => value,
54            })
55            .collect();
56        normalize_values(&mut environment_values);
57        Self {
58            home,
59            environment_values,
60        }
61    }
62
63    pub(super) fn text(&self, text: &str) -> String {
64        let text = self
65            .environment_values
66            .iter()
67            // Common flags and nesting levels are not secret identities. Do not
68            // erase HTTP codes or counts just because the environment has `1`.
69            .filter(|value| {
70                !(value.len() <= MAX_SHORT_ENVIRONMENT_CHARS
71                    && value.bytes().all(|byte| byte.is_ascii_digit()))
72            })
73            .fold(self.home_text(text), |text, value| {
74                text.replace(value, MASK)
75            });
76        bounded(&scrub(&text))
77    }
78
79    pub(super) fn error_text(&self, text: &str, private_values: &[String]) -> String {
80        let text = private_values
81            .iter()
82            .map(|value| self.home_text(value))
83            .filter(|value| value != "~")
84            .fold(self.home_text(text), |text, value| {
85                mask_identity(&text, &value)
86            });
87        self.text(&text)
88    }
89
90    /// Registered identities are not arbitrary environment text. In particular,
91    /// an environment value of `1` must not erase version numbers.
92    pub(super) fn public_field(&self, text: &str) -> String {
93        bounded(&scrub(&self.home_text(text)))
94    }
95
96    /// Named paths permit short environment values and absolute path values,
97    /// but opaque values of four or more characters are still private. This
98    /// preserves `/bin/zsh` and version segments when the environment has `1`.
99    pub(super) fn path_field(&self, text: &str) -> String {
100        let text = self.home_text(text);
101        if path_list(&text) {
102            return MASK.into();
103        }
104        let text = self
105            .environment_values
106            .iter()
107            .filter(|value| {
108                value.chars().count() > MAX_SHORT_ENVIRONMENT_CHARS && !absolute_path(value)
109            })
110            .fold(text, |text, value| text.replace(value, MASK));
111        bounded(&scrub(&text))
112    }
113
114    /// `Source::describe()` names the shell path explicitly. Other descriptions
115    /// are untrusted prose, including inherited-PATH failure reasons.
116    pub(super) fn source(&self, text: &str) -> String {
117        match text.strip_prefix("login shell ") {
118            Some(path) if absolute_path(path) => {
119                format!("login shell {}", self.path_field(path))
120            }
121            _ => self.text(text),
122        }
123    }
124
125    fn home_text(&self, text: &str) -> String {
126        self.home
127            .as_ref()
128            .map_or_else(|| text.into(), |home| home.replace(text))
129    }
130}
131
132fn absolute_path(value: &str) -> bool {
133    value.starts_with('/')
134        || value.starts_with("~/")
135        || value.starts_with("~\\")
136        || windows_path(value)
137}
138
139fn path_list(text: &str) -> bool {
140    text.contains(';') || (text.contains(':') && !windows_path(text))
141}
142
143fn windows_path(value: &str) -> bool {
144    value
145        .as_bytes()
146        .first()
147        .is_some_and(u8::is_ascii_alphabetic)
148        && value.as_bytes().get(1) == Some(&b':')
149        && matches!(value.as_bytes().get(2), Some(b'/' | b'\\'))
150}
151
152fn scrub(text: &str) -> String {
153    let text = RULES.iter().fold(text.to_owned(), |text, pattern| {
154        pattern.replace_all(&text, MASK).into_owned()
155    });
156    crate::log::redact(&text)
157}
158
159pub(super) fn normalize_values(values: &mut Vec<String>) {
160    values.retain(|value| !value.is_empty());
161    values.sort_by(|left, right| right.len().cmp(&left.len()).then_with(|| left.cmp(right)));
162    values.dedup();
163}
164
165fn mask_identity(text: &str, value: &str) -> String {
166    let mut result = String::new();
167    let mut cursor = 0;
168    for (start, found) in text.match_indices(value) {
169        let end = start + found.len();
170        let left = text[..start].chars().next_back();
171        let right = text[end..].chars().next();
172        if left.is_some_and(identity_character) || right.is_some_and(identity_character) {
173            continue;
174        }
175        result.push_str(&text[cursor..start]);
176        result.push_str(MASK);
177        cursor = end;
178    }
179    result.push_str(&text[cursor..]);
180    result
181}
182
183fn identity_character(value: char) -> bool {
184    value.is_alphanumeric() || "_-".contains(value)
185}
186
187fn bounded(text: &str) -> String {
188    let text = text.split_whitespace().collect::<Vec<_>>().join(" ");
189    if text.chars().count() <= MAX_FIELD_CHARS {
190        return text;
191    }
192    let prefix: String = text.chars().take(MAX_FIELD_CHARS).collect();
193    format!("{prefix} [truncated]")
194}
195
196#[cfg(test)]
197mod tests {
198    use super::RedactionContext;
199
200    #[test]
201    fn removes_urls_assignments_and_planted_values_without_losing_friendly_text() {
202        let context = RedactionContext::new(None, ["test-only-environment-value".into()]);
203        let input = concat!(
204            "Azure CLI was not found. Try again after installing it. ",
205            "https://test-user:test-proxy-password@proxy.invalid:8080/path ",
206            "HTTP_PROXY = 'test spaced proxy value' CUSTOM_ENV=\"another test value\" ",
207            "test-only-environment-value"
208        );
209        let result = context.text(input);
210        assert!(result.starts_with("Azure CLI was not found. Try again after installing it."));
211        for forbidden in [
212            "proxy.invalid",
213            "test-proxy-password",
214            "test spaced proxy value",
215            "another test value",
216            "test-only-environment-value",
217        ] {
218            assert!(!result.contains(forbidden), "{result}");
219        }
220        assert!(!format!("{context:?}").contains("test-only-environment-value"));
221    }
222}