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