1use std::fmt;
4use std::path::PathBuf;
5use std::time::Duration;
6
7use crate::error::{PgError, PgResult};
8
9#[non_exhaustive]
14#[derive(Clone)]
15pub struct PgConfig {
16 pub url: String,
18 pub host: String,
20 pub port: u16,
22 pub database: String,
24 pub user: String,
26 pub password: Option<String>,
28 pub ssl_mode: SslMode,
36 pub ssl_root_cert: Option<PathBuf>,
49 pub connect_timeout: Duration,
51 pub statement_timeout: Option<Duration>,
53 pub application_name: Option<String>,
55 pub options: Vec<(String, String)>,
57}
58
59impl fmt::Debug for PgConfig {
60 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
61 f.debug_struct("PgConfig")
62 .field("url", &redact_url(&self.url, self.password.as_deref()))
63 .field("host", &self.host)
64 .field("port", &self.port)
65 .field("database", &self.database)
66 .field("user", &self.user)
67 .field("password", &self.password.as_ref().map(|_| REDACTED))
68 .field("ssl_mode", &self.ssl_mode)
69 .field("ssl_root_cert", &self.ssl_root_cert)
70 .field("connect_timeout", &self.connect_timeout)
71 .field("statement_timeout", &self.statement_timeout)
72 .field("application_name", &self.application_name)
73 .field(
74 "options",
75 &self
76 .options
77 .iter()
78 .map(|(key, value)| {
79 let value = if is_password_key(key) {
80 REDACTED
81 } else {
82 value
83 };
84 (key.as_str(), value)
85 })
86 .collect::<Vec<_>>(),
87 )
88 .finish()
89 }
90}
91
92const REDACTED: &str = "REDACTED";
94
95pub(crate) fn redact_url(url: &str, password: Option<&str>) -> String {
109 let Some(start) = url.find("://").map(|i| i + 3) else {
110 return url.to_owned();
111 };
112 let redacted = redact_userinfo(url, start, password);
113 redact_query_passwords(&redacted, start)
114}
115
116fn redact_userinfo(url: &str, start: usize, password: Option<&str>) -> String {
118 if let Some(password) = password.filter(|p| !p.is_empty())
119 && let Some(redacted) = splice_password(url, start, password)
120 {
121 return redacted;
122 }
123 match url::Url::parse(url) {
124 Ok(parsed) => match parsed.password() {
125 Some(password) => splice_password(url, start, password)
126 .unwrap_or_else(|| redact_to_last_at(url, start)),
127 None if parsed.username().is_empty() && url[start..].contains('@') => {
128 redact_to_last_at(url, start)
129 }
130 None => url.to_owned(),
131 },
132 Err(_) => redact_to_last_at(url, start),
133 }
134}
135
136fn redact_query_passwords(url: &str, start: usize) -> String {
139 let Some(query_start) = url[start..].find('?').map(|i| start + i + 1) else {
140 return url.to_owned();
141 };
142 let query_end = url[query_start..]
143 .find('#')
144 .map_or(url.len(), |i| query_start + i);
145 let query = url[query_start..query_end]
146 .split('&')
147 .map(|pair| {
148 let key = pair.split_once('=').map_or(pair, |(key, _)| key);
149 if is_password_key(key) {
150 format!("{key}={REDACTED}")
151 } else {
152 pair.to_owned()
153 }
154 })
155 .collect::<Vec<_>>()
156 .join("&");
157 format!("{}{query}{}", &url[..query_start], &url[query_end..])
158}
159
160fn is_password_key(key: &str) -> bool {
163 url::form_urlencoded::parse(key.as_bytes())
164 .next()
165 .is_some_and(|(key, _)| key.eq_ignore_ascii_case("password"))
166}
167
168fn splice_password(url: &str, start: usize, password: &str) -> Option<String> {
171 let from = start + url[start..].find(':')? + 1;
172 let after = url[from..].strip_prefix(password)?;
173 after
174 .starts_with('@')
175 .then(|| format!("{}{REDACTED}{after}", &url[..from]))
176}
177
178fn redact_to_last_at(url: &str, start: usize) -> String {
180 match url[start..].rfind('@') {
181 Some(at) => format!("{}{REDACTED}{}", &url[..start], &url[start + at..]),
182 None => url.to_owned(),
183 }
184}
185
186#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
196pub enum SslMode {
197 Disable,
199 #[default]
201 Prefer,
202 Require,
205 VerifyCa,
209 VerifyFull,
211}
212
213fn is_valid_guc_key(key: &str) -> bool {
217 let mut chars = key.chars();
218 matches!(chars.next(), Some(c) if c.is_ascii_alphabetic() || c == '_')
219 && chars.all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '.')
220}
221
222fn is_safe_guc_value(value: &str) -> bool {
228 !value
229 .chars()
230 .any(|c| c.is_whitespace() || c == '\\' || c == '\'')
231}
232
233const PERCENT_ENCODE_HINT: &str = "percent-encode reserved characters in the password \
235 (`@` as %40, `/` as %2F, `?` as %3F, `#` as %23, `:` as %3A)";
236
237fn reject_unencoded_userinfo(parsed: &url::Url) -> PgResult<()> {
245 let in_query_key = parsed.query().is_some_and(|query| {
246 query.split('&').any(|pair| {
247 pair.split_once('=')
248 .map_or(pair, |(key, _)| key)
249 .contains('@')
250 })
251 });
252 if parsed.path().contains('@')
253 || parsed
254 .fragment()
255 .is_some_and(|fragment| fragment.contains('@'))
256 || in_query_key
257 {
258 return Err(PgError::config(format!(
259 "invalid database URL: an `@` follows the host, so the password \
260 seems to contain unencoded reserved characters; {PERCENT_ENCODE_HINT}"
261 )));
262 }
263 Ok(())
264}
265
266fn percent_decode(component: &str, what: &str) -> PgResult<String> {
269 percent_encoding::percent_decode_str(component)
270 .decode_utf8()
271 .map(|decoded| decoded.into_owned())
272 .map_err(|_| {
273 PgError::config(format!(
274 "invalid database URL: the {what} is not valid UTF-8 once percent-decoded"
275 ))
276 })
277}
278
279impl PgConfig {
280 pub fn from_url(url: impl Into<String>) -> PgResult<Self> {
292 let url = url.into();
293 let parsed = url::Url::parse(&url).map_err(|e| {
294 let hint = if url.contains('@') {
297 format!("; {PERCENT_ENCODE_HINT}")
298 } else {
299 String::new()
300 };
301 PgError::config(format!("invalid database URL: {e}{hint}"))
302 })?;
303 reject_unencoded_userinfo(&parsed)?;
304
305 if parsed.scheme() != "postgresql" && parsed.scheme() != "postgres" {
306 return Err(PgError::config(format!(
307 "invalid scheme: expected 'postgresql' or 'postgres', got '{}'",
308 parsed.scheme()
309 )));
310 }
311
312 let host = parsed
313 .host_str()
314 .ok_or_else(|| PgError::config("missing host in URL"))?
315 .to_string();
316
317 let port = parsed.port().unwrap_or(5432);
318
319 let database = percent_decode(parsed.path().trim_start_matches('/'), "database name")?;
320
321 if database.is_empty() {
322 return Err(PgError::config("missing database name in URL"));
323 }
324
325 let mut user = if parsed.username().is_empty() {
326 "postgres".to_string()
327 } else {
328 percent_decode(parsed.username(), "user name")?
329 };
330
331 let mut password = parsed
332 .password()
333 .map(|password| percent_decode(password, "password"))
334 .transpose()?;
335
336 for pair in parsed.query().unwrap_or_default().split('&') {
341 let (key, value) = pair.split_once('=').unwrap_or((pair, ""));
342 match percent_decode(key, "query parameter name")?.as_str() {
343 "user" => user = percent_decode(value, "user name")?,
344 "password" => password = Some(percent_decode(value, "password")?),
345 _ => {}
346 }
347 }
348
349 let mut ssl_mode = SslMode::Prefer;
351 let mut connect_timeout = Duration::from_secs(30);
352 let mut statement_timeout = None;
353 let mut application_name = None;
354 let mut ssl_root_cert = None;
355 let mut options = Vec::new();
356
357 for (key, value) in parsed.query_pairs() {
358 let key_str: &str = &key;
359 let value_str: &str = &value;
360 match key_str {
361 "sslmode" => {
362 ssl_mode = match value_str {
363 "disable" => SslMode::Disable,
364 "prefer" => SslMode::Prefer,
365 "require" => SslMode::Require,
366 "verify-ca" => SslMode::VerifyCa,
367 "verify-full" => SslMode::VerifyFull,
368 other => {
369 return Err(PgError::config(format!("invalid sslmode: {}", other)));
370 }
371 };
372 }
373 "connect_timeout" => {
374 let secs: u64 = value_str
375 .parse()
376 .map_err(|_| PgError::config("invalid connect_timeout"))?;
377 connect_timeout = Duration::from_secs(secs);
378 }
379 "statement_timeout" => {
380 let ms: u64 = value_str
381 .parse()
382 .map_err(|_| PgError::config("invalid statement_timeout"))?;
383 statement_timeout = Some(Duration::from_millis(ms));
384 }
385 "application_name" => {
386 application_name = Some(value_str.to_string());
387 }
388 "sslrootcert" => {
389 ssl_root_cert = Some(PathBuf::from(value_str));
390 }
391 "user" | "password" => {}
393 _ => {
394 options.push((key_str.to_string(), value_str.to_string()));
395 }
396 }
397 }
398
399 Ok(Self {
400 url,
401 host,
402 port,
403 database,
404 user,
405 password,
406 ssl_mode,
407 ssl_root_cert,
408 connect_timeout,
409 statement_timeout,
410 application_name,
411 options,
412 })
413 }
414
415 pub fn builder() -> PgConfigBuilder {
417 PgConfigBuilder::new()
418 }
419
420 pub fn to_pg_config(&self) -> tokio_postgres::Config {
438 let mut config = tokio_postgres::Config::new();
439 config.host(&self.host);
440 config.port(self.port);
441 config.dbname(&self.database);
442 config.user(&self.user);
443
444 if let Some(ref password) = self.password {
445 config.password(password);
446 }
447
448 if let Some(ref app_name) = self.application_name {
449 config.application_name(app_name);
450 }
451
452 config.connect_timeout(self.connect_timeout);
453
454 let driver_ssl_mode = match self.ssl_mode {
455 SslMode::Disable => tokio_postgres::config::SslMode::Disable,
456 SslMode::Prefer => tokio_postgres::config::SslMode::Prefer,
457 SslMode::Require | SslMode::VerifyCa | SslMode::VerifyFull => {
458 tokio_postgres::config::SslMode::Require
459 }
460 };
461 config.ssl_mode(driver_ssl_mode);
462
463 let mut options = Vec::new();
466 if let Some(timeout) = self.statement_timeout {
467 options.push(format!("-c statement_timeout={}", timeout.as_millis()));
469 }
470 for (key, value) in &self.options {
471 if !is_valid_guc_key(key) {
472 tracing::warn!(key = %key, "dropping connection option with invalid GUC name");
473 continue;
474 }
475 if !is_safe_guc_value(value) {
476 tracing::warn!(
479 key = %key,
480 "dropping connection option whose value contains whitespace or quoting characters"
481 );
482 continue;
483 }
484 options.push(format!("-c {}={}", key, value));
485 }
486 if !options.is_empty() {
487 config.options(options.join(" "));
488 }
489
490 config
491 }
492}
493
494#[derive(Default)]
498pub struct PgConfigBuilder {
499 url: Option<String>,
500 host: Option<String>,
501 port: Option<u16>,
502 database: Option<String>,
503 user: Option<String>,
504 password: Option<String>,
505 ssl_mode: Option<SslMode>,
506 ssl_root_cert: Option<PathBuf>,
507 connect_timeout: Option<Duration>,
508 statement_timeout: Option<Duration>,
509 application_name: Option<String>,
510}
511
512impl fmt::Debug for PgConfigBuilder {
513 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
514 f.debug_struct("PgConfigBuilder")
515 .field(
516 "url",
517 &self
518 .url
519 .as_deref()
520 .map(|url| redact_url(url, self.password.as_deref())),
521 )
522 .field("host", &self.host)
523 .field("port", &self.port)
524 .field("database", &self.database)
525 .field("user", &self.user)
526 .field("password", &self.password.as_ref().map(|_| REDACTED))
527 .field("ssl_mode", &self.ssl_mode)
528 .field("ssl_root_cert", &self.ssl_root_cert)
529 .field("connect_timeout", &self.connect_timeout)
530 .field("statement_timeout", &self.statement_timeout)
531 .field("application_name", &self.application_name)
532 .finish()
533 }
534}
535
536impl PgConfigBuilder {
537 pub fn new() -> Self {
539 Self::default()
540 }
541
542 pub fn url(mut self, url: impl Into<String>) -> Self {
544 self.url = Some(url.into());
545 self
546 }
547
548 pub fn host(mut self, host: impl Into<String>) -> Self {
550 self.host = Some(host.into());
551 self
552 }
553
554 pub fn port(mut self, port: u16) -> Self {
556 self.port = Some(port);
557 self
558 }
559
560 pub fn database(mut self, database: impl Into<String>) -> Self {
562 self.database = Some(database.into());
563 self
564 }
565
566 pub fn user(mut self, user: impl Into<String>) -> Self {
568 self.user = Some(user.into());
569 self
570 }
571
572 pub fn password(mut self, password: impl Into<String>) -> Self {
574 self.password = Some(password.into());
575 self
576 }
577
578 pub fn ssl_mode(mut self, mode: SslMode) -> Self {
580 self.ssl_mode = Some(mode);
581 self
582 }
583
584 pub fn ssl_root_cert(mut self, path: impl Into<PathBuf>) -> Self {
588 self.ssl_root_cert = Some(path.into());
589 self
590 }
591
592 pub fn connect_timeout(mut self, timeout: Duration) -> Self {
594 self.connect_timeout = Some(timeout);
595 self
596 }
597
598 pub fn statement_timeout(mut self, timeout: Duration) -> Self {
600 self.statement_timeout = Some(timeout);
601 self
602 }
603
604 pub fn application_name(mut self, name: impl Into<String>) -> Self {
606 self.application_name = Some(name.into());
607 self
608 }
609
610 pub fn build(self) -> PgResult<PgConfig> {
612 if let Some(url) = self.url {
613 let mut config = PgConfig::from_url(url)?;
614
615 if let Some(host) = self.host {
617 config.host = host;
618 }
619 if let Some(port) = self.port {
620 config.port = port;
621 }
622 if let Some(database) = self.database {
623 config.database = database;
624 }
625 if let Some(user) = self.user {
626 config.user = user;
627 }
628 if let Some(password) = self.password {
629 config.password = Some(password);
630 }
631 if let Some(ssl_root_cert) = self.ssl_root_cert {
632 config.ssl_root_cert = Some(ssl_root_cert);
633 }
634 if let Some(ssl_mode) = self.ssl_mode {
635 config.ssl_mode = ssl_mode;
636 }
637 if let Some(timeout) = self.connect_timeout {
638 config.connect_timeout = timeout;
639 }
640 if let Some(timeout) = self.statement_timeout {
641 config.statement_timeout = Some(timeout);
642 }
643 if let Some(name) = self.application_name {
644 config.application_name = Some(name);
645 }
646
647 Ok(config)
648 } else {
649 let host = self.host.unwrap_or_else(|| "localhost".to_string());
651 let port = self.port.unwrap_or(5432);
652 let database = self
653 .database
654 .ok_or_else(|| PgError::config("database name is required"))?;
655 let user = self.user.unwrap_or_else(|| "postgres".to_string());
656
657 let url = format!(
658 "postgresql://{}{}@{}:{}/{}",
659 user,
660 self.password
661 .as_ref()
662 .map(|p| format!(":{}", p))
663 .unwrap_or_default(),
664 host,
665 port,
666 database
667 );
668
669 Ok(PgConfig {
670 url,
671 host,
672 port,
673 database,
674 user,
675 password: self.password,
676 ssl_mode: self.ssl_mode.unwrap_or_default(),
677 ssl_root_cert: self.ssl_root_cert,
678 connect_timeout: self.connect_timeout.unwrap_or(Duration::from_secs(30)),
679 statement_timeout: self.statement_timeout,
680 application_name: self.application_name,
681 options: Vec::new(),
682 })
683 }
684 }
685}
686
687#[cfg(test)]
688mod tests {
689 use super::*;
690
691 #[test]
692 fn test_config_from_url() {
693 let config = PgConfig::from_url("postgresql://user:pass@localhost:5432/mydb").unwrap();
694 assert_eq!(config.host, "localhost");
695 assert_eq!(config.port, 5432);
696 assert_eq!(config.database, "mydb");
697 assert_eq!(config.user, "user");
698 assert_eq!(config.password, Some("pass".to_string()));
699 }
700
701 #[test]
702 fn test_config_from_url_with_params() {
703 let config =
704 PgConfig::from_url("postgresql://localhost/mydb?sslmode=require&application_name=prax")
705 .unwrap();
706 assert_eq!(config.ssl_mode, SslMode::Require);
707 assert_eq!(config.application_name, Some("prax".to_string()));
708 }
709
710 #[test]
711 fn test_to_pg_config_applies_statement_timeout_and_options() {
712 let config = PgConfig::from_url(
713 "postgresql://localhost/mydb?statement_timeout=5000&search_path=public",
714 )
715 .unwrap();
716 let pg_config = config.to_pg_config();
717 assert_eq!(
718 pg_config.get_options(),
719 Some("-c statement_timeout=5000 -c search_path=public")
720 );
721 }
722
723 #[test]
724 fn test_to_pg_config_without_timeouts_or_options_sets_none() {
725 let config = PgConfig::from_url("postgresql://localhost/mydb").unwrap();
726 let pg_config = config.to_pg_config();
727 assert_eq!(pg_config.get_options(), None);
728 }
729
730 #[test]
731 fn test_to_pg_config_drops_option_with_smuggled_value() {
732 let config =
736 PgConfig::from_url("postgresql://localhost/mydb?x=1%20-c%20search_path%3Devil")
737 .unwrap();
738 let pg_config = config.to_pg_config();
739 assert_eq!(pg_config.get_options(), None);
740 }
741
742 #[test]
743 fn test_to_pg_config_drops_option_with_invalid_key() {
744 let config =
745 PgConfig::from_url("postgresql://localhost/mydb?bad%20key=1&search_path=public")
746 .unwrap();
747 let pg_config = config.to_pg_config();
748 assert_eq!(pg_config.get_options(), Some("-c search_path=public"));
750 }
751
752 #[test]
753 fn test_to_pg_config_drops_option_with_quoting_chars() {
754 let config = PgConfig::from_url("postgresql://localhost/mydb?a=b%5Cc&d=e%27f").unwrap();
756 let pg_config = config.to_pg_config();
757 assert_eq!(pg_config.get_options(), None);
758 }
759
760 #[test]
761 fn parses_sslrootcert_from_the_url() {
762 let config = PgConfig::from_url(
763 "postgresql://localhost/mydb?sslmode=verify-full&sslrootcert=/etc/ssl/rds.pem",
764 )
765 .unwrap();
766 assert_eq!(
767 config.ssl_root_cert,
768 Some(std::path::PathBuf::from("/etc/ssl/rds.pem"))
769 );
770 assert!(!config.options.iter().any(|(k, _)| k == "sslrootcert"));
773 }
774
775 #[test]
776 fn sslrootcert_defaults_to_none() {
777 let config = PgConfig::from_url("postgresql://localhost/mydb").unwrap();
778 assert_eq!(config.ssl_root_cert, None);
779 }
780
781 #[test]
782 fn builder_sets_sslrootcert() {
783 let config = PgConfig::builder()
784 .url("postgresql://localhost/mydb")
785 .ssl_root_cert("/etc/ssl/override.pem")
786 .build()
787 .unwrap();
788 assert_eq!(
789 config.ssl_root_cert,
790 Some(std::path::PathBuf::from("/etc/ssl/override.pem"))
791 );
792 }
793
794 #[test]
795 fn test_to_pg_config_maps_sslmode_require() {
796 let config = PgConfig::from_url("postgresql://localhost/mydb?sslmode=require").unwrap();
799 let pg_config = config.to_pg_config();
800 assert_eq!(
801 pg_config.get_ssl_mode(),
802 tokio_postgres::config::SslMode::Require
803 );
804 }
805
806 #[test]
807 fn test_from_url_parses_verify_modes() {
808 let config = PgConfig::from_url("postgresql://localhost/mydb?sslmode=verify-ca").unwrap();
809 assert_eq!(config.ssl_mode, SslMode::VerifyCa);
810 let pg_config = config.to_pg_config();
811 assert_eq!(
812 pg_config.get_ssl_mode(),
813 tokio_postgres::config::SslMode::Require
814 );
815
816 let config = PgConfig::from_url("postgresql://localhost/mydb?sslmode=verify-full").unwrap();
817 assert_eq!(config.ssl_mode, SslMode::VerifyFull);
818
819 assert!(PgConfig::from_url("postgresql://localhost/mydb?sslmode=bogus").is_err());
820 }
821
822 #[test]
823 fn test_to_pg_config_maps_sslmode_disable() {
824 let config = PgConfig::from_url("postgresql://localhost/mydb?sslmode=disable").unwrap();
825 let pg_config = config.to_pg_config();
826 assert_eq!(
827 pg_config.get_ssl_mode(),
828 tokio_postgres::config::SslMode::Disable
829 );
830 }
831
832 #[test]
833 fn test_config_builder() {
834 let config = PgConfig::builder()
835 .host("localhost")
836 .port(5432)
837 .database("mydb")
838 .user("postgres")
839 .build()
840 .unwrap();
841
842 assert_eq!(config.host, "localhost");
843 assert_eq!(config.database, "mydb");
844 }
845
846 const SENTINEL: &str = "hunter2-sentinel";
847
848 #[test]
849 fn debug_redacts_the_password_and_the_url_password() {
850 let config = PgConfig::from_url(format!(
851 "postgres://prax:{SENTINEL}@db.internal:5432/prax?application_name=app"
852 ))
853 .unwrap();
854 let debug = format!("{config:?}");
855 assert!(!debug.contains(SENTINEL), "{debug}");
856 for visible in [
858 "db.internal",
859 "5432",
860 "prax",
861 "application_name=app",
862 "REDACTED",
863 ] {
864 assert!(debug.contains(visible), "{visible}: {debug}");
865 }
866 let alternate = format!("{config:#?}");
867 assert!(!alternate.contains(SENTINEL), "{alternate}");
868 }
869
870 #[test]
871 fn debug_redacts_unencoded_builder_passwords() {
872 let config = PgConfig::builder()
875 .host("db.internal")
876 .database("prax")
877 .user("prax")
878 .password(format!("{SENTINEL}@x/y"))
879 .build()
880 .unwrap();
881 let debug = format!("{config:?}");
882 assert!(!debug.contains("hunter2"), "{debug}");
883 assert!(!debug.contains("x/y"), "{debug}");
884
885 let mut config = config;
887 config.url = format!("postgres://prax:{SENTINEL}@bad host/prax");
888 let debug = format!("{config:?}");
889 assert!(!debug.contains(SENTINEL), "{debug}");
890 }
891
892 #[test]
893 fn url_redaction_touches_only_the_password() {
894 assert_eq!(
897 redact_url(
898 "postgres://postgres:postgres@localhost:5432/postgres",
899 Some("postgres")
900 ),
901 "postgres://postgres:REDACTED@localhost:5432/postgres"
902 );
903 assert_eq!(
904 redact_url(
905 "postgres://app:a@db.internal:5432/app_db?sslmode=disable",
906 Some("a")
907 ),
908 "postgres://app:REDACTED@db.internal:5432/app_db?sslmode=disable"
909 );
910 assert_eq!(
913 redact_url("postgres://app:a@db.internal/app_db", None),
914 "postgres://app:REDACTED@db.internal/app_db"
915 );
916 let config =
917 PgConfig::from_url("postgres://postgres:postgres@localhost:5432/postgres").unwrap();
918 let debug = format!("{config:?}");
919 assert!(
920 debug.contains("\"postgres://postgres:REDACTED@localhost:5432/postgres\""),
921 "{debug}"
922 );
923 assert!(debug.contains("database: \"postgres\""), "{debug}");
924 }
925
926 #[test]
927 fn url_redaction_without_a_password_hint() {
928 for url in [
931 format!("postgres://u:8/{SENTINEL}@host/db"),
932 format!("postgres://u:123#{SENTINEL}@host/db"),
933 format!("postgres://u:123?{SENTINEL}@host/db"),
934 ] {
935 let redacted = redact_url(&url, None);
936 assert!(!redacted.contains(SENTINEL), "{url} -> {redacted}");
937 assert_eq!(redacted, "postgres://REDACTED@host/db", "{url}");
938 }
939 for url in [
941 format!("postgres://u@host/db?password={SENTINEL}&sslmode=disable"),
942 format!("postgres://u@host/db?sslmode=disable&PASSWORD={SENTINEL}#frag"),
943 format!("postgres://u@host/db?pass%77ord={SENTINEL}"),
944 ] {
945 let redacted = redact_url(&url, None);
946 assert!(!redacted.contains(SENTINEL), "{url} -> {redacted}");
947 assert!(redacted.starts_with("postgres://u@host/db?"), "{redacted}");
948 }
949 assert_eq!(
950 redact_url(
951 &format!("postgres://u@host/db?password={SENTINEL}&sslmode=disable"),
952 None
953 ),
954 "postgres://u@host/db?password=REDACTED&sslmode=disable"
955 );
956 assert_eq!(
958 redact_url("postgres://u@host/db", None),
959 "postgres://u@host/db"
960 );
961 }
962
963 #[test]
964 fn debug_redacts_password_options_and_query() {
965 let url = format!("postgres://u@db.internal/prax?password={SENTINEL}&search_path=app");
966 let config = PgConfig::from_url(&url).unwrap();
967 let debug = format!("{config:?}");
968 assert!(!debug.contains(SENTINEL), "{debug}");
969 assert!(debug.contains("search_path"), "{debug}");
970
971 let config =
974 PgConfig::from_url(format!("postgres://u@db.internal/prax?PASSWORD={SENTINEL}"))
975 .unwrap();
976 assert!(config.options.iter().any(|(k, _)| k == "PASSWORD"));
977 let debug = format!("{config:?}");
978 assert!(!debug.contains(SENTINEL), "{debug}");
979
980 let builder = crate::pool::PgPoolBuilder::new().url(&url);
981 let debug = format!("{builder:?}");
982 assert!(!debug.contains(SENTINEL), "{debug}");
983
984 let builder = crate::pool::PgPoolBuilder::new()
985 .url(format!("postgres://u:8/{SENTINEL}@db.internal/prax"));
986 let debug = format!("{builder:?}");
987 assert!(!debug.contains(SENTINEL), "{debug}");
988 }
989
990 #[test]
991 fn debug_keeps_urls_without_a_password() {
992 let config = PgConfig::from_url("postgres://prax@db.internal/prax").unwrap();
993 let debug = format!("{config:?}");
994 assert!(
995 debug.contains("postgres://prax@db.internal/prax"),
996 "{debug}"
997 );
998 assert!(debug.contains("password: None"), "{debug}");
999 }
1000
1001 #[test]
1002 fn config_builder_debug_redacts_secrets() {
1003 let builder = PgConfig::builder()
1004 .url(format!("postgres://prax:{SENTINEL}@db.internal/prax"))
1005 .password(SENTINEL);
1006 let debug = format!("{builder:?}");
1007 assert!(!debug.contains(SENTINEL), "{debug}");
1008 assert!(debug.contains("db.internal"), "{debug}");
1009 }
1010
1011 #[test]
1012 fn from_url_rejects_passwords_with_unencoded_reserved_characters() {
1013 for url in [
1014 "postgres://u:8/Hx@host/db",
1015 "postgres://u:123#456@host/db",
1016 "postgres://u:123?x@host/db",
1017 "postgres://u:a@b/c@host/db",
1018 "postgres://u:8/x:y@host:5432/db?sslmode=disable",
1019 ] {
1020 match PgConfig::from_url(url) {
1021 Err(PgError::Config(message)) => {
1022 assert!(message.contains("percent-encode"), "{url}: {message}");
1023 assert!(
1025 !message.contains("Hx") && !message.contains("456"),
1026 "{message}"
1027 );
1028 }
1029 other => panic!("{url}: expected a config error, got {other:?}"),
1030 }
1031 }
1032 }
1033
1034 #[test]
1035 fn from_url_decodes_percent_encoded_credentials_and_database() {
1036 let config = PgConfig::from_url("postgres://u:8%2FHx@host/db").unwrap();
1037 assert_eq!(
1038 (
1039 config.user.as_str(),
1040 config.password.as_deref(),
1041 config.host.as_str()
1042 ),
1043 ("u", Some("8/Hx"), "host")
1044 );
1045 assert_eq!((config.port, config.database.as_str()), (5432, "db"));
1046
1047 let config = PgConfig::from_url("postgres://u:123%23456@host:6543/db").unwrap();
1048 assert_eq!(config.password.as_deref(), Some("123#456"));
1049 assert_eq!(config.port, 6543);
1050
1051 let config =
1052 PgConfig::from_url("postgres://app%40corp:p%40ss%3Aw%2B@host/my%40db").unwrap();
1053 assert_eq!(config.user, "app@corp");
1054 assert_eq!(config.password.as_deref(), Some("p@ss:w+"));
1055 assert_eq!(config.database, "my@db");
1056 let pg_config = config.to_pg_config();
1057 assert_eq!(pg_config.get_password(), Some(&b"p@ss:w+"[..]));
1058 assert_eq!(pg_config.get_user(), Some("app@corp"));
1059
1060 let config =
1062 PgConfig::from_url("postgres://u:pw@host/db?application_name=me@work").unwrap();
1063 assert_eq!(config.application_name.as_deref(), Some("me@work"));
1064 assert_eq!(config.password.as_deref(), Some("pw"));
1065 }
1066
1067 #[test]
1068 fn from_url_takes_credentials_from_query_parameters() {
1069 let config = PgConfig::from_url(format!(
1070 "postgres://db.internal/prax?user=alice&password={SENTINEL}&sslmode=disable"
1071 ))
1072 .unwrap();
1073 assert_eq!(config.user, "alice");
1074 assert_eq!(config.password.as_deref(), Some(SENTINEL));
1075 assert_eq!(config.ssl_mode, SslMode::Disable);
1076 assert!(config.options.is_empty(), "{:?}", config.options);
1078 let pg_config = config.to_pg_config();
1079 assert_eq!(pg_config.get_user(), Some("alice"));
1080 assert_eq!(pg_config.get_password(), Some(SENTINEL.as_bytes()));
1081 assert_eq!(pg_config.get_options(), None);
1082 let debug = format!("{config:?}");
1084 assert!(!debug.contains(SENTINEL), "{debug}");
1085 assert!(debug.contains("alice"), "{debug}");
1086
1087 let config =
1090 PgConfig::from_url("postgres://bob:old@host/db?password=n%26w+1&user=carol").unwrap();
1091 assert_eq!(config.user, "carol");
1092 assert_eq!(config.password.as_deref(), Some("n&w+1"));
1093 assert!(config.options.is_empty(), "{:?}", config.options);
1094 }
1095
1096 #[test]
1097 fn test_config_invalid_scheme() {
1098 let result = PgConfig::from_url("mysql://localhost/db");
1099 assert!(result.is_err());
1100 }
1101}