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    pub(crate) batch_reads: bool,
125}
126
127impl Default for Config {
128    fn default() -> Self {
129        Self::new()
130    }
131}
132
133/// Whether `host` names a Unix socket rather than a server on the network:
134/// an absolute path, which on Windows may also start with a drive letter
135/// (`C:\run\...`), as Windows' own Unix sockets are named.
136fn is_socket_path(host: &str) -> bool {
137    host.starts_with('/') || (cfg!(windows) && std::path::Path::new(host).is_absolute())
138}
139
140impl Config {
141    /// The server and database, without user or password, for diagnostics:
142    /// `db.internal:5432/app`.
143    pub(crate) fn describe(&self) -> String {
144        let server = match &self.host {
145            Host::Tcp(host) if host.contains(':') => format!("[{host}]:{}", self.port),
146            Host::Tcp(host) => format!("{host}:{}", self.port),
147            Host::Unix(dir) => format!("{}/.s.PGSQL.{}", dir.display(), self.port),
148        };
149        match &self.dbname {
150            Some(db) => format!("{server}/{db}"),
151            None => server,
152        }
153    }
154
155    /// Settings for `localhost:5432`, with no user yet and the default
156    /// limits.
157    pub fn new() -> Self {
158        Self {
159            host: Host::Tcp("localhost".to_owned()),
160            port: 5432,
161            user: None,
162            password: None,
163            dbname: None,
164            application_name: None,
165            params: Vec::new(),
166            tls: None,
167            system_roots: Arc::new(OnceLock::new()),
168            require_auth: None,
169            scram_keys: Arc::default(),
170            connect_timeout: Duration::from_secs(10),
171            statement_timeout: Some(Duration::from_secs(30)),
172            max_result_size: 64 << 20,
173            statement_cache: 256,
174            batch_reads: false,
175        }
176    }
177
178    /// The server's host: a DNS name, an IP address, or the absolute path of
179    /// the directory holding its Unix socket (such as
180    /// `/var/run/postgresql`, or on Windows `C:\pgsql\run`: PostgreSQL 13
181    /// and later listen on Unix sockets there too).
182    pub fn host(mut self, host: &str) -> Self {
183        self.host = if is_socket_path(host) {
184            Host::Unix(PathBuf::from(host))
185        } else {
186            let host = host
187                .strip_prefix('[')
188                .and_then(|h| h.strip_suffix(']'))
189                .unwrap_or(host);
190            Host::Tcp(host.to_owned())
191        };
192        self
193    }
194
195    /// The server's port, 5432 by default. For a Unix socket it picks the
196    /// socket file, `.s.PGSQL.<port>`.
197    pub fn port(mut self, port: u16) -> Self {
198        self.port = port;
199        self
200    }
201
202    /// The user to log in as. Required.
203    pub fn user(mut self, user: &str) -> Self {
204        self.user = Some(user.to_owned());
205        self
206    }
207
208    /// The password, if the server asks for one.
209    pub fn password(mut self, password: &str) -> Self {
210        self.password = Some(password.to_owned());
211        self.scram_keys = Arc::default();
212        self
213    }
214
215    /// The database; the server uses the user's name when it is not set.
216    /// In a URL it is the path, or the `dbname` parameter.
217    pub fn database(mut self, database: &str) -> Self {
218        self.dbname = Some(database.to_owned());
219        self
220    }
221
222    /// The name the server shows for this connection in `pg_stat_activity`
223    /// and in its logs.
224    pub fn application_name(mut self, name: &str) -> Self {
225        self.application_name = Some(name.to_owned());
226        self
227    }
228
229    /// Sets a server setting for the whole session when connecting, such as
230    /// `search_path` or `TimeZone`.
231    pub fn param(mut self, name: &str, value: &str) -> Self {
232        self.params.push((name.to_owned(), value.to_owned()));
233        self
234    }
235
236    /// Whether and how to use TLS (see [the type's documentation](Self) for
237    /// what happens when this is not set).
238    pub fn tls(mut self, tls: Tls) -> Self {
239        self.tls = Some(tls);
240        self
241    }
242
243    /// The only authentication methods the server may use; by default, any
244    /// this crate supports. Connecting fails with
245    /// [`ErrorKind::Auth`](crate::ErrorKind::Auth), before anything is sent
246    /// for the password, when the server asks for another method or lets the
247    /// connection in without one.
248    ///
249    /// Without TLS (over a Unix socket, to a loopback address, or with
250    /// `sslmode=disable`), nothing proves that the server is the real one: an
251    /// impostor can ask for MD5 instead of SCRAM and attack the answer
252    /// offline, or let the client in without asking anything.
253    /// `require_auth(&[AuthMethod::ScramSha256])` rules that out, since SCRAM
254    /// makes the server prove that it knows the password too. In a URL:
255    /// `require_auth=scram-sha-256` (a comma-separated list, as in libpq,
256    /// without libpq's `!` negations).
257    pub fn require_auth(mut self, methods: &[AuthMethod]) -> Self {
258        self.require_auth = Some(methods.to_vec());
259        self
260    }
261
262    /// The longest that opening a connection may take, from name resolution
263    /// to the end of authentication: 10 seconds by default.
264    pub fn connect_timeout(mut self, timeout: Duration) -> Self {
265        self.connect_timeout = timeout;
266        self
267    }
268
269    /// The longest a statement may run on the server before the server
270    /// cancels it: 30 seconds by default.
271    ///
272    /// It is sent as the session's `statement_timeout` when connecting, so the
273    /// server enforces it exactly, and only on the statement that runs too
274    /// long (SQLSTATE `57014`). It is rounded up to whole milliseconds and
275    /// must be from 1 ms to `i32::MAX` milliseconds (24.8 days): connecting
276    /// fails with [`ErrorKind::Config`](crate::ErrorKind::Config) otherwise.
277    /// Raise it for the connections that run migrations or reports, rather
278    /// than turning it off with `SET`.
279    ///
280    /// `None` sends nothing, leaving the limit to the server's own setting,
281    /// which is no limit unless someone set one. Through a connection pooler
282    /// such as PgBouncer, give `None` and set the limit on the role
283    /// (`ALTER ROLE app SET statement_timeout = '30s'`): PgBouncer refuses a
284    /// connection that sends `statement_timeout`, and its settings that
285    /// accept it (`track_extra_parameters`, `ignore_startup_parameters`)
286    /// do not pass it on to the server (checked with PgBouncer 1.22).
287    pub fn statement_timeout(mut self, timeout: impl Into<Option<Duration>>) -> Self {
288        self.statement_timeout = timeout.into();
289        self
290    }
291
292    /// The largest result one statement may return, in bytes of row data:
293    /// 64 MiB by default. A larger result fails with
294    /// [`ErrorKind::TooLarge`](crate::ErrorKind::TooLarge), and the
295    /// connection stays usable.
296    pub fn max_result_size(mut self, bytes: usize) -> Self {
297        self.max_result_size = bytes;
298        self
299    }
300
301    /// How many prepared statements each connection keeps, 256 by default.
302    ///
303    /// Every statement is prepared on the server the first time a connection
304    /// runs it, and kept, so running it again takes one round trip instead
305    /// of two. The least recently used statement is closed when the cache is
306    /// full. 0 prepares and closes every statement each time it runs, which
307    /// takes two round trips; the statement is still a named one, prepared
308    /// in one request and run in the next, so 0 does not make a connection
309    /// pooler in transaction mode work: that needs PgBouncer 1.21 or newer
310    /// with `max_prepared_statements` above 0, which supports any cache
311    /// size.
312    pub fn statement_cache_capacity(mut self, statements: usize) -> Self {
313        self.statement_cache = statements;
314        self
315    }
316
317    /// Lets [`Pool`](crate::Pool) send the `SELECT` statements it runs on
318    /// its shared connections (`query`, `query_one`, `query_opt`) in batches:
319    /// off by default.
320    ///
321    /// The server sends its answers to the statements before one `Sync`
322    /// message in one write, where it otherwise makes a write, and wakes the
323    /// client, for each statement; when it is the busy side, it then answers
324    /// more statements a second (on PostgreSQL 16, about 50% more one-row
325    /// `SELECT`s, measured with pgbench in batches of 16). A batch is the
326    /// `SELECT`s that are waiting to be written to one connection when it
327    /// writes, at most 16: a statement never waits for others to join it.
328    ///
329    /// A `SELECT` whose text contains `set_config` runs alone, never in a
330    /// batch: the statements of a batch share one transaction, and a
331    /// transaction-local setting (`set_config(name, value, true)`, as
332    /// row-level security set up per request uses) would apply to the
333    /// statements of other tasks after it. The text is matched in any case,
334    /// quoted strings and comments included; a false match only costs the
335    /// statement its batch. **Do not turn it on if functions that
336    /// statements call make such settings** (`set_config(.., true)` or
337    /// `SET LOCAL` inside a function): those calls cannot be seen in the
338    /// statement's text.
339    ///
340    /// What changes for a statement in a batch:
341    ///
342    /// * It runs in one transaction with the others, made read-only first
343    ///   (`set_config('transaction_read_only', 'on', true)`). A `SELECT`
344    ///   that writes (one that calls a function that writes, or takes a row
345    ///   lock with `FOR UPDATE`) fails with the server's `25006` and is sent
346    ///   again on its own, where it runs as it would without batches; it is
347    ///   not batched again on that connection.
348    /// * When a statement in a batch fails, or the batch's commit does (a
349    ///   deferred constraint on a temporary table, say), the batch's
350    ///   transaction is rolled back: the statement that failed fails, and
351    ///   every other statement of the batch is sent again, on its own,
352    ///   whether it had run (what it did was rolled back) or the server had
353    ///   skipped it. What a transaction's rollback does not undo happens
354    ///   twice then: a sequence advanced by `nextval` (allowed on temporary
355    ///   sequences) is advanced again, and a session-level advisory lock
356    ///   (`pg_advisory_lock`, `pg_try_advisory_lock`) is taken twice, so one
357    ///   unlock leaves it held. One statement that fails on its input (a bad
358    ///   `$1::int4`, say) also makes up to 15 statements before it run
359    ///   again: bounded, but more work for a database that is the limit.
360    /// * Its answer arrives when the batch ends, once its commit is known:
361    ///   a statement waits for up to 15 others that were written after it.
362    ///   They run one after another on the server either way, so this is
363    ///   added only to the statements early in a batch; keep slow statements
364    ///   and fast ones in different pools when that matters.
365    /// * `now()` and `transaction_timestamp()` give the time the batch
366    ///   started, and a transaction-scoped advisory lock is held until the
367    ///   batch ends.
368    /// * The locks its statements take are held until the batch ends, so a
369    ///   statement of a batch waits at most 50 ms for a lock: past that, or
370    ///   when it fails with a deadlock (`40P01`) or a serialization failure
371    ///   (`40001`), the batch is rolled back and the statement is sent
372    ///   again alone, where it waits as it would without batches (a
373    ///   `lock_timeout` shorter than 50 ms then applies to that run). Without
374    ///   that, a batch could deadlock with a transaction that the same
375    ///   statements one by one never would (a migration that locks two
376    ///   tables the batch reads), and the server would roll one of them
377    ///   back.
378    pub fn batch_reads(mut self, batch: bool) -> Self {
379        self.batch_reads = batch;
380        self
381    }
382
383    /// Reads a connection URL:
384    ///
385    /// ```text
386    /// postgres://user:password@host:port/dbname?param=value&...
387    /// ```
388    ///
389    /// `postgresql://` works too. User, password and database are
390    /// percent-decoded. The host can be an IPv6 address in brackets, or, as
391    /// with libpq, empty with the socket directory in a `host` parameter:
392    /// `postgres:///shop?host=/var/run/postgresql`.
393    ///
394    /// The parameters understood are `sslmode`, `sslrootcert`, `host`,
395    /// `port`, `user`, `password`, `dbname`, `application_name`,
396    /// `connect_timeout` (seconds) and `require_auth` (see
397    /// [`require_auth`](Self::require_auth)); any other is an error rather
398    /// than being ignored. `sslmode` is `disable`, or `require`, `verify-ca` or
399    /// `verify-full`, which all check the certificate and the host name
400    /// (stricter than libpq, which checks nothing for `require`).
401    /// `sslrootcert` is a PEM file of authorities to trust instead of the
402    /// machine's, or `system`.
403    ///
404    /// The user name, the password and the database name are
405    /// percent-decoded: write `/` as `%2F`, `?` as `%3F` and `@` as `%40`
406    /// in them. A URL with an `@` after the first `/` or `?` that would
407    /// otherwise not read, or with an `@` in its database name, is refused
408    /// with a message that quotes none of it, since a piece of a password
409    /// with an unescaped `/` or `?` would end up in the message (or, as the
410    /// database name, be sent to the wrong host).
411    pub fn from_url(url: &str) -> Result<Self, Error> {
412        parse_url(url)
413    }
414
415    /// The URL this config was read from, or would be, without the password,
416    /// for messages.
417    pub(crate) fn target(&self) -> String {
418        match &self.host {
419            Host::Tcp(h) if h.contains(':') => format!("[{h}]:{}", self.port),
420            Host::Tcp(h) => format!("{h}:{}", self.port),
421            Host::Unix(dir) => self.socket_path(dir).display().to_string(),
422        }
423    }
424
425    pub(crate) fn socket_path(&self, dir: &Path) -> PathBuf {
426        dir.join(format!(".s.PGSQL.{}", self.port))
427    }
428
429    /// The same settings without the password, for cancel requests, which
430    /// do not authenticate.
431    pub(crate) fn without_password(&self) -> Config {
432        Config {
433            password: None,
434            // The cached SCRAM keys would log in as well as the password.
435            scram_keys: Arc::default(),
436            ..self.clone()
437        }
438    }
439
440    /// Whether the host is this machine: a Unix socket or a loopback address.
441    pub(crate) fn is_local(&self) -> bool {
442        match &self.host {
443            Host::Unix(_) => true,
444            Host::Tcp(h) => {
445                h.eq_ignore_ascii_case("localhost")
446                    || h.parse::<IpAddr>().is_ok_and(|ip| match ip {
447                        IpAddr::V4(v4) => v4.is_loopback(),
448                        IpAddr::V6(v6) => {
449                            v6.is_loopback()
450                                || v6.to_ipv4_mapped().is_some_and(|v4| v4.is_loopback())
451                        }
452                    })
453            }
454        }
455    }
456
457    /// The connector to use, or `None` for no TLS.
458    pub(crate) fn tls_connector(&self) -> Result<Option<TlsConnector>, Error> {
459        match (&self.tls, &self.host) {
460            (_, Host::Unix(_)) | (Some(Tls::Disable), _) => Ok(None),
461            (Some(Tls::Verify(connector)), _) => Ok(Some(connector.clone())),
462            (None, _) if self.is_local() => Ok(None),
463            (None, Host::Tcp(host)) => {
464                let roots = self
465                    .system_roots
466                    .get_or_init(|| TlsConnector::with_system_roots().map_err(|e| e.to_string()));
467                match roots {
468                    Ok(connector) => Ok(Some(connector.clone())),
469                    Err(e) => Err(Error::new(
470                        ErrorKind::Config,
471                        format!(
472                            "a connection to {host} uses TLS checked against the machine's \
473                             certificate authorities, but they could not be loaded ({e}); give \
474                             the server's authority with sslrootcert=/path/ca.pem or \
475                             Config::tls, or add sslmode=disable if the network is trusted"
476                        ),
477                    )),
478                }
479            }
480        }
481    }
482}
483
484impl fmt::Debug for Config {
485    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
486        f.debug_struct("Config")
487            .field("host", &self.host)
488            .field("port", &self.port)
489            .field("user", &self.user)
490            .field("password", &self.password.as_ref().map(|_| "<hidden>"))
491            .field("dbname", &self.dbname)
492            .field("application_name", &self.application_name)
493            .field("params", &self.params)
494            .field("tls", &self.tls)
495            .field("require_auth", &self.require_auth)
496            .field("connect_timeout", &self.connect_timeout)
497            .field("statement_timeout", &self.statement_timeout)
498            .field("max_result_size", &self.max_result_size)
499            .field("statement_cache_capacity", &self.statement_cache)
500            .finish()
501    }
502}
503
504impl FromStr for Config {
505    type Err = Error;
506
507    fn from_str(url: &str) -> Result<Self, Error> {
508        parse_url(url)
509    }
510}
511
512fn percent_decode(s: &str, what: &str) -> Result<String, Error> {
513    let bytes = s.as_bytes();
514    let mut out = Vec::with_capacity(bytes.len());
515    let mut i = 0;
516    while i < bytes.len() {
517        if bytes[i] == b'%' {
518            let hex = bytes
519                .get(i + 1..i + 3)
520                .and_then(|h| std::str::from_utf8(h).ok())
521                .filter(|h| h.bytes().all(|c| c.is_ascii_hexdigit()))
522                .and_then(|h| u8::from_str_radix(h, 16).ok())
523                .ok_or_else(|| {
524                    Error::config(format!(
525                        "the {what} in the URL has a '%' that is not followed by two hex digits; \
526                         write a literal % as %25"
527                    ))
528                })?;
529            out.push(hex);
530            i += 3;
531        } else {
532            out.push(bytes[i]);
533            i += 1;
534        }
535    }
536    String::from_utf8(out)
537        .map_err(|_| Error::config(format!("the {what} in the URL is not UTF-8 once decoded")))
538}
539
540fn parse_url(url: &str) -> Result<Config, Error> {
541    // An `@` after the first `/` or `?` is most likely the end of a password
542    // holding an unescaped `/` or `?`: the URL is cut in the wrong place, so
543    // a piece of the password would be read as the port, the database name
544    // or a parameter, and quoted in the error, or sent to the server as the
545    // database name. Say what to fix instead, quoting nothing.
546    let after_cut = |accepted: bool| {
547        let Some((_, rest)) = url.split_once("://") else {
548            return false;
549        };
550        let Some(cut) = rest.find(['/', '?']) else {
551            return false;
552        };
553        if accepted {
554            // Read without an error: only a database name holding an `@`
555            // gives it away (parameters may hold one).
556            let before_query = rest.split_once('?').map_or(rest, |(r, _)| r);
557            before_query.get(cut..).is_some_and(|db| db.contains('@'))
558        } else {
559            rest[cut..].contains('@')
560        }
561    };
562    let cut_password = |read: &str| {
563        Error::config(format!(
564            "the URL {read}has an @ after a / or ?: if the password (or the user name) holds one \
565             of them, percent-encode it (/ as %2F, ? as %3F, @ as %40); write an @ in the \
566             database name as %40 too"
567        ))
568    };
569    match parse(url) {
570        Ok(_) if after_cut(true) => Err(cut_password("")),
571        Err(_) if after_cut(false) => Err(cut_password("could not be read, and it ")),
572        result => result,
573    }
574}
575
576fn parse(url: &str) -> Result<Config, Error> {
577    let rest = url
578        .strip_prefix("postgres://")
579        .or_else(|| url.strip_prefix("postgresql://"))
580        .ok_or_else(|| {
581            Error::config(
582                "a connection URL starts with postgres:// or postgresql://, \
583                 as in postgres://user:password@host:5432/dbname",
584            )
585        })?;
586    let (rest, query) = match rest.split_once('?') {
587        Some((r, q)) => (r, Some(q)),
588        None => (rest, None),
589    };
590    let (authority, path) = match rest.split_once('/') {
591        Some((a, p)) => (a, Some(p)),
592        None => (rest, None),
593    };
594    let mut config = Config::new();
595    let hostport = match authority.rsplit_once('@') {
596        Some((userinfo, hostport)) => {
597            let (user, password) = match userinfo.split_once(':') {
598                Some((u, p)) => (u, Some(p)),
599                None => (userinfo, None),
600            };
601            if !user.is_empty() {
602                config.user = Some(percent_decode(user, "user")?);
603            }
604            if let Some(p) = password {
605                config.password = Some(percent_decode(p, "password")?);
606            }
607            hostport
608        }
609        None => authority,
610    };
611    if hostport.contains(',') {
612        return Err(Error::config(
613            "the URL names several hosts; giong-postgres connects to one, so give one host",
614        ));
615    }
616    let (host, port) = if let Some(v6) = hostport.strip_prefix('[') {
617        let (addr, after) = v6.split_once(']').ok_or_else(|| {
618            Error::config("an IPv6 address in the URL is missing its closing ']'")
619        })?;
620        let port = match after {
621            "" => None,
622            p => Some(p.strip_prefix(':').ok_or_else(|| {
623                Error::config("an IPv6 address in the URL must be followed by :port or nothing")
624            })?),
625        };
626        (format!("[{addr}]"), port)
627    } else {
628        match hostport.rsplit_once(':') {
629            Some((h, p)) => (percent_decode(h, "host")?, Some(p)),
630            None => (percent_decode(hostport, "host")?, None),
631        }
632    };
633    if !host.is_empty() {
634        config = config.host(&host);
635    }
636    if let Some(port) = port {
637        config.port = parse_port(port)?;
638    }
639    if let Some(db) = path.filter(|p| !p.is_empty()) {
640        config.dbname = Some(percent_decode(db, "database name")?);
641    }
642
643    let mut sslmode = None;
644    let mut sslrootcert = None;
645    for pair in query.unwrap_or("").split('&').filter(|p| !p.is_empty()) {
646        let (key, value) = pair.split_once('=').ok_or_else(|| {
647            Error::config(format!(
648                "the URL parameter {pair:?} has no value; write {pair}=value"
649            ))
650        })?;
651        let value = percent_decode(value, key)?;
652        match key {
653            "sslmode" => sslmode = Some(value),
654            "sslrootcert" => sslrootcert = Some(value),
655            "host" => config = config.host(&value),
656            "port" => config.port = parse_port(&value)?,
657            "user" => config.user = Some(value),
658            "password" => config.password = Some(value),
659            "require_auth" => config.require_auth = Some(parse_auth_methods(&value)?),
660            "dbname" => config.dbname = Some(value),
661            "application_name" => config.application_name = Some(value),
662            "connect_timeout" => {
663                let secs: u64 = value.parse().ok().filter(|&s| s > 0).ok_or_else(|| {
664                    Error::config(format!(
665                        "connect_timeout={value} is not a whole number of seconds above zero"
666                    ))
667                })?;
668                config.connect_timeout = Duration::from_secs(secs);
669            }
670            other => {
671                return Err(Error::config(format!(
672                    "the URL parameter {other:?} is not supported; the supported ones are \
673                     sslmode, sslrootcert, host, port, user, password, dbname, \
674                     application_name, connect_timeout and require_auth"
675                )))
676            }
677        }
678    }
679
680    let verify = || -> Result<Tls, Error> {
681        match sslrootcert.as_deref() {
682            None | Some("system") => Ok(Tls::Verify(TlsConnector::with_system_roots().map_err(
683                |e| {
684                    Error::io(
685                        ErrorKind::Config,
686                        "cannot load the machine's certificate authorities for sslmode",
687                        e,
688                    )
689                },
690            )?)),
691            Some(path) => {
692                let pem = std::fs::read(path).map_err(|e| {
693                    Error::io(
694                        ErrorKind::Config,
695                        format!("cannot read sslrootcert {path:?}"),
696                        e,
697                    )
698                })?;
699                let connector = TlsConnector::with_root_pem(&pem).map_err(|e| {
700                    Error::io(
701                        ErrorKind::Config,
702                        format!("sslrootcert {path:?} holds no usable certificate"),
703                        e,
704                    )
705                })?;
706                Ok(Tls::Verify(connector))
707            }
708        }
709    };
710    match sslmode.as_deref() {
711        None if sslrootcert.is_some() => config.tls = Some(verify()?),
712        None => {}
713        Some("disable") => config.tls = Some(Tls::Disable),
714        Some("require" | "verify-ca" | "verify-full") => config.tls = Some(verify()?),
715        Some(mode @ ("prefer" | "allow")) => {
716            return Err(Error::config(format!(
717                "sslmode={mode} would silently connect without encryption when TLS fails; \
718                 use sslmode=verify-full to require TLS, or sslmode=disable on a trusted network"
719            )))
720        }
721        Some(other) => {
722            return Err(Error::config(format!(
723            "sslmode={other} is not a known mode; use disable, require, verify-ca or verify-full"
724        )))
725        }
726    }
727    Ok(config)
728}
729
730fn parse_auth_methods(list: &str) -> Result<Vec<AuthMethod>, Error> {
731    let all = [
732        AuthMethod::None,
733        AuthMethod::Password,
734        AuthMethod::Md5,
735        AuthMethod::ScramSha256,
736    ];
737    list.split(',')
738        .map(|name| {
739            if name.starts_with('!') {
740                return Err(Error::config(format!(
741                    "require_auth={list}: giong-postgres takes the methods to allow, not the ones \
742                     to refuse (libpq's {name:?}); list the allowed ones, such as \
743                     require_auth=scram-sha-256"
744                )));
745            }
746            all.into_iter().find(|m| m.name() == name).ok_or_else(|| {
747                Error::config(format!(
748                    "require_auth={list}: {name:?} is not a method giong-postgres knows; use \
749                     scram-sha-256, md5, password or none, separated by commas"
750                ))
751            })
752        })
753        .collect()
754}
755
756fn parse_port(port: &str) -> Result<u16, Error> {
757    port.parse().ok().filter(|&p| p != 0).ok_or_else(|| {
758        Error::config(format!(
759            "the port {port:?} in the URL is not a number from 1 to 65535"
760        ))
761    })
762}
763
764#[cfg(test)]
765mod tests {
766    use super::*;
767
768    #[test]
769    fn a_config_without_its_password_keeps_everything_else() {
770        let c = Config::from_url("postgres://app:secret@db.internal:6543/shop?sslmode=disable")
771            .unwrap();
772        let bare = c.without_password();
773        assert_eq!(bare.password, None);
774        assert!(!Arc::ptr_eq(&bare.scram_keys, &c.scram_keys));
775        assert_eq!(c.password.as_deref(), Some("secret"));
776        assert_eq!((&bare.host, bare.port), (&c.host, c.port));
777        assert_eq!(bare.user, c.user);
778        assert!(bare.tls_connector().unwrap().is_none());
779    }
780
781    #[test]
782    fn a_full_url_is_read() {
783        let c = Config::from_url(
784            "postgres://app%40corp:p%3Ass%40w@db.internal:6543/shop%20db?application_name=api&connect_timeout=3&sslmode=disable",
785        )
786        .unwrap();
787        assert_eq!(c.host, Host::Tcp("db.internal".into()));
788        assert_eq!(c.port, 6543);
789        assert_eq!(c.user.as_deref(), Some("app@corp"));
790        assert_eq!(c.password.as_deref(), Some("p:ss@w"));
791        assert_eq!(c.dbname.as_deref(), Some("shop db"));
792        assert_eq!(c.application_name.as_deref(), Some("api"));
793        assert_eq!(c.connect_timeout, Duration::from_secs(3));
794        assert!(c.tls_connector().unwrap().is_none());
795        assert!(!format!("{c:?}").contains("p:ss@w"));
796    }
797
798    /// On Windows a path with a drive letter names a socket directory too.
799    #[cfg(windows)]
800    #[test]
801    fn windows_paths_are_socket_directories() {
802        let c = Config::new().host(r"C:\pgsql\run");
803        assert_eq!(c.host, Host::Unix(r"C:\pgsql\run".into()));
804        let c = Config::new().host("db.internal");
805        assert_eq!(c.host, Host::Tcp("db.internal".into()));
806    }
807
808    #[test]
809    fn hosts_can_be_ipv6_or_sockets() {
810        let c = Config::from_url("postgresql://u@[::1]:5433").unwrap();
811        assert_eq!(c.host, Host::Tcp("::1".into()));
812        assert_eq!(c.port, 5433);
813        assert_eq!(c.target(), "[::1]:5433");
814        assert!(c.is_local());
815
816        let c = Config::from_url("postgres:///shop?host=/var/run/postgresql&user=u").unwrap();
817        assert_eq!(c.host, Host::Unix("/var/run/postgresql".into()));
818        // The socket file's path, joined as the system joins paths.
819        let socket = std::path::Path::new("/var/run/postgresql").join(".s.PGSQL.5432");
820        assert_eq!(c.target(), socket.display().to_string());
821        let c = Config::from_url("postgres://u@%2Ftmp/shop").unwrap();
822        assert_eq!(c.host, Host::Unix("/tmp".into()));
823    }
824
825    #[test]
826    fn tls_is_on_for_remote_hosts_unless_disabled() {
827        assert!(Config::new()
828            .host("127.0.0.1")
829            .tls_connector()
830            .unwrap()
831            .is_none());
832        assert!(Config::new()
833            .host("localhost")
834            .tls_connector()
835            .unwrap()
836            .is_none());
837        let cert = rcgen::generate_simple_self_signed(vec!["localhost".into()]).unwrap();
838        let connector = TlsConnector::with_root_pem(cert.cert.pem().as_bytes()).unwrap();
839        let unix = Config::new()
840            .host("/tmp")
841            .tls(Tls::Verify(connector.clone()));
842        assert!(unix.tls_connector().unwrap().is_none());
843        let local = Config::new().host("127.0.0.1").tls(Tls::Verify(connector));
844        assert!(local.tls_connector().unwrap().is_some());
845        assert!(Config::new()
846            .host("10.1.2.3")
847            .tls(Tls::Disable)
848            .tls_connector()
849            .unwrap()
850            .is_none());
851        // The machine's authorities: present here, so TLS is on.
852        if let Ok(Some(_)) = Config::new().host("db.example.com").tls_connector() {
853        } else {
854            panic!("expected TLS for a remote host");
855        }
856    }
857
858    #[test]
859    fn bad_urls_say_what_is_wrong() {
860        let err = |url: &str| Config::from_url(url).unwrap_err().to_string();
861        assert!(err("mysql://x").contains("postgres://"));
862        assert!(err("postgres://u@h/db?sslmode=prefer").contains("silently"));
863        assert!(err("postgres://u@h/db?sslmode=bogus").contains("not a known mode"));
864        assert!(err("postgres://u@h/db?sslcert=x").contains("not supported"));
865        assert!(err("postgres://u@h:99999/db").contains("1 to 65535"));
866        assert!(err("postgres://u@h1,h2/db").contains("several hosts"));
867        assert!(err("postgres://u@[::1/db").contains("closing"));
868        assert!(err("postgres://u:%zz@h/db").contains("%25"));
869        // A sign is not a hex digit (u8::from_str_radix takes "+5").
870        assert!(err("postgres://u:%+5@h/db").contains("%25"));
871        assert!(err("postgres://u@h/db?connect_timeout=0").contains("above zero"));
872        assert!(err("postgres://u@h/db?sslrootcert=/nonexistent/ca.pem").contains("cannot read"));
873        assert!(err("postgres://u@h/db?flag").contains("no value"));
874    }
875
876    #[test]
877    fn statement_timeout_can_be_left_to_the_server() {
878        let c = Config::new();
879        assert_eq!(c.statement_timeout, Some(Duration::from_secs(30)));
880        let c = c.statement_timeout(Duration::from_secs(5));
881        assert_eq!(c.statement_timeout, Some(Duration::from_secs(5)));
882        assert_eq!(c.statement_timeout(None).statement_timeout, None);
883    }
884
885    #[test]
886    fn require_auth_reads_libpq_names() {
887        let c = Config::from_url("postgres://u@h/db?require_auth=scram-sha-256,md5").unwrap();
888        assert_eq!(
889            c.require_auth,
890            Some(vec![AuthMethod::ScramSha256, AuthMethod::Md5])
891        );
892        let err = |url: &str| Config::from_url(url).unwrap_err().to_string();
893        assert!(err("postgres://u@h/db?require_auth=!md5").contains("not the ones"));
894        assert!(err("postgres://u@h/db?require_auth=gss").contains("not a method"));
895    }
896    #[test]
897    fn a_password_cut_by_an_unescaped_slash_or_question_mark_is_never_quoted() {
898        for url in [
899            "postgres://app:s3cr/et@db/x",
900            "postgres://app:pa?ss@db/x",
901            "postgres://app:se:cr/et@db/x",
902            "postgres://app:pa?ss=1@db",
903            "postgres://app:pa%zz/ss@db",
904            // Read without an error, these would connect to the host "app"
905            // with a piece of the password as the port and the rest, with
906            // the real host, as the database name.
907            "postgres://app:12/34@db/x",
908            "postgres://app:p@ss/word@db/x",
909        ] {
910            let e = Config::from_url(url).unwrap_err().to_string();
911            assert!(e.contains("percent-encode"), "{url}: {e}");
912            for piece in ["s3cr", "et", "pa", "ss", "cr", "zz", "12", "34", "word"] {
913                assert!(!e.contains(&format!("\"{piece}")), "{url}: {e}");
914                assert!(!e.contains(&format!("{piece}\"")), "{url}: {e}");
915            }
916        }
917        // An @ in a parameter is fine when the URL reads.
918        let c = Config::from_url("postgres://db/x?application_name=me@here").unwrap();
919        assert_eq!(c.application_name.as_deref(), Some("me@here"));
920        // Encoded, the same passwords work, and so does an @ in the
921        // database name.
922        let c = Config::from_url("postgres://app:s3cr%2Fet@db/x%40y").unwrap();
923        assert_eq!(c.password.as_deref(), Some("s3cr/et"));
924        assert_eq!(c.target(), "db:5432");
925        assert_eq!(c.dbname.as_deref(), Some("x@y"));
926    }
927}