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