Skip to main content

prax_postgres/
config.rs

1//! PostgreSQL connection configuration.
2
3use std::fmt;
4use std::path::PathBuf;
5use std::time::Duration;
6
7use crate::error::{PgError, PgResult};
8
9/// PostgreSQL connection configuration.
10///
11/// `Debug` output redacts [`password`](Self::password) and any password in
12/// [`url`](Self::url).
13#[non_exhaustive]
14#[derive(Clone)]
15pub struct PgConfig {
16    /// Database URL.
17    pub url: String,
18    /// Host (extracted from URL or explicit).
19    pub host: String,
20    /// Port (default: 5432).
21    pub port: u16,
22    /// Database name.
23    pub database: String,
24    /// Username.
25    pub user: String,
26    /// Password.
27    pub password: Option<String>,
28    /// SSL mode.
29    ///
30    /// With the default `tls` cargo feature, TLS connections are established
31    /// via rustls with certificates verified against the Mozilla root store
32    /// (chain + hostname). Without the feature, any TLS-requiring mode fails
33    /// at pool build time with a clear error — it is never silently
34    /// downgraded to plaintext.
35    pub ssl_mode: SslMode,
36    /// Path to a PEM file of root certificates to verify the server against,
37    /// from the libpq-compatible `sslrootcert` URL parameter.
38    ///
39    /// When set, these certificates *replace* the Mozilla root store rather
40    /// than adding to it, matching libpq: a pool talks to one server, and
41    /// "trust exactly this bundle" is both the stricter and the more
42    /// predictable reading.
43    ///
44    /// The case this exists for is a server whose CA is deliberately not
45    /// publicly trusted — Amazon RDS being the common one, since its
46    /// `rds-ca-*` authorities are Amazon-operated and absent from the Mozilla
47    /// store, so the default configuration cannot verify them at all.
48    pub ssl_root_cert: Option<PathBuf>,
49    /// Connection timeout.
50    pub connect_timeout: Duration,
51    /// Statement timeout.
52    pub statement_timeout: Option<Duration>,
53    /// Application name (shown in pg_stat_activity).
54    pub application_name: Option<String>,
55    /// Additional options.
56    pub options: Vec<(String, String)>,
57}
58
59impl fmt::Debug for PgConfig {
60    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
61        f.debug_struct("PgConfig")
62            .field("url", &redact_url(&self.url, self.password.as_deref()))
63            .field("host", &self.host)
64            .field("port", &self.port)
65            .field("database", &self.database)
66            .field("user", &self.user)
67            .field("password", &self.password.as_ref().map(|_| REDACTED))
68            .field("ssl_mode", &self.ssl_mode)
69            .field("ssl_root_cert", &self.ssl_root_cert)
70            .field("connect_timeout", &self.connect_timeout)
71            .field("statement_timeout", &self.statement_timeout)
72            .field("application_name", &self.application_name)
73            .field(
74                "options",
75                &self
76                    .options
77                    .iter()
78                    .map(|(key, value)| {
79                        let value = if is_password_key(key) {
80                            REDACTED
81                        } else {
82                            value
83                        };
84                        (key.as_str(), value)
85                    })
86                    .collect::<Vec<_>>(),
87            )
88            .finish()
89    }
90}
91
92/// Shown in place of a password in `Debug` output.
93const REDACTED: &str = "REDACTED";
94
95/// `url` with its password replaced by [`REDACTED`], for `Debug` output.
96/// Only the password inside the user info (`user:password@`) is touched;
97/// the rest of the URL is kept exactly as written.
98///
99/// `password` is the config's password, when known. It is matched right
100/// after `user:` first, because the config builder writes it into the URL
101/// without percent-encoding, where an `@` or `/` in it would not parse as
102/// one URL password. Otherwise the parser locates the password. When it
103/// finds none although an `@` follows the scheme and no user name parsed
104/// (an unencoded password starting with digits and then `/`, `?` or `#`
105/// parses as a port), or the URL does not parse at all, everything between
106/// the scheme and its last `@` is redacted. libpq-style `password` query
107/// parameters are redacted too.
108pub(crate) fn redact_url(url: &str, password: Option<&str>) -> String {
109    let Some(start) = url.find("://").map(|i| i + 3) else {
110        return url.to_owned();
111    };
112    let redacted = redact_userinfo(url, start, password);
113    redact_query_passwords(&redacted, start)
114}
115
116/// The user-info part of [`redact_url`].
117fn redact_userinfo(url: &str, start: usize, password: Option<&str>) -> String {
118    if let Some(password) = password.filter(|p| !p.is_empty())
119        && let Some(redacted) = splice_password(url, start, password)
120    {
121        return redacted;
122    }
123    match url::Url::parse(url) {
124        Ok(parsed) => match parsed.password() {
125            Some(password) => splice_password(url, start, password)
126                .unwrap_or_else(|| redact_to_last_at(url, start)),
127            None if parsed.username().is_empty() && url[start..].contains('@') => {
128                redact_to_last_at(url, start)
129            }
130            None => url.to_owned(),
131        },
132        Err(_) => redact_to_last_at(url, start),
133    }
134}
135
136/// `url` with the value of every `password` query parameter (any case,
137/// percent-decoded key) replaced. The query is searched from `start`.
138fn redact_query_passwords(url: &str, start: usize) -> String {
139    let Some(query_start) = url[start..].find('?').map(|i| start + i + 1) else {
140        return url.to_owned();
141    };
142    let query_end = url[query_start..]
143        .find('#')
144        .map_or(url.len(), |i| query_start + i);
145    let query = url[query_start..query_end]
146        .split('&')
147        .map(|pair| {
148            let key = pair.split_once('=').map_or(pair, |(key, _)| key);
149            if is_password_key(key) {
150                format!("{key}={REDACTED}")
151            } else {
152                pair.to_owned()
153            }
154        })
155        .collect::<Vec<_>>()
156        .join("&");
157    format!("{}{query}{}", &url[..query_start], &url[query_end..])
158}
159
160/// Whether a (possibly percent-encoded) query or option key names a
161/// password.
162fn is_password_key(key: &str) -> bool {
163    url::form_urlencoded::parse(key.as_bytes())
164        .next()
165        .is_some_and(|(key, _)| key.eq_ignore_ascii_case("password"))
166}
167
168/// `url` with `password` replaced, when it follows the first `:` of the
169/// user info (which starts at `start`) and is followed by `@`.
170fn splice_password(url: &str, start: usize, password: &str) -> Option<String> {
171    let from = start + url[start..].find(':')? + 1;
172    let after = url[from..].strip_prefix(password)?;
173    after
174        .starts_with('@')
175        .then(|| format!("{}{REDACTED}{after}", &url[..from]))
176}
177
178/// `url` with everything from `start` to its last `@` replaced.
179fn redact_to_last_at(url: &str, start: usize) -> String {
180    match url[start..].rfind('@') {
181        Some(at) => format!("{}{REDACTED}{}", &url[..start], &url[start + at..]),
182        None => url.to_owned(),
183    }
184}
185
186/// SSL mode for connections.
187///
188/// With the default `tls` cargo feature, `Require`/`VerifyCa`/`VerifyFull`
189/// establish rustls-encrypted connections verified against the Mozilla root
190/// store. `Prefer` uses TLS when the server offers it and falls back to
191/// plaintext only when the server declines TLS (note: stricter than libpq —
192/// a certificate verification failure fails the connection rather than
193/// retrying plaintext). Without the `tls` feature, TLS-requiring modes fail
194/// at pool build time.
195#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
196pub enum SslMode {
197    /// Disable SSL.
198    Disable,
199    /// Prefer SSL but allow non-SSL when the server declines TLS.
200    #[default]
201    Prefer,
202    /// Require SSL. Certificates are verified (chain + hostname) — stricter
203    /// than libpq's `require`, which skips verification.
204    Require,
205    /// Require SSL and verify the certificate chain. Currently also verifies
206    /// the hostname (i.e. behaves as `VerifyFull`; libpq's hostname-less
207    /// `verify-ca` is not yet distinguished).
208    VerifyCa,
209    /// Require SSL and verify the certificate chain and hostname.
210    VerifyFull,
211}
212
213/// Validate a GUC name destined for the `options` startup parameter.
214/// Postgres GUC names match `^[A-Za-z_][A-Za-z0-9_.]*$` (the `.`
215/// separates extension namespaces, e.g. `pg_trgm.similarity_threshold`).
216fn is_valid_guc_key(key: &str) -> bool {
217    let mut chars = key.chars();
218    matches!(chars.next(), Some(c) if c.is_ascii_alphabetic() || c == '_')
219        && chars.all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '.')
220}
221
222/// Reject values that could break out of the space-joined `options`
223/// startup parameter: whitespace terminates the assignment and starts a
224/// new token, and `\` / `'` are libpq's quoting characters in that
225/// string. A percent-decoded URL value could otherwise smuggle extra
226/// `-c key=value` assignments (e.g. `?x=1%20-c%20search_path%3Devil`).
227fn is_safe_guc_value(value: &str) -> bool {
228    !value
229        .chars()
230        .any(|c| c.is_whitespace() || c == '\\' || c == '\'')
231}
232
233/// How to fix a URL whose password breaks its structure.
234const PERCENT_ENCODE_HINT: &str = "percent-encode reserved characters in the password \
235     (`@` as %40, `/` as %2F, `?` as %3F, `#` as %23, `:` as %3A)";
236
237/// Reject a URL in which an unencoded `/`, `?` or `#` in the password ended
238/// the authority early, so the rest of the password and the real host
239/// landed in the path, query or fragment (`postgres://u:8/x@host/db` parses
240/// as host `u`, port 8 and database `x@host/db`). The telltale is an `@`
241/// after the authority: in the path, the fragment, or a query key (a query
242/// *value* such as `application_name=me@work` is fine). An `@` in a
243/// database name must be written `%40`. The error never repeats the URL.
244fn reject_unencoded_userinfo(parsed: &url::Url) -> PgResult<()> {
245    let in_query_key = parsed.query().is_some_and(|query| {
246        query.split('&').any(|pair| {
247            pair.split_once('=')
248                .map_or(pair, |(key, _)| key)
249                .contains('@')
250        })
251    });
252    if parsed.path().contains('@')
253        || parsed
254            .fragment()
255            .is_some_and(|fragment| fragment.contains('@'))
256        || in_query_key
257    {
258        return Err(PgError::config(format!(
259            "invalid database URL: an `@` follows the host, so the password \
260             seems to contain unencoded reserved characters; {PERCENT_ENCODE_HINT}"
261        )));
262    }
263    Ok(())
264}
265
266/// Percent-decode a URL component (`what` names it in the error), as libpq
267/// does for the user, password and database name.
268fn percent_decode(component: &str, what: &str) -> PgResult<String> {
269    percent_encoding::percent_decode_str(component)
270        .decode_utf8()
271        .map(|decoded| decoded.into_owned())
272        .map_err(|_| {
273            PgError::config(format!(
274                "invalid database URL: the {what} is not valid UTF-8 once percent-decoded"
275            ))
276        })
277}
278
279impl PgConfig {
280    /// Create a new configuration from a database URL.
281    ///
282    /// The user name, password and database name are percent-decoded, as
283    /// libpq does: write reserved characters in them (`@`, `/`, `?`, `#`,
284    /// `:`) percent-encoded. A URL whose password evidently contains them
285    /// unencoded (an `@` after the host) is rejected with a configuration
286    /// error rather than parsed into the wrong host, port or database.
287    ///
288    /// As with libpq, `user` and `password` query parameters set the
289    /// credentials (overriding the user info). Other unrecognised
290    /// parameters become [`options`](Self::options).
291    pub fn from_url(url: impl Into<String>) -> PgResult<Self> {
292        let url = url.into();
293        let parsed = url::Url::parse(&url).map_err(|e| {
294            // An unencoded `/`, `?` or `#` in the password ends the authority
295            // early, which often leaves an invalid port behind.
296            let hint = if url.contains('@') {
297                format!("; {PERCENT_ENCODE_HINT}")
298            } else {
299                String::new()
300            };
301            PgError::config(format!("invalid database URL: {e}{hint}"))
302        })?;
303        reject_unencoded_userinfo(&parsed)?;
304
305        if parsed.scheme() != "postgresql" && parsed.scheme() != "postgres" {
306            return Err(PgError::config(format!(
307                "invalid scheme: expected 'postgresql' or 'postgres', got '{}'",
308                parsed.scheme()
309            )));
310        }
311
312        let host = parsed
313            .host_str()
314            .ok_or_else(|| PgError::config("missing host in URL"))?
315            .to_string();
316
317        let port = parsed.port().unwrap_or(5432);
318
319        let database = percent_decode(parsed.path().trim_start_matches('/'), "database name")?;
320
321        if database.is_empty() {
322            return Err(PgError::config("missing database name in URL"));
323        }
324
325        let mut user = if parsed.username().is_empty() {
326            "postgres".to_string()
327        } else {
328            percent_decode(parsed.username(), "user name")?
329        };
330
331        let mut password = parsed
332            .password()
333            .map(|password| percent_decode(password, "password"))
334            .transpose()?;
335
336        // libpq-style `user=` / `password=` query parameters set the
337        // credentials (overriding the user info; the last one wins). Their
338        // values are percent-decoded like libpq's, so a `+` stays a plus
339        // sign (unlike form decoding, which `query_pairs` uses).
340        for pair in parsed.query().unwrap_or_default().split('&') {
341            let (key, value) = pair.split_once('=').unwrap_or((pair, ""));
342            match percent_decode(key, "query parameter name")?.as_str() {
343                "user" => user = percent_decode(value, "user name")?,
344                "password" => password = Some(percent_decode(value, "password")?),
345                _ => {}
346            }
347        }
348
349        // Parse query parameters
350        let mut ssl_mode = SslMode::Prefer;
351        let mut connect_timeout = Duration::from_secs(30);
352        let mut statement_timeout = None;
353        let mut application_name = None;
354        let mut ssl_root_cert = None;
355        let mut options = Vec::new();
356
357        for (key, value) in parsed.query_pairs() {
358            let key_str: &str = &key;
359            let value_str: &str = &value;
360            match key_str {
361                "sslmode" => {
362                    ssl_mode = match value_str {
363                        "disable" => SslMode::Disable,
364                        "prefer" => SslMode::Prefer,
365                        "require" => SslMode::Require,
366                        "verify-ca" => SslMode::VerifyCa,
367                        "verify-full" => SslMode::VerifyFull,
368                        other => {
369                            return Err(PgError::config(format!("invalid sslmode: {}", other)));
370                        }
371                    };
372                }
373                "connect_timeout" => {
374                    let secs: u64 = value_str
375                        .parse()
376                        .map_err(|_| PgError::config("invalid connect_timeout"))?;
377                    connect_timeout = Duration::from_secs(secs);
378                }
379                "statement_timeout" => {
380                    let ms: u64 = value_str
381                        .parse()
382                        .map_err(|_| PgError::config("invalid statement_timeout"))?;
383                    statement_timeout = Some(Duration::from_millis(ms));
384                }
385                "application_name" => {
386                    application_name = Some(value_str.to_string());
387                }
388                "sslrootcert" => {
389                    ssl_root_cert = Some(PathBuf::from(value_str));
390                }
391                // Credentials, taken above; never a server startup option.
392                "user" | "password" => {}
393                _ => {
394                    options.push((key_str.to_string(), value_str.to_string()));
395                }
396            }
397        }
398
399        Ok(Self {
400            url,
401            host,
402            port,
403            database,
404            user,
405            password,
406            ssl_mode,
407            ssl_root_cert,
408            connect_timeout,
409            statement_timeout,
410            application_name,
411            options,
412        })
413    }
414
415    /// Create a builder for configuration.
416    pub fn builder() -> PgConfigBuilder {
417        PgConfigBuilder::new()
418    }
419
420    /// Convert to tokio-postgres config.
421    ///
422    /// Applies everything `tokio_postgres::Config` can express without a TLS
423    /// connector: host/port/dbname/user/password, `application_name`,
424    /// `connect_timeout`, the driver's [`tokio_postgres::config::SslMode`],
425    /// plus `statement_timeout` and any extra `options` (passed via the
426    /// libpq-style `options` startup parameter as space-separated
427    /// `-c key=value` pairs).
428    ///
429    /// Option pairs whose key is not a valid GUC name, or whose value
430    /// contains whitespace / `\` / `'`, are dropped with a warning:
431    /// percent-decoded values could otherwise smuggle extra `-c`
432    /// assignments into the space-joined string.
433    ///
434    /// `Require`/`VerifyCa`/`VerifyFull` all map to the driver's
435    /// `SslMode::Require`; the pool supplies the rustls connector (with
436    /// webpki certificate verification) that makes the mode satisfiable.
437    pub fn to_pg_config(&self) -> tokio_postgres::Config {
438        let mut config = tokio_postgres::Config::new();
439        config.host(&self.host);
440        config.port(self.port);
441        config.dbname(&self.database);
442        config.user(&self.user);
443
444        if let Some(ref password) = self.password {
445            config.password(password);
446        }
447
448        if let Some(ref app_name) = self.application_name {
449            config.application_name(app_name);
450        }
451
452        config.connect_timeout(self.connect_timeout);
453
454        let driver_ssl_mode = match self.ssl_mode {
455            SslMode::Disable => tokio_postgres::config::SslMode::Disable,
456            SslMode::Prefer => tokio_postgres::config::SslMode::Prefer,
457            SslMode::Require | SslMode::VerifyCa | SslMode::VerifyFull => {
458                tokio_postgres::config::SslMode::Require
459            }
460        };
461        config.ssl_mode(driver_ssl_mode);
462
463        // `statement_timeout` and arbitrary GUC options ride the libpq-style
464        // `options` startup parameter as space-separated `-c key=value` pairs.
465        let mut options = Vec::new();
466        if let Some(timeout) = self.statement_timeout {
467            // A bare integer is interpreted as milliseconds by PostgreSQL.
468            options.push(format!("-c statement_timeout={}", timeout.as_millis()));
469        }
470        for (key, value) in &self.options {
471            if !is_valid_guc_key(key) {
472                tracing::warn!(key = %key, "dropping connection option with invalid GUC name");
473                continue;
474            }
475            if !is_safe_guc_value(value) {
476                // Name the key but never the value, so a malicious
477                // payload doesn't land in the logs.
478                tracing::warn!(
479                    key = %key,
480                    "dropping connection option whose value contains whitespace or quoting characters"
481                );
482                continue;
483            }
484            options.push(format!("-c {}={}", key, value));
485        }
486        if !options.is_empty() {
487            config.options(options.join(" "));
488        }
489
490        config
491    }
492}
493
494/// Builder for PostgreSQL configuration.
495///
496/// `Debug` output redacts the password, also inside the URL.
497#[derive(Default)]
498pub struct PgConfigBuilder {
499    url: Option<String>,
500    host: Option<String>,
501    port: Option<u16>,
502    database: Option<String>,
503    user: Option<String>,
504    password: Option<String>,
505    ssl_mode: Option<SslMode>,
506    ssl_root_cert: Option<PathBuf>,
507    connect_timeout: Option<Duration>,
508    statement_timeout: Option<Duration>,
509    application_name: Option<String>,
510}
511
512impl fmt::Debug for PgConfigBuilder {
513    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
514        f.debug_struct("PgConfigBuilder")
515            .field(
516                "url",
517                &self
518                    .url
519                    .as_deref()
520                    .map(|url| redact_url(url, self.password.as_deref())),
521            )
522            .field("host", &self.host)
523            .field("port", &self.port)
524            .field("database", &self.database)
525            .field("user", &self.user)
526            .field("password", &self.password.as_ref().map(|_| REDACTED))
527            .field("ssl_mode", &self.ssl_mode)
528            .field("ssl_root_cert", &self.ssl_root_cert)
529            .field("connect_timeout", &self.connect_timeout)
530            .field("statement_timeout", &self.statement_timeout)
531            .field("application_name", &self.application_name)
532            .finish()
533    }
534}
535
536impl PgConfigBuilder {
537    /// Create a new builder.
538    pub fn new() -> Self {
539        Self::default()
540    }
541
542    /// Set the database URL (parses all connection parameters).
543    pub fn url(mut self, url: impl Into<String>) -> Self {
544        self.url = Some(url.into());
545        self
546    }
547
548    /// Set the host.
549    pub fn host(mut self, host: impl Into<String>) -> Self {
550        self.host = Some(host.into());
551        self
552    }
553
554    /// Set the port.
555    pub fn port(mut self, port: u16) -> Self {
556        self.port = Some(port);
557        self
558    }
559
560    /// Set the database name.
561    pub fn database(mut self, database: impl Into<String>) -> Self {
562        self.database = Some(database.into());
563        self
564    }
565
566    /// Set the username.
567    pub fn user(mut self, user: impl Into<String>) -> Self {
568        self.user = Some(user.into());
569        self
570    }
571
572    /// Set the password.
573    pub fn password(mut self, password: impl Into<String>) -> Self {
574        self.password = Some(password.into());
575        self
576    }
577
578    /// Set the SSL mode.
579    pub fn ssl_mode(mut self, mode: SslMode) -> Self {
580        self.ssl_mode = Some(mode);
581        self
582    }
583
584    /// Set a PEM bundle of root certificates to verify the server against,
585    /// replacing the Mozilla root store. Equivalent to the `sslrootcert` URL
586    /// parameter.
587    pub fn ssl_root_cert(mut self, path: impl Into<PathBuf>) -> Self {
588        self.ssl_root_cert = Some(path.into());
589        self
590    }
591
592    /// Set the connection timeout.
593    pub fn connect_timeout(mut self, timeout: Duration) -> Self {
594        self.connect_timeout = Some(timeout);
595        self
596    }
597
598    /// Set the statement timeout.
599    pub fn statement_timeout(mut self, timeout: Duration) -> Self {
600        self.statement_timeout = Some(timeout);
601        self
602    }
603
604    /// Set the application name.
605    pub fn application_name(mut self, name: impl Into<String>) -> Self {
606        self.application_name = Some(name.into());
607        self
608    }
609
610    /// Build the configuration.
611    pub fn build(self) -> PgResult<PgConfig> {
612        if let Some(url) = self.url {
613            let mut config = PgConfig::from_url(url)?;
614
615            // Override with explicit values
616            if let Some(host) = self.host {
617                config.host = host;
618            }
619            if let Some(port) = self.port {
620                config.port = port;
621            }
622            if let Some(database) = self.database {
623                config.database = database;
624            }
625            if let Some(user) = self.user {
626                config.user = user;
627            }
628            if let Some(password) = self.password {
629                config.password = Some(password);
630            }
631            if let Some(ssl_root_cert) = self.ssl_root_cert {
632                config.ssl_root_cert = Some(ssl_root_cert);
633            }
634            if let Some(ssl_mode) = self.ssl_mode {
635                config.ssl_mode = ssl_mode;
636            }
637            if let Some(timeout) = self.connect_timeout {
638                config.connect_timeout = timeout;
639            }
640            if let Some(timeout) = self.statement_timeout {
641                config.statement_timeout = Some(timeout);
642            }
643            if let Some(name) = self.application_name {
644                config.application_name = Some(name);
645            }
646
647            Ok(config)
648        } else {
649            // Build from individual components
650            let host = self.host.unwrap_or_else(|| "localhost".to_string());
651            let port = self.port.unwrap_or(5432);
652            let database = self
653                .database
654                .ok_or_else(|| PgError::config("database name is required"))?;
655            let user = self.user.unwrap_or_else(|| "postgres".to_string());
656
657            let url = format!(
658                "postgresql://{}{}@{}:{}/{}",
659                user,
660                self.password
661                    .as_ref()
662                    .map(|p| format!(":{}", p))
663                    .unwrap_or_default(),
664                host,
665                port,
666                database
667            );
668
669            Ok(PgConfig {
670                url,
671                host,
672                port,
673                database,
674                user,
675                password: self.password,
676                ssl_mode: self.ssl_mode.unwrap_or_default(),
677                ssl_root_cert: self.ssl_root_cert,
678                connect_timeout: self.connect_timeout.unwrap_or(Duration::from_secs(30)),
679                statement_timeout: self.statement_timeout,
680                application_name: self.application_name,
681                options: Vec::new(),
682            })
683        }
684    }
685}
686
687#[cfg(test)]
688mod tests {
689    use super::*;
690
691    #[test]
692    fn test_config_from_url() {
693        let config = PgConfig::from_url("postgresql://user:pass@localhost:5432/mydb").unwrap();
694        assert_eq!(config.host, "localhost");
695        assert_eq!(config.port, 5432);
696        assert_eq!(config.database, "mydb");
697        assert_eq!(config.user, "user");
698        assert_eq!(config.password, Some("pass".to_string()));
699    }
700
701    #[test]
702    fn test_config_from_url_with_params() {
703        let config =
704            PgConfig::from_url("postgresql://localhost/mydb?sslmode=require&application_name=prax")
705                .unwrap();
706        assert_eq!(config.ssl_mode, SslMode::Require);
707        assert_eq!(config.application_name, Some("prax".to_string()));
708    }
709
710    #[test]
711    fn test_to_pg_config_applies_statement_timeout_and_options() {
712        let config = PgConfig::from_url(
713            "postgresql://localhost/mydb?statement_timeout=5000&search_path=public",
714        )
715        .unwrap();
716        let pg_config = config.to_pg_config();
717        assert_eq!(
718            pg_config.get_options(),
719            Some("-c statement_timeout=5000 -c search_path=public")
720        );
721    }
722
723    #[test]
724    fn test_to_pg_config_without_timeouts_or_options_sets_none() {
725        let config = PgConfig::from_url("postgresql://localhost/mydb").unwrap();
726        let pg_config = config.to_pg_config();
727        assert_eq!(pg_config.get_options(), None);
728    }
729
730    #[test]
731    fn test_to_pg_config_drops_option_with_smuggled_value() {
732        // Percent-decoded whitespace in a value must not survive into
733        // the space-joined `options` string, where it would smuggle in
734        // extra `-c key=value` assignments.
735        let config =
736            PgConfig::from_url("postgresql://localhost/mydb?x=1%20-c%20search_path%3Devil")
737                .unwrap();
738        let pg_config = config.to_pg_config();
739        assert_eq!(pg_config.get_options(), None);
740    }
741
742    #[test]
743    fn test_to_pg_config_drops_option_with_invalid_key() {
744        let config =
745            PgConfig::from_url("postgresql://localhost/mydb?bad%20key=1&search_path=public")
746                .unwrap();
747        let pg_config = config.to_pg_config();
748        // The invalid key is dropped; the valid option is kept.
749        assert_eq!(pg_config.get_options(), Some("-c search_path=public"));
750    }
751
752    #[test]
753    fn test_to_pg_config_drops_option_with_quoting_chars() {
754        // `\` and `'` are libpq's quoting characters inside `options`.
755        let config = PgConfig::from_url("postgresql://localhost/mydb?a=b%5Cc&d=e%27f").unwrap();
756        let pg_config = config.to_pg_config();
757        assert_eq!(pg_config.get_options(), None);
758    }
759
760    #[test]
761    fn parses_sslrootcert_from_the_url() {
762        let config = PgConfig::from_url(
763            "postgresql://localhost/mydb?sslmode=verify-full&sslrootcert=/etc/ssl/rds.pem",
764        )
765        .unwrap();
766        assert_eq!(
767            config.ssl_root_cert,
768            Some(std::path::PathBuf::from("/etc/ssl/rds.pem"))
769        );
770        // It must not fall through into the generic `options` bag, which would
771        // send it to the server as a GUC.
772        assert!(!config.options.iter().any(|(k, _)| k == "sslrootcert"));
773    }
774
775    #[test]
776    fn sslrootcert_defaults_to_none() {
777        let config = PgConfig::from_url("postgresql://localhost/mydb").unwrap();
778        assert_eq!(config.ssl_root_cert, None);
779    }
780
781    #[test]
782    fn builder_sets_sslrootcert() {
783        let config = PgConfig::builder()
784            .url("postgresql://localhost/mydb")
785            .ssl_root_cert("/etc/ssl/override.pem")
786            .build()
787            .unwrap();
788        assert_eq!(
789            config.ssl_root_cert,
790            Some(std::path::PathBuf::from("/etc/ssl/override.pem"))
791        );
792    }
793
794    #[test]
795    fn test_to_pg_config_maps_sslmode_require() {
796        // TLS is supported via rustls: `require` maps to the driver's
797        // `Require` (never downgraded).
798        let config = PgConfig::from_url("postgresql://localhost/mydb?sslmode=require").unwrap();
799        let pg_config = config.to_pg_config();
800        assert_eq!(
801            pg_config.get_ssl_mode(),
802            tokio_postgres::config::SslMode::Require
803        );
804    }
805
806    #[test]
807    fn test_from_url_parses_verify_modes() {
808        let config = PgConfig::from_url("postgresql://localhost/mydb?sslmode=verify-ca").unwrap();
809        assert_eq!(config.ssl_mode, SslMode::VerifyCa);
810        let pg_config = config.to_pg_config();
811        assert_eq!(
812            pg_config.get_ssl_mode(),
813            tokio_postgres::config::SslMode::Require
814        );
815
816        let config = PgConfig::from_url("postgresql://localhost/mydb?sslmode=verify-full").unwrap();
817        assert_eq!(config.ssl_mode, SslMode::VerifyFull);
818
819        assert!(PgConfig::from_url("postgresql://localhost/mydb?sslmode=bogus").is_err());
820    }
821
822    #[test]
823    fn test_to_pg_config_maps_sslmode_disable() {
824        let config = PgConfig::from_url("postgresql://localhost/mydb?sslmode=disable").unwrap();
825        let pg_config = config.to_pg_config();
826        assert_eq!(
827            pg_config.get_ssl_mode(),
828            tokio_postgres::config::SslMode::Disable
829        );
830    }
831
832    #[test]
833    fn test_config_builder() {
834        let config = PgConfig::builder()
835            .host("localhost")
836            .port(5432)
837            .database("mydb")
838            .user("postgres")
839            .build()
840            .unwrap();
841
842        assert_eq!(config.host, "localhost");
843        assert_eq!(config.database, "mydb");
844    }
845
846    const SENTINEL: &str = "hunter2-sentinel";
847
848    #[test]
849    fn debug_redacts_the_password_and_the_url_password() {
850        let config = PgConfig::from_url(format!(
851            "postgres://prax:{SENTINEL}@db.internal:5432/prax?application_name=app"
852        ))
853        .unwrap();
854        let debug = format!("{config:?}");
855        assert!(!debug.contains(SENTINEL), "{debug}");
856        // Everything else stays visible.
857        for visible in [
858            "db.internal",
859            "5432",
860            "prax",
861            "application_name=app",
862            "REDACTED",
863        ] {
864            assert!(debug.contains(visible), "{visible}: {debug}");
865        }
866        let alternate = format!("{config:#?}");
867        assert!(!alternate.contains(SENTINEL), "{alternate}");
868    }
869
870    #[test]
871    fn debug_redacts_unencoded_builder_passwords() {
872        // The builder writes the password into `url` verbatim, so `@` and
873        // `/` in it do not parse as one URL password.
874        let config = PgConfig::builder()
875            .host("db.internal")
876            .database("prax")
877            .user("prax")
878            .password(format!("{SENTINEL}@x/y"))
879            .build()
880            .unwrap();
881        let debug = format!("{config:?}");
882        assert!(!debug.contains("hunter2"), "{debug}");
883        assert!(!debug.contains("x/y"), "{debug}");
884
885        // A URL that does not parse is redacted up to its last `@`.
886        let mut config = config;
887        config.url = format!("postgres://prax:{SENTINEL}@bad host/prax");
888        let debug = format!("{config:?}");
889        assert!(!debug.contains(SENTINEL), "{debug}");
890    }
891
892    #[test]
893    fn url_redaction_touches_only_the_password() {
894        // A password equal to the user, host or database name (or a single
895        // letter of them) must not be replaced anywhere else.
896        assert_eq!(
897            redact_url(
898                "postgres://postgres:postgres@localhost:5432/postgres",
899                Some("postgres")
900            ),
901            "postgres://postgres:REDACTED@localhost:5432/postgres"
902        );
903        assert_eq!(
904            redact_url(
905                "postgres://app:a@db.internal:5432/app_db?sslmode=disable",
906                Some("a")
907            ),
908            "postgres://app:REDACTED@db.internal:5432/app_db?sslmode=disable"
909        );
910        // Without a hint the parser finds the password; the rest of the URL
911        // is kept as written.
912        assert_eq!(
913            redact_url("postgres://app:a@db.internal/app_db", None),
914            "postgres://app:REDACTED@db.internal/app_db"
915        );
916        let config =
917            PgConfig::from_url("postgres://postgres:postgres@localhost:5432/postgres").unwrap();
918        let debug = format!("{config:?}");
919        assert!(
920            debug.contains("\"postgres://postgres:REDACTED@localhost:5432/postgres\""),
921            "{debug}"
922        );
923        assert!(debug.contains("database: \"postgres\""), "{debug}");
924    }
925
926    #[test]
927    fn url_redaction_without_a_password_hint() {
928        // An unencoded password starting with digits and then `/`, `?` or
929        // `#` parses as a port, so the parser reports no password.
930        for url in [
931            format!("postgres://u:8/{SENTINEL}@host/db"),
932            format!("postgres://u:123#{SENTINEL}@host/db"),
933            format!("postgres://u:123?{SENTINEL}@host/db"),
934        ] {
935            let redacted = redact_url(&url, None);
936            assert!(!redacted.contains(SENTINEL), "{url} -> {redacted}");
937            assert_eq!(redacted, "postgres://REDACTED@host/db", "{url}");
938        }
939        // libpq-style `?password=` (key case and encoding ignored).
940        for url in [
941            format!("postgres://u@host/db?password={SENTINEL}&sslmode=disable"),
942            format!("postgres://u@host/db?sslmode=disable&PASSWORD={SENTINEL}#frag"),
943            format!("postgres://u@host/db?pass%77ord={SENTINEL}"),
944        ] {
945            let redacted = redact_url(&url, None);
946            assert!(!redacted.contains(SENTINEL), "{url} -> {redacted}");
947            assert!(redacted.starts_with("postgres://u@host/db?"), "{redacted}");
948        }
949        assert_eq!(
950            redact_url(
951                &format!("postgres://u@host/db?password={SENTINEL}&sslmode=disable"),
952                None
953            ),
954            "postgres://u@host/db?password=REDACTED&sslmode=disable"
955        );
956        // A user name without a password stays.
957        assert_eq!(
958            redact_url("postgres://u@host/db", None),
959            "postgres://u@host/db"
960        );
961    }
962
963    #[test]
964    fn debug_redacts_password_options_and_query() {
965        let url = format!("postgres://u@db.internal/prax?password={SENTINEL}&search_path=app");
966        let config = PgConfig::from_url(&url).unwrap();
967        let debug = format!("{config:?}");
968        assert!(!debug.contains(SENTINEL), "{debug}");
969        assert!(debug.contains("search_path"), "{debug}");
970
971        // Not the libpq keyword (case differs), so it stays an option, which
972        // Debug redacts all the same.
973        let config =
974            PgConfig::from_url(format!("postgres://u@db.internal/prax?PASSWORD={SENTINEL}"))
975                .unwrap();
976        assert!(config.options.iter().any(|(k, _)| k == "PASSWORD"));
977        let debug = format!("{config:?}");
978        assert!(!debug.contains(SENTINEL), "{debug}");
979
980        let builder = crate::pool::PgPoolBuilder::new().url(&url);
981        let debug = format!("{builder:?}");
982        assert!(!debug.contains(SENTINEL), "{debug}");
983
984        let builder = crate::pool::PgPoolBuilder::new()
985            .url(format!("postgres://u:8/{SENTINEL}@db.internal/prax"));
986        let debug = format!("{builder:?}");
987        assert!(!debug.contains(SENTINEL), "{debug}");
988    }
989
990    #[test]
991    fn debug_keeps_urls_without_a_password() {
992        let config = PgConfig::from_url("postgres://prax@db.internal/prax").unwrap();
993        let debug = format!("{config:?}");
994        assert!(
995            debug.contains("postgres://prax@db.internal/prax"),
996            "{debug}"
997        );
998        assert!(debug.contains("password: None"), "{debug}");
999    }
1000
1001    #[test]
1002    fn config_builder_debug_redacts_secrets() {
1003        let builder = PgConfig::builder()
1004            .url(format!("postgres://prax:{SENTINEL}@db.internal/prax"))
1005            .password(SENTINEL);
1006        let debug = format!("{builder:?}");
1007        assert!(!debug.contains(SENTINEL), "{debug}");
1008        assert!(debug.contains("db.internal"), "{debug}");
1009    }
1010
1011    #[test]
1012    fn from_url_rejects_passwords_with_unencoded_reserved_characters() {
1013        for url in [
1014            "postgres://u:8/Hx@host/db",
1015            "postgres://u:123#456@host/db",
1016            "postgres://u:123?x@host/db",
1017            "postgres://u:a@b/c@host/db",
1018            "postgres://u:8/x:y@host:5432/db?sslmode=disable",
1019        ] {
1020            match PgConfig::from_url(url) {
1021                Err(PgError::Config(message)) => {
1022                    assert!(message.contains("percent-encode"), "{url}: {message}");
1023                    // The error never repeats the URL (or the password).
1024                    assert!(
1025                        !message.contains("Hx") && !message.contains("456"),
1026                        "{message}"
1027                    );
1028                }
1029                other => panic!("{url}: expected a config error, got {other:?}"),
1030            }
1031        }
1032    }
1033
1034    #[test]
1035    fn from_url_decodes_percent_encoded_credentials_and_database() {
1036        let config = PgConfig::from_url("postgres://u:8%2FHx@host/db").unwrap();
1037        assert_eq!(
1038            (
1039                config.user.as_str(),
1040                config.password.as_deref(),
1041                config.host.as_str()
1042            ),
1043            ("u", Some("8/Hx"), "host")
1044        );
1045        assert_eq!((config.port, config.database.as_str()), (5432, "db"));
1046
1047        let config = PgConfig::from_url("postgres://u:123%23456@host:6543/db").unwrap();
1048        assert_eq!(config.password.as_deref(), Some("123#456"));
1049        assert_eq!(config.port, 6543);
1050
1051        let config =
1052            PgConfig::from_url("postgres://app%40corp:p%40ss%3Aw%2B@host/my%40db").unwrap();
1053        assert_eq!(config.user, "app@corp");
1054        assert_eq!(config.password.as_deref(), Some("p@ss:w+"));
1055        assert_eq!(config.database, "my@db");
1056        let pg_config = config.to_pg_config();
1057        assert_eq!(pg_config.get_password(), Some(&b"p@ss:w+"[..]));
1058        assert_eq!(pg_config.get_user(), Some("app@corp"));
1059
1060        // An `@` inside a query value is not mistaken for user info.
1061        let config =
1062            PgConfig::from_url("postgres://u:pw@host/db?application_name=me@work").unwrap();
1063        assert_eq!(config.application_name.as_deref(), Some("me@work"));
1064        assert_eq!(config.password.as_deref(), Some("pw"));
1065    }
1066
1067    #[test]
1068    fn from_url_takes_credentials_from_query_parameters() {
1069        let config = PgConfig::from_url(format!(
1070            "postgres://db.internal/prax?user=alice&password={SENTINEL}&sslmode=disable"
1071        ))
1072        .unwrap();
1073        assert_eq!(config.user, "alice");
1074        assert_eq!(config.password.as_deref(), Some(SENTINEL));
1075        assert_eq!(config.ssl_mode, SslMode::Disable);
1076        // Credentials, not server startup options.
1077        assert!(config.options.is_empty(), "{:?}", config.options);
1078        let pg_config = config.to_pg_config();
1079        assert_eq!(pg_config.get_user(), Some("alice"));
1080        assert_eq!(pg_config.get_password(), Some(SENTINEL.as_bytes()));
1081        assert_eq!(pg_config.get_options(), None);
1082        // Debug still redacts the password (field and URL).
1083        let debug = format!("{config:?}");
1084        assert!(!debug.contains(SENTINEL), "{debug}");
1085        assert!(debug.contains("alice"), "{debug}");
1086
1087        // They override the user info; values are percent-decoded like
1088        // libpq, so `+` stays a plus sign.
1089        let config =
1090            PgConfig::from_url("postgres://bob:old@host/db?password=n%26w+1&user=carol").unwrap();
1091        assert_eq!(config.user, "carol");
1092        assert_eq!(config.password.as_deref(), Some("n&w+1"));
1093        assert!(config.options.is_empty(), "{:?}", config.options);
1094    }
1095
1096    #[test]
1097    fn test_config_invalid_scheme() {
1098        let result = PgConfig::from_url("mysql://localhost/db");
1099        assert!(result.is_err());
1100    }
1101}