summaryrefslogtreecommitdiffstats
path: root/third_party/rust/error-support/src/redact.rs
blob: 01a333ee35f586cb0bbc368d576486a7062cd402 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

//! Functions to redact strings to remove PII before logging them

/// Redact a URL.
///
/// It's tricky to redact an URL without revealing PII.  We check for various known bad URL forms
/// and report them, otherwise we just log "<URL>".
pub fn redact_url(url: &str) -> String {
    if url.is_empty() {
        return "<URL (empty)>".to_string();
    }
    match url.find(':') {
        None => "<URL (no scheme)>".to_string(),
        Some(n) => {
            let mut chars = url[0..n].chars();
            match chars.next() {
                // No characters in the scheme
                None => return "<URL (empty scheme)>".to_string(),
                Some(c) => {
                    // First character must be alphabetic
                    if !c.is_ascii_alphabetic() {
                        return "<URL (invalid scheme)>".to_string();
                    }
                }
            }
            for c in chars {
                // Subsequent characters must be in the set ( alpha | digit | "+" | "-" | "." )
                if !(c.is_ascii_alphanumeric() || c == '+' || c == '-' || c == '.') {
                    return "<URL (invalid scheme)>".to_string();
                }
            }
            "<URL>".to_string()
        }
    }
}

/// Redact compact jwe string (Five base64 segments, separated by `.` chars)
pub fn redact_compact_jwe(url: &str) -> String {
    url.replace(|ch| ch != '.', "x")
}

#[cfg(test)]
mod test {
    use super::*;

    #[test]
    fn test_redact_url() {
        assert_eq!(redact_url("http://some.website.com/index.html"), "<URL>");
        assert_eq!(redact_url("about:config"), "<URL>");
        assert_eq!(redact_url(""), "<URL (empty)>");
        assert_eq!(redact_url("://some.website.com/"), "<URL (empty scheme)>");
        assert_eq!(redact_url("some.website.com/"), "<URL (no scheme)>");
        assert_eq!(redact_url("some.website.com/"), "<URL (no scheme)>");
        assert_eq!(
            redact_url("abc%@=://some.website.com/"),
            "<URL (invalid scheme)>"
        );
        assert_eq!(
            redact_url("0https://some.website.com/"),
            "<URL (invalid scheme)>"
        );
        assert_eq!(
            redact_url("a+weird-but.lega1-SCHEME://some.website.com/"),
            "<URL>"
        );
    }

    #[test]
    fn test_redact_compact_jwe() {
        assert_eq!(redact_compact_jwe("abc.1234.x3243"), "xxx.xxxx.xxxxx")
    }
}