1use rustls::ClientConfig;
10use tokio_postgres_rustls::MakeRustlsConnect;
11
12pub fn wants_tls(connection_string: &str) -> bool {
14 sslmode(connection_string)
15 .map(|m| {
16 matches!(
17 m.as_str(),
18 "require" | "verify-ca" | "verify-full" | "prefer"
19 )
20 })
21 .unwrap_or(false)
22}
23
24fn sslmode(connection_string: &str) -> Option<String> {
26 let lower = connection_string.to_ascii_lowercase();
29 let idx = lower.find("sslmode=")?;
30 let rest = &lower[idx + "sslmode=".len()..];
31 let end = rest.find([' ', '&', '\'']).unwrap_or(rest.len());
32 Some(rest[..end].trim().to_string())
33}
34
35pub fn make_connector() -> anyhow::Result<MakeRustlsConnect> {
40 let _ = rustls::crypto::ring::default_provider().install_default();
42
43 let mut roots = rustls::RootCertStore::empty();
44 let result = rustls_native_certs::load_native_certs();
45 if !result.errors.is_empty() {
46 tracing::warn!(
47 "Some native root certificates failed to load: {:?}",
48 result.errors
49 );
50 }
51 for cert in result.certs {
52 let _ = roots.add(cert);
54 }
55 if roots.is_empty() {
56 anyhow::bail!("No native root certificates available for TLS verification");
57 }
58
59 let config = ClientConfig::builder()
60 .with_root_certificates(roots)
61 .with_no_client_auth();
62
63 Ok(MakeRustlsConnect::new(config))
64}
65
66#[cfg(test)]
67mod tests {
68 use super::*;
69
70 #[test]
71 fn test_sslmode_url_form() {
72 assert_eq!(
73 sslmode("postgres://u:p@h/db?sslmode=require"),
74 Some("require".to_string())
75 );
76 }
77
78 #[test]
79 fn test_sslmode_kv_form() {
80 assert_eq!(
81 sslmode("host=localhost sslmode=verify-full dbname=x"),
82 Some("verify-full".to_string())
83 );
84 }
85
86 #[test]
87 fn test_wants_tls() {
88 assert!(wants_tls("postgres://h/db?sslmode=require"));
89 assert!(wants_tls("sslmode=verify-ca"));
90 assert!(wants_tls("sslmode=prefer"));
91 assert!(!wants_tls("postgres://h/db?sslmode=disable"));
92 assert!(!wants_tls("postgres://h/db")); assert!(!wants_tls("host=localhost dbname=x"));
94 }
95}