Skip to main content

giong_postgres/
config.rs

1//! Where to connect and how.
2
3use std::fmt;
4use std::net::IpAddr;
5use std::path::{Path, PathBuf};
6use std::str::FromStr;
7use std::sync::{Arc, OnceLock};
8use std::time::Duration;
9
10use giong_tls::TlsConnector;
11
12use crate::auth::KeyCache;
13use crate::error::{Error, ErrorKind};
14
15/// A way for the server to check who connects, for
16/// [`Config::require_auth`].
17#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
18#[non_exhaustive]
19pub enum AuthMethod {
20    /// No check at all: the server lets the connection in without asking
21    /// for anything (`trust` in `pg_hba.conf`, or peer authentication on a
22    /// Unix socket).
23    None,
24    /// The password in clear text (`password`).
25    Password,
26    /// The MD5 challenge (`md5`), which an eavesdropper can attack offline.
27    Md5,
28    /// SCRAM-SHA-256 (`scram-sha-256`).
29    ScramSha256,
30}
31
32impl AuthMethod {
33    /// The method's name in libpq's `require_auth` and in `pg_hba.conf`.
34    pub(crate) fn name(self) -> &'static str {
35        match self {
36            AuthMethod::None => "none",
37            AuthMethod::Password => "password",
38            AuthMethod::Md5 => "md5",
39            AuthMethod::ScramSha256 => "scram-sha-256",
40        }
41    }
42}
43
44/// How the connection is encrypted.
45#[derive(Clone)]
46pub enum Tls {
47    /// No TLS. Use it only on a network you trust: anyone on the path can
48    /// read and change what is sent, though not a SCRAM password.
49    Disable,
50    /// TLS, checking the server's certificate with this connector: against
51    /// its trusted authorities, and against the host name the client connects
52    /// to. The connection fails if the server does not support TLS.
53    Verify(TlsConnector),
54}
55
56impl fmt::Debug for Tls {
57    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
58        match self {
59            Tls::Disable => f.write_str("Disable"),
60            Tls::Verify(_) => f.write_str("Verify(..)"),
61        }
62    }
63}
64
65#[derive(Clone, Debug, PartialEq, Eq)]
66pub(crate) enum Host {
67    /// A DNS name or an IP address.
68    Tcp(String),
69    /// The directory holding the server's Unix socket.
70    Unix(PathBuf),
71}
72
73/// Connection settings: where the server is, who to log in as, and the limits
74/// that apply to the connection.
75///
76/// Build one with [`Config::from_url`] or with the setters:
77///
78/// ```
79/// use std::time::Duration;
80/// use giong_postgres::Config;
81///
82/// let config = Config::from_url("postgres://app:secret@db.internal:5432/shop?sslmode=verify-full")?;
83///
84/// let same_place = Config::new()
85///     .host("db.internal")
86///     .user("app")
87///     .password("secret")
88///     .dbname("shop")
89///     .statement_timeout(Duration::from_secs(5));
90/// # Ok::<_, giong_postgres::Error>(())
91/// ```
92///
93/// Every limit has a finite default, documented on its setter: a connection
94/// never waits forever, and a result never grows without bound.
95///
96/// **TLS.** Unless [`tls`](Self::tls) or `sslmode` says otherwise, a TCP
97/// connection to anything but a loopback address uses TLS and checks the
98/// server's certificate against the certificate authorities installed on the
99/// machine; connections over a Unix socket or to a loopback address do not
100/// use TLS.
101#[derive(Clone)]
102pub struct Config {
103    pub(crate) host: Host,
104    pub(crate) port: u16,
105    pub(crate) user: Option<String>,
106    pub(crate) password: Option<String>,
107    pub(crate) dbname: Option<String>,
108    pub(crate) application_name: Option<String>,
109    pub(crate) params: Vec<(String, String)>,
110    tls: Option<Tls>,
111    system_roots: Arc<OnceLock<Result<TlsConnector, String>>>,
112    /// The authentication methods the server may use; any when `None`.
113    pub(crate) require_auth: Option<Vec<AuthMethod>>,
114    /// SCRAM keys derived for this config's password, shared by its clones.
115    pub(crate) scram_keys: Arc<KeyCache>,
116    pub(crate) connect_timeout: Duration,
117    pub(crate) statement_timeout: Option<Duration>,
118    pub(crate) max_result_size: usize,
119    pub(crate) statement_cache: usize,
120}
121
122impl Default for Config {
123    fn default() -> Self {
124        Self::new()
125    }
126}
127
128impl Config {
129    /// The server and database, without user or password, for diagnostics:
130    /// `db.internal:5432/app`.
131    pub(crate) fn describe(&self) -> String {
132        let server = match &self.host {
133            Host::Tcp(host) if host.contains(':') => format!("[{host}]:{}", self.port),
134            Host::Tcp(host) => format!("{host}:{}", self.port),
135            Host::Unix(dir) => format!("{}/.s.PGSQL.{}", dir.display(), self.port),
136        };
137        match &self.dbname {
138            Some(db) => format!("{server}/{db}"),
139            None => server,
140        }
141    }
142
143    /// Settings for `localhost:5432`, with no user yet and the default
144    /// limits.
145    pub fn new() -> Self {
146        Self {
147            host: Host::Tcp("localhost".to_owned()),
148            port: 5432,
149            user: None,
150            password: None,
151            dbname: None,
152            application_name: None,
153            params: Vec::new(),
154            tls: None,
155            system_roots: Arc::new(OnceLock::new()),
156            require_auth: None,
157            scram_keys: Arc::default(),
158            connect_timeout: Duration::from_secs(10),
159            statement_timeout: Some(Duration::from_secs(30)),
160            max_result_size: 64 << 20,
161            statement_cache: 256,
162        }
163    }
164
165    /// The server's host: a DNS name, an IP address, or the absolute path of
166    /// the directory holding its Unix socket (such as
167    /// `/var/run/postgresql`).
168    pub fn host(mut self, host: &str) -> Self {
169        self.host = if host.starts_with('/') {
170            Host::Unix(PathBuf::from(host))
171        } else {
172            let host = host
173                .strip_prefix('[')
174                .and_then(|h| h.strip_suffix(']'))
175                .unwrap_or(host);
176            Host::Tcp(host.to_owned())
177        };
178        self
179    }
180
181    /// The server's port, 5432 by default. For a Unix socket it picks the
182    /// socket file, `.s.PGSQL.<port>`.
183    pub fn port(mut self, port: u16) -> Self {
184        self.port = port;
185        self
186    }
187
188    /// The user to log in as. Required.
189    pub fn user(mut self, user: &str) -> Self {
190        self.user = Some(user.to_owned());
191        self
192    }
193
194    /// The password, if the server asks for one.
195    pub fn password(mut self, password: &str) -> Self {
196        self.password = Some(password.to_owned());
197        self.scram_keys = Arc::default();
198        self
199    }
200
201    /// The database; the server uses the user's name when it is not set.
202    pub fn dbname(mut self, dbname: &str) -> Self {
203        self.dbname = Some(dbname.to_owned());
204        self
205    }
206
207    /// The name the server shows for this connection in `pg_stat_activity`
208    /// and in its logs.
209    pub fn application_name(mut self, name: &str) -> Self {
210        self.application_name = Some(name.to_owned());
211        self
212    }
213
214    /// Sets a server setting for the whole session when connecting, such as
215    /// `search_path` or `TimeZone`.
216    pub fn param(mut self, name: &str, value: &str) -> Self {
217        self.params.push((name.to_owned(), value.to_owned()));
218        self
219    }
220
221    /// Whether and how to use TLS (see [the type's documentation](Self) for
222    /// what happens when this is not set).
223    pub fn tls(mut self, tls: Tls) -> Self {
224        self.tls = Some(tls);
225        self
226    }
227
228    /// The only authentication methods the server may use; by default, any
229    /// this crate supports. Connecting fails with
230    /// [`ErrorKind::Auth`](crate::ErrorKind::Auth), before anything is sent
231    /// for the password, when the server asks for another method or lets the
232    /// connection in without one.
233    ///
234    /// Without TLS (over a Unix socket, to a loopback address, or with
235    /// `sslmode=disable`), nothing proves that the server is the real one: an
236    /// impostor can ask for MD5 instead of SCRAM and attack the answer
237    /// offline, or let the client in without asking anything.
238    /// `require_auth(&[AuthMethod::ScramSha256])` rules that out, since SCRAM
239    /// makes the server prove that it knows the password too. In a URL:
240    /// `require_auth=scram-sha-256` (a comma-separated list, as in libpq,
241    /// without libpq's `!` negations).
242    pub fn require_auth(mut self, methods: &[AuthMethod]) -> Self {
243        self.require_auth = Some(methods.to_vec());
244        self
245    }
246
247    /// The longest that opening a connection may take, from name resolution
248    /// to the end of authentication: 10 seconds by default.
249    pub fn connect_timeout(mut self, timeout: Duration) -> Self {
250        self.connect_timeout = timeout;
251        self
252    }
253
254    /// The longest a statement may run on the server before the server
255    /// cancels it: 30 seconds by default.
256    ///
257    /// It is sent as the session's `statement_timeout` when connecting, so the
258    /// server enforces it exactly, and only on the statement that runs too
259    /// long (SQLSTATE `57014`). It is rounded up to whole milliseconds and
260    /// must be from 1 ms to `i32::MAX` milliseconds (24.8 days): connecting
261    /// fails with [`ErrorKind::Config`](crate::ErrorKind::Config) otherwise.
262    /// Raise it for the connections that run migrations or reports, rather
263    /// than turning it off with `SET`.
264    ///
265    /// `None` sends nothing, leaving the limit to the server's own setting,
266    /// which is no limit unless someone set one. Through a connection pooler
267    /// such as PgBouncer, give `None` and set the limit on the role
268    /// (`ALTER ROLE app SET statement_timeout = '30s'`): PgBouncer refuses a
269    /// connection that sends `statement_timeout`, and its settings that
270    /// accept it (`track_extra_parameters`, `ignore_startup_parameters`)
271    /// do not pass it on to the server (checked with PgBouncer 1.22).
272    pub fn statement_timeout(mut self, timeout: impl Into<Option<Duration>>) -> Self {
273        self.statement_timeout = timeout.into();
274        self
275    }
276
277    /// The largest result one statement may return, in bytes of row data:
278    /// 64 MiB by default. A larger result fails with
279    /// [`ErrorKind::TooLarge`](crate::ErrorKind::TooLarge), and the
280    /// connection stays usable.
281    pub fn max_result_size(mut self, bytes: usize) -> Self {
282        self.max_result_size = bytes;
283        self
284    }
285
286    /// How many prepared statements each connection keeps, 256 by default.
287    ///
288    /// Every statement is prepared on the server the first time a connection
289    /// runs it, and kept, so running it again takes one round trip instead
290    /// of two. The least recently used statement is closed when the cache is
291    /// full. 0 prepares and closes every statement each time it runs, which
292    /// takes two round trips; the statement is still a named one, prepared
293    /// in one request and run in the next, so 0 does not make a connection
294    /// pooler in transaction mode work: that needs PgBouncer 1.21 or newer
295    /// with `max_prepared_statements` above 0, which supports any cache
296    /// size.
297    pub fn statement_cache_capacity(mut self, statements: usize) -> Self {
298        self.statement_cache = statements;
299        self
300    }
301
302    /// Reads a connection URL:
303    ///
304    /// ```text
305    /// postgres://user:password@host:port/dbname?param=value&...
306    /// ```
307    ///
308    /// `postgresql://` works too. User, password and database are
309    /// percent-decoded. The host can be an IPv6 address in brackets, or, as
310    /// with libpq, empty with the socket directory in a `host` parameter:
311    /// `postgres:///shop?host=/var/run/postgresql`.
312    ///
313    /// The parameters understood are `sslmode`, `sslrootcert`, `host`,
314    /// `port`, `user`, `password`, `dbname`, `application_name`,
315    /// `connect_timeout` (seconds) and `require_auth` (see
316    /// [`require_auth`](Self::require_auth)); any other is an error rather
317    /// than being ignored. `sslmode` is `disable`, or `require`, `verify-ca` or
318    /// `verify-full`, which all check the certificate and the host name
319    /// (stricter than libpq, which checks nothing for `require`).
320    /// `sslrootcert` is a PEM file of authorities to trust instead of the
321    /// machine's, or `system`.
322    pub fn from_url(url: &str) -> Result<Self, Error> {
323        parse_url(url)
324    }
325
326    /// The URL this config was read from, or would be, without the password,
327    /// for messages.
328    pub(crate) fn target(&self) -> String {
329        match &self.host {
330            Host::Tcp(h) if h.contains(':') => format!("[{h}]:{}", self.port),
331            Host::Tcp(h) => format!("{h}:{}", self.port),
332            Host::Unix(dir) => self.socket_path(dir).display().to_string(),
333        }
334    }
335
336    pub(crate) fn socket_path(&self, dir: &Path) -> PathBuf {
337        dir.join(format!(".s.PGSQL.{}", self.port))
338    }
339
340    /// The same settings without the password, for cancel requests, which
341    /// do not authenticate.
342    pub(crate) fn without_password(&self) -> Config {
343        Config {
344            password: None,
345            // The cached SCRAM keys would log in as well as the password.
346            scram_keys: Arc::default(),
347            ..self.clone()
348        }
349    }
350
351    /// Whether the host is this machine: a Unix socket or a loopback address.
352    pub(crate) fn is_local(&self) -> bool {
353        match &self.host {
354            Host::Unix(_) => true,
355            Host::Tcp(h) => {
356                h.eq_ignore_ascii_case("localhost")
357                    || h.parse::<IpAddr>().is_ok_and(|ip| match ip {
358                        IpAddr::V4(v4) => v4.is_loopback(),
359                        IpAddr::V6(v6) => {
360                            v6.is_loopback()
361                                || v6.to_ipv4_mapped().is_some_and(|v4| v4.is_loopback())
362                        }
363                    })
364            }
365        }
366    }
367
368    /// The connector to use, or `None` for no TLS.
369    pub(crate) fn tls_connector(&self) -> Result<Option<TlsConnector>, Error> {
370        match (&self.tls, &self.host) {
371            (_, Host::Unix(_)) | (Some(Tls::Disable), _) => Ok(None),
372            (Some(Tls::Verify(connector)), _) => Ok(Some(connector.clone())),
373            (None, _) if self.is_local() => Ok(None),
374            (None, Host::Tcp(host)) => {
375                let roots = self
376                    .system_roots
377                    .get_or_init(|| TlsConnector::with_system_roots().map_err(|e| e.to_string()));
378                match roots {
379                    Ok(connector) => Ok(Some(connector.clone())),
380                    Err(e) => Err(Error::new(
381                        ErrorKind::Config,
382                        format!(
383                            "a connection to {host} uses TLS checked against the machine's \
384                             certificate authorities, but they could not be loaded ({e}); give \
385                             the server's authority with sslrootcert=/path/ca.pem or \
386                             Config::tls, or add sslmode=disable if the network is trusted"
387                        ),
388                    )),
389                }
390            }
391        }
392    }
393}
394
395impl fmt::Debug for Config {
396    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
397        f.debug_struct("Config")
398            .field("host", &self.host)
399            .field("port", &self.port)
400            .field("user", &self.user)
401            .field("password", &self.password.as_ref().map(|_| "<hidden>"))
402            .field("dbname", &self.dbname)
403            .field("application_name", &self.application_name)
404            .field("params", &self.params)
405            .field("tls", &self.tls)
406            .field("require_auth", &self.require_auth)
407            .field("connect_timeout", &self.connect_timeout)
408            .field("statement_timeout", &self.statement_timeout)
409            .field("max_result_size", &self.max_result_size)
410            .field("statement_cache_capacity", &self.statement_cache)
411            .finish()
412    }
413}
414
415impl FromStr for Config {
416    type Err = Error;
417
418    fn from_str(url: &str) -> Result<Self, Error> {
419        parse_url(url)
420    }
421}
422
423fn percent_decode(s: &str, what: &str) -> Result<String, Error> {
424    let bytes = s.as_bytes();
425    let mut out = Vec::with_capacity(bytes.len());
426    let mut i = 0;
427    while i < bytes.len() {
428        if bytes[i] == b'%' {
429            let hex = bytes
430                .get(i + 1..i + 3)
431                .and_then(|h| std::str::from_utf8(h).ok())
432                .and_then(|h| u8::from_str_radix(h, 16).ok())
433                .ok_or_else(|| {
434                    Error::config(format!(
435                        "the {what} in the URL has a '%' that is not followed by two hex digits; \
436                         write a literal % as %25"
437                    ))
438                })?;
439            out.push(hex);
440            i += 3;
441        } else {
442            out.push(bytes[i]);
443            i += 1;
444        }
445    }
446    String::from_utf8(out)
447        .map_err(|_| Error::config(format!("the {what} in the URL is not UTF-8 once decoded")))
448}
449
450fn parse_url(url: &str) -> Result<Config, Error> {
451    let rest = url
452        .strip_prefix("postgres://")
453        .or_else(|| url.strip_prefix("postgresql://"))
454        .ok_or_else(|| {
455            Error::config(
456                "a connection URL starts with postgres:// or postgresql://, \
457                 as in postgres://user:password@host:5432/dbname",
458            )
459        })?;
460    let (rest, query) = match rest.split_once('?') {
461        Some((r, q)) => (r, Some(q)),
462        None => (rest, None),
463    };
464    let (authority, path) = match rest.split_once('/') {
465        Some((a, p)) => (a, Some(p)),
466        None => (rest, None),
467    };
468    let mut config = Config::new();
469    let hostport = match authority.rsplit_once('@') {
470        Some((userinfo, hostport)) => {
471            let (user, password) = match userinfo.split_once(':') {
472                Some((u, p)) => (u, Some(p)),
473                None => (userinfo, None),
474            };
475            if !user.is_empty() {
476                config.user = Some(percent_decode(user, "user")?);
477            }
478            if let Some(p) = password {
479                config.password = Some(percent_decode(p, "password")?);
480            }
481            hostport
482        }
483        None => authority,
484    };
485    if hostport.contains(',') {
486        return Err(Error::config(
487            "the URL names several hosts; giong-postgres connects to one, so give one host",
488        ));
489    }
490    let (host, port) = if let Some(v6) = hostport.strip_prefix('[') {
491        let (addr, after) = v6.split_once(']').ok_or_else(|| {
492            Error::config("an IPv6 address in the URL is missing its closing ']'")
493        })?;
494        let port = match after {
495            "" => None,
496            p => Some(p.strip_prefix(':').ok_or_else(|| {
497                Error::config("an IPv6 address in the URL must be followed by :port or nothing")
498            })?),
499        };
500        (format!("[{addr}]"), port)
501    } else {
502        match hostport.rsplit_once(':') {
503            Some((h, p)) => (percent_decode(h, "host")?, Some(p)),
504            None => (percent_decode(hostport, "host")?, None),
505        }
506    };
507    if !host.is_empty() {
508        config = config.host(&host);
509    }
510    if let Some(port) = port {
511        config.port = parse_port(port)?;
512    }
513    if let Some(db) = path.filter(|p| !p.is_empty()) {
514        config.dbname = Some(percent_decode(db, "database name")?);
515    }
516
517    let mut sslmode = None;
518    let mut sslrootcert = None;
519    for pair in query.unwrap_or("").split('&').filter(|p| !p.is_empty()) {
520        let (key, value) = pair.split_once('=').ok_or_else(|| {
521            Error::config(format!(
522                "the URL parameter {pair:?} has no value; write {pair}=value"
523            ))
524        })?;
525        let value = percent_decode(value, key)?;
526        match key {
527            "sslmode" => sslmode = Some(value),
528            "sslrootcert" => sslrootcert = Some(value),
529            "host" => config = config.host(&value),
530            "port" => config.port = parse_port(&value)?,
531            "user" => config.user = Some(value),
532            "password" => config.password = Some(value),
533            "require_auth" => config.require_auth = Some(parse_auth_methods(&value)?),
534            "dbname" => config.dbname = Some(value),
535            "application_name" => config.application_name = Some(value),
536            "connect_timeout" => {
537                let secs: u64 = value.parse().ok().filter(|&s| s > 0).ok_or_else(|| {
538                    Error::config(format!(
539                        "connect_timeout={value} is not a whole number of seconds above zero"
540                    ))
541                })?;
542                config.connect_timeout = Duration::from_secs(secs);
543            }
544            other => {
545                return Err(Error::config(format!(
546                    "the URL parameter {other:?} is not supported; the supported ones are \
547                     sslmode, sslrootcert, host, port, user, password, dbname, \
548                     application_name, connect_timeout and require_auth"
549                )))
550            }
551        }
552    }
553
554    let verify = || -> Result<Tls, Error> {
555        match sslrootcert.as_deref() {
556            None | Some("system") => Ok(Tls::Verify(TlsConnector::with_system_roots().map_err(
557                |e| {
558                    Error::io(
559                        ErrorKind::Config,
560                        "cannot load the machine's certificate authorities for sslmode",
561                        e,
562                    )
563                },
564            )?)),
565            Some(path) => {
566                let pem = std::fs::read(path).map_err(|e| {
567                    Error::io(
568                        ErrorKind::Config,
569                        format!("cannot read sslrootcert {path:?}"),
570                        e,
571                    )
572                })?;
573                let connector = TlsConnector::with_root_pem(&pem).map_err(|e| {
574                    Error::io(
575                        ErrorKind::Config,
576                        format!("sslrootcert {path:?} holds no usable certificate"),
577                        e,
578                    )
579                })?;
580                Ok(Tls::Verify(connector))
581            }
582        }
583    };
584    match sslmode.as_deref() {
585        None if sslrootcert.is_some() => config.tls = Some(verify()?),
586        None => {}
587        Some("disable") => config.tls = Some(Tls::Disable),
588        Some("require" | "verify-ca" | "verify-full") => config.tls = Some(verify()?),
589        Some(mode @ ("prefer" | "allow")) => {
590            return Err(Error::config(format!(
591                "sslmode={mode} would silently connect without encryption when TLS fails; \
592                 use sslmode=verify-full to require TLS, or sslmode=disable on a trusted network"
593            )))
594        }
595        Some(other) => {
596            return Err(Error::config(format!(
597            "sslmode={other} is not a known mode; use disable, require, verify-ca or verify-full"
598        )))
599        }
600    }
601    Ok(config)
602}
603
604fn parse_auth_methods(list: &str) -> Result<Vec<AuthMethod>, Error> {
605    let all = [
606        AuthMethod::None,
607        AuthMethod::Password,
608        AuthMethod::Md5,
609        AuthMethod::ScramSha256,
610    ];
611    list.split(',')
612        .map(|name| {
613            if name.starts_with('!') {
614                return Err(Error::config(format!(
615                    "require_auth={list}: giong-postgres takes the methods to allow, not the ones \
616                     to refuse (libpq's {name:?}); list the allowed ones, such as \
617                     require_auth=scram-sha-256"
618                )));
619            }
620            all.into_iter().find(|m| m.name() == name).ok_or_else(|| {
621                Error::config(format!(
622                    "require_auth={list}: {name:?} is not a method giong-postgres knows; use \
623                     scram-sha-256, md5, password or none, separated by commas"
624                ))
625            })
626        })
627        .collect()
628}
629
630fn parse_port(port: &str) -> Result<u16, Error> {
631    port.parse().ok().filter(|&p| p != 0).ok_or_else(|| {
632        Error::config(format!(
633            "the port {port:?} in the URL is not a number from 1 to 65535"
634        ))
635    })
636}
637
638#[cfg(test)]
639mod tests {
640    use super::*;
641
642    #[test]
643    fn a_config_without_its_password_keeps_everything_else() {
644        let c = Config::from_url("postgres://app:secret@db.internal:6543/shop?sslmode=disable")
645            .unwrap();
646        let bare = c.without_password();
647        assert_eq!(bare.password, None);
648        assert!(!Arc::ptr_eq(&bare.scram_keys, &c.scram_keys));
649        assert_eq!(c.password.as_deref(), Some("secret"));
650        assert_eq!((&bare.host, bare.port), (&c.host, c.port));
651        assert_eq!(bare.user, c.user);
652        assert!(bare.tls_connector().unwrap().is_none());
653    }
654
655    #[test]
656    fn a_full_url_is_read() {
657        let c = Config::from_url(
658            "postgres://app%40corp:p%3Ass%40w@db.internal:6543/shop%20db?application_name=api&connect_timeout=3&sslmode=disable",
659        )
660        .unwrap();
661        assert_eq!(c.host, Host::Tcp("db.internal".into()));
662        assert_eq!(c.port, 6543);
663        assert_eq!(c.user.as_deref(), Some("app@corp"));
664        assert_eq!(c.password.as_deref(), Some("p:ss@w"));
665        assert_eq!(c.dbname.as_deref(), Some("shop db"));
666        assert_eq!(c.application_name.as_deref(), Some("api"));
667        assert_eq!(c.connect_timeout, Duration::from_secs(3));
668        assert!(c.tls_connector().unwrap().is_none());
669        assert!(!format!("{c:?}").contains("p:ss@w"));
670    }
671
672    #[test]
673    fn hosts_can_be_ipv6_or_sockets() {
674        let c = Config::from_url("postgresql://u@[::1]:5433").unwrap();
675        assert_eq!(c.host, Host::Tcp("::1".into()));
676        assert_eq!(c.port, 5433);
677        assert_eq!(c.target(), "[::1]:5433");
678        assert!(c.is_local());
679
680        let c = Config::from_url("postgres:///shop?host=/var/run/postgresql&user=u").unwrap();
681        assert_eq!(c.host, Host::Unix("/var/run/postgresql".into()));
682        assert_eq!(c.target(), "/var/run/postgresql/.s.PGSQL.5432");
683        let c = Config::from_url("postgres://u@%2Ftmp/shop").unwrap();
684        assert_eq!(c.host, Host::Unix("/tmp".into()));
685    }
686
687    #[test]
688    fn tls_is_on_for_remote_hosts_unless_disabled() {
689        assert!(Config::new()
690            .host("127.0.0.1")
691            .tls_connector()
692            .unwrap()
693            .is_none());
694        assert!(Config::new()
695            .host("localhost")
696            .tls_connector()
697            .unwrap()
698            .is_none());
699        let cert = rcgen::generate_simple_self_signed(vec!["localhost".into()]).unwrap();
700        let connector = TlsConnector::with_root_pem(cert.cert.pem().as_bytes()).unwrap();
701        let unix = Config::new()
702            .host("/tmp")
703            .tls(Tls::Verify(connector.clone()));
704        assert!(unix.tls_connector().unwrap().is_none());
705        let local = Config::new().host("127.0.0.1").tls(Tls::Verify(connector));
706        assert!(local.tls_connector().unwrap().is_some());
707        assert!(Config::new()
708            .host("10.1.2.3")
709            .tls(Tls::Disable)
710            .tls_connector()
711            .unwrap()
712            .is_none());
713        // The machine's authorities: present here, so TLS is on.
714        if let Ok(Some(_)) = Config::new().host("db.example.com").tls_connector() {
715        } else {
716            panic!("expected TLS for a remote host");
717        }
718    }
719
720    #[test]
721    fn bad_urls_say_what_is_wrong() {
722        let err = |url: &str| Config::from_url(url).unwrap_err().to_string();
723        assert!(err("mysql://x").contains("postgres://"));
724        assert!(err("postgres://u@h/db?sslmode=prefer").contains("silently"));
725        assert!(err("postgres://u@h/db?sslmode=bogus").contains("not a known mode"));
726        assert!(err("postgres://u@h/db?sslcert=x").contains("not supported"));
727        assert!(err("postgres://u@h:99999/db").contains("1 to 65535"));
728        assert!(err("postgres://u@h1,h2/db").contains("several hosts"));
729        assert!(err("postgres://u@[::1/db").contains("closing"));
730        assert!(err("postgres://u:%zz@h/db").contains("%25"));
731        assert!(err("postgres://u@h/db?connect_timeout=0").contains("above zero"));
732        assert!(err("postgres://u@h/db?sslrootcert=/nonexistent/ca.pem").contains("cannot read"));
733        assert!(err("postgres://u@h/db?flag").contains("no value"));
734    }
735
736    #[test]
737    fn statement_timeout_can_be_left_to_the_server() {
738        let c = Config::new();
739        assert_eq!(c.statement_timeout, Some(Duration::from_secs(30)));
740        let c = c.statement_timeout(Duration::from_secs(5));
741        assert_eq!(c.statement_timeout, Some(Duration::from_secs(5)));
742        assert_eq!(c.statement_timeout(None).statement_timeout, None);
743    }
744
745    #[test]
746    fn require_auth_reads_libpq_names() {
747        let c = Config::from_url("postgres://u@h/db?require_auth=scram-sha-256,md5").unwrap();
748        assert_eq!(
749            c.require_auth,
750            Some(vec![AuthMethod::ScramSha256, AuthMethod::Md5])
751        );
752        let err = |url: &str| Config::from_url(url).unwrap_err().to_string();
753        assert!(err("postgres://u@h/db?require_auth=!md5").contains("not the ones"));
754        assert!(err("postgres://u@h/db?require_auth=gss").contains("not a method"));
755    }
756}