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> {
404 parse_url(url)
405 }
406
407 pub(crate) fn target(&self) -> String {
410 match &self.host {
411 Host::Tcp(h) if h.contains(':') => format!("[{h}]:{}", self.port),
412 Host::Tcp(h) => format!("{h}:{}", self.port),
413 Host::Unix(dir) => self.socket_path(dir).display().to_string(),
414 }
415 }
416
417 pub(crate) fn socket_path(&self, dir: &Path) -> PathBuf {
418 dir.join(format!(".s.PGSQL.{}", self.port))
419 }
420
421 pub(crate) fn without_password(&self) -> Config {
424 Config {
425 password: None,
426 scram_keys: Arc::default(),
428 ..self.clone()
429 }
430 }
431
432 pub(crate) fn is_local(&self) -> bool {
434 match &self.host {
435 Host::Unix(_) => true,
436 Host::Tcp(h) => {
437 h.eq_ignore_ascii_case("localhost")
438 || h.parse::<IpAddr>().is_ok_and(|ip| match ip {
439 IpAddr::V4(v4) => v4.is_loopback(),
440 IpAddr::V6(v6) => {
441 v6.is_loopback()
442 || v6.to_ipv4_mapped().is_some_and(|v4| v4.is_loopback())
443 }
444 })
445 }
446 }
447 }
448
449 pub(crate) fn tls_connector(&self) -> Result<Option<TlsConnector>, Error> {
451 match (&self.tls, &self.host) {
452 (_, Host::Unix(_)) | (Some(Tls::Disable), _) => Ok(None),
453 (Some(Tls::Verify(connector)), _) => Ok(Some(connector.clone())),
454 (None, _) if self.is_local() => Ok(None),
455 (None, Host::Tcp(host)) => {
456 let roots = self
457 .system_roots
458 .get_or_init(|| TlsConnector::with_system_roots().map_err(|e| e.to_string()));
459 match roots {
460 Ok(connector) => Ok(Some(connector.clone())),
461 Err(e) => Err(Error::new(
462 ErrorKind::Config,
463 format!(
464 "a connection to {host} uses TLS checked against the machine's \
465 certificate authorities, but they could not be loaded ({e}); give \
466 the server's authority with sslrootcert=/path/ca.pem or \
467 Config::tls, or add sslmode=disable if the network is trusted"
468 ),
469 )),
470 }
471 }
472 }
473 }
474}
475
476impl fmt::Debug for Config {
477 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
478 f.debug_struct("Config")
479 .field("host", &self.host)
480 .field("port", &self.port)
481 .field("user", &self.user)
482 .field("password", &self.password.as_ref().map(|_| "<hidden>"))
483 .field("dbname", &self.dbname)
484 .field("application_name", &self.application_name)
485 .field("params", &self.params)
486 .field("tls", &self.tls)
487 .field("require_auth", &self.require_auth)
488 .field("connect_timeout", &self.connect_timeout)
489 .field("statement_timeout", &self.statement_timeout)
490 .field("max_result_size", &self.max_result_size)
491 .field("statement_cache_capacity", &self.statement_cache)
492 .finish()
493 }
494}
495
496impl FromStr for Config {
497 type Err = Error;
498
499 fn from_str(url: &str) -> Result<Self, Error> {
500 parse_url(url)
501 }
502}
503
504fn percent_decode(s: &str, what: &str) -> Result<String, Error> {
505 let bytes = s.as_bytes();
506 let mut out = Vec::with_capacity(bytes.len());
507 let mut i = 0;
508 while i < bytes.len() {
509 if bytes[i] == b'%' {
510 let hex = bytes
511 .get(i + 1..i + 3)
512 .and_then(|h| std::str::from_utf8(h).ok())
513 .and_then(|h| u8::from_str_radix(h, 16).ok())
514 .ok_or_else(|| {
515 Error::config(format!(
516 "the {what} in the URL has a '%' that is not followed by two hex digits; \
517 write a literal % as %25"
518 ))
519 })?;
520 out.push(hex);
521 i += 3;
522 } else {
523 out.push(bytes[i]);
524 i += 1;
525 }
526 }
527 String::from_utf8(out)
528 .map_err(|_| Error::config(format!("the {what} in the URL is not UTF-8 once decoded")))
529}
530
531fn parse_url(url: &str) -> Result<Config, Error> {
532 let after_cut = |accepted: bool| {
538 let Some((_, rest)) = url.split_once("://") else {
539 return false;
540 };
541 let Some(cut) = rest.find(['/', '?']) else {
542 return false;
543 };
544 if accepted {
545 let before_query = rest.split_once('?').map_or(rest, |(r, _)| r);
548 before_query.get(cut..).is_some_and(|db| db.contains('@'))
549 } else {
550 rest[cut..].contains('@')
551 }
552 };
553 let cut_password = |read: &str| {
554 Error::config(format!(
555 "the URL {read}has an @ after a / or ?: if the password (or the user name) holds one \
556 of them, percent-encode it (/ as %2F, ? as %3F, @ as %40); write an @ in the \
557 database name as %40 too"
558 ))
559 };
560 match parse(url) {
561 Ok(_) if after_cut(true) => Err(cut_password("")),
562 Err(_) if after_cut(false) => Err(cut_password("could not be read, and it ")),
563 result => result,
564 }
565}
566
567fn parse(url: &str) -> Result<Config, Error> {
568 let rest = url
569 .strip_prefix("postgres://")
570 .or_else(|| url.strip_prefix("postgresql://"))
571 .ok_or_else(|| {
572 Error::config(
573 "a connection URL starts with postgres:// or postgresql://, \
574 as in postgres://user:password@host:5432/dbname",
575 )
576 })?;
577 let (rest, query) = match rest.split_once('?') {
578 Some((r, q)) => (r, Some(q)),
579 None => (rest, None),
580 };
581 let (authority, path) = match rest.split_once('/') {
582 Some((a, p)) => (a, Some(p)),
583 None => (rest, None),
584 };
585 let mut config = Config::new();
586 let hostport = match authority.rsplit_once('@') {
587 Some((userinfo, hostport)) => {
588 let (user, password) = match userinfo.split_once(':') {
589 Some((u, p)) => (u, Some(p)),
590 None => (userinfo, None),
591 };
592 if !user.is_empty() {
593 config.user = Some(percent_decode(user, "user")?);
594 }
595 if let Some(p) = password {
596 config.password = Some(percent_decode(p, "password")?);
597 }
598 hostport
599 }
600 None => authority,
601 };
602 if hostport.contains(',') {
603 return Err(Error::config(
604 "the URL names several hosts; giong-postgres connects to one, so give one host",
605 ));
606 }
607 let (host, port) = if let Some(v6) = hostport.strip_prefix('[') {
608 let (addr, after) = v6.split_once(']').ok_or_else(|| {
609 Error::config("an IPv6 address in the URL is missing its closing ']'")
610 })?;
611 let port = match after {
612 "" => None,
613 p => Some(p.strip_prefix(':').ok_or_else(|| {
614 Error::config("an IPv6 address in the URL must be followed by :port or nothing")
615 })?),
616 };
617 (format!("[{addr}]"), port)
618 } else {
619 match hostport.rsplit_once(':') {
620 Some((h, p)) => (percent_decode(h, "host")?, Some(p)),
621 None => (percent_decode(hostport, "host")?, None),
622 }
623 };
624 if !host.is_empty() {
625 config = config.host(&host);
626 }
627 if let Some(port) = port {
628 config.port = parse_port(port)?;
629 }
630 if let Some(db) = path.filter(|p| !p.is_empty()) {
631 config.dbname = Some(percent_decode(db, "database name")?);
632 }
633
634 let mut sslmode = None;
635 let mut sslrootcert = None;
636 for pair in query.unwrap_or("").split('&').filter(|p| !p.is_empty()) {
637 let (key, value) = pair.split_once('=').ok_or_else(|| {
638 Error::config(format!(
639 "the URL parameter {pair:?} has no value; write {pair}=value"
640 ))
641 })?;
642 let value = percent_decode(value, key)?;
643 match key {
644 "sslmode" => sslmode = Some(value),
645 "sslrootcert" => sslrootcert = Some(value),
646 "host" => config = config.host(&value),
647 "port" => config.port = parse_port(&value)?,
648 "user" => config.user = Some(value),
649 "password" => config.password = Some(value),
650 "require_auth" => config.require_auth = Some(parse_auth_methods(&value)?),
651 "dbname" => config.dbname = Some(value),
652 "application_name" => config.application_name = Some(value),
653 "connect_timeout" => {
654 let secs: u64 = value.parse().ok().filter(|&s| s > 0).ok_or_else(|| {
655 Error::config(format!(
656 "connect_timeout={value} is not a whole number of seconds above zero"
657 ))
658 })?;
659 config.connect_timeout = Duration::from_secs(secs);
660 }
661 other => {
662 return Err(Error::config(format!(
663 "the URL parameter {other:?} is not supported; the supported ones are \
664 sslmode, sslrootcert, host, port, user, password, dbname, \
665 application_name, connect_timeout and require_auth"
666 )))
667 }
668 }
669 }
670
671 let verify = || -> Result<Tls, Error> {
672 match sslrootcert.as_deref() {
673 None | Some("system") => Ok(Tls::Verify(TlsConnector::with_system_roots().map_err(
674 |e| {
675 Error::io(
676 ErrorKind::Config,
677 "cannot load the machine's certificate authorities for sslmode",
678 e,
679 )
680 },
681 )?)),
682 Some(path) => {
683 let pem = std::fs::read(path).map_err(|e| {
684 Error::io(
685 ErrorKind::Config,
686 format!("cannot read sslrootcert {path:?}"),
687 e,
688 )
689 })?;
690 let connector = TlsConnector::with_root_pem(&pem).map_err(|e| {
691 Error::io(
692 ErrorKind::Config,
693 format!("sslrootcert {path:?} holds no usable certificate"),
694 e,
695 )
696 })?;
697 Ok(Tls::Verify(connector))
698 }
699 }
700 };
701 match sslmode.as_deref() {
702 None if sslrootcert.is_some() => config.tls = Some(verify()?),
703 None => {}
704 Some("disable") => config.tls = Some(Tls::Disable),
705 Some("require" | "verify-ca" | "verify-full") => config.tls = Some(verify()?),
706 Some(mode @ ("prefer" | "allow")) => {
707 return Err(Error::config(format!(
708 "sslmode={mode} would silently connect without encryption when TLS fails; \
709 use sslmode=verify-full to require TLS, or sslmode=disable on a trusted network"
710 )))
711 }
712 Some(other) => {
713 return Err(Error::config(format!(
714 "sslmode={other} is not a known mode; use disable, require, verify-ca or verify-full"
715 )))
716 }
717 }
718 Ok(config)
719}
720
721fn parse_auth_methods(list: &str) -> Result<Vec<AuthMethod>, Error> {
722 let all = [
723 AuthMethod::None,
724 AuthMethod::Password,
725 AuthMethod::Md5,
726 AuthMethod::ScramSha256,
727 ];
728 list.split(',')
729 .map(|name| {
730 if name.starts_with('!') {
731 return Err(Error::config(format!(
732 "require_auth={list}: giong-postgres takes the methods to allow, not the ones \
733 to refuse (libpq's {name:?}); list the allowed ones, such as \
734 require_auth=scram-sha-256"
735 )));
736 }
737 all.into_iter().find(|m| m.name() == name).ok_or_else(|| {
738 Error::config(format!(
739 "require_auth={list}: {name:?} is not a method giong-postgres knows; use \
740 scram-sha-256, md5, password or none, separated by commas"
741 ))
742 })
743 })
744 .collect()
745}
746
747fn parse_port(port: &str) -> Result<u16, Error> {
748 port.parse().ok().filter(|&p| p != 0).ok_or_else(|| {
749 Error::config(format!(
750 "the port {port:?} in the URL is not a number from 1 to 65535"
751 ))
752 })
753}
754
755#[cfg(test)]
756mod tests {
757 use super::*;
758
759 #[test]
760 fn a_config_without_its_password_keeps_everything_else() {
761 let c = Config::from_url("postgres://app:secret@db.internal:6543/shop?sslmode=disable")
762 .unwrap();
763 let bare = c.without_password();
764 assert_eq!(bare.password, None);
765 assert!(!Arc::ptr_eq(&bare.scram_keys, &c.scram_keys));
766 assert_eq!(c.password.as_deref(), Some("secret"));
767 assert_eq!((&bare.host, bare.port), (&c.host, c.port));
768 assert_eq!(bare.user, c.user);
769 assert!(bare.tls_connector().unwrap().is_none());
770 }
771
772 #[test]
773 fn a_full_url_is_read() {
774 let c = Config::from_url(
775 "postgres://app%40corp:p%3Ass%40w@db.internal:6543/shop%20db?application_name=api&connect_timeout=3&sslmode=disable",
776 )
777 .unwrap();
778 assert_eq!(c.host, Host::Tcp("db.internal".into()));
779 assert_eq!(c.port, 6543);
780 assert_eq!(c.user.as_deref(), Some("app@corp"));
781 assert_eq!(c.password.as_deref(), Some("p:ss@w"));
782 assert_eq!(c.dbname.as_deref(), Some("shop db"));
783 assert_eq!(c.application_name.as_deref(), Some("api"));
784 assert_eq!(c.connect_timeout, Duration::from_secs(3));
785 assert!(c.tls_connector().unwrap().is_none());
786 assert!(!format!("{c:?}").contains("p:ss@w"));
787 }
788
789 #[test]
790 fn hosts_can_be_ipv6_or_sockets() {
791 let c = Config::from_url("postgresql://u@[::1]:5433").unwrap();
792 assert_eq!(c.host, Host::Tcp("::1".into()));
793 assert_eq!(c.port, 5433);
794 assert_eq!(c.target(), "[::1]:5433");
795 assert!(c.is_local());
796
797 let c = Config::from_url("postgres:///shop?host=/var/run/postgresql&user=u").unwrap();
798 assert_eq!(c.host, Host::Unix("/var/run/postgresql".into()));
799 assert_eq!(c.target(), "/var/run/postgresql/.s.PGSQL.5432");
800 let c = Config::from_url("postgres://u@%2Ftmp/shop").unwrap();
801 assert_eq!(c.host, Host::Unix("/tmp".into()));
802 }
803
804 #[test]
805 fn tls_is_on_for_remote_hosts_unless_disabled() {
806 assert!(Config::new()
807 .host("127.0.0.1")
808 .tls_connector()
809 .unwrap()
810 .is_none());
811 assert!(Config::new()
812 .host("localhost")
813 .tls_connector()
814 .unwrap()
815 .is_none());
816 let cert = rcgen::generate_simple_self_signed(vec!["localhost".into()]).unwrap();
817 let connector = TlsConnector::with_root_pem(cert.cert.pem().as_bytes()).unwrap();
818 let unix = Config::new()
819 .host("/tmp")
820 .tls(Tls::Verify(connector.clone()));
821 assert!(unix.tls_connector().unwrap().is_none());
822 let local = Config::new().host("127.0.0.1").tls(Tls::Verify(connector));
823 assert!(local.tls_connector().unwrap().is_some());
824 assert!(Config::new()
825 .host("10.1.2.3")
826 .tls(Tls::Disable)
827 .tls_connector()
828 .unwrap()
829 .is_none());
830 if let Ok(Some(_)) = Config::new().host("db.example.com").tls_connector() {
832 } else {
833 panic!("expected TLS for a remote host");
834 }
835 }
836
837 #[test]
838 fn bad_urls_say_what_is_wrong() {
839 let err = |url: &str| Config::from_url(url).unwrap_err().to_string();
840 assert!(err("mysql://x").contains("postgres://"));
841 assert!(err("postgres://u@h/db?sslmode=prefer").contains("silently"));
842 assert!(err("postgres://u@h/db?sslmode=bogus").contains("not a known mode"));
843 assert!(err("postgres://u@h/db?sslcert=x").contains("not supported"));
844 assert!(err("postgres://u@h:99999/db").contains("1 to 65535"));
845 assert!(err("postgres://u@h1,h2/db").contains("several hosts"));
846 assert!(err("postgres://u@[::1/db").contains("closing"));
847 assert!(err("postgres://u:%zz@h/db").contains("%25"));
848 assert!(err("postgres://u@h/db?connect_timeout=0").contains("above zero"));
849 assert!(err("postgres://u@h/db?sslrootcert=/nonexistent/ca.pem").contains("cannot read"));
850 assert!(err("postgres://u@h/db?flag").contains("no value"));
851 }
852
853 #[test]
854 fn statement_timeout_can_be_left_to_the_server() {
855 let c = Config::new();
856 assert_eq!(c.statement_timeout, Some(Duration::from_secs(30)));
857 let c = c.statement_timeout(Duration::from_secs(5));
858 assert_eq!(c.statement_timeout, Some(Duration::from_secs(5)));
859 assert_eq!(c.statement_timeout(None).statement_timeout, None);
860 }
861
862 #[test]
863 fn require_auth_reads_libpq_names() {
864 let c = Config::from_url("postgres://u@h/db?require_auth=scram-sha-256,md5").unwrap();
865 assert_eq!(
866 c.require_auth,
867 Some(vec![AuthMethod::ScramSha256, AuthMethod::Md5])
868 );
869 let err = |url: &str| Config::from_url(url).unwrap_err().to_string();
870 assert!(err("postgres://u@h/db?require_auth=!md5").contains("not the ones"));
871 assert!(err("postgres://u@h/db?require_auth=gss").contains("not a method"));
872 }
873 #[test]
874 fn a_password_cut_by_an_unescaped_slash_or_question_mark_is_never_quoted() {
875 for url in [
876 "postgres://app:s3cr/et@db/x",
877 "postgres://app:pa?ss@db/x",
878 "postgres://app:se:cr/et@db/x",
879 "postgres://app:pa?ss=1@db",
880 "postgres://app:pa%zz/ss@db",
881 "postgres://app:12/34@db/x",
885 "postgres://app:p@ss/word@db/x",
886 ] {
887 let e = Config::from_url(url).unwrap_err().to_string();
888 assert!(e.contains("percent-encode"), "{url}: {e}");
889 for piece in ["s3cr", "et", "pa", "ss", "cr", "zz", "12", "34", "word"] {
890 assert!(!e.contains(&format!("\"{piece}")), "{url}: {e}");
891 assert!(!e.contains(&format!("{piece}\"")), "{url}: {e}");
892 }
893 }
894 let c = Config::from_url("postgres://db/x?application_name=me@here").unwrap();
896 assert_eq!(c.application_name.as_deref(), Some("me@here"));
897 let c = Config::from_url("postgres://app:s3cr%2Fet@db/x%40y").unwrap();
900 assert_eq!(c.password.as_deref(), Some("s3cr/et"));
901 assert_eq!(c.target(), "db:5432");
902 assert_eq!(c.dbname.as_deref(), Some("x@y"));
903 }
904}