martin_core/tiles/postgres/
connection_string.rs1use std::fmt::{self, Debug, Display};
4use std::sync::LazyLock;
5
6use regex::Regex;
7use url::Url;
8
9const REDACTED: &str = "REDACTED";
11
12#[derive(Clone, PartialEq, Eq)]
21pub struct RedactedConnectionString(String);
22
23impl RedactedConnectionString {
24 #[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 Debug::fmt(&self.0, f)
47 }
48}
49
50fn 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 return redact_keyword_password(url.as_str());
58 }
59 redact_keyword_password(&redact_url_userinfo(conn_str))
61}
62
63fn 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: ®ex::Captures| {
70 format!("{}{REDACTED}{}", &caps[1], &caps[2])
71 })
72 .into_owned()
73}
74
75fn redact_keyword_password(conn_str: &str) -> String {
77 static KEYWORD: LazyLock<Regex> = LazyLock::new(|| {
78 Regex::new(r"(?i)(\bpassword\s*=\s*)('(?:[^'\\]|\\.)*'|[^\s&]*)").expect("password redaction regex is valid")
80 });
81 KEYWORD
82 .replace_all(conn_str, |caps: ®ex::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}