Skip to main content

feldera_types/
display_url.rs

1//! A URL for logs and errors: shown without its credentials.
2
3use url::Url;
4
5/// Stands in for a value that can hold a credential.
6pub const REDACTED: &str = "[REDACTED]";
7
8/// Debug output of named values as `{name: "[REDACTED]"}`: it shows that each
9/// value exists, and hides it.
10pub struct HiddenValues<'a>(pub Vec<&'a str>);
11
12impl std::fmt::Debug for HiddenValues<'_> {
13    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
14        f.debug_map()
15            .entries(self.0.iter().map(|name| (name, REDACTED)))
16            .finish()
17    }
18}
19
20/// Schemes whose username is a container name, not a credential.
21const SCHEMES_WITH_CONTAINER_USERNAME: [&str; 4] = ["abfs", "abfss", "wasb", "wasbs"];
22
23/// `url` without userinfo, query string and fragment. All three can hold
24/// credentials: a password, a token used as the username, or the token of
25/// a signed URL.
26///
27/// A local path, or any text that holds none of them, is returned as is.
28/// Text that holds one of them but does not parse as a URL with a host,
29/// such as `user:pw@host/db`, is replaced by [`REDACTED`].
30pub fn url_without_credentials(url: &str) -> String {
31    match Url::parse(url) {
32        Ok(parsed) if parsed.cannot_be_a_base() && url.contains('@') => REDACTED.to_string(),
33        Ok(mut parsed) => {
34            // An Azure URL names the container in the username.
35            let keep_username = parsed.password().is_none()
36                && SCHEMES_WITH_CONTAINER_USERNAME.contains(&parsed.scheme());
37            if !keep_username {
38                let _ = parsed.set_username("");
39            }
40            let _ = parsed.set_password(None);
41            parsed.set_query(None);
42            parsed.set_fragment(None);
43            parsed.to_string()
44        }
45        Err(_) if !url.contains('@') && !url.contains('?') && !url.contains('#') => url.to_string(),
46        Err(_) => REDACTED.to_string(),
47    }
48}
49
50/// `text` with every copy of `url` replaced by [`url_without_credentials`],
51/// for the message of a library error that repeats the URL it was given.
52/// A library can also print the URL after parsing it, with the path
53/// normalized and the credentials kept, so the canonical form, the userinfo
54/// and the query string go on their own as well.
55pub fn text_without_url(text: &str, url: &str) -> String {
56    if url.is_empty() {
57        return text.to_string();
58    }
59    let safe = url_without_credentials(url);
60    let mut text = text.replace(url, &safe);
61    let Ok(parsed) = Url::parse(url) else {
62        return text;
63    };
64    text = text.replace(parsed.as_str(), &safe);
65    let mut parts = Vec::new();
66    if let Some(query) = parsed.query() {
67        parts.push(format!("?{query}"));
68    }
69    if let Some(fragment) = parsed.fragment() {
70        parts.push(format!("#{fragment}"));
71    }
72    if !parsed.username().is_empty() || parsed.password().is_some() {
73        parts.push(match parsed.password() {
74            Some(password) => format!("{}:{password}@", parsed.username()),
75            None => format!("{}@", parsed.username()),
76        });
77    }
78    // The text as written can differ from the parsed form in its encoding.
79    if let Some((_, rest)) = url.split_once("://") {
80        let authority_end = rest.find(['/', '?', '#']).unwrap_or(rest.len());
81        if let Some(at) = rest[..authority_end].rfind('@') {
82            parts.push(rest[..=at].to_string());
83        }
84        if let Some(query) = rest.find('?') {
85            let end = rest[query..].find('#').map_or(rest.len(), |i| query + i);
86            parts.push(rest[query..end].to_string());
87        }
88    }
89    for part in parts {
90        if part.len() > 1 {
91            text = text.replace(&part, "");
92        }
93    }
94    text
95}
96
97#[cfg(test)]
98mod tests {
99    use super::{REDACTED, text_without_url, url_without_credentials};
100
101    /// A library can print the URL after normalizing its path; the
102    /// credentials and the query string still go.
103    #[test]
104    fn a_normalized_copy_of_the_url_is_covered() {
105        let url = "s3://ak:secret-key@bucket/table?X-Amz-Signature=sig";
106        assert_eq!(
107            text_without_url(
108                "open s3://ak:secret-key@bucket/table/?X-Amz-Signature=sig failed",
109                url
110            ),
111            "open s3://bucket/table/ failed"
112        );
113    }
114
115    #[test]
116    fn credentials_and_query_string_are_left_out() {
117        assert_eq!(
118            url_without_credentials("s3://ak:secret-key@bucket/table?X-Amz-Signature=sig"),
119            "s3://bucket/table"
120        );
121        assert_eq!(
122            url_without_credentials("postgres://u:pw@db.internal:5432/app"),
123            "postgres://db.internal:5432/app"
124        );
125        assert_eq!(url_without_credentials("/tmp/table"), "/tmp/table");
126        assert_eq!(url_without_credentials("not a url?token=secret"), REDACTED);
127    }
128
129    /// A string without a scheme parses as an opaque URL whose "scheme" is
130    /// the username, so its password cannot be removed; a fragment can
131    /// carry a token; a token can be the username of a Git or HTTP URL.
132    #[test]
133    fn opaque_urls_fragments_and_username_tokens_are_left_out() {
134        assert_eq!(url_without_credentials("user:pw@host/db"), REDACTED);
135        assert_eq!(url_without_credentials("user:pw@host:5432"), REDACTED);
136        assert_eq!(
137            url_without_credentials("https://h/p#token=abc"),
138            "https://h/p"
139        );
140        assert_eq!(
141            url_without_credentials("https://ghp_token@github.com/org/repo.git"),
142            "https://github.com/org/repo.git"
143        );
144    }
145
146    /// Azure URLs name the container in the username; it is no credential.
147    #[test]
148    fn azure_container_names_stay() {
149        assert_eq!(
150            url_without_credentials("abfss://container@acct.dfs.core.windows.net/t"),
151            "abfss://container@acct.dfs.core.windows.net/t"
152        );
153        assert_eq!(
154            url_without_credentials("wasbs://container:key@acct.blob.core.windows.net/t"),
155            "wasbs://acct.blob.core.windows.net/t"
156        );
157    }
158
159    #[test]
160    fn a_library_error_that_repeats_the_url_loses_the_credentials() {
161        let url = "s3://ak:secret-key@bucket/table?X-Amz-Signature=sig";
162        assert_eq!(
163            text_without_url(&format!("Could not parse {url} as a URL: {url}"), url),
164            "Could not parse s3://bucket/table as a URL: s3://bucket/table"
165        );
166        assert_eq!(text_without_url("no url here", url), "no url here");
167    }
168}