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    /// Whether TCP keepalives are enabled on the client socket (default:
56    /// `true`, the tokio-postgres default). From the libpq-compatible
57    /// `keepalives` URL parameter (`0` disables, any other integer enables).
58    pub keepalives: bool,
59    /// Idle time before the first TCP keepalive probe is sent. `None` keeps
60    /// the driver default (2 hours). From the `keepalives_idle` URL parameter
61    /// (seconds; `0` keeps the default, as in libpq).
62    ///
63    /// Together with [`keepalives_interval`](Self::keepalives_interval) and
64    /// [`keepalives_retries`](Self::keepalives_retries) this bounds how long
65    /// an *idle* connection whose peer vanished (failover, network
66    /// black-hole) goes undetected.
67    pub keepalives_idle: Option<Duration>,
68    /// Interval between unanswered TCP keepalive probes. `None` keeps the
69    /// OS default. From the `keepalives_interval` URL parameter (seconds;
70    /// `0` keeps the default).
71    pub keepalives_interval: Option<Duration>,
72    /// Number of unanswered TCP keepalive probes before the connection is
73    /// dropped. `None` keeps the OS default. From the libpq
74    /// `keepalives_count` URL parameter (also accepted as tokio-postgres's
75    /// `keepalives_retries`; `0` keeps the default).
76    pub keepalives_retries: Option<u32>,
77    /// `TCP_USER_TIMEOUT`: how long transmitted data may stay unacknowledged
78    /// before the OS closes the connection (Linux only; ignored elsewhere).
79    /// `None` keeps the OS default (~15 minutes of retransmissions on
80    /// Linux). From the `tcp_user_timeout` URL parameter (milliseconds;
81    /// `0` keeps the default, as in libpq).
82    ///
83    /// This bounds how long a query sent on a connection whose peer vanished
84    /// hangs, which keepalives alone do not.
85    pub tcp_user_timeout: Option<Duration>,
86    /// Additional options.
87    pub options: Vec<(String, String)>,
88}
89
90impl fmt::Debug for PgConfig {
91    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
92        f.debug_struct("PgConfig")
93            .field("url", &redact_url(&self.url, self.password.as_deref()))
94            .field("host", &self.host)
95            .field("port", &self.port)
96            .field("database", &self.database)
97            .field("user", &self.user)
98            .field("password", &self.password.as_ref().map(|_| REDACTED))
99            .field("ssl_mode", &self.ssl_mode)
100            .field("ssl_root_cert", &self.ssl_root_cert)
101            .field("connect_timeout", &self.connect_timeout)
102            .field("statement_timeout", &self.statement_timeout)
103            .field("application_name", &self.application_name)
104            .field("keepalives", &self.keepalives)
105            .field("keepalives_idle", &self.keepalives_idle)
106            .field("keepalives_interval", &self.keepalives_interval)
107            .field("keepalives_retries", &self.keepalives_retries)
108            .field("tcp_user_timeout", &self.tcp_user_timeout)
109            .field(
110                "options",
111                &self
112                    .options
113                    .iter()
114                    .map(|(key, value)| {
115                        let value = if is_password_key(key) {
116                            REDACTED
117                        } else {
118                            value
119                        };
120                        (key.as_str(), value)
121                    })
122                    .collect::<Vec<_>>(),
123            )
124            .finish()
125    }
126}
127
128/// Shown in place of a password in `Debug` output.
129const REDACTED: &str = "REDACTED";
130
131/// `url` with its password replaced by [`REDACTED`], for `Debug` output.
132/// Only the password inside the user info (`user:password@`) is touched;
133/// the rest of the URL is kept exactly as written.
134///
135/// `password` is the config's password, when known. It is matched right
136/// after `user:` first, because the config builder writes it into the URL
137/// without percent-encoding, where an `@` or `/` in it would not parse as
138/// one URL password. Otherwise the parser locates the password. When it
139/// finds none although an `@` follows the scheme and no user name parsed
140/// (an unencoded password starting with digits and then `/`, `?` or `#`
141/// parses as a port), or the URL does not parse at all, everything between
142/// the scheme and its last `@` is redacted. libpq-style `password` query
143/// parameters are redacted too.
144pub(crate) fn redact_url(url: &str, password: Option<&str>) -> String {
145    let Some(start) = url.find("://").map(|i| i + 3) else {
146        return url.to_owned();
147    };
148    let redacted = redact_userinfo(url, start, password);
149    redact_query_passwords(&redacted, start)
150}
151
152/// The user-info part of [`redact_url`].
153fn redact_userinfo(url: &str, start: usize, password: Option<&str>) -> String {
154    if let Some(password) = password.filter(|p| !p.is_empty())
155        && let Some(redacted) = splice_password(url, start, password)
156    {
157        return redacted;
158    }
159    match url::Url::parse(url) {
160        Ok(parsed) => match parsed.password() {
161            Some(password) => splice_password(url, start, password)
162                .unwrap_or_else(|| redact_to_last_at(url, start)),
163            None if parsed.username().is_empty() && url[start..].contains('@') => {
164                redact_to_last_at(url, start)
165            }
166            None => url.to_owned(),
167        },
168        Err(_) => redact_to_last_at(url, start),
169    }
170}
171
172/// `url` with the value of every `password` query parameter (any case,
173/// percent-decoded key) replaced. The query is searched from `start`.
174fn redact_query_passwords(url: &str, start: usize) -> String {
175    let Some(query_start) = url[start..].find('?').map(|i| start + i + 1) else {
176        return url.to_owned();
177    };
178    let query_end = url[query_start..]
179        .find('#')
180        .map_or(url.len(), |i| query_start + i);
181    let query = url[query_start..query_end]
182        .split('&')
183        .map(|pair| {
184            let key = pair.split_once('=').map_or(pair, |(key, _)| key);
185            if is_password_key(key) {
186                format!("{key}={REDACTED}")
187            } else {
188                pair.to_owned()
189            }
190        })
191        .collect::<Vec<_>>()
192        .join("&");
193    format!("{}{query}{}", &url[..query_start], &url[query_end..])
194}
195
196/// Whether a (possibly percent-encoded) query or option key names a
197/// password.
198fn is_password_key(key: &str) -> bool {
199    url::form_urlencoded::parse(key.as_bytes())
200        .next()
201        .is_some_and(|(key, _)| key.eq_ignore_ascii_case("password"))
202}
203
204/// `url` with `password` replaced, when it follows the first `:` of the
205/// user info (which starts at `start`) and is followed by `@`.
206fn splice_password(url: &str, start: usize, password: &str) -> Option<String> {
207    let from = start + url[start..].find(':')? + 1;
208    let after = url[from..].strip_prefix(password)?;
209    after
210        .starts_with('@')
211        .then(|| format!("{}{REDACTED}{after}", &url[..from]))
212}
213
214/// `url` with everything from `start` to its last `@` replaced.
215fn redact_to_last_at(url: &str, start: usize) -> String {
216    match url[start..].rfind('@') {
217        Some(at) => format!("{}{REDACTED}{}", &url[..start], &url[start + at..]),
218        None => url.to_owned(),
219    }
220}
221
222/// SSL mode for connections.
223///
224/// With the default `tls` cargo feature, `Require`/`VerifyCa`/`VerifyFull`
225/// establish rustls-encrypted connections verified against the Mozilla root
226/// store. `Prefer` uses TLS when the server offers it and falls back to
227/// plaintext only when the server declines TLS (note: stricter than libpq —
228/// a certificate verification failure fails the connection rather than
229/// retrying plaintext). Without the `tls` feature, TLS-requiring modes fail
230/// at pool build time.
231#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
232pub enum SslMode {
233    /// Disable SSL.
234    Disable,
235    /// Prefer SSL but allow non-SSL when the server declines TLS.
236    #[default]
237    Prefer,
238    /// Require SSL. Certificates are verified (chain + hostname) — stricter
239    /// than libpq's `require`, which skips verification.
240    Require,
241    /// Require SSL and verify the certificate chain. Currently also verifies
242    /// the hostname (i.e. behaves as `VerifyFull`; libpq's hostname-less
243    /// `verify-ca` is not yet distinguished).
244    VerifyCa,
245    /// Require SSL and verify the certificate chain and hostname.
246    VerifyFull,
247}
248
249/// Validate a GUC name destined for the `options` startup parameter.
250/// Postgres GUC names match `^[A-Za-z_][A-Za-z0-9_.]*$` (the `.`
251/// separates extension namespaces, e.g. `pg_trgm.similarity_threshold`).
252fn is_valid_guc_key(key: &str) -> bool {
253    let mut chars = key.chars();
254    matches!(chars.next(), Some(c) if c.is_ascii_alphabetic() || c == '_')
255        && chars.all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '.')
256}
257
258/// Reject values that could break out of the space-joined `options`
259/// startup parameter: whitespace terminates the assignment and starts a
260/// new token, and `\` / `'` are libpq's quoting characters in that
261/// string. A percent-decoded URL value could otherwise smuggle extra
262/// `-c key=value` assignments (e.g. `?x=1%20-c%20search_path%3Devil`).
263fn is_safe_guc_value(value: &str) -> bool {
264    !value
265        .chars()
266        .any(|c| c.is_whitespace() || c == '\\' || c == '\'')
267}
268
269/// Parse a libpq-style non-negative integer URL parameter, naming `key` (but
270/// not the value) in the error.
271fn parse_client_param<T: std::str::FromStr>(key: &str, value: &str) -> PgResult<T> {
272    value
273        .trim()
274        .parse()
275        .map_err(|_| PgError::config(format!("invalid {key}: expected a non-negative integer")))
276}
277
278/// `Some(duration)` unless it is zero, which (as in libpq) means "keep the
279/// system default".
280fn non_zero(duration: Duration) -> Option<Duration> {
281    (!duration.is_zero()).then_some(duration)
282}
283
284/// How to fix a URL whose password breaks its structure.
285const PERCENT_ENCODE_HINT: &str = "percent-encode reserved characters in the password \
286     (`@` as %40, `/` as %2F, `?` as %3F, `#` as %23, `:` as %3A)";
287
288/// Reject a URL in which an unencoded `/`, `?` or `#` in the password ended
289/// the authority early, so the rest of the password and the real host
290/// landed in the path, query or fragment (`postgres://u:8/x@host/db` parses
291/// as host `u`, port 8 and database `x@host/db`). The telltale is an `@`
292/// after the authority: in the path, the fragment, or a query key (a query
293/// *value* such as `application_name=me@work` is fine). An `@` in a
294/// database name must be written `%40`. The error never repeats the URL.
295fn reject_unencoded_userinfo(parsed: &url::Url) -> PgResult<()> {
296    let in_query_key = parsed.query().is_some_and(|query| {
297        query.split('&').any(|pair| {
298            pair.split_once('=')
299                .map_or(pair, |(key, _)| key)
300                .contains('@')
301        })
302    });
303    if parsed.path().contains('@')
304        || parsed
305            .fragment()
306            .is_some_and(|fragment| fragment.contains('@'))
307        || in_query_key
308    {
309        return Err(PgError::config(format!(
310            "invalid database URL: an `@` follows the host, so the password \
311             seems to contain unencoded reserved characters; {PERCENT_ENCODE_HINT}"
312        )));
313    }
314    Ok(())
315}
316
317/// Percent-decode a URL component (`what` names it in the error), as libpq
318/// does for the user, password and database name.
319fn percent_decode(component: &str, what: &str) -> PgResult<String> {
320    percent_encoding::percent_decode_str(component)
321        .decode_utf8()
322        .map(|decoded| decoded.into_owned())
323        .map_err(|_| {
324            PgError::config(format!(
325                "invalid database URL: the {what} is not valid UTF-8 once percent-decoded"
326            ))
327        })
328}
329
330impl PgConfig {
331    /// Create a new configuration from a database URL.
332    ///
333    /// The user name, password and database name are percent-decoded, as
334    /// libpq does: write reserved characters in them (`@`, `/`, `?`, `#`,
335    /// `:`) percent-encoded. A URL whose password evidently contains them
336    /// unencoded (an `@` after the host) is rejected with a configuration
337    /// error rather than parsed into the wrong host, port or database.
338    ///
339    /// As with libpq, `user` and `password` query parameters set the
340    /// credentials (overriding the user info). The libpq client-side TCP
341    /// parameters `keepalives`, `keepalives_idle` (seconds),
342    /// `keepalives_interval` (seconds), `keepalives_count` (alias
343    /// `keepalives_retries`) and `tcp_user_timeout` (milliseconds) configure
344    /// the client socket; an invalid value is a configuration error. Other
345    /// unrecognised parameters become [`options`](Self::options) (server
346    /// GUCs).
347    pub fn from_url(url: impl Into<String>) -> PgResult<Self> {
348        let url = url.into();
349        let parsed = url::Url::parse(&url).map_err(|e| {
350            // An unencoded `/`, `?` or `#` in the password ends the authority
351            // early, which often leaves an invalid port behind.
352            let hint = if url.contains('@') {
353                format!("; {PERCENT_ENCODE_HINT}")
354            } else {
355                String::new()
356            };
357            PgError::config(format!("invalid database URL: {e}{hint}"))
358        })?;
359        reject_unencoded_userinfo(&parsed)?;
360
361        if parsed.scheme() != "postgresql" && parsed.scheme() != "postgres" {
362            return Err(PgError::config(format!(
363                "invalid scheme: expected 'postgresql' or 'postgres', got '{}'",
364                parsed.scheme()
365            )));
366        }
367
368        let host = parsed
369            .host_str()
370            .ok_or_else(|| PgError::config("missing host in URL"))?
371            .to_string();
372
373        let port = parsed.port().unwrap_or(5432);
374
375        let database = percent_decode(parsed.path().trim_start_matches('/'), "database name")?;
376
377        if database.is_empty() {
378            return Err(PgError::config("missing database name in URL"));
379        }
380
381        let mut user = if parsed.username().is_empty() {
382            "postgres".to_string()
383        } else {
384            percent_decode(parsed.username(), "user name")?
385        };
386
387        let mut password = parsed
388            .password()
389            .map(|password| percent_decode(password, "password"))
390            .transpose()?;
391
392        // libpq-style `user=` / `password=` query parameters set the
393        // credentials (overriding the user info; the last one wins). Their
394        // values are percent-decoded like libpq's, so a `+` stays a plus
395        // sign (unlike form decoding, which `query_pairs` uses).
396        for pair in parsed.query().unwrap_or_default().split('&') {
397            let (key, value) = pair.split_once('=').unwrap_or((pair, ""));
398            match percent_decode(key, "query parameter name")?.as_str() {
399                "user" => user = percent_decode(value, "user name")?,
400                "password" => password = Some(percent_decode(value, "password")?),
401                _ => {}
402            }
403        }
404
405        // Parse query parameters
406        let mut ssl_mode = SslMode::Prefer;
407        let mut connect_timeout = Duration::from_secs(30);
408        let mut statement_timeout = None;
409        let mut application_name = None;
410        let mut ssl_root_cert = None;
411        let mut keepalives = true;
412        let mut keepalives_idle = None;
413        let mut keepalives_interval = None;
414        let mut keepalives_retries = None;
415        let mut tcp_user_timeout = None;
416        let mut options = Vec::new();
417
418        for (key, value) in parsed.query_pairs() {
419            let key_str: &str = &key;
420            let value_str: &str = &value;
421            match key_str {
422                "sslmode" => {
423                    ssl_mode = match value_str {
424                        "disable" => SslMode::Disable,
425                        "prefer" => SslMode::Prefer,
426                        "require" => SslMode::Require,
427                        "verify-ca" => SslMode::VerifyCa,
428                        "verify-full" => SslMode::VerifyFull,
429                        other => {
430                            return Err(PgError::config(format!("invalid sslmode: {}", other)));
431                        }
432                    };
433                }
434                "connect_timeout" => {
435                    let secs: u64 = value_str
436                        .parse()
437                        .map_err(|_| PgError::config("invalid connect_timeout"))?;
438                    connect_timeout = Duration::from_secs(secs);
439                }
440                "statement_timeout" => {
441                    let ms: u64 = value_str
442                        .parse()
443                        .map_err(|_| PgError::config("invalid statement_timeout"))?;
444                    statement_timeout = Some(Duration::from_millis(ms));
445                }
446                "application_name" => {
447                    application_name = Some(value_str.to_string());
448                }
449                "sslrootcert" => {
450                    ssl_root_cert = Some(PathBuf::from(value_str));
451                }
452                // Client-side TCP liveness (libpq names and units). These
453                // configure the socket, so they must never reach the server
454                // as GUCs: an unknown GUC fails the startup, and the server's
455                // own `tcp_user_timeout` is not the client's.
456                "keepalives" => {
457                    keepalives = parse_client_param::<i64>(key_str, value_str)? != 0;
458                }
459                "keepalives_idle" => {
460                    let secs: u64 = parse_client_param(key_str, value_str)?;
461                    keepalives_idle = non_zero(Duration::from_secs(secs));
462                }
463                "keepalives_interval" => {
464                    let secs: u64 = parse_client_param(key_str, value_str)?;
465                    keepalives_interval = non_zero(Duration::from_secs(secs));
466                }
467                "keepalives_count" | "keepalives_retries" => {
468                    let count: u32 = parse_client_param(key_str, value_str)?;
469                    keepalives_retries = (count != 0).then_some(count);
470                }
471                "tcp_user_timeout" => {
472                    let ms: u64 = parse_client_param(key_str, value_str)?;
473                    tcp_user_timeout = non_zero(Duration::from_millis(ms));
474                }
475                // Credentials, taken above; never a server startup option.
476                "user" | "password" => {}
477                _ => {
478                    options.push((key_str.to_string(), value_str.to_string()));
479                }
480            }
481        }
482
483        Ok(Self {
484            url,
485            host,
486            port,
487            database,
488            user,
489            password,
490            ssl_mode,
491            ssl_root_cert,
492            connect_timeout,
493            statement_timeout,
494            application_name,
495            keepalives,
496            keepalives_idle,
497            keepalives_interval,
498            keepalives_retries,
499            tcp_user_timeout,
500            options,
501        })
502    }
503
504    /// Create a builder for configuration.
505    pub fn builder() -> PgConfigBuilder {
506        PgConfigBuilder::new()
507    }
508
509    /// Convert to tokio-postgres config.
510    ///
511    /// Applies everything `tokio_postgres::Config` can express without a TLS
512    /// connector: host/port/dbname/user/password, `application_name`,
513    /// `connect_timeout`, the driver's [`tokio_postgres::config::SslMode`],
514    /// the client TCP settings (`keepalives`, `keepalives_idle`,
515    /// `keepalives_interval`, `keepalives_retries`, `tcp_user_timeout`;
516    /// unset or zero values keep the driver/OS defaults), plus `statement_timeout` and any extra `options` (passed via the
517    /// libpq-style `options` startup parameter as space-separated
518    /// `-c key=value` pairs).
519    ///
520    /// Option pairs whose key is not a valid GUC name, or whose value
521    /// contains whitespace / `\` / `'`, are dropped with a warning:
522    /// percent-decoded values could otherwise smuggle extra `-c`
523    /// assignments into the space-joined string.
524    ///
525    /// `Require`/`VerifyCa`/`VerifyFull` all map to the driver's
526    /// `SslMode::Require`; the pool supplies the rustls connector (with
527    /// webpki certificate verification) that makes the mode satisfiable.
528    pub fn to_pg_config(&self) -> tokio_postgres::Config {
529        let mut config = tokio_postgres::Config::new();
530        config.host(&self.host);
531        config.port(self.port);
532        config.dbname(&self.database);
533        config.user(&self.user);
534
535        if let Some(ref password) = self.password {
536            config.password(password);
537        }
538
539        if let Some(ref app_name) = self.application_name {
540            config.application_name(app_name);
541        }
542
543        config.connect_timeout(self.connect_timeout);
544
545        let driver_ssl_mode = match self.ssl_mode {
546            SslMode::Disable => tokio_postgres::config::SslMode::Disable,
547            SslMode::Prefer => tokio_postgres::config::SslMode::Prefer,
548            SslMode::Require | SslMode::VerifyCa | SslMode::VerifyFull => {
549                tokio_postgres::config::SslMode::Require
550            }
551        };
552        config.ssl_mode(driver_ssl_mode);
553
554        // Client TCP liveness. Unset (or zero) values keep the driver's
555        // defaults: keepalives on, 2h idle, OS interval/count, no
556        // TCP_USER_TIMEOUT.
557        config.keepalives(self.keepalives);
558        if let Some(idle) = self.keepalives_idle.and_then(non_zero) {
559            config.keepalives_idle(idle);
560        }
561        if let Some(interval) = self.keepalives_interval.and_then(non_zero) {
562            config.keepalives_interval(interval);
563        }
564        if let Some(retries) = self.keepalives_retries.filter(|&n| n != 0) {
565            config.keepalives_retries(retries);
566        }
567        if let Some(timeout) = self.tcp_user_timeout.and_then(non_zero) {
568            config.tcp_user_timeout(timeout);
569        }
570
571        // `statement_timeout` and arbitrary GUC options ride the libpq-style
572        // `options` startup parameter as space-separated `-c key=value` pairs.
573        let mut options = Vec::new();
574        if let Some(timeout) = self.statement_timeout {
575            // A bare integer is interpreted as milliseconds by PostgreSQL.
576            options.push(format!("-c statement_timeout={}", timeout.as_millis()));
577        }
578        for (key, value) in &self.options {
579            if !is_valid_guc_key(key) {
580                tracing::warn!(key = %key, "dropping connection option with invalid GUC name");
581                continue;
582            }
583            if !is_safe_guc_value(value) {
584                // Name the key but never the value, so a malicious
585                // payload doesn't land in the logs.
586                tracing::warn!(
587                    key = %key,
588                    "dropping connection option whose value contains whitespace or quoting characters"
589                );
590                continue;
591            }
592            options.push(format!("-c {}={}", key, value));
593        }
594        if !options.is_empty() {
595            config.options(options.join(" "));
596        }
597
598        config
599    }
600}
601
602/// Builder for PostgreSQL configuration.
603///
604/// `Debug` output redacts the password, also inside the URL.
605#[derive(Default)]
606pub struct PgConfigBuilder {
607    url: Option<String>,
608    host: Option<String>,
609    port: Option<u16>,
610    database: Option<String>,
611    user: Option<String>,
612    password: Option<String>,
613    ssl_mode: Option<SslMode>,
614    ssl_root_cert: Option<PathBuf>,
615    connect_timeout: Option<Duration>,
616    statement_timeout: Option<Duration>,
617    application_name: Option<String>,
618    keepalives: Option<bool>,
619    keepalives_idle: Option<Duration>,
620    keepalives_interval: Option<Duration>,
621    keepalives_retries: Option<u32>,
622    tcp_user_timeout: Option<Duration>,
623}
624
625impl fmt::Debug for PgConfigBuilder {
626    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
627        f.debug_struct("PgConfigBuilder")
628            .field(
629                "url",
630                &self
631                    .url
632                    .as_deref()
633                    .map(|url| redact_url(url, self.password.as_deref())),
634            )
635            .field("host", &self.host)
636            .field("port", &self.port)
637            .field("database", &self.database)
638            .field("user", &self.user)
639            .field("password", &self.password.as_ref().map(|_| REDACTED))
640            .field("ssl_mode", &self.ssl_mode)
641            .field("ssl_root_cert", &self.ssl_root_cert)
642            .field("connect_timeout", &self.connect_timeout)
643            .field("statement_timeout", &self.statement_timeout)
644            .field("application_name", &self.application_name)
645            .field("keepalives", &self.keepalives)
646            .field("keepalives_idle", &self.keepalives_idle)
647            .field("keepalives_interval", &self.keepalives_interval)
648            .field("keepalives_retries", &self.keepalives_retries)
649            .field("tcp_user_timeout", &self.tcp_user_timeout)
650            .finish()
651    }
652}
653
654impl PgConfigBuilder {
655    /// Create a new builder.
656    pub fn new() -> Self {
657        Self::default()
658    }
659
660    /// Set the database URL (parses all connection parameters).
661    pub fn url(mut self, url: impl Into<String>) -> Self {
662        self.url = Some(url.into());
663        self
664    }
665
666    /// Set the host.
667    pub fn host(mut self, host: impl Into<String>) -> Self {
668        self.host = Some(host.into());
669        self
670    }
671
672    /// Set the port.
673    pub fn port(mut self, port: u16) -> Self {
674        self.port = Some(port);
675        self
676    }
677
678    /// Set the database name.
679    pub fn database(mut self, database: impl Into<String>) -> Self {
680        self.database = Some(database.into());
681        self
682    }
683
684    /// Set the username.
685    pub fn user(mut self, user: impl Into<String>) -> Self {
686        self.user = Some(user.into());
687        self
688    }
689
690    /// Set the password.
691    pub fn password(mut self, password: impl Into<String>) -> Self {
692        self.password = Some(password.into());
693        self
694    }
695
696    /// Set the SSL mode.
697    pub fn ssl_mode(mut self, mode: SslMode) -> Self {
698        self.ssl_mode = Some(mode);
699        self
700    }
701
702    /// Set a PEM bundle of root certificates to verify the server against,
703    /// replacing the Mozilla root store. Equivalent to the `sslrootcert` URL
704    /// parameter.
705    pub fn ssl_root_cert(mut self, path: impl Into<PathBuf>) -> Self {
706        self.ssl_root_cert = Some(path.into());
707        self
708    }
709
710    /// Set the connection timeout.
711    pub fn connect_timeout(mut self, timeout: Duration) -> Self {
712        self.connect_timeout = Some(timeout);
713        self
714    }
715
716    /// Set the statement timeout.
717    pub fn statement_timeout(mut self, timeout: Duration) -> Self {
718        self.statement_timeout = Some(timeout);
719        self
720    }
721
722    /// Set the application name.
723    pub fn application_name(mut self, name: impl Into<String>) -> Self {
724        self.application_name = Some(name.into());
725        self
726    }
727
728    /// Enable or disable TCP keepalives (see [`PgConfig::keepalives`]).
729    pub fn keepalives(mut self, enabled: bool) -> Self {
730        self.keepalives = Some(enabled);
731        self
732    }
733
734    /// Set the idle time before the first TCP keepalive probe (see
735    /// [`PgConfig::keepalives_idle`]). Zero keeps the driver default.
736    pub fn keepalives_idle(mut self, idle: Duration) -> Self {
737        self.keepalives_idle = Some(idle);
738        self
739    }
740
741    /// Set the interval between TCP keepalive probes (see
742    /// [`PgConfig::keepalives_interval`]). Zero keeps the OS default.
743    pub fn keepalives_interval(mut self, interval: Duration) -> Self {
744        self.keepalives_interval = Some(interval);
745        self
746    }
747
748    /// Set the number of unanswered TCP keepalive probes before the
749    /// connection is dropped (see [`PgConfig::keepalives_retries`]). Zero
750    /// keeps the OS default.
751    pub fn keepalives_retries(mut self, retries: u32) -> Self {
752        self.keepalives_retries = Some(retries);
753        self
754    }
755
756    /// Set `TCP_USER_TIMEOUT` (see [`PgConfig::tcp_user_timeout`]). Zero
757    /// keeps the OS default.
758    pub fn tcp_user_timeout(mut self, timeout: Duration) -> Self {
759        self.tcp_user_timeout = Some(timeout);
760        self
761    }
762
763    /// Build the configuration.
764    pub fn build(self) -> PgResult<PgConfig> {
765        if let Some(url) = self.url {
766            let mut config = PgConfig::from_url(url)?;
767
768            // Override with explicit values
769            if let Some(host) = self.host {
770                config.host = host;
771            }
772            if let Some(port) = self.port {
773                config.port = port;
774            }
775            if let Some(database) = self.database {
776                config.database = database;
777            }
778            if let Some(user) = self.user {
779                config.user = user;
780            }
781            if let Some(password) = self.password {
782                config.password = Some(password);
783            }
784            if let Some(ssl_root_cert) = self.ssl_root_cert {
785                config.ssl_root_cert = Some(ssl_root_cert);
786            }
787            if let Some(ssl_mode) = self.ssl_mode {
788                config.ssl_mode = ssl_mode;
789            }
790            if let Some(timeout) = self.connect_timeout {
791                config.connect_timeout = timeout;
792            }
793            if let Some(timeout) = self.statement_timeout {
794                config.statement_timeout = Some(timeout);
795            }
796            if let Some(name) = self.application_name {
797                config.application_name = Some(name);
798            }
799            if let Some(keepalives) = self.keepalives {
800                config.keepalives = keepalives;
801            }
802            if let Some(idle) = self.keepalives_idle {
803                config.keepalives_idle = Some(idle);
804            }
805            if let Some(interval) = self.keepalives_interval {
806                config.keepalives_interval = Some(interval);
807            }
808            if let Some(retries) = self.keepalives_retries {
809                config.keepalives_retries = Some(retries);
810            }
811            if let Some(timeout) = self.tcp_user_timeout {
812                config.tcp_user_timeout = Some(timeout);
813            }
814
815            Ok(config)
816        } else {
817            // Build from individual components
818            let host = self.host.unwrap_or_else(|| "localhost".to_string());
819            let port = self.port.unwrap_or(5432);
820            let database = self
821                .database
822                .ok_or_else(|| PgError::config("database name is required"))?;
823            let user = self.user.unwrap_or_else(|| "postgres".to_string());
824
825            let url = format!(
826                "postgresql://{}{}@{}:{}/{}",
827                user,
828                self.password
829                    .as_ref()
830                    .map(|p| format!(":{}", p))
831                    .unwrap_or_default(),
832                host,
833                port,
834                database
835            );
836
837            Ok(PgConfig {
838                url,
839                host,
840                port,
841                database,
842                user,
843                password: self.password,
844                ssl_mode: self.ssl_mode.unwrap_or_default(),
845                ssl_root_cert: self.ssl_root_cert,
846                connect_timeout: self.connect_timeout.unwrap_or(Duration::from_secs(30)),
847                statement_timeout: self.statement_timeout,
848                application_name: self.application_name,
849                keepalives: self.keepalives.unwrap_or(true),
850                keepalives_idle: self.keepalives_idle,
851                keepalives_interval: self.keepalives_interval,
852                keepalives_retries: self.keepalives_retries,
853                tcp_user_timeout: self.tcp_user_timeout,
854                options: Vec::new(),
855            })
856        }
857    }
858}
859
860#[cfg(test)]
861mod tests {
862    use super::*;
863
864    #[test]
865    fn test_config_from_url() {
866        let config = PgConfig::from_url("postgresql://user:pass@localhost:5432/mydb").unwrap();
867        assert_eq!(config.host, "localhost");
868        assert_eq!(config.port, 5432);
869        assert_eq!(config.database, "mydb");
870        assert_eq!(config.user, "user");
871        assert_eq!(config.password, Some("pass".to_string()));
872    }
873
874    #[test]
875    fn test_config_from_url_with_params() {
876        let config =
877            PgConfig::from_url("postgresql://localhost/mydb?sslmode=require&application_name=prax")
878                .unwrap();
879        assert_eq!(config.ssl_mode, SslMode::Require);
880        assert_eq!(config.application_name, Some("prax".to_string()));
881    }
882
883    #[test]
884    fn test_to_pg_config_applies_statement_timeout_and_options() {
885        let config = PgConfig::from_url(
886            "postgresql://localhost/mydb?statement_timeout=5000&search_path=public",
887        )
888        .unwrap();
889        let pg_config = config.to_pg_config();
890        assert_eq!(
891            pg_config.get_options(),
892            Some("-c statement_timeout=5000 -c search_path=public")
893        );
894    }
895
896    #[test]
897    fn test_to_pg_config_without_timeouts_or_options_sets_none() {
898        let config = PgConfig::from_url("postgresql://localhost/mydb").unwrap();
899        let pg_config = config.to_pg_config();
900        assert_eq!(pg_config.get_options(), None);
901    }
902
903    #[test]
904    fn test_to_pg_config_drops_option_with_smuggled_value() {
905        // Percent-decoded whitespace in a value must not survive into
906        // the space-joined `options` string, where it would smuggle in
907        // extra `-c key=value` assignments.
908        let config =
909            PgConfig::from_url("postgresql://localhost/mydb?x=1%20-c%20search_path%3Devil")
910                .unwrap();
911        let pg_config = config.to_pg_config();
912        assert_eq!(pg_config.get_options(), None);
913    }
914
915    #[test]
916    fn test_to_pg_config_drops_option_with_invalid_key() {
917        let config =
918            PgConfig::from_url("postgresql://localhost/mydb?bad%20key=1&search_path=public")
919                .unwrap();
920        let pg_config = config.to_pg_config();
921        // The invalid key is dropped; the valid option is kept.
922        assert_eq!(pg_config.get_options(), Some("-c search_path=public"));
923    }
924
925    #[test]
926    fn test_to_pg_config_drops_option_with_quoting_chars() {
927        // `\` and `'` are libpq's quoting characters inside `options`.
928        let config = PgConfig::from_url("postgresql://localhost/mydb?a=b%5Cc&d=e%27f").unwrap();
929        let pg_config = config.to_pg_config();
930        assert_eq!(pg_config.get_options(), None);
931    }
932
933    #[test]
934    fn tcp_liveness_defaults_match_the_driver() {
935        let config = PgConfig::from_url("postgresql://localhost/mydb").unwrap();
936        assert!(config.keepalives);
937        assert_eq!(config.keepalives_idle, None);
938        assert_eq!(config.keepalives_interval, None);
939        assert_eq!(config.keepalives_retries, None);
940        assert_eq!(config.tcp_user_timeout, None);
941
942        let pg = config.to_pg_config();
943        let default = tokio_postgres::Config::new();
944        assert_eq!(pg.get_keepalives(), default.get_keepalives());
945        assert_eq!(pg.get_keepalives_idle(), default.get_keepalives_idle());
946        assert_eq!(
947            pg.get_keepalives_interval(),
948            default.get_keepalives_interval()
949        );
950        assert_eq!(
951            pg.get_keepalives_retries(),
952            default.get_keepalives_retries()
953        );
954        assert_eq!(pg.get_tcp_user_timeout(), None);
955    }
956
957    #[test]
958    fn parses_tcp_liveness_params_with_libpq_units() {
959        let config = PgConfig::from_url(
960            "postgresql://localhost/mydb?keepalives=1&keepalives_idle=30\
961             &keepalives_interval=10&keepalives_count=3&tcp_user_timeout=15000",
962        )
963        .unwrap();
964        assert!(config.keepalives);
965        assert_eq!(config.keepalives_idle, Some(Duration::from_secs(30)));
966        assert_eq!(config.keepalives_interval, Some(Duration::from_secs(10)));
967        assert_eq!(config.keepalives_retries, Some(3));
968        assert_eq!(config.tcp_user_timeout, Some(Duration::from_millis(15_000)));
969        assert!(config.options.is_empty());
970
971        let pg = config.to_pg_config();
972        assert!(pg.get_keepalives());
973        assert_eq!(pg.get_keepalives_idle(), Duration::from_secs(30));
974        assert_eq!(pg.get_keepalives_interval(), Some(Duration::from_secs(10)));
975        assert_eq!(pg.get_keepalives_retries(), Some(3));
976        assert_eq!(
977            pg.get_tcp_user_timeout(),
978            Some(&Duration::from_millis(15_000))
979        );
980    }
981
982    #[test]
983    fn tcp_liveness_params_are_not_forwarded_as_server_options() {
984        let config = PgConfig::from_url(
985            "postgresql://localhost/mydb?keepalives_idle=30&tcp_user_timeout=5000\
986             &keepalives_interval=5&keepalives_count=2&keepalives=1&search_path=public",
987        )
988        .unwrap();
989        assert_eq!(
990            config.options,
991            vec![("search_path".to_string(), "public".to_string())]
992        );
993        assert_eq!(
994            config.to_pg_config().get_options(),
995            Some("-c search_path=public")
996        );
997    }
998
999    #[test]
1000    fn keepalives_zero_disables_and_retries_alias_is_accepted() {
1001        let config =
1002            PgConfig::from_url("postgresql://localhost/mydb?keepalives=0&keepalives_retries=4")
1003                .unwrap();
1004        assert!(!config.keepalives);
1005        assert_eq!(config.keepalives_retries, Some(4));
1006        let pg = config.to_pg_config();
1007        assert!(!pg.get_keepalives());
1008        assert_eq!(pg.get_keepalives_retries(), Some(4));
1009        assert_eq!(pg.get_options(), None);
1010    }
1011
1012    #[test]
1013    fn zero_tcp_liveness_values_keep_the_defaults() {
1014        let config = PgConfig::from_url(
1015            "postgresql://localhost/mydb?keepalives_idle=0&keepalives_interval=0\
1016             &keepalives_count=0&tcp_user_timeout=0",
1017        )
1018        .unwrap();
1019        assert_eq!(config.keepalives_idle, None);
1020        assert_eq!(config.keepalives_interval, None);
1021        assert_eq!(config.keepalives_retries, None);
1022        assert_eq!(config.tcp_user_timeout, None);
1023
1024        // Zero set programmatically is ignored by `to_pg_config` too.
1025        let mut config = PgConfig::from_url("postgresql://localhost/mydb").unwrap();
1026        config.keepalives_idle = Some(Duration::ZERO);
1027        config.keepalives_interval = Some(Duration::ZERO);
1028        config.keepalives_retries = Some(0);
1029        config.tcp_user_timeout = Some(Duration::ZERO);
1030        let pg = config.to_pg_config();
1031        let default = tokio_postgres::Config::new();
1032        assert_eq!(pg.get_keepalives_idle(), default.get_keepalives_idle());
1033        assert_eq!(
1034            pg.get_keepalives_interval(),
1035            default.get_keepalives_interval()
1036        );
1037        assert_eq!(
1038            pg.get_keepalives_retries(),
1039            default.get_keepalives_retries()
1040        );
1041        assert_eq!(pg.get_tcp_user_timeout(), None);
1042    }
1043
1044    #[test]
1045    fn rejects_invalid_tcp_liveness_values() {
1046        for query in [
1047            "keepalives=yes",
1048            "keepalives_idle=-1",
1049            "keepalives_idle=30s",
1050            "keepalives_interval=abc",
1051            "keepalives_count=-2",
1052            "keepalives_retries=99999999999",
1053            "tcp_user_timeout=1.5",
1054            "tcp_user_timeout=",
1055        ] {
1056            let err = PgConfig::from_url(format!("postgresql://localhost/mydb?{query}"))
1057                .expect_err(query);
1058            let key = query.split('=').next().unwrap();
1059            assert!(err.to_string().contains(key), "{query}: {err}");
1060        }
1061    }
1062
1063    #[test]
1064    fn builder_sets_tcp_liveness() {
1065        let config = PgConfig::builder()
1066            .database("mydb")
1067            .keepalives(true)
1068            .keepalives_idle(Duration::from_secs(60))
1069            .keepalives_interval(Duration::from_secs(15))
1070            .keepalives_retries(4)
1071            .tcp_user_timeout(Duration::from_secs(30))
1072            .build()
1073            .unwrap();
1074        let pg = config.to_pg_config();
1075        assert!(pg.get_keepalives());
1076        assert_eq!(pg.get_keepalives_idle(), Duration::from_secs(60));
1077        assert_eq!(pg.get_keepalives_interval(), Some(Duration::from_secs(15)));
1078        assert_eq!(pg.get_keepalives_retries(), Some(4));
1079        assert_eq!(pg.get_tcp_user_timeout(), Some(&Duration::from_secs(30)));
1080
1081        // Explicit builder values override the URL's.
1082        let config = PgConfig::builder()
1083            .url("postgresql://localhost/mydb?keepalives_idle=30&tcp_user_timeout=1000")
1084            .keepalives(false)
1085            .keepalives_idle(Duration::from_secs(90))
1086            .tcp_user_timeout(Duration::from_secs(5))
1087            .build()
1088            .unwrap();
1089        assert!(!config.keepalives);
1090        assert_eq!(config.keepalives_idle, Some(Duration::from_secs(90)));
1091        assert_eq!(config.tcp_user_timeout, Some(Duration::from_secs(5)));
1092
1093        let config = PgConfig::builder().database("mydb").build().unwrap();
1094        assert!(config.keepalives);
1095        assert_eq!(config.tcp_user_timeout, None);
1096    }
1097
1098    #[test]
1099    fn parses_sslrootcert_from_the_url() {
1100        let config = PgConfig::from_url(
1101            "postgresql://localhost/mydb?sslmode=verify-full&sslrootcert=/etc/ssl/rds.pem",
1102        )
1103        .unwrap();
1104        assert_eq!(
1105            config.ssl_root_cert,
1106            Some(std::path::PathBuf::from("/etc/ssl/rds.pem"))
1107        );
1108        // It must not fall through into the generic `options` bag, which would
1109        // send it to the server as a GUC.
1110        assert!(!config.options.iter().any(|(k, _)| k == "sslrootcert"));
1111    }
1112
1113    #[test]
1114    fn sslrootcert_defaults_to_none() {
1115        let config = PgConfig::from_url("postgresql://localhost/mydb").unwrap();
1116        assert_eq!(config.ssl_root_cert, None);
1117    }
1118
1119    #[test]
1120    fn builder_sets_sslrootcert() {
1121        let config = PgConfig::builder()
1122            .url("postgresql://localhost/mydb")
1123            .ssl_root_cert("/etc/ssl/override.pem")
1124            .build()
1125            .unwrap();
1126        assert_eq!(
1127            config.ssl_root_cert,
1128            Some(std::path::PathBuf::from("/etc/ssl/override.pem"))
1129        );
1130    }
1131
1132    #[test]
1133    fn test_to_pg_config_maps_sslmode_require() {
1134        // TLS is supported via rustls: `require` maps to the driver's
1135        // `Require` (never downgraded).
1136        let config = PgConfig::from_url("postgresql://localhost/mydb?sslmode=require").unwrap();
1137        let pg_config = config.to_pg_config();
1138        assert_eq!(
1139            pg_config.get_ssl_mode(),
1140            tokio_postgres::config::SslMode::Require
1141        );
1142    }
1143
1144    #[test]
1145    fn test_from_url_parses_verify_modes() {
1146        let config = PgConfig::from_url("postgresql://localhost/mydb?sslmode=verify-ca").unwrap();
1147        assert_eq!(config.ssl_mode, SslMode::VerifyCa);
1148        let pg_config = config.to_pg_config();
1149        assert_eq!(
1150            pg_config.get_ssl_mode(),
1151            tokio_postgres::config::SslMode::Require
1152        );
1153
1154        let config = PgConfig::from_url("postgresql://localhost/mydb?sslmode=verify-full").unwrap();
1155        assert_eq!(config.ssl_mode, SslMode::VerifyFull);
1156
1157        assert!(PgConfig::from_url("postgresql://localhost/mydb?sslmode=bogus").is_err());
1158    }
1159
1160    #[test]
1161    fn test_to_pg_config_maps_sslmode_disable() {
1162        let config = PgConfig::from_url("postgresql://localhost/mydb?sslmode=disable").unwrap();
1163        let pg_config = config.to_pg_config();
1164        assert_eq!(
1165            pg_config.get_ssl_mode(),
1166            tokio_postgres::config::SslMode::Disable
1167        );
1168    }
1169
1170    #[test]
1171    fn test_config_builder() {
1172        let config = PgConfig::builder()
1173            .host("localhost")
1174            .port(5432)
1175            .database("mydb")
1176            .user("postgres")
1177            .build()
1178            .unwrap();
1179
1180        assert_eq!(config.host, "localhost");
1181        assert_eq!(config.database, "mydb");
1182    }
1183
1184    const SENTINEL: &str = "hunter2-sentinel";
1185
1186    #[test]
1187    fn debug_redacts_the_password_and_the_url_password() {
1188        let config = PgConfig::from_url(format!(
1189            "postgres://prax:{SENTINEL}@db.internal:5432/prax?application_name=app"
1190        ))
1191        .unwrap();
1192        let debug = format!("{config:?}");
1193        assert!(!debug.contains(SENTINEL), "{debug}");
1194        // Everything else stays visible.
1195        for visible in [
1196            "db.internal",
1197            "5432",
1198            "prax",
1199            "application_name=app",
1200            "REDACTED",
1201        ] {
1202            assert!(debug.contains(visible), "{visible}: {debug}");
1203        }
1204        let alternate = format!("{config:#?}");
1205        assert!(!alternate.contains(SENTINEL), "{alternate}");
1206    }
1207
1208    #[test]
1209    fn debug_redacts_unencoded_builder_passwords() {
1210        // The builder writes the password into `url` verbatim, so `@` and
1211        // `/` in it do not parse as one URL password.
1212        let config = PgConfig::builder()
1213            .host("db.internal")
1214            .database("prax")
1215            .user("prax")
1216            .password(format!("{SENTINEL}@x/y"))
1217            .build()
1218            .unwrap();
1219        let debug = format!("{config:?}");
1220        assert!(!debug.contains("hunter2"), "{debug}");
1221        assert!(!debug.contains("x/y"), "{debug}");
1222
1223        // A URL that does not parse is redacted up to its last `@`.
1224        let mut config = config;
1225        config.url = format!("postgres://prax:{SENTINEL}@bad host/prax");
1226        let debug = format!("{config:?}");
1227        assert!(!debug.contains(SENTINEL), "{debug}");
1228    }
1229
1230    #[test]
1231    fn url_redaction_touches_only_the_password() {
1232        // A password equal to the user, host or database name (or a single
1233        // letter of them) must not be replaced anywhere else.
1234        assert_eq!(
1235            redact_url(
1236                "postgres://postgres:postgres@localhost:5432/postgres",
1237                Some("postgres")
1238            ),
1239            "postgres://postgres:REDACTED@localhost:5432/postgres"
1240        );
1241        assert_eq!(
1242            redact_url(
1243                "postgres://app:a@db.internal:5432/app_db?sslmode=disable",
1244                Some("a")
1245            ),
1246            "postgres://app:REDACTED@db.internal:5432/app_db?sslmode=disable"
1247        );
1248        // Without a hint the parser finds the password; the rest of the URL
1249        // is kept as written.
1250        assert_eq!(
1251            redact_url("postgres://app:a@db.internal/app_db", None),
1252            "postgres://app:REDACTED@db.internal/app_db"
1253        );
1254        let config =
1255            PgConfig::from_url("postgres://postgres:postgres@localhost:5432/postgres").unwrap();
1256        let debug = format!("{config:?}");
1257        assert!(
1258            debug.contains("\"postgres://postgres:REDACTED@localhost:5432/postgres\""),
1259            "{debug}"
1260        );
1261        assert!(debug.contains("database: \"postgres\""), "{debug}");
1262    }
1263
1264    #[test]
1265    fn url_redaction_without_a_password_hint() {
1266        // An unencoded password starting with digits and then `/`, `?` or
1267        // `#` parses as a port, so the parser reports no password.
1268        for url in [
1269            format!("postgres://u:8/{SENTINEL}@host/db"),
1270            format!("postgres://u:123#{SENTINEL}@host/db"),
1271            format!("postgres://u:123?{SENTINEL}@host/db"),
1272        ] {
1273            let redacted = redact_url(&url, None);
1274            assert!(!redacted.contains(SENTINEL), "{url} -> {redacted}");
1275            assert_eq!(redacted, "postgres://REDACTED@host/db", "{url}");
1276        }
1277        // libpq-style `?password=` (key case and encoding ignored).
1278        for url in [
1279            format!("postgres://u@host/db?password={SENTINEL}&sslmode=disable"),
1280            format!("postgres://u@host/db?sslmode=disable&PASSWORD={SENTINEL}#frag"),
1281            format!("postgres://u@host/db?pass%77ord={SENTINEL}"),
1282        ] {
1283            let redacted = redact_url(&url, None);
1284            assert!(!redacted.contains(SENTINEL), "{url} -> {redacted}");
1285            assert!(redacted.starts_with("postgres://u@host/db?"), "{redacted}");
1286        }
1287        assert_eq!(
1288            redact_url(
1289                &format!("postgres://u@host/db?password={SENTINEL}&sslmode=disable"),
1290                None
1291            ),
1292            "postgres://u@host/db?password=REDACTED&sslmode=disable"
1293        );
1294        // A user name without a password stays.
1295        assert_eq!(
1296            redact_url("postgres://u@host/db", None),
1297            "postgres://u@host/db"
1298        );
1299    }
1300
1301    #[test]
1302    fn debug_redacts_password_options_and_query() {
1303        let url = format!("postgres://u@db.internal/prax?password={SENTINEL}&search_path=app");
1304        let config = PgConfig::from_url(&url).unwrap();
1305        let debug = format!("{config:?}");
1306        assert!(!debug.contains(SENTINEL), "{debug}");
1307        assert!(debug.contains("search_path"), "{debug}");
1308
1309        // Not the libpq keyword (case differs), so it stays an option, which
1310        // Debug redacts all the same.
1311        let config =
1312            PgConfig::from_url(format!("postgres://u@db.internal/prax?PASSWORD={SENTINEL}"))
1313                .unwrap();
1314        assert!(config.options.iter().any(|(k, _)| k == "PASSWORD"));
1315        let debug = format!("{config:?}");
1316        assert!(!debug.contains(SENTINEL), "{debug}");
1317
1318        let builder = crate::pool::PgPoolBuilder::new().url(&url);
1319        let debug = format!("{builder:?}");
1320        assert!(!debug.contains(SENTINEL), "{debug}");
1321
1322        let builder = crate::pool::PgPoolBuilder::new()
1323            .url(format!("postgres://u:8/{SENTINEL}@db.internal/prax"));
1324        let debug = format!("{builder:?}");
1325        assert!(!debug.contains(SENTINEL), "{debug}");
1326    }
1327
1328    #[test]
1329    fn debug_keeps_urls_without_a_password() {
1330        let config = PgConfig::from_url("postgres://prax@db.internal/prax").unwrap();
1331        let debug = format!("{config:?}");
1332        assert!(
1333            debug.contains("postgres://prax@db.internal/prax"),
1334            "{debug}"
1335        );
1336        assert!(debug.contains("password: None"), "{debug}");
1337    }
1338
1339    #[test]
1340    fn config_builder_debug_redacts_secrets() {
1341        let builder = PgConfig::builder()
1342            .url(format!("postgres://prax:{SENTINEL}@db.internal/prax"))
1343            .password(SENTINEL);
1344        let debug = format!("{builder:?}");
1345        assert!(!debug.contains(SENTINEL), "{debug}");
1346        assert!(debug.contains("db.internal"), "{debug}");
1347    }
1348
1349    #[test]
1350    fn from_url_rejects_passwords_with_unencoded_reserved_characters() {
1351        for url in [
1352            "postgres://u:8/Hx@host/db",
1353            "postgres://u:123#456@host/db",
1354            "postgres://u:123?x@host/db",
1355            "postgres://u:a@b/c@host/db",
1356            "postgres://u:8/x:y@host:5432/db?sslmode=disable",
1357        ] {
1358            match PgConfig::from_url(url) {
1359                Err(PgError::Config(message)) => {
1360                    assert!(message.contains("percent-encode"), "{url}: {message}");
1361                    // The error never repeats the URL (or the password).
1362                    assert!(
1363                        !message.contains("Hx") && !message.contains("456"),
1364                        "{message}"
1365                    );
1366                }
1367                other => panic!("{url}: expected a config error, got {other:?}"),
1368            }
1369        }
1370    }
1371
1372    #[test]
1373    fn from_url_decodes_percent_encoded_credentials_and_database() {
1374        let config = PgConfig::from_url("postgres://u:8%2FHx@host/db").unwrap();
1375        assert_eq!(
1376            (
1377                config.user.as_str(),
1378                config.password.as_deref(),
1379                config.host.as_str()
1380            ),
1381            ("u", Some("8/Hx"), "host")
1382        );
1383        assert_eq!((config.port, config.database.as_str()), (5432, "db"));
1384
1385        let config = PgConfig::from_url("postgres://u:123%23456@host:6543/db").unwrap();
1386        assert_eq!(config.password.as_deref(), Some("123#456"));
1387        assert_eq!(config.port, 6543);
1388
1389        let config =
1390            PgConfig::from_url("postgres://app%40corp:p%40ss%3Aw%2B@host/my%40db").unwrap();
1391        assert_eq!(config.user, "app@corp");
1392        assert_eq!(config.password.as_deref(), Some("p@ss:w+"));
1393        assert_eq!(config.database, "my@db");
1394        let pg_config = config.to_pg_config();
1395        assert_eq!(pg_config.get_password(), Some(&b"p@ss:w+"[..]));
1396        assert_eq!(pg_config.get_user(), Some("app@corp"));
1397
1398        // An `@` inside a query value is not mistaken for user info.
1399        let config =
1400            PgConfig::from_url("postgres://u:pw@host/db?application_name=me@work").unwrap();
1401        assert_eq!(config.application_name.as_deref(), Some("me@work"));
1402        assert_eq!(config.password.as_deref(), Some("pw"));
1403    }
1404
1405    #[test]
1406    fn from_url_takes_credentials_from_query_parameters() {
1407        let config = PgConfig::from_url(format!(
1408            "postgres://db.internal/prax?user=alice&password={SENTINEL}&sslmode=disable"
1409        ))
1410        .unwrap();
1411        assert_eq!(config.user, "alice");
1412        assert_eq!(config.password.as_deref(), Some(SENTINEL));
1413        assert_eq!(config.ssl_mode, SslMode::Disable);
1414        // Credentials, not server startup options.
1415        assert!(config.options.is_empty(), "{:?}", config.options);
1416        let pg_config = config.to_pg_config();
1417        assert_eq!(pg_config.get_user(), Some("alice"));
1418        assert_eq!(pg_config.get_password(), Some(SENTINEL.as_bytes()));
1419        assert_eq!(pg_config.get_options(), None);
1420        // Debug still redacts the password (field and URL).
1421        let debug = format!("{config:?}");
1422        assert!(!debug.contains(SENTINEL), "{debug}");
1423        assert!(debug.contains("alice"), "{debug}");
1424
1425        // They override the user info; values are percent-decoded like
1426        // libpq, so `+` stays a plus sign.
1427        let config =
1428            PgConfig::from_url("postgres://bob:old@host/db?password=n%26w+1&user=carol").unwrap();
1429        assert_eq!(config.user, "carol");
1430        assert_eq!(config.password.as_deref(), Some("n&w+1"));
1431        assert!(config.options.is_empty(), "{:?}", config.options);
1432    }
1433
1434    #[test]
1435    fn test_config_invalid_scheme() {
1436        let result = PgConfig::from_url("mysql://localhost/db");
1437        assert!(result.is_err());
1438    }
1439}