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;
11use zeroize::Zeroizing;
12
13use crate::auth::KeyCache;
14use crate::error::{Error, ErrorKind};
15
16#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
19#[non_exhaustive]
20pub enum AuthMethod {
21 None,
25 Password,
27 Md5,
29 ScramSha256,
31}
32
33impl AuthMethod {
34 pub(crate) fn name(self) -> &'static str {
36 match self {
37 AuthMethod::None => "none",
38 AuthMethod::Password => "password",
39 AuthMethod::Md5 => "md5",
40 AuthMethod::ScramSha256 => "scram-sha-256",
41 }
42 }
43}
44
45#[derive(Clone)]
50#[non_exhaustive]
51pub enum Tls {
52 Disable,
55 Verify(TlsConnector),
59}
60
61impl fmt::Debug for Tls {
62 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
63 match self {
64 Tls::Disable => f.write_str("Disable"),
65 Tls::Verify(_) => f.write_str("Verify(..)"),
66 }
67 }
68}
69
70#[derive(Clone, Debug, PartialEq, Eq)]
71pub(crate) enum Host {
72 Tcp(String),
74 Unix(PathBuf),
76}
77
78#[derive(Clone)]
81pub(crate) struct Password(Zeroizing<String>);
82
83impl Password {
84 fn new(password: &str) -> Self {
85 Self(Zeroizing::new(password.to_owned()))
86 }
87}
88
89impl std::ops::Deref for Password {
90 type Target = str;
91
92 fn deref(&self) -> &str {
93 &self.0
94 }
95}
96
97#[derive(Clone)]
126pub struct Config {
127 pub(crate) host: Host,
128 pub(crate) port: u16,
129 pub(crate) user: Option<String>,
130 pub(crate) password: Option<Password>,
131 pub(crate) dbname: Option<String>,
132 pub(crate) application_name: Option<String>,
133 pub(crate) params: Vec<(String, String)>,
134 tls: Option<Tls>,
135 system_roots: Arc<OnceLock<Result<TlsConnector, String>>>,
136 pub(crate) require_auth: Option<Vec<AuthMethod>>,
138 pub(crate) scram_keys: Arc<KeyCache>,
140 pub(crate) connect_timeout: Duration,
141 pub(crate) statement_timeout: Option<Duration>,
142 pub(crate) max_result_size: usize,
143 pub(crate) statement_cache: usize,
144 pub(crate) batch_reads: bool,
145}
146
147impl Default for Config {
148 fn default() -> Self {
149 Self::new()
150 }
151}
152
153fn is_socket_path(host: &str) -> bool {
157 host.starts_with('/') || (cfg!(windows) && std::path::Path::new(host).is_absolute())
158}
159
160impl Config {
161 pub(crate) fn describe(&self) -> String {
164 let server = match &self.host {
165 Host::Tcp(host) if host.contains(':') => format!("[{host}]:{}", self.port),
166 Host::Tcp(host) => format!("{host}:{}", self.port),
167 Host::Unix(dir) => format!("{}/.s.PGSQL.{}", dir.display(), self.port),
168 };
169 match &self.dbname {
170 Some(db) => format!("{server}/{db}"),
171 None => server,
172 }
173 }
174
175 pub fn new() -> Self {
178 Self {
179 host: Host::Tcp("localhost".to_owned()),
180 port: 5432,
181 user: None,
182 password: None,
183 dbname: None,
184 application_name: None,
185 params: Vec::new(),
186 tls: None,
187 system_roots: Arc::new(OnceLock::new()),
188 require_auth: None,
189 scram_keys: Arc::default(),
190 connect_timeout: Duration::from_secs(10),
191 statement_timeout: Some(Duration::from_secs(30)),
192 max_result_size: 64 << 20,
193 statement_cache: 256,
194 batch_reads: false,
195 }
196 }
197
198 pub fn host(mut self, host: &str) -> Self {
203 self.host = if is_socket_path(host) {
204 Host::Unix(PathBuf::from(host))
205 } else {
206 let host = host
207 .strip_prefix('[')
208 .and_then(|h| h.strip_suffix(']'))
209 .unwrap_or(host);
210 Host::Tcp(host.to_owned())
211 };
212 self
213 }
214
215 pub fn port(mut self, port: u16) -> Self {
218 self.port = port;
219 self
220 }
221
222 pub fn user(mut self, user: &str) -> Self {
224 self.user = Some(user.to_owned());
225 self
226 }
227
228 pub fn password(mut self, password: &str) -> Self {
233 self.password = Some(Password::new(password));
234 self.scram_keys = Arc::default();
235 self
236 }
237
238 pub fn database(mut self, database: &str) -> Self {
241 self.dbname = Some(database.to_owned());
242 self
243 }
244
245 pub fn application_name(mut self, name: &str) -> Self {
248 self.application_name = Some(name.to_owned());
249 self
250 }
251
252 pub fn param(mut self, name: &str, value: &str) -> Self {
255 self.params.push((name.to_owned(), value.to_owned()));
256 self
257 }
258
259 pub fn tls(mut self, tls: Tls) -> Self {
262 self.tls = Some(tls);
263 self
264 }
265
266 pub fn require_auth(mut self, methods: &[AuthMethod]) -> Self {
281 self.require_auth = Some(methods.to_vec());
282 self
283 }
284
285 pub fn connect_timeout(mut self, timeout: Duration) -> Self {
288 self.connect_timeout = timeout;
289 self
290 }
291
292 pub fn statement_timeout(mut self, timeout: impl Into<Option<Duration>>) -> Self {
311 self.statement_timeout = timeout.into();
312 self
313 }
314
315 pub fn max_result_size(mut self, bytes: usize) -> Self {
320 self.max_result_size = bytes;
321 self
322 }
323
324 pub fn statement_cache_capacity(mut self, statements: usize) -> Self {
336 self.statement_cache = statements;
337 self
338 }
339
340 pub fn batch_reads(mut self, batch: bool) -> Self {
402 self.batch_reads = batch;
403 self
404 }
405
406 pub fn from_url(url: &str) -> Result<Self, Error> {
435 parse_url(url)
436 }
437
438 pub(crate) fn target(&self) -> String {
441 match &self.host {
442 Host::Tcp(h) if h.contains(':') => format!("[{h}]:{}", self.port),
443 Host::Tcp(h) => format!("{h}:{}", self.port),
444 Host::Unix(dir) => self.socket_path(dir).display().to_string(),
445 }
446 }
447
448 pub(crate) fn socket_path(&self, dir: &Path) -> PathBuf {
449 dir.join(format!(".s.PGSQL.{}", self.port))
450 }
451
452 pub(crate) fn without_password(&self) -> Config {
455 Config {
456 password: None,
457 scram_keys: Arc::default(),
459 ..self.clone()
460 }
461 }
462
463 pub(crate) fn is_local(&self) -> bool {
465 match &self.host {
466 Host::Unix(_) => true,
467 Host::Tcp(h) => {
468 h.eq_ignore_ascii_case("localhost")
469 || h.parse::<IpAddr>().is_ok_and(|ip| match ip {
470 IpAddr::V4(v4) => v4.is_loopback(),
471 IpAddr::V6(v6) => {
472 v6.is_loopback()
473 || v6.to_ipv4_mapped().is_some_and(|v4| v4.is_loopback())
474 }
475 })
476 }
477 }
478 }
479
480 pub(crate) fn tls_connector(&self) -> Result<Option<TlsConnector>, Error> {
482 match (&self.tls, &self.host) {
483 (_, Host::Unix(_)) | (Some(Tls::Disable), _) => Ok(None),
484 (Some(Tls::Verify(connector)), _) => Ok(Some(connector.clone())),
485 (None, _) if self.is_local() => Ok(None),
486 (None, Host::Tcp(host)) => {
487 let roots = self
488 .system_roots
489 .get_or_init(|| TlsConnector::with_system_roots().map_err(|e| e.to_string()));
490 match roots {
491 Ok(connector) => Ok(Some(connector.clone())),
492 Err(e) => Err(Error::new(
493 ErrorKind::Config,
494 format!(
495 "a connection to {host} uses TLS checked against the machine's \
496 certificate authorities, but they could not be loaded ({e}); give \
497 the server's authority with sslrootcert=/path/ca.pem or \
498 Config::tls, or add sslmode=disable if the network is trusted"
499 ),
500 )),
501 }
502 }
503 }
504 }
505}
506
507impl fmt::Debug for Config {
508 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
509 f.debug_struct("Config")
510 .field("host", &self.host)
511 .field("port", &self.port)
512 .field("user", &self.user)
513 .field("password", &self.password.as_ref().map(|_| "<hidden>"))
514 .field("dbname", &self.dbname)
515 .field("application_name", &self.application_name)
516 .field("params", &self.params)
517 .field("tls", &self.tls)
518 .field("require_auth", &self.require_auth)
519 .field("connect_timeout", &self.connect_timeout)
520 .field("statement_timeout", &self.statement_timeout)
521 .field("max_result_size", &self.max_result_size)
522 .field("statement_cache_capacity", &self.statement_cache)
523 .finish()
524 }
525}
526
527impl FromStr for Config {
528 type Err = Error;
529
530 fn from_str(url: &str) -> Result<Self, Error> {
531 parse_url(url)
532 }
533}
534
535fn percent_decode(s: &str, what: &str) -> Result<String, Error> {
536 let bytes = s.as_bytes();
537 let mut out = Zeroizing::new(Vec::with_capacity(bytes.len()));
540 let mut i = 0;
541 while i < bytes.len() {
542 if bytes[i] == b'%' {
543 let hex = bytes
544 .get(i + 1..i + 3)
545 .and_then(|h| std::str::from_utf8(h).ok())
546 .filter(|h| h.bytes().all(|c| c.is_ascii_hexdigit()))
547 .and_then(|h| u8::from_str_radix(h, 16).ok())
548 .ok_or_else(|| {
549 Error::config(format!(
550 "the {what} in the URL has a '%' that is not followed by two hex digits; \
551 write a literal % as %25"
552 ))
553 })?;
554 out.push(hex);
555 i += 3;
556 } else {
557 out.push(bytes[i]);
558 i += 1;
559 }
560 }
561 String::from_utf8(std::mem::take(&mut *out)).map_err(|e| {
562 zeroize::Zeroize::zeroize(&mut e.into_bytes());
563 Error::config(format!("the {what} in the URL is not UTF-8 once decoded"))
564 })
565}
566
567fn parse_url(url: &str) -> Result<Config, Error> {
568 let after_cut = |accepted: bool| {
574 let Some((_, rest)) = url.split_once("://") else {
575 return false;
576 };
577 let Some(cut) = rest.find(['/', '?']) else {
578 return false;
579 };
580 if accepted {
581 let before_query = rest.split_once('?').map_or(rest, |(r, _)| r);
584 before_query.get(cut..).is_some_and(|db| db.contains('@'))
585 } else {
586 rest[cut..].contains('@')
587 }
588 };
589 let cut_password = |read: &str| {
590 Error::config(format!(
591 "the URL {read}has an @ after a / or ?: if the password (or the user name) holds one \
592 of them, percent-encode it (/ as %2F, ? as %3F, @ as %40); write an @ in the \
593 database name as %40 too"
594 ))
595 };
596 match parse(url) {
597 Ok(_) if after_cut(true) => Err(cut_password("")),
598 Err(_) if after_cut(false) => Err(cut_password("could not be read, and it ")),
599 result => result,
600 }
601}
602
603fn parse(url: &str) -> Result<Config, Error> {
604 let rest = url
605 .strip_prefix("postgres://")
606 .or_else(|| url.strip_prefix("postgresql://"))
607 .ok_or_else(|| {
608 Error::config(
609 "a connection URL starts with postgres:// or postgresql://, \
610 as in postgres://user:password@host:5432/dbname",
611 )
612 })?;
613 let (rest, query) = match rest.split_once('?') {
614 Some((r, q)) => (r, Some(q)),
615 None => (rest, None),
616 };
617 let (authority, path) = match rest.split_once('/') {
618 Some((a, p)) => (a, Some(p)),
619 None => (rest, None),
620 };
621 let mut config = Config::new();
622 let hostport = match authority.rsplit_once('@') {
623 Some((userinfo, hostport)) => {
624 let (user, password) = match userinfo.split_once(':') {
625 Some((u, p)) => (u, Some(p)),
626 None => (userinfo, None),
627 };
628 if !user.is_empty() {
629 config.user = Some(percent_decode(user, "user")?);
630 }
631 if let Some(p) = password {
632 config.password = Some(Password(Zeroizing::new(percent_decode(p, "password")?)));
633 }
634 hostport
635 }
636 None => authority,
637 };
638 if hostport.contains(',') {
639 return Err(Error::config(
640 "the URL names several hosts; giong-postgres connects to one, so give one host",
641 ));
642 }
643 let (host, port) = if let Some(v6) = hostport.strip_prefix('[') {
644 let (addr, after) = v6.split_once(']').ok_or_else(|| {
645 Error::config("an IPv6 address in the URL is missing its closing ']'")
646 })?;
647 let port = match after {
648 "" => None,
649 p => Some(p.strip_prefix(':').ok_or_else(|| {
650 Error::config("an IPv6 address in the URL must be followed by :port or nothing")
651 })?),
652 };
653 (format!("[{addr}]"), port)
654 } else {
655 match hostport.rsplit_once(':') {
656 Some((h, p)) => (percent_decode(h, "host")?, Some(p)),
657 None => (percent_decode(hostport, "host")?, None),
658 }
659 };
660 if !host.is_empty() {
661 config = config.host(&host);
662 }
663 if let Some(port) = port {
664 config.port = parse_port(port)?;
665 }
666 if let Some(db) = path.filter(|p| !p.is_empty()) {
667 config.dbname = Some(percent_decode(db, "database name")?);
668 }
669
670 let mut sslmode = None;
671 let mut sslrootcert = None;
672 for pair in query.unwrap_or("").split('&').filter(|p| !p.is_empty()) {
673 let (key, value) = pair.split_once('=').ok_or_else(|| {
674 Error::config(format!(
675 "the URL parameter {pair:?} has no value; write {pair}=value"
676 ))
677 })?;
678 let value = percent_decode(value, key)?;
679 match key {
680 "sslmode" => sslmode = Some(value),
681 "sslrootcert" => sslrootcert = Some(value),
682 "host" => config = config.host(&value),
683 "port" => config.port = parse_port(&value)?,
684 "user" => config.user = Some(value),
685 "password" => config.password = Some(Password(Zeroizing::new(value))),
686 "require_auth" => config.require_auth = Some(parse_auth_methods(&value)?),
687 "dbname" => config.dbname = Some(value),
688 "application_name" => config.application_name = Some(value),
689 "connect_timeout" => {
690 let secs: u64 = value.parse().ok().filter(|&s| s > 0).ok_or_else(|| {
691 Error::config(format!(
692 "connect_timeout={value} is not a whole number of seconds above zero"
693 ))
694 })?;
695 config.connect_timeout = Duration::from_secs(secs);
696 }
697 other => {
698 return Err(Error::config(format!(
699 "the URL parameter {other:?} is not supported; the supported ones are \
700 sslmode, sslrootcert, host, port, user, password, dbname, \
701 application_name, connect_timeout and require_auth"
702 )))
703 }
704 }
705 }
706
707 let verify = || -> Result<Tls, Error> {
708 match sslrootcert.as_deref() {
709 None | Some("system") => Ok(Tls::Verify(TlsConnector::with_system_roots().map_err(
710 |e| {
711 Error::io(
712 ErrorKind::Config,
713 "cannot load the machine's certificate authorities for sslmode",
714 e,
715 )
716 },
717 )?)),
718 Some(path) => {
719 let pem = std::fs::read(path).map_err(|e| {
720 Error::io(
721 ErrorKind::Config,
722 format!("cannot read sslrootcert {path:?}"),
723 e,
724 )
725 })?;
726 let connector = TlsConnector::with_root_pem(&pem).map_err(|e| {
727 Error::io(
728 ErrorKind::Config,
729 format!("sslrootcert {path:?} holds no usable certificate"),
730 e,
731 )
732 })?;
733 Ok(Tls::Verify(connector))
734 }
735 }
736 };
737 match sslmode.as_deref() {
738 None if sslrootcert.is_some() => config.tls = Some(verify()?),
739 None => {}
740 Some("disable") => config.tls = Some(Tls::Disable),
741 Some("require" | "verify-ca" | "verify-full") => config.tls = Some(verify()?),
742 Some(mode @ ("prefer" | "allow")) => {
743 return Err(Error::config(format!(
744 "sslmode={mode} would silently connect without encryption when TLS fails; \
745 use sslmode=verify-full to require TLS, or sslmode=disable on a trusted network"
746 )))
747 }
748 Some(other) => {
749 return Err(Error::config(format!(
750 "sslmode={other} is not a known mode; use disable, require, verify-ca or verify-full"
751 )))
752 }
753 }
754 Ok(config)
755}
756
757fn parse_auth_methods(list: &str) -> Result<Vec<AuthMethod>, Error> {
758 let all = [
759 AuthMethod::None,
760 AuthMethod::Password,
761 AuthMethod::Md5,
762 AuthMethod::ScramSha256,
763 ];
764 list.split(',')
765 .map(|name| {
766 if name.starts_with('!') {
767 return Err(Error::config(format!(
768 "require_auth={list}: giong-postgres takes the methods to allow, not the ones \
769 to refuse (libpq's {name:?}); list the allowed ones, such as \
770 require_auth=scram-sha-256"
771 )));
772 }
773 all.into_iter().find(|m| m.name() == name).ok_or_else(|| {
774 Error::config(format!(
775 "require_auth={list}: {name:?} is not a method giong-postgres knows; use \
776 scram-sha-256, md5, password or none, separated by commas"
777 ))
778 })
779 })
780 .collect()
781}
782
783fn parse_port(port: &str) -> Result<u16, Error> {
784 port.parse().ok().filter(|&p| p != 0).ok_or_else(|| {
785 Error::config(format!(
786 "the port {port:?} in the URL is not a number from 1 to 65535"
787 ))
788 })
789}
790
791#[cfg(test)]
792mod tests {
793 use super::*;
794
795 #[test]
796 fn a_config_without_its_password_keeps_everything_else() {
797 let c = Config::from_url("postgres://app:secret@db.internal:6543/shop?sslmode=disable")
798 .unwrap();
799 let bare = c.without_password();
800 assert!(bare.password.is_none());
801 assert!(!Arc::ptr_eq(&bare.scram_keys, &c.scram_keys));
802 assert_eq!(c.password.as_deref(), Some("secret"));
803 assert_eq!((&bare.host, bare.port), (&c.host, c.port));
804 assert_eq!(bare.user, c.user);
805 assert!(bare.tls_connector().unwrap().is_none());
806 }
807
808 #[test]
809 fn a_full_url_is_read() {
810 let c = Config::from_url(
811 "postgres://app%40corp:p%3Ass%40w@db.internal:6543/shop%20db?application_name=api&connect_timeout=3&sslmode=disable",
812 )
813 .unwrap();
814 assert_eq!(c.host, Host::Tcp("db.internal".into()));
815 assert_eq!(c.port, 6543);
816 assert_eq!(c.user.as_deref(), Some("app@corp"));
817 assert_eq!(c.password.as_deref(), Some("p:ss@w"));
818 assert_eq!(c.dbname.as_deref(), Some("shop db"));
819 assert_eq!(c.application_name.as_deref(), Some("api"));
820 assert_eq!(c.connect_timeout, Duration::from_secs(3));
821 assert!(c.tls_connector().unwrap().is_none());
822 assert!(!format!("{c:?}").contains("p:ss@w"));
823 }
824
825 #[cfg(windows)]
827 #[test]
828 fn windows_paths_are_socket_directories() {
829 let c = Config::new().host(r"C:\pgsql\run");
830 assert_eq!(c.host, Host::Unix(r"C:\pgsql\run".into()));
831 let c = Config::new().host("db.internal");
832 assert_eq!(c.host, Host::Tcp("db.internal".into()));
833 }
834
835 #[test]
836 fn hosts_can_be_ipv6_or_sockets() {
837 let c = Config::from_url("postgresql://u@[::1]:5433").unwrap();
838 assert_eq!(c.host, Host::Tcp("::1".into()));
839 assert_eq!(c.port, 5433);
840 assert_eq!(c.target(), "[::1]:5433");
841 assert!(c.is_local());
842
843 let c = Config::from_url("postgres:///shop?host=/var/run/postgresql&user=u").unwrap();
844 assert_eq!(c.host, Host::Unix("/var/run/postgresql".into()));
845 let socket = std::path::Path::new("/var/run/postgresql").join(".s.PGSQL.5432");
847 assert_eq!(c.target(), socket.display().to_string());
848 let c = Config::from_url("postgres://u@%2Ftmp/shop").unwrap();
849 assert_eq!(c.host, Host::Unix("/tmp".into()));
850 }
851
852 #[test]
853 fn tls_is_on_for_remote_hosts_unless_disabled() {
854 assert!(Config::new()
855 .host("127.0.0.1")
856 .tls_connector()
857 .unwrap()
858 .is_none());
859 assert!(Config::new()
860 .host("localhost")
861 .tls_connector()
862 .unwrap()
863 .is_none());
864 let cert = rcgen::generate_simple_self_signed(vec!["localhost".into()]).unwrap();
865 let connector = TlsConnector::with_root_pem(cert.cert.pem().as_bytes()).unwrap();
866 let unix = Config::new()
867 .host("/tmp")
868 .tls(Tls::Verify(connector.clone()));
869 assert!(unix.tls_connector().unwrap().is_none());
870 let local = Config::new().host("127.0.0.1").tls(Tls::Verify(connector));
871 assert!(local.tls_connector().unwrap().is_some());
872 assert!(Config::new()
873 .host("10.1.2.3")
874 .tls(Tls::Disable)
875 .tls_connector()
876 .unwrap()
877 .is_none());
878 if let Ok(Some(_)) = Config::new().host("db.example.com").tls_connector() {
880 } else {
881 panic!("expected TLS for a remote host");
882 }
883 }
884
885 #[test]
886 fn bad_urls_say_what_is_wrong() {
887 let err = |url: &str| Config::from_url(url).unwrap_err().to_string();
888 assert!(err("mysql://x").contains("postgres://"));
889 assert!(err("postgres://u@h/db?sslmode=prefer").contains("silently"));
890 assert!(err("postgres://u@h/db?sslmode=bogus").contains("not a known mode"));
891 assert!(err("postgres://u@h/db?sslcert=x").contains("not supported"));
892 assert!(err("postgres://u@h:99999/db").contains("1 to 65535"));
893 assert!(err("postgres://u@h1,h2/db").contains("several hosts"));
894 assert!(err("postgres://u@[::1/db").contains("closing"));
895 assert!(err("postgres://u:%zz@h/db").contains("%25"));
896 assert!(err("postgres://u:%+5@h/db").contains("%25"));
898 assert!(err("postgres://u@h/db?connect_timeout=0").contains("above zero"));
899 assert!(err("postgres://u@h/db?sslrootcert=/nonexistent/ca.pem").contains("cannot read"));
900 assert!(err("postgres://u@h/db?flag").contains("no value"));
901 }
902
903 #[test]
904 fn statement_timeout_can_be_left_to_the_server() {
905 let c = Config::new();
906 assert_eq!(c.statement_timeout, Some(Duration::from_secs(30)));
907 let c = c.statement_timeout(Duration::from_secs(5));
908 assert_eq!(c.statement_timeout, Some(Duration::from_secs(5)));
909 assert_eq!(c.statement_timeout(None).statement_timeout, None);
910 }
911
912 #[test]
913 fn require_auth_reads_libpq_names() {
914 let c = Config::from_url("postgres://u@h/db?require_auth=scram-sha-256,md5").unwrap();
915 assert_eq!(
916 c.require_auth,
917 Some(vec![AuthMethod::ScramSha256, AuthMethod::Md5])
918 );
919 let err = |url: &str| Config::from_url(url).unwrap_err().to_string();
920 assert!(err("postgres://u@h/db?require_auth=!md5").contains("not the ones"));
921 assert!(err("postgres://u@h/db?require_auth=gss").contains("not a method"));
922 }
923 #[test]
924 fn a_password_cut_by_an_unescaped_slash_or_question_mark_is_never_quoted() {
925 for url in [
926 "postgres://app:s3cr/et@db/x",
927 "postgres://app:pa?ss@db/x",
928 "postgres://app:se:cr/et@db/x",
929 "postgres://app:pa?ss=1@db",
930 "postgres://app:pa%zz/ss@db",
931 "postgres://app:12/34@db/x",
935 "postgres://app:p@ss/word@db/x",
936 ] {
937 let e = Config::from_url(url).unwrap_err().to_string();
938 assert!(e.contains("percent-encode"), "{url}: {e}");
939 for piece in ["s3cr", "et", "pa", "ss", "cr", "zz", "12", "34", "word"] {
940 assert!(!e.contains(&format!("\"{piece}")), "{url}: {e}");
941 assert!(!e.contains(&format!("{piece}\"")), "{url}: {e}");
942 }
943 }
944 let c = Config::from_url("postgres://db/x?application_name=me@here").unwrap();
946 assert_eq!(c.application_name.as_deref(), Some("me@here"));
947 let c = Config::from_url("postgres://app:s3cr%2Fet@db/x%40y").unwrap();
950 assert_eq!(c.password.as_deref(), Some("s3cr/et"));
951 assert_eq!(c.target(), "db:5432");
952 assert_eq!(c.dbname.as_deref(), Some("x@y"));
953 }
954}