Skip to main content

mcp_postgres/
tls.rs

1//! TLS support for PostgreSQL connections.
2//!
3//! TLS is opt-in via the connection string's `sslmode`. When `sslmode` is
4//! `require`, `verify-ca`, `verify-full`, or `prefer`, the pool uses a rustls
5//! connector with the system's native root certificates. Otherwise (the
6//! default, or `sslmode=disable`/`allow`) connections stay plaintext, matching
7//! the previous behavior exactly.
8
9use rustls::ClientConfig;
10use tokio_postgres_rustls::MakeRustlsConnect;
11
12/// Return `true` if the connection string opts into TLS via `sslmode`.
13pub 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
24/// Extract the `sslmode` value from a key=value or URL-style connection string.
25fn sslmode(connection_string: &str) -> Option<String> {
26    // Handle both "key=value ..." and "postgres://...?sslmode=..." forms by
27    // scanning for the sslmode token anywhere after a '=' delimiter.
28    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
35/// Build a rustls connector loading the OS trust store.
36///
37/// Installs the ring crypto provider as the process default on first call
38/// (idempotent — a second install is ignored).
39pub fn make_connector() -> anyhow::Result<MakeRustlsConnect> {
40    // Safe to call repeatedly; only the first install wins.
41    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        // Skip individual malformed certs rather than failing the whole pool.
53        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")); // default: plaintext
93        assert!(!wants_tls("host=localhost dbname=x"));
94    }
95}