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