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