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