Skip to main content

ocre/errors/
scrub.rs

1//! [`scrub`]: personal data and secrets out of error reports, ids and durations normalized.
2
3use serde_json::Value;
4
5use super::Report;
6
7/// Prefixes of well-known API keys and tokens.
8const SECRET_PREFIXES: &[&str] = &[
9    "whsec_",
10    "sk_live_",
11    "sk_test_",
12    "rk_live_",
13    "rk_test_",
14    "pk_live_",
15    "pk_test_",
16    "ghp_",
17    "gho_",
18    "ghs_",
19    "github_pat_",
20    "xoxb-",
21    "xoxp-",
22    "phc_",
23    "phx_",
24    "AKIA",
25];
26
27/// Query-string parameters whose value is a credential.
28const SECRET_PARAMS: &[&str] = &[
29    "password",
30    "passwd",
31    "secret",
32    "token",
33    "access_token",
34    "api_key",
35    "apikey",
36    "key",
37    "signature",
38    "sig",
39    "X-Amz-Signature",
40    "X-Amz-Credential",
41];
42
43/// Replaces what must not leave the app in an error report, and what keeps the same error from grouping.
44///
45/// For [`Subscriber`](crate::errors::Subscriber)s that send reports to an
46/// outside service ([`Report::scrubbed`] applies it to a whole report):
47///
48/// | Found | Becomes |
49/// |---|---|
50/// | `Bearer <token>`, `Basic <credentials>`, well-known key prefixes (`sk_live_`, `whsec_`, `ghp_`, `AKIA`...) | `[secret]` |
51/// | `password=`, `token=`, `key=`, `signature=`... query values | `<name>=[secret]` |
52/// | email addresses | `[email]` |
53/// | UUIDs | `[id]` |
54/// | runs of 32 or more letters and digits (tokens, digests) | `[secret]` |
55/// | durations (`12 ms`, `3.5s`, `40µs`) | `[n]ms`, `[n]s`, `[n]µs` |
56///
57/// Pure CPU, a single pass per rule over the text.
58///
59/// # Examples
60///
61/// ```
62/// use ocre::errors::scrub;
63///
64/// assert_eq!(scrub("Authorization: Bearer eyJ.abc/def="), "Authorization: [secret]");
65/// assert_eq!(scrub("no user ada.l+x@example.co.uk"), "no user [email]");
66/// assert_eq!(scrub("video 0b9c2f44-1d2e-4f7a-9c3b-2a1b0c9d8e7f gone"), "video [id] gone");
67/// assert_eq!(scrub("GET /reset?token=abc123&x=1 took 12.5 ms"), "GET /reset?token=[secret]&x=1 took [n]ms");
68/// ```
69pub fn scrub(text: &str) -> String {
70    let text = secrets(text);
71    let text = params(&text);
72    let text = emails(&text);
73    let text = uuids(&text);
74    let text = tokens(&text);
75    durations(&text)
76}
77
78impl Report {
79    /// The report with [`scrub`] applied to its message and every text in its context.
80    ///
81    /// # Examples
82    ///
83    /// ```
84    /// use ocre::errors::{Options, Reporter};
85    ///
86    /// let reporter = Reporter::default();
87    /// reporter.report(&"no user ada@example.com", Options::new().context("email", "ada@example.com"));
88    /// let report = reporter.take().remove(0).scrubbed();
89    /// assert_eq!(report.message, "no user [email]");
90    /// assert_eq!(report.context["email"], "[email]");
91    /// ```
92    pub fn scrubbed(mut self) -> Self {
93        self.message = scrub(&self.message);
94        for value in self.context.values_mut() {
95            scrub_value(value);
96        }
97        self
98    }
99}
100
101fn scrub_value(value: &mut Value) {
102    match value {
103        Value::String(text) => *text = scrub(text),
104        Value::Array(items) => items.iter_mut().for_each(scrub_value),
105        Value::Object(map) => map.values_mut().for_each(scrub_value),
106        _ => {}
107    }
108}
109
110fn word(c: char) -> bool {
111    c.is_alphanumeric() || c == '_'
112}
113
114/// Replaces the ranges `find(chars, i) -> Some((i, end))` returns with `with(matched)`.
115fn replace(text: &str, with: impl Fn(&[char]) -> String, find: impl Fn(&[char], usize) -> Option<usize>) -> String {
116    let chars: Vec<char> = text.chars().collect();
117    let mut out = String::with_capacity(text.len());
118    let mut i = 0;
119    while i < chars.len() {
120        match find(&chars, i) {
121            Some(end) if end > i => {
122                out.push_str(&with(&chars[i..end]));
123                i = end;
124            }
125            _ => {
126                out.push(chars[i]);
127                i += 1;
128            }
129        }
130    }
131    out
132}
133
134fn starts_with(chars: &[char], i: usize, prefix: &str) -> bool {
135    (i..).zip(prefix.chars()).all(|(n, p)| chars.get(n) == Some(&p))
136}
137
138fn run(chars: &[char], from: usize, allowed: impl Fn(char) -> bool) -> usize {
139    let mut end = from;
140    while end < chars.len() && allowed(chars[end]) {
141        end += 1;
142    }
143    end
144}
145
146fn boundary(chars: &[char], i: usize) -> bool {
147    i == 0 || !word(chars[i - 1])
148}
149
150fn secrets(text: &str) -> String {
151    replace(
152        text,
153        |_| "[secret]".to_owned(),
154        |chars, i| {
155            if !boundary(chars, i) {
156                return None;
157            }
158            for prefix in SECRET_PREFIXES {
159                if starts_with(chars, i, prefix) {
160                    let start = i + prefix.chars().count();
161                    let end = run(chars, start, |c| c.is_ascii_alphanumeric() || c == '_' || c == '-');
162                    if end > start {
163                        return Some(end);
164                    }
165                }
166            }
167            for scheme in ["Bearer", "Basic"] {
168                if starts_with(chars, i, scheme) {
169                    let after = i + scheme.len();
170                    let spaces = run(chars, after, |c| c == ' ' || c == '\t');
171                    let end = run(chars, spaces, |c| c.is_ascii_alphanumeric() || "._~+/=-".contains(c));
172                    if spaces > after && end > spaces {
173                        return Some(end);
174                    }
175                }
176            }
177            None
178        },
179    )
180}
181
182/// `name=value` of a credential parameter: the value only.
183fn params(text: &str) -> String {
184    replace(
185        text,
186        |matched| {
187            let name: String = matched.iter().take_while(|c| **c != '=').collect();
188            format!("{name}=[secret]")
189        },
190        |chars, i| {
191            let after_separator = i == 0 || matches!(chars[i - 1], '?' | '&' | ' ' | '"' | '\'' | ';');
192            if !after_separator {
193                return None;
194            }
195            let name = SECRET_PARAMS.iter().find(|name| {
196                let len = name.chars().count();
197                chars.get(i..i + len).is_some_and(|got| got.iter().copied().eq(name.chars()))
198                    && chars.get(i + len) == Some(&'=')
199            })?;
200            let start = i + name.chars().count() + 1;
201            let end = run(chars, start, |c| !c.is_whitespace() && !"&\"'#;".contains(c));
202            (end > start).then_some(end)
203        },
204    )
205}
206
207/// `[\w.+-]+@[\w-]+\.[\w.-]+`.
208fn emails(text: &str) -> String {
209    let local = |c: char| word(c) || ".+-".contains(c);
210    replace(
211        text,
212        |_| "[email]".to_owned(),
213        |chars, i| {
214            if !local(chars[i]) || (i > 0 && local(chars[i - 1])) {
215                return None;
216            }
217            let at = run(chars, i, local);
218            if chars.get(at) != Some(&'@') {
219                return None;
220            }
221            let domain = run(chars, at + 1, |c| word(c) || c == '-');
222            if domain == at + 1 || chars.get(domain) != Some(&'.') {
223                return None;
224            }
225            let end = run(chars, domain + 1, |c| word(c) || ".-".contains(c));
226            (end > domain + 1).then_some(end)
227        },
228    )
229}
230
231fn uuids(text: &str) -> String {
232    replace(
233        text,
234        |_| "[id]".to_owned(),
235        |chars, i| {
236            if !boundary(chars, i) {
237                return None;
238            }
239            let mut n = i;
240            for (k, len) in [8, 4, 4, 4, 12].into_iter().enumerate() {
241                if k > 0 {
242                    if chars.get(n) != Some(&'-') {
243                        return None;
244                    }
245                    n += 1;
246                }
247                let end = run(chars, n, |c| c.is_ascii_hexdigit());
248                if end - n != len {
249                    return None;
250                }
251                n = end;
252            }
253            chars.get(n).is_none_or(|c| !word(*c)).then_some(n)
254        },
255    )
256}
257
258/// Runs of 32 or more URL-safe characters mixing letters and digits.
259fn tokens(text: &str) -> String {
260    let token = |c: char| c.is_ascii_alphanumeric() || c == '-' || c == '_';
261    replace(
262        text,
263        |_| "[secret]".to_owned(),
264        |chars, i| {
265            if i > 0 && token(chars[i - 1]) {
266                return None;
267            }
268            let end = run(chars, i, token);
269            let run = &chars[i..end];
270            let mixed = run.iter().any(char::is_ascii_digit) && run.iter().any(char::is_ascii_alphabetic);
271            (end - i >= 32 && mixed).then_some(end)
272        },
273    )
274}
275
276/// `\b\d+(\.\d+)?\s?(ms|µs|s)\b` → `[n]<unit>`.
277fn durations(text: &str) -> String {
278    replace(
279        text,
280        |matched| {
281            let unit = if matched.ends_with(&['m', 's']) {
282                "ms"
283            } else if matched.ends_with(&['µ', 's']) {
284                "µs"
285            } else {
286                "s"
287            };
288            format!("[n]{unit}")
289        },
290        |chars, i| {
291            if !boundary(chars, i) || !chars[i].is_ascii_digit() {
292                return None;
293            }
294            let mut end = run(chars, i, |c| c.is_ascii_digit());
295            if chars.get(end) == Some(&'.') && chars.get(end + 1).is_some_and(char::is_ascii_digit) {
296                end = run(chars, end + 1, |c| c.is_ascii_digit());
297            }
298            let unit_at = if chars.get(end) == Some(&' ') { end + 1 } else { end };
299            ["ms", "µs", "s"].into_iter().find_map(|unit| {
300                let after = unit_at + unit.chars().count();
301                (starts_with(chars, unit_at, unit) && chars.get(after).is_none_or(|c| !word(*c))).then_some(after)
302            })
303        },
304    )
305}
306
307#[cfg(test)]
308#[path = "../../tests/errors/scrub.rs"]
309mod tests;