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