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 pub(crate) batch_reads: bool,
125}
126
127impl Default for Config {
128 fn default() -> Self {
129 Self::new()
130 }
131}
132
133impl Config {
134 pub(crate) fn describe(&self) -> String {
137 let server = match &self.host {
138 Host::Tcp(host) if host.contains(':') => format!("[{host}]:{}", self.port),
139 Host::Tcp(host) => format!("{host}:{}", self.port),
140 Host::Unix(dir) => format!("{}/.s.PGSQL.{}", dir.display(), self.port),
141 };
142 match &self.dbname {
143 Some(db) => format!("{server}/{db}"),
144 None => server,
145 }
146 }
147
148 pub fn new() -> Self {
151 Self {
152 host: Host::Tcp("localhost".to_owned()),
153 port: 5432,
154 user: None,
155 password: None,
156 dbname: None,
157 application_name: None,
158 params: Vec::new(),
159 tls: None,
160 system_roots: Arc::new(OnceLock::new()),
161 require_auth: None,
162 scram_keys: Arc::default(),
163 connect_timeout: Duration::from_secs(10),
164 statement_timeout: Some(Duration::from_secs(30)),
165 max_result_size: 64 << 20,
166 statement_cache: 256,
167 batch_reads: false,
168 }
169 }
170
171 pub fn host(mut self, host: &str) -> Self {
175 self.host = if host.starts_with('/') {
176 Host::Unix(PathBuf::from(host))
177 } else {
178 let host = host
179 .strip_prefix('[')
180 .and_then(|h| h.strip_suffix(']'))
181 .unwrap_or(host);
182 Host::Tcp(host.to_owned())
183 };
184 self
185 }
186
187 pub fn port(mut self, port: u16) -> Self {
190 self.port = port;
191 self
192 }
193
194 pub fn user(mut self, user: &str) -> Self {
196 self.user = Some(user.to_owned());
197 self
198 }
199
200 pub fn password(mut self, password: &str) -> Self {
202 self.password = Some(password.to_owned());
203 self.scram_keys = Arc::default();
204 self
205 }
206
207 pub fn database(mut self, database: &str) -> Self {
210 self.dbname = Some(database.to_owned());
211 self
212 }
213
214 pub fn application_name(mut self, name: &str) -> Self {
217 self.application_name = Some(name.to_owned());
218 self
219 }
220
221 pub fn param(mut self, name: &str, value: &str) -> Self {
224 self.params.push((name.to_owned(), value.to_owned()));
225 self
226 }
227
228 pub fn tls(mut self, tls: Tls) -> Self {
231 self.tls = Some(tls);
232 self
233 }
234
235 pub fn require_auth(mut self, methods: &[AuthMethod]) -> Self {
250 self.require_auth = Some(methods.to_vec());
251 self
252 }
253
254 pub fn connect_timeout(mut self, timeout: Duration) -> Self {
257 self.connect_timeout = timeout;
258 self
259 }
260
261 pub fn statement_timeout(mut self, timeout: impl Into<Option<Duration>>) -> Self {
280 self.statement_timeout = timeout.into();
281 self
282 }
283
284 pub fn max_result_size(mut self, bytes: usize) -> Self {
289 self.max_result_size = bytes;
290 self
291 }
292
293 pub fn statement_cache_capacity(mut self, statements: usize) -> Self {
305 self.statement_cache = statements;
306 self
307 }
308
309 pub fn batch_reads(mut self, batch: bool) -> Self {
371 self.batch_reads = batch;
372 self
373 }
374
375 pub fn from_url(url: &str) -> Result<Self, Error> {
396 parse_url(url)
397 }
398
399 pub(crate) fn target(&self) -> String {
402 match &self.host {
403 Host::Tcp(h) if h.contains(':') => format!("[{h}]:{}", self.port),
404 Host::Tcp(h) => format!("{h}:{}", self.port),
405 Host::Unix(dir) => self.socket_path(dir).display().to_string(),
406 }
407 }
408
409 pub(crate) fn socket_path(&self, dir: &Path) -> PathBuf {
410 dir.join(format!(".s.PGSQL.{}", self.port))
411 }
412
413 pub(crate) fn without_password(&self) -> Config {
416 Config {
417 password: None,
418 scram_keys: Arc::default(),
420 ..self.clone()
421 }
422 }
423
424 pub(crate) fn is_local(&self) -> bool {
426 match &self.host {
427 Host::Unix(_) => true,
428 Host::Tcp(h) => {
429 h.eq_ignore_ascii_case("localhost")
430 || h.parse::<IpAddr>().is_ok_and(|ip| match ip {
431 IpAddr::V4(v4) => v4.is_loopback(),
432 IpAddr::V6(v6) => {
433 v6.is_loopback()
434 || v6.to_ipv4_mapped().is_some_and(|v4| v4.is_loopback())
435 }
436 })
437 }
438 }
439 }
440
441 pub(crate) fn tls_connector(&self) -> Result<Option<TlsConnector>, Error> {
443 match (&self.tls, &self.host) {
444 (_, Host::Unix(_)) | (Some(Tls::Disable), _) => Ok(None),
445 (Some(Tls::Verify(connector)), _) => Ok(Some(connector.clone())),
446 (None, _) if self.is_local() => Ok(None),
447 (None, Host::Tcp(host)) => {
448 let roots = self
449 .system_roots
450 .get_or_init(|| TlsConnector::with_system_roots().map_err(|e| e.to_string()));
451 match roots {
452 Ok(connector) => Ok(Some(connector.clone())),
453 Err(e) => Err(Error::new(
454 ErrorKind::Config,
455 format!(
456 "a connection to {host} uses TLS checked against the machine's \
457 certificate authorities, but they could not be loaded ({e}); give \
458 the server's authority with sslrootcert=/path/ca.pem or \
459 Config::tls, or add sslmode=disable if the network is trusted"
460 ),
461 )),
462 }
463 }
464 }
465 }
466}
467
468impl fmt::Debug for Config {
469 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
470 f.debug_struct("Config")
471 .field("host", &self.host)
472 .field("port", &self.port)
473 .field("user", &self.user)
474 .field("password", &self.password.as_ref().map(|_| "<hidden>"))
475 .field("dbname", &self.dbname)
476 .field("application_name", &self.application_name)
477 .field("params", &self.params)
478 .field("tls", &self.tls)
479 .field("require_auth", &self.require_auth)
480 .field("connect_timeout", &self.connect_timeout)
481 .field("statement_timeout", &self.statement_timeout)
482 .field("max_result_size", &self.max_result_size)
483 .field("statement_cache_capacity", &self.statement_cache)
484 .finish()
485 }
486}
487
488impl FromStr for Config {
489 type Err = Error;
490
491 fn from_str(url: &str) -> Result<Self, Error> {
492 parse_url(url)
493 }
494}
495
496fn percent_decode(s: &str, what: &str) -> Result<String, Error> {
497 let bytes = s.as_bytes();
498 let mut out = Vec::with_capacity(bytes.len());
499 let mut i = 0;
500 while i < bytes.len() {
501 if bytes[i] == b'%' {
502 let hex = bytes
503 .get(i + 1..i + 3)
504 .and_then(|h| std::str::from_utf8(h).ok())
505 .and_then(|h| u8::from_str_radix(h, 16).ok())
506 .ok_or_else(|| {
507 Error::config(format!(
508 "the {what} in the URL has a '%' that is not followed by two hex digits; \
509 write a literal % as %25"
510 ))
511 })?;
512 out.push(hex);
513 i += 3;
514 } else {
515 out.push(bytes[i]);
516 i += 1;
517 }
518 }
519 String::from_utf8(out)
520 .map_err(|_| Error::config(format!("the {what} in the URL is not UTF-8 once decoded")))
521}
522
523fn parse_url(url: &str) -> Result<Config, Error> {
524 let rest = url
525 .strip_prefix("postgres://")
526 .or_else(|| url.strip_prefix("postgresql://"))
527 .ok_or_else(|| {
528 Error::config(
529 "a connection URL starts with postgres:// or postgresql://, \
530 as in postgres://user:password@host:5432/dbname",
531 )
532 })?;
533 let (rest, query) = match rest.split_once('?') {
534 Some((r, q)) => (r, Some(q)),
535 None => (rest, None),
536 };
537 let (authority, path) = match rest.split_once('/') {
538 Some((a, p)) => (a, Some(p)),
539 None => (rest, None),
540 };
541 let mut config = Config::new();
542 let hostport = match authority.rsplit_once('@') {
543 Some((userinfo, hostport)) => {
544 let (user, password) = match userinfo.split_once(':') {
545 Some((u, p)) => (u, Some(p)),
546 None => (userinfo, None),
547 };
548 if !user.is_empty() {
549 config.user = Some(percent_decode(user, "user")?);
550 }
551 if let Some(p) = password {
552 config.password = Some(percent_decode(p, "password")?);
553 }
554 hostport
555 }
556 None => authority,
557 };
558 if hostport.contains(',') {
559 return Err(Error::config(
560 "the URL names several hosts; giong-postgres connects to one, so give one host",
561 ));
562 }
563 let (host, port) = if let Some(v6) = hostport.strip_prefix('[') {
564 let (addr, after) = v6.split_once(']').ok_or_else(|| {
565 Error::config("an IPv6 address in the URL is missing its closing ']'")
566 })?;
567 let port = match after {
568 "" => None,
569 p => Some(p.strip_prefix(':').ok_or_else(|| {
570 Error::config("an IPv6 address in the URL must be followed by :port or nothing")
571 })?),
572 };
573 (format!("[{addr}]"), port)
574 } else {
575 match hostport.rsplit_once(':') {
576 Some((h, p)) => (percent_decode(h, "host")?, Some(p)),
577 None => (percent_decode(hostport, "host")?, None),
578 }
579 };
580 if !host.is_empty() {
581 config = config.host(&host);
582 }
583 if let Some(port) = port {
584 config.port = parse_port(port)?;
585 }
586 if let Some(db) = path.filter(|p| !p.is_empty()) {
587 config.dbname = Some(percent_decode(db, "database name")?);
588 }
589
590 let mut sslmode = None;
591 let mut sslrootcert = None;
592 for pair in query.unwrap_or("").split('&').filter(|p| !p.is_empty()) {
593 let (key, value) = pair.split_once('=').ok_or_else(|| {
594 Error::config(format!(
595 "the URL parameter {pair:?} has no value; write {pair}=value"
596 ))
597 })?;
598 let value = percent_decode(value, key)?;
599 match key {
600 "sslmode" => sslmode = Some(value),
601 "sslrootcert" => sslrootcert = Some(value),
602 "host" => config = config.host(&value),
603 "port" => config.port = parse_port(&value)?,
604 "user" => config.user = Some(value),
605 "password" => config.password = Some(value),
606 "require_auth" => config.require_auth = Some(parse_auth_methods(&value)?),
607 "dbname" => config.dbname = Some(value),
608 "application_name" => config.application_name = Some(value),
609 "connect_timeout" => {
610 let secs: u64 = value.parse().ok().filter(|&s| s > 0).ok_or_else(|| {
611 Error::config(format!(
612 "connect_timeout={value} is not a whole number of seconds above zero"
613 ))
614 })?;
615 config.connect_timeout = Duration::from_secs(secs);
616 }
617 other => {
618 return Err(Error::config(format!(
619 "the URL parameter {other:?} is not supported; the supported ones are \
620 sslmode, sslrootcert, host, port, user, password, dbname, \
621 application_name, connect_timeout and require_auth"
622 )))
623 }
624 }
625 }
626
627 let verify = || -> Result<Tls, Error> {
628 match sslrootcert.as_deref() {
629 None | Some("system") => Ok(Tls::Verify(TlsConnector::with_system_roots().map_err(
630 |e| {
631 Error::io(
632 ErrorKind::Config,
633 "cannot load the machine's certificate authorities for sslmode",
634 e,
635 )
636 },
637 )?)),
638 Some(path) => {
639 let pem = std::fs::read(path).map_err(|e| {
640 Error::io(
641 ErrorKind::Config,
642 format!("cannot read sslrootcert {path:?}"),
643 e,
644 )
645 })?;
646 let connector = TlsConnector::with_root_pem(&pem).map_err(|e| {
647 Error::io(
648 ErrorKind::Config,
649 format!("sslrootcert {path:?} holds no usable certificate"),
650 e,
651 )
652 })?;
653 Ok(Tls::Verify(connector))
654 }
655 }
656 };
657 match sslmode.as_deref() {
658 None if sslrootcert.is_some() => config.tls = Some(verify()?),
659 None => {}
660 Some("disable") => config.tls = Some(Tls::Disable),
661 Some("require" | "verify-ca" | "verify-full") => config.tls = Some(verify()?),
662 Some(mode @ ("prefer" | "allow")) => {
663 return Err(Error::config(format!(
664 "sslmode={mode} would silently connect without encryption when TLS fails; \
665 use sslmode=verify-full to require TLS, or sslmode=disable on a trusted network"
666 )))
667 }
668 Some(other) => {
669 return Err(Error::config(format!(
670 "sslmode={other} is not a known mode; use disable, require, verify-ca or verify-full"
671 )))
672 }
673 }
674 Ok(config)
675}
676
677fn parse_auth_methods(list: &str) -> Result<Vec<AuthMethod>, Error> {
678 let all = [
679 AuthMethod::None,
680 AuthMethod::Password,
681 AuthMethod::Md5,
682 AuthMethod::ScramSha256,
683 ];
684 list.split(',')
685 .map(|name| {
686 if name.starts_with('!') {
687 return Err(Error::config(format!(
688 "require_auth={list}: giong-postgres takes the methods to allow, not the ones \
689 to refuse (libpq's {name:?}); list the allowed ones, such as \
690 require_auth=scram-sha-256"
691 )));
692 }
693 all.into_iter().find(|m| m.name() == name).ok_or_else(|| {
694 Error::config(format!(
695 "require_auth={list}: {name:?} is not a method giong-postgres knows; use \
696 scram-sha-256, md5, password or none, separated by commas"
697 ))
698 })
699 })
700 .collect()
701}
702
703fn parse_port(port: &str) -> Result<u16, Error> {
704 port.parse().ok().filter(|&p| p != 0).ok_or_else(|| {
705 Error::config(format!(
706 "the port {port:?} in the URL is not a number from 1 to 65535"
707 ))
708 })
709}
710
711#[cfg(test)]
712mod tests {
713 use super::*;
714
715 #[test]
716 fn a_config_without_its_password_keeps_everything_else() {
717 let c = Config::from_url("postgres://app:secret@db.internal:6543/shop?sslmode=disable")
718 .unwrap();
719 let bare = c.without_password();
720 assert_eq!(bare.password, None);
721 assert!(!Arc::ptr_eq(&bare.scram_keys, &c.scram_keys));
722 assert_eq!(c.password.as_deref(), Some("secret"));
723 assert_eq!((&bare.host, bare.port), (&c.host, c.port));
724 assert_eq!(bare.user, c.user);
725 assert!(bare.tls_connector().unwrap().is_none());
726 }
727
728 #[test]
729 fn a_full_url_is_read() {
730 let c = Config::from_url(
731 "postgres://app%40corp:p%3Ass%40w@db.internal:6543/shop%20db?application_name=api&connect_timeout=3&sslmode=disable",
732 )
733 .unwrap();
734 assert_eq!(c.host, Host::Tcp("db.internal".into()));
735 assert_eq!(c.port, 6543);
736 assert_eq!(c.user.as_deref(), Some("app@corp"));
737 assert_eq!(c.password.as_deref(), Some("p:ss@w"));
738 assert_eq!(c.dbname.as_deref(), Some("shop db"));
739 assert_eq!(c.application_name.as_deref(), Some("api"));
740 assert_eq!(c.connect_timeout, Duration::from_secs(3));
741 assert!(c.tls_connector().unwrap().is_none());
742 assert!(!format!("{c:?}").contains("p:ss@w"));
743 }
744
745 #[test]
746 fn hosts_can_be_ipv6_or_sockets() {
747 let c = Config::from_url("postgresql://u@[::1]:5433").unwrap();
748 assert_eq!(c.host, Host::Tcp("::1".into()));
749 assert_eq!(c.port, 5433);
750 assert_eq!(c.target(), "[::1]:5433");
751 assert!(c.is_local());
752
753 let c = Config::from_url("postgres:///shop?host=/var/run/postgresql&user=u").unwrap();
754 assert_eq!(c.host, Host::Unix("/var/run/postgresql".into()));
755 assert_eq!(c.target(), "/var/run/postgresql/.s.PGSQL.5432");
756 let c = Config::from_url("postgres://u@%2Ftmp/shop").unwrap();
757 assert_eq!(c.host, Host::Unix("/tmp".into()));
758 }
759
760 #[test]
761 fn tls_is_on_for_remote_hosts_unless_disabled() {
762 assert!(Config::new()
763 .host("127.0.0.1")
764 .tls_connector()
765 .unwrap()
766 .is_none());
767 assert!(Config::new()
768 .host("localhost")
769 .tls_connector()
770 .unwrap()
771 .is_none());
772 let cert = rcgen::generate_simple_self_signed(vec!["localhost".into()]).unwrap();
773 let connector = TlsConnector::with_root_pem(cert.cert.pem().as_bytes()).unwrap();
774 let unix = Config::new()
775 .host("/tmp")
776 .tls(Tls::Verify(connector.clone()));
777 assert!(unix.tls_connector().unwrap().is_none());
778 let local = Config::new().host("127.0.0.1").tls(Tls::Verify(connector));
779 assert!(local.tls_connector().unwrap().is_some());
780 assert!(Config::new()
781 .host("10.1.2.3")
782 .tls(Tls::Disable)
783 .tls_connector()
784 .unwrap()
785 .is_none());
786 if let Ok(Some(_)) = Config::new().host("db.example.com").tls_connector() {
788 } else {
789 panic!("expected TLS for a remote host");
790 }
791 }
792
793 #[test]
794 fn bad_urls_say_what_is_wrong() {
795 let err = |url: &str| Config::from_url(url).unwrap_err().to_string();
796 assert!(err("mysql://x").contains("postgres://"));
797 assert!(err("postgres://u@h/db?sslmode=prefer").contains("silently"));
798 assert!(err("postgres://u@h/db?sslmode=bogus").contains("not a known mode"));
799 assert!(err("postgres://u@h/db?sslcert=x").contains("not supported"));
800 assert!(err("postgres://u@h:99999/db").contains("1 to 65535"));
801 assert!(err("postgres://u@h1,h2/db").contains("several hosts"));
802 assert!(err("postgres://u@[::1/db").contains("closing"));
803 assert!(err("postgres://u:%zz@h/db").contains("%25"));
804 assert!(err("postgres://u@h/db?connect_timeout=0").contains("above zero"));
805 assert!(err("postgres://u@h/db?sslrootcert=/nonexistent/ca.pem").contains("cannot read"));
806 assert!(err("postgres://u@h/db?flag").contains("no value"));
807 }
808
809 #[test]
810 fn statement_timeout_can_be_left_to_the_server() {
811 let c = Config::new();
812 assert_eq!(c.statement_timeout, Some(Duration::from_secs(30)));
813 let c = c.statement_timeout(Duration::from_secs(5));
814 assert_eq!(c.statement_timeout, Some(Duration::from_secs(5)));
815 assert_eq!(c.statement_timeout(None).statement_timeout, None);
816 }
817
818 #[test]
819 fn require_auth_reads_libpq_names() {
820 let c = Config::from_url("postgres://u@h/db?require_auth=scram-sha-256,md5").unwrap();
821 assert_eq!(
822 c.require_auth,
823 Some(vec![AuthMethod::ScramSha256, AuthMethod::Md5])
824 );
825 let err = |url: &str| Config::from_url(url).unwrap_err().to_string();
826 assert!(err("postgres://u@h/db?require_auth=!md5").contains("not the ones"));
827 assert!(err("postgres://u@h/db?require_auth=gss").contains("not a method"));
828 }
829}