error_support/
redact.rs

1/* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
4
5//! Functions to redact strings to remove PII before logging them
6
7/// Redact a URL.
8///
9/// It's tricky to redact an URL without revealing PII.  We check for various known bad URL forms
10/// and report them, otherwise we just log "<URL>".
11pub fn redact_url(url: &str) -> String {
12    if url.is_empty() {
13        return "<URL (empty)>".to_string();
14    }
15    match url.find(':') {
16        None => "<URL (no scheme)>".to_string(),
17        Some(n) => {
18            let mut chars = url[0..n].chars();
19            match chars.next() {
20                // No characters in the scheme
21                None => return "<URL (empty scheme)>".to_string(),
22                Some(c) => {
23                    // First character must be alphabetic
24                    if !c.is_ascii_alphabetic() {
25                        return "<URL (invalid scheme)>".to_string();
26                    }
27                }
28            }
29            for c in chars {
30                // Subsequent characters must be in the set ( alpha | digit | "+" | "-" | "." )
31                if !(c.is_ascii_alphanumeric() || c == '+' || c == '-' || c == '.') {
32                    return "<URL (invalid scheme)>".to_string();
33                }
34            }
35            "<URL>".to_string()
36        }
37    }
38}
39
40/// Redact compact jwe string (Five base64 segments, separated by `.` chars)
41pub fn redact_compact_jwe(url: &str) -> String {
42    url.replace(|ch| ch != '.', "x")
43}
44
45#[cfg(test)]
46mod test {
47    use super::*;
48
49    #[test]
50    fn test_redact_url() {
51        assert_eq!(redact_url("http://some.website.com/index.html"), "<URL>");
52        assert_eq!(redact_url("about:config"), "<URL>");
53        assert_eq!(redact_url(""), "<URL (empty)>");
54        assert_eq!(redact_url("://some.website.com/"), "<URL (empty scheme)>");
55        assert_eq!(redact_url("some.website.com/"), "<URL (no scheme)>");
56        assert_eq!(redact_url("some.website.com/"), "<URL (no scheme)>");
57        assert_eq!(
58            redact_url("abc%@=://some.website.com/"),
59            "<URL (invalid scheme)>"
60        );
61        assert_eq!(
62            redact_url("0https://some.website.com/"),
63            "<URL (invalid scheme)>"
64        );
65        assert_eq!(
66            redact_url("a+weird-but.lega1-SCHEME://some.website.com/"),
67            "<URL>"
68        );
69    }
70
71    #[test]
72    fn test_redact_compact_jwe() {
73        assert_eq!(redact_compact_jwe("abc.1234.x3243"), "xxx.xxxx.xxxxx")
74    }
75}