Skip to main content

martin_core/tiles/postgres/
connection_string.rs

1//! A wrapper around a `PostgreSQL` connection string that redacts its password when displayed.
2
3use std::fmt::{self, Debug, Display};
4use std::sync::LazyLock;
5
6use regex::Regex;
7use url::Url;
8
9/// Placeholder substituted for any password found in a connection string.
10const REDACTED: &str = "REDACTED";
11
12/// A `PostgreSQL` connection string whose password is redacted for display.
13///
14/// `PostgreSQL` connection strings usually embed a password, either in the userinfo of a URL
15/// (`postgres://user:secret@host/db`) or as a `password=` keyword/value pair.
16/// Logging such a string verbatim leaks the credential, see <https://github.com/maplibre/martin/issues/2895>.
17///
18/// This wrapper stores only the already-redacted form, so the original password can never be
19/// recovered or accidentally logged through [`Display`] or [`Debug`].
20#[derive(Clone, PartialEq, Eq)]
21pub struct RedactedConnectionString(String);
22
23impl RedactedConnectionString {
24    /// Redacts any password embedded in `conn_str` and wraps the result.
25    #[must_use]
26    pub fn new(conn_str: &str) -> Self {
27        Self(redact(conn_str))
28    }
29}
30
31impl From<&str> for RedactedConnectionString {
32    fn from(conn_str: &str) -> Self {
33        Self::new(conn_str)
34    }
35}
36
37impl Display for RedactedConnectionString {
38    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
39        f.write_str(&self.0)
40    }
41}
42
43impl Debug for RedactedConnectionString {
44    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
45        // Render as a bare quoted string, not `RedactedConnectionString("…")`.
46        Debug::fmt(&self.0, f)
47    }
48}
49
50/// Redacts the password in a `PostgreSQL` connection string, whichever format it is in.
51fn redact(conn_str: &str) -> String {
52    if let Ok(mut url) = Url::parse(conn_str) {
53        if url.password().is_some() {
54            let _ = url.set_password(Some(REDACTED));
55        }
56        // A parseable URL may still carry `?password=` in its query string.
57        return redact_keyword_password(url.as_str());
58    }
59    // Not a parseable URL: a malformed URL or the `keyword=value` format.
60    redact_keyword_password(&redact_url_userinfo(conn_str))
61}
62
63/// Redacts the `scheme://user:PASSWORD@` userinfo of a URL the `url` crate could not parse.
64fn redact_url_userinfo(conn_str: &str) -> String {
65    static USERINFO: LazyLock<Regex> = LazyLock::new(|| {
66        Regex::new(r"(?i)([a-z][a-z0-9+.\-]*://[^@/?#:\s]*:)[^@/?#\s]*(@)").expect("userinfo redaction regex is valid")
67    });
68    USERINFO
69        .replace_all(conn_str, |caps: &regex::Captures| {
70            format!("{}{REDACTED}{}", &caps[1], &caps[2])
71        })
72        .into_owned()
73}
74
75/// Redacts a `password=value` pair, as used by the `keyword=value` format and URL query strings.
76fn redact_keyword_password(conn_str: &str) -> String {
77    static KEYWORD: LazyLock<Regex> = LazyLock::new(|| {
78        // `password = 'quoted value'` or `password=unquoted`, delimited by whitespace or `&`.
79        Regex::new(r"(?i)(\bpassword\s*=\s*)('(?:[^'\\]|\\.)*'|[^\s&]*)").expect("password redaction regex is valid")
80    });
81    KEYWORD
82        .replace_all(conn_str, |caps: &regex::Captures| format!("{}{REDACTED}", &caps[1]))
83        .into_owned()
84}
85
86#[cfg(test)]
87mod tests {
88    use rstest::rstest;
89
90    use super::*;
91
92    #[rstest]
93    #[case::url_userinfo(
94        "postgres://user:secret@localhost:5432/db",
95        "postgres://user:REDACTED@localhost:5432/db"
96    )]
97    #[case::url_userinfo_with_colon(
98        "postgres://user:p@ss:word@localhost:5432/db",
99        "postgres://user:REDACTED@localhost:5432/db"
100    )]
101    #[case::url_userinfo_percent_encoded(
102        "postgres://user:p%26ss%3Aword@localhost:5432/db",
103        "postgres://user:REDACTED@localhost:5432/db"
104    )]
105    #[case::url_query_password(
106        "postgres://host/db?password=secret&sslmode=require",
107        "postgres://host/db?password=REDACTED&sslmode=require"
108    )]
109    #[case::url_query_password_percent_encoded(
110        "postgres://host/db?password=p%26w%3Drd&sslmode=require",
111        "postgres://host/db?password=REDACTED&sslmode=require"
112    )]
113    #[case::keyword_password(
114        "host=localhost password=secret sslmode=verify-full",
115        "host=localhost password=REDACTED sslmode=verify-full"
116    )]
117    #[case::keyword_password_quoted(
118        "host=localhost password='se cret' dbname=db",
119        "host=localhost password=REDACTED dbname=db"
120    )]
121    #[case::url_no_password("postgres://user@localhost:5432/db", "postgres://user@localhost:5432/db")]
122    #[case::url_no_userinfo("postgres://localhost:5432/db", "postgres://localhost:5432/db")]
123    #[case::keyword_password_substring("host=localhost mypassword=keep", "host=localhost mypassword=keep")]
124    #[case::keyword_no_password(
125        "host=localhost dbname=db sslmode=verify-full",
126        "host=localhost dbname=db sslmode=verify-full"
127    )]
128    fn redacts(#[case] conn_str: &str, #[case] expected: &str) {
129        assert_eq!(RedactedConnectionString::new(conn_str).to_string(), expected);
130    }
131
132    #[rstest]
133    #[case::bad_port(
134        "postgres://postgres:testpassword@host:notaport/db",
135        "postgres://postgres:REDACTED@host:notaport/db"
136    )]
137    #[case::bad_port_colon_password(
138        "postgres://postgres:test:password@host:notaport/db",
139        "postgres://postgres:REDACTED@host:notaport/db"
140    )]
141    fn redacts_unparseable_url(#[case] conn_str: &str, #[case] expected: &str) {
142        assert!(Url::parse(conn_str).is_err(), "test needs the regex fallback path");
143        assert_eq!(RedactedConnectionString::new(conn_str).to_string(), expected);
144    }
145}