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