1use 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#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
18#[non_exhaustive]
19pub enum AuthMethod {
20 None,
24 Password,
26 Md5,
28 ScramSha256,
30}
31
32impl AuthMethod {
33 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#[derive(Clone)]
49#[non_exhaustive]
50pub enum Tls {
51 Disable,
54 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 Tcp(String),
73 Unix(PathBuf),
75}
76
77#[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 pub(crate) require_auth: Option<Vec<AuthMethod>>,
118 pub(crate) scram_keys: Arc<KeyCache>,
120 pub(crate) connect_timeout: Duration,
121 pub(crate) statement_timeout: Option<Duration>,
122 pub(crate) max_result_size: usize,
123 pub(crate) statement_cache: usize,
124}
125
126impl Default for Config {
127 fn default() -> Self {
128 Self::new()
129 }
130}
131
132impl Config {
133 pub(crate) fn describe(&self) -> String {
136 let server = match &self.host {
137 Host::Tcp(host) if host.contains(':') => format!("[{host}]:{}", self.port),
138 Host::Tcp(host) => format!("{host}:{}", self.port),
139 Host::Unix(dir) => format!("{}/.s.PGSQL.{}", dir.display(), self.port),
140 };
141 match &self.dbname {
142 Some(db) => format!("{server}/{db}"),
143 None => server,
144 }
145 }
146
147 pub fn new() -> Self {
150 Self {
151 host: Host::Tcp("localhost".to_owned()),
152 port: 5432,
153 user: None,
154 password: None,
155 dbname: None,
156 application_name: None,
157 params: Vec::new(),
158 tls: None,
159 system_roots: Arc::new(OnceLock::new()),
160 require_auth: None,
161 scram_keys: Arc::default(),
162 connect_timeout: Duration::from_secs(10),
163 statement_timeout: Some(Duration::from_secs(30)),
164 max_result_size: 64 << 20,
165 statement_cache: 256,
166 }
167 }
168
169 pub fn host(mut self, host: &str) -> Self {
173 self.host = if host.starts_with('/') {
174 Host::Unix(PathBuf::from(host))
175 } else {
176 let host = host
177 .strip_prefix('[')
178 .and_then(|h| h.strip_suffix(']'))
179 .unwrap_or(host);
180 Host::Tcp(host.to_owned())
181 };
182 self
183 }
184
185 pub fn port(mut self, port: u16) -> Self {
188 self.port = port;
189 self
190 }
191
192 pub fn user(mut self, user: &str) -> Self {
194 self.user = Some(user.to_owned());
195 self
196 }
197
198 pub fn password(mut self, password: &str) -> Self {
200 self.password = Some(password.to_owned());
201 self.scram_keys = Arc::default();
202 self
203 }
204
205 pub fn dbname(mut self, dbname: &str) -> Self {
207 self.dbname = Some(dbname.to_owned());
208 self
209 }
210
211 pub fn application_name(mut self, name: &str) -> Self {
214 self.application_name = Some(name.to_owned());
215 self
216 }
217
218 pub fn param(mut self, name: &str, value: &str) -> Self {
221 self.params.push((name.to_owned(), value.to_owned()));
222 self
223 }
224
225 pub fn tls(mut self, tls: Tls) -> Self {
228 self.tls = Some(tls);
229 self
230 }
231
232 pub fn require_auth(mut self, methods: &[AuthMethod]) -> Self {
247 self.require_auth = Some(methods.to_vec());
248 self
249 }
250
251 pub fn connect_timeout(mut self, timeout: Duration) -> Self {
254 self.connect_timeout = timeout;
255 self
256 }
257
258 pub fn statement_timeout(mut self, timeout: impl Into<Option<Duration>>) -> Self {
277 self.statement_timeout = timeout.into();
278 self
279 }
280
281 pub fn max_result_size(mut self, bytes: usize) -> Self {
286 self.max_result_size = bytes;
287 self
288 }
289
290 pub fn statement_cache_capacity(mut self, statements: usize) -> Self {
302 self.statement_cache = statements;
303 self
304 }
305
306 pub fn from_url(url: &str) -> Result<Self, Error> {
327 parse_url(url)
328 }
329
330 pub(crate) fn target(&self) -> String {
333 match &self.host {
334 Host::Tcp(h) if h.contains(':') => format!("[{h}]:{}", self.port),
335 Host::Tcp(h) => format!("{h}:{}", self.port),
336 Host::Unix(dir) => self.socket_path(dir).display().to_string(),
337 }
338 }
339
340 pub(crate) fn socket_path(&self, dir: &Path) -> PathBuf {
341 dir.join(format!(".s.PGSQL.{}", self.port))
342 }
343
344 pub(crate) fn without_password(&self) -> Config {
347 Config {
348 password: None,
349 scram_keys: Arc::default(),
351 ..self.clone()
352 }
353 }
354
355 pub(crate) fn is_local(&self) -> bool {
357 match &self.host {
358 Host::Unix(_) => true,
359 Host::Tcp(h) => {
360 h.eq_ignore_ascii_case("localhost")
361 || h.parse::<IpAddr>().is_ok_and(|ip| match ip {
362 IpAddr::V4(v4) => v4.is_loopback(),
363 IpAddr::V6(v6) => {
364 v6.is_loopback()
365 || v6.to_ipv4_mapped().is_some_and(|v4| v4.is_loopback())
366 }
367 })
368 }
369 }
370 }
371
372 pub(crate) fn tls_connector(&self) -> Result<Option<TlsConnector>, Error> {
374 match (&self.tls, &self.host) {
375 (_, Host::Unix(_)) | (Some(Tls::Disable), _) => Ok(None),
376 (Some(Tls::Verify(connector)), _) => Ok(Some(connector.clone())),
377 (None, _) if self.is_local() => Ok(None),
378 (None, Host::Tcp(host)) => {
379 let roots = self
380 .system_roots
381 .get_or_init(|| TlsConnector::with_system_roots().map_err(|e| e.to_string()));
382 match roots {
383 Ok(connector) => Ok(Some(connector.clone())),
384 Err(e) => Err(Error::new(
385 ErrorKind::Config,
386 format!(
387 "a connection to {host} uses TLS checked against the machine's \
388 certificate authorities, but they could not be loaded ({e}); give \
389 the server's authority with sslrootcert=/path/ca.pem or \
390 Config::tls, or add sslmode=disable if the network is trusted"
391 ),
392 )),
393 }
394 }
395 }
396 }
397}
398
399impl fmt::Debug for Config {
400 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
401 f.debug_struct("Config")
402 .field("host", &self.host)
403 .field("port", &self.port)
404 .field("user", &self.user)
405 .field("password", &self.password.as_ref().map(|_| "<hidden>"))
406 .field("dbname", &self.dbname)
407 .field("application_name", &self.application_name)
408 .field("params", &self.params)
409 .field("tls", &self.tls)
410 .field("require_auth", &self.require_auth)
411 .field("connect_timeout", &self.connect_timeout)
412 .field("statement_timeout", &self.statement_timeout)
413 .field("max_result_size", &self.max_result_size)
414 .field("statement_cache_capacity", &self.statement_cache)
415 .finish()
416 }
417}
418
419impl FromStr for Config {
420 type Err = Error;
421
422 fn from_str(url: &str) -> Result<Self, Error> {
423 parse_url(url)
424 }
425}
426
427fn percent_decode(s: &str, what: &str) -> Result<String, Error> {
428 let bytes = s.as_bytes();
429 let mut out = Vec::with_capacity(bytes.len());
430 let mut i = 0;
431 while i < bytes.len() {
432 if bytes[i] == b'%' {
433 let hex = bytes
434 .get(i + 1..i + 3)
435 .and_then(|h| std::str::from_utf8(h).ok())
436 .and_then(|h| u8::from_str_radix(h, 16).ok())
437 .ok_or_else(|| {
438 Error::config(format!(
439 "the {what} in the URL has a '%' that is not followed by two hex digits; \
440 write a literal % as %25"
441 ))
442 })?;
443 out.push(hex);
444 i += 3;
445 } else {
446 out.push(bytes[i]);
447 i += 1;
448 }
449 }
450 String::from_utf8(out)
451 .map_err(|_| Error::config(format!("the {what} in the URL is not UTF-8 once decoded")))
452}
453
454fn parse_url(url: &str) -> Result<Config, Error> {
455 let rest = url
456 .strip_prefix("postgres://")
457 .or_else(|| url.strip_prefix("postgresql://"))
458 .ok_or_else(|| {
459 Error::config(
460 "a connection URL starts with postgres:// or postgresql://, \
461 as in postgres://user:password@host:5432/dbname",
462 )
463 })?;
464 let (rest, query) = match rest.split_once('?') {
465 Some((r, q)) => (r, Some(q)),
466 None => (rest, None),
467 };
468 let (authority, path) = match rest.split_once('/') {
469 Some((a, p)) => (a, Some(p)),
470 None => (rest, None),
471 };
472 let mut config = Config::new();
473 let hostport = match authority.rsplit_once('@') {
474 Some((userinfo, hostport)) => {
475 let (user, password) = match userinfo.split_once(':') {
476 Some((u, p)) => (u, Some(p)),
477 None => (userinfo, None),
478 };
479 if !user.is_empty() {
480 config.user = Some(percent_decode(user, "user")?);
481 }
482 if let Some(p) = password {
483 config.password = Some(percent_decode(p, "password")?);
484 }
485 hostport
486 }
487 None => authority,
488 };
489 if hostport.contains(',') {
490 return Err(Error::config(
491 "the URL names several hosts; giong-postgres connects to one, so give one host",
492 ));
493 }
494 let (host, port) = if let Some(v6) = hostport.strip_prefix('[') {
495 let (addr, after) = v6.split_once(']').ok_or_else(|| {
496 Error::config("an IPv6 address in the URL is missing its closing ']'")
497 })?;
498 let port = match after {
499 "" => None,
500 p => Some(p.strip_prefix(':').ok_or_else(|| {
501 Error::config("an IPv6 address in the URL must be followed by :port or nothing")
502 })?),
503 };
504 (format!("[{addr}]"), port)
505 } else {
506 match hostport.rsplit_once(':') {
507 Some((h, p)) => (percent_decode(h, "host")?, Some(p)),
508 None => (percent_decode(hostport, "host")?, None),
509 }
510 };
511 if !host.is_empty() {
512 config = config.host(&host);
513 }
514 if let Some(port) = port {
515 config.port = parse_port(port)?;
516 }
517 if let Some(db) = path.filter(|p| !p.is_empty()) {
518 config.dbname = Some(percent_decode(db, "database name")?);
519 }
520
521 let mut sslmode = None;
522 let mut sslrootcert = None;
523 for pair in query.unwrap_or("").split('&').filter(|p| !p.is_empty()) {
524 let (key, value) = pair.split_once('=').ok_or_else(|| {
525 Error::config(format!(
526 "the URL parameter {pair:?} has no value; write {pair}=value"
527 ))
528 })?;
529 let value = percent_decode(value, key)?;
530 match key {
531 "sslmode" => sslmode = Some(value),
532 "sslrootcert" => sslrootcert = Some(value),
533 "host" => config = config.host(&value),
534 "port" => config.port = parse_port(&value)?,
535 "user" => config.user = Some(value),
536 "password" => config.password = Some(value),
537 "require_auth" => config.require_auth = Some(parse_auth_methods(&value)?),
538 "dbname" => config.dbname = Some(value),
539 "application_name" => config.application_name = Some(value),
540 "connect_timeout" => {
541 let secs: u64 = value.parse().ok().filter(|&s| s > 0).ok_or_else(|| {
542 Error::config(format!(
543 "connect_timeout={value} is not a whole number of seconds above zero"
544 ))
545 })?;
546 config.connect_timeout = Duration::from_secs(secs);
547 }
548 other => {
549 return Err(Error::config(format!(
550 "the URL parameter {other:?} is not supported; the supported ones are \
551 sslmode, sslrootcert, host, port, user, password, dbname, \
552 application_name, connect_timeout and require_auth"
553 )))
554 }
555 }
556 }
557
558 let verify = || -> Result<Tls, Error> {
559 match sslrootcert.as_deref() {
560 None | Some("system") => Ok(Tls::Verify(TlsConnector::with_system_roots().map_err(
561 |e| {
562 Error::io(
563 ErrorKind::Config,
564 "cannot load the machine's certificate authorities for sslmode",
565 e,
566 )
567 },
568 )?)),
569 Some(path) => {
570 let pem = std::fs::read(path).map_err(|e| {
571 Error::io(
572 ErrorKind::Config,
573 format!("cannot read sslrootcert {path:?}"),
574 e,
575 )
576 })?;
577 let connector = TlsConnector::with_root_pem(&pem).map_err(|e| {
578 Error::io(
579 ErrorKind::Config,
580 format!("sslrootcert {path:?} holds no usable certificate"),
581 e,
582 )
583 })?;
584 Ok(Tls::Verify(connector))
585 }
586 }
587 };
588 match sslmode.as_deref() {
589 None if sslrootcert.is_some() => config.tls = Some(verify()?),
590 None => {}
591 Some("disable") => config.tls = Some(Tls::Disable),
592 Some("require" | "verify-ca" | "verify-full") => config.tls = Some(verify()?),
593 Some(mode @ ("prefer" | "allow")) => {
594 return Err(Error::config(format!(
595 "sslmode={mode} would silently connect without encryption when TLS fails; \
596 use sslmode=verify-full to require TLS, or sslmode=disable on a trusted network"
597 )))
598 }
599 Some(other) => {
600 return Err(Error::config(format!(
601 "sslmode={other} is not a known mode; use disable, require, verify-ca or verify-full"
602 )))
603 }
604 }
605 Ok(config)
606}
607
608fn parse_auth_methods(list: &str) -> Result<Vec<AuthMethod>, Error> {
609 let all = [
610 AuthMethod::None,
611 AuthMethod::Password,
612 AuthMethod::Md5,
613 AuthMethod::ScramSha256,
614 ];
615 list.split(',')
616 .map(|name| {
617 if name.starts_with('!') {
618 return Err(Error::config(format!(
619 "require_auth={list}: giong-postgres takes the methods to allow, not the ones \
620 to refuse (libpq's {name:?}); list the allowed ones, such as \
621 require_auth=scram-sha-256"
622 )));
623 }
624 all.into_iter().find(|m| m.name() == name).ok_or_else(|| {
625 Error::config(format!(
626 "require_auth={list}: {name:?} is not a method giong-postgres knows; use \
627 scram-sha-256, md5, password or none, separated by commas"
628 ))
629 })
630 })
631 .collect()
632}
633
634fn parse_port(port: &str) -> Result<u16, Error> {
635 port.parse().ok().filter(|&p| p != 0).ok_or_else(|| {
636 Error::config(format!(
637 "the port {port:?} in the URL is not a number from 1 to 65535"
638 ))
639 })
640}
641
642#[cfg(test)]
643mod tests {
644 use super::*;
645
646 #[test]
647 fn a_config_without_its_password_keeps_everything_else() {
648 let c = Config::from_url("postgres://app:secret@db.internal:6543/shop?sslmode=disable")
649 .unwrap();
650 let bare = c.without_password();
651 assert_eq!(bare.password, None);
652 assert!(!Arc::ptr_eq(&bare.scram_keys, &c.scram_keys));
653 assert_eq!(c.password.as_deref(), Some("secret"));
654 assert_eq!((&bare.host, bare.port), (&c.host, c.port));
655 assert_eq!(bare.user, c.user);
656 assert!(bare.tls_connector().unwrap().is_none());
657 }
658
659 #[test]
660 fn a_full_url_is_read() {
661 let c = Config::from_url(
662 "postgres://app%40corp:p%3Ass%40w@db.internal:6543/shop%20db?application_name=api&connect_timeout=3&sslmode=disable",
663 )
664 .unwrap();
665 assert_eq!(c.host, Host::Tcp("db.internal".into()));
666 assert_eq!(c.port, 6543);
667 assert_eq!(c.user.as_deref(), Some("app@corp"));
668 assert_eq!(c.password.as_deref(), Some("p:ss@w"));
669 assert_eq!(c.dbname.as_deref(), Some("shop db"));
670 assert_eq!(c.application_name.as_deref(), Some("api"));
671 assert_eq!(c.connect_timeout, Duration::from_secs(3));
672 assert!(c.tls_connector().unwrap().is_none());
673 assert!(!format!("{c:?}").contains("p:ss@w"));
674 }
675
676 #[test]
677 fn hosts_can_be_ipv6_or_sockets() {
678 let c = Config::from_url("postgresql://u@[::1]:5433").unwrap();
679 assert_eq!(c.host, Host::Tcp("::1".into()));
680 assert_eq!(c.port, 5433);
681 assert_eq!(c.target(), "[::1]:5433");
682 assert!(c.is_local());
683
684 let c = Config::from_url("postgres:///shop?host=/var/run/postgresql&user=u").unwrap();
685 assert_eq!(c.host, Host::Unix("/var/run/postgresql".into()));
686 assert_eq!(c.target(), "/var/run/postgresql/.s.PGSQL.5432");
687 let c = Config::from_url("postgres://u@%2Ftmp/shop").unwrap();
688 assert_eq!(c.host, Host::Unix("/tmp".into()));
689 }
690
691 #[test]
692 fn tls_is_on_for_remote_hosts_unless_disabled() {
693 assert!(Config::new()
694 .host("127.0.0.1")
695 .tls_connector()
696 .unwrap()
697 .is_none());
698 assert!(Config::new()
699 .host("localhost")
700 .tls_connector()
701 .unwrap()
702 .is_none());
703 let cert = rcgen::generate_simple_self_signed(vec!["localhost".into()]).unwrap();
704 let connector = TlsConnector::with_root_pem(cert.cert.pem().as_bytes()).unwrap();
705 let unix = Config::new()
706 .host("/tmp")
707 .tls(Tls::Verify(connector.clone()));
708 assert!(unix.tls_connector().unwrap().is_none());
709 let local = Config::new().host("127.0.0.1").tls(Tls::Verify(connector));
710 assert!(local.tls_connector().unwrap().is_some());
711 assert!(Config::new()
712 .host("10.1.2.3")
713 .tls(Tls::Disable)
714 .tls_connector()
715 .unwrap()
716 .is_none());
717 if let Ok(Some(_)) = Config::new().host("db.example.com").tls_connector() {
719 } else {
720 panic!("expected TLS for a remote host");
721 }
722 }
723
724 #[test]
725 fn bad_urls_say_what_is_wrong() {
726 let err = |url: &str| Config::from_url(url).unwrap_err().to_string();
727 assert!(err("mysql://x").contains("postgres://"));
728 assert!(err("postgres://u@h/db?sslmode=prefer").contains("silently"));
729 assert!(err("postgres://u@h/db?sslmode=bogus").contains("not a known mode"));
730 assert!(err("postgres://u@h/db?sslcert=x").contains("not supported"));
731 assert!(err("postgres://u@h:99999/db").contains("1 to 65535"));
732 assert!(err("postgres://u@h1,h2/db").contains("several hosts"));
733 assert!(err("postgres://u@[::1/db").contains("closing"));
734 assert!(err("postgres://u:%zz@h/db").contains("%25"));
735 assert!(err("postgres://u@h/db?connect_timeout=0").contains("above zero"));
736 assert!(err("postgres://u@h/db?sslrootcert=/nonexistent/ca.pem").contains("cannot read"));
737 assert!(err("postgres://u@h/db?flag").contains("no value"));
738 }
739
740 #[test]
741 fn statement_timeout_can_be_left_to_the_server() {
742 let c = Config::new();
743 assert_eq!(c.statement_timeout, Some(Duration::from_secs(30)));
744 let c = c.statement_timeout(Duration::from_secs(5));
745 assert_eq!(c.statement_timeout, Some(Duration::from_secs(5)));
746 assert_eq!(c.statement_timeout(None).statement_timeout, None);
747 }
748
749 #[test]
750 fn require_auth_reads_libpq_names() {
751 let c = Config::from_url("postgres://u@h/db?require_auth=scram-sha-256,md5").unwrap();
752 assert_eq!(
753 c.require_auth,
754 Some(vec![AuthMethod::ScramSha256, AuthMethod::Md5])
755 );
756 let err = |url: &str| Config::from_url(url).unwrap_err().to_string();
757 assert!(err("postgres://u@h/db?require_auth=!md5").contains("not the ones"));
758 assert!(err("postgres://u@h/db?require_auth=gss").contains("not a method"));
759 }
760}