Skip to main content

hyprstream_pds/
rds.rs

1//! Records/repository RDS (Multi-AZ Postgres) binding and its contract
2//! validation (#1257).
3//!
4//! This module is the single home of the records-role configuration type so
5//! both the application crate (TOML/env layered config) and the discovery
6//! crate (accepted-state authority backend selection) bind the same audited
7//! resolution and verify-full validation code. The app crate re-exports
8//! `RdsConfig` from `crate::config`; no divergent copy may exist.
9
10use serde::{Deserialize, Serialize};
11use std::path::{Path, PathBuf};
12
13/// Records/repository RDS (Multi-AZ Postgres) configuration.
14///
15/// The effective binding is resolved by [`RdsConfig::resolved_from_env`]:
16/// explicit TOML values win; otherwise the records role's scoped environment
17/// variables carry the paths (`HYPRSTREAM_RECORDS_URL_FILE`,
18/// `HYPRSTREAM_RECORDS_SSLROOTCERT_FILE` — metal RDS runtime contract v1.1);
19/// as a last resort the shared credentials directory is consulted
20/// (`$HYPRSTREAM_POSTGRES_CREDENTIALS_PATH/records-url` and `rds-ca.pem`),
21/// but only when the `records-url` file actually exists there, so a
22/// credentials-role-only deployment never silently activates the records
23/// backend. An env var carries only the *path* to a secret file — the
24/// password-bearing URL itself never transits the process environment.
25///
26/// The URL file contains one newline-terminated libpq URL. It is file-backed
27/// so rotation/repointing is a deployment-side file swap, not a secret-bearing
28/// config or environment value.
29///
30/// `cell_id` stamps the cell (single-writer consistency domain) this node
31/// belongs to — the honorable-mention guard from the arch verdict so no code
32/// path assumes it is the only cell in the universe. For the demo leaf this is
33/// the one provider/region cell; it becomes the placement key at Stage 2.
34#[derive(Debug, Clone, Default, Serialize, Deserialize)]
35pub struct RdsConfig {
36    /// Path to the records role's Postgres URL file. When `None` (and no
37    /// env binding resolves), the local backend (RocksDB) is used; deployed
38    /// records services resolve this to the records role's URL file.
39    #[serde(default)]
40    pub url_file: Option<PathBuf>,
41
42    /// Path to the records role's PEM CA file. Mandatory whenever
43    /// `url_file` is configured; the connector pins this trust store for the
44    /// RDS connection.
45    #[serde(default)]
46    pub root_cert_file: Option<PathBuf>,
47
48    /// Cell identifier (consistency-domain label). Stamped into the schema;
49    /// the demo leaf has exactly one cell. Honorable-mention guard from the
50    /// recursive-federation arch verdict.
51    #[serde(default = "default_rds_cell_id")]
52    pub cell_id: String,
53}
54
55/// A contract-validated records URL translated for the pinned driver.
56///
57/// The original password-bearing URL is intentionally private and this type
58/// does not implement `Debug` or `Display`. Metal's `verify-full` policy has
59/// already been checked structurally; the internal URL uses the pinned
60/// driver's `sslmode=require`, with CA and hostname verification supplied by
61/// the rustls connector. It deliberately does not implement `Debug` or
62/// `Display`, so a password-bearing URL cannot leak through diagnostics.
63#[cfg(feature = "postgres")]
64pub(crate) struct ValidatedRdsUrl {
65    driver_url: String,
66    dns_hostname: String,
67}
68
69#[cfg(feature = "postgres")]
70impl ValidatedRdsUrl {
71    #[cfg(feature = "postgres")]
72    pub(crate) fn driver_url(&self) -> &str {
73        &self.driver_url
74    }
75
76    #[cfg(feature = "postgres")]
77    pub(crate) fn dns_hostname(&self) -> &str {
78        &self.dns_hostname
79    }
80}
81
82fn default_rds_cell_id() -> String {
83    "demo-leaf".to_owned()
84}
85
86impl RdsConfig {
87    /// Records-role env var carrying the PATH to the Postgres URL file
88    /// (metal RDS runtime contract v1.1). Never the URL itself.
89    pub const RECORDS_URL_FILE_ENV: &'static str = "HYPRSTREAM_RECORDS_URL_FILE";
90    /// Records-role env var carrying the PATH to the pinned RDS CA PEM.
91    pub const RECORDS_SSLROOTCERT_FILE_ENV: &'static str = "HYPRSTREAM_RECORDS_SSLROOTCERT_FILE";
92    /// Shared Postgres credentials directory env var (metal renders the
93    /// per-role URL files and `rds-ca.pem` under it).
94    pub const POSTGRES_CREDENTIALS_PATH_ENV: &'static str = "HYPRSTREAM_POSTGRES_CREDENTIALS_PATH";
95    /// File names metal renders under the shared credentials directory.
96    const RECORDS_URL_FILE_NAME: &'static str = "records-url";
97    const RDS_CA_FILE_NAME: &'static str = "rds-ca.pem";
98
99    /// True when a Postgres URL is configured (the deployed posture).
100    pub fn is_configured(&self) -> bool {
101        self.url_file.is_some()
102    }
103
104    /// Resolve the effective records-role binding. Explicit TOML values win;
105    /// otherwise the records role's scoped env vars; otherwise the shared
106    /// credentials directory — consulted only when `records-url` actually
107    /// exists there, so a credentials-role-only deployment does not activate
108    /// the records backend. The `cell_id` is preserved as configured.
109    ///
110    /// Fails closed when the directory fallback's `records-url` candidate is
111    /// rendered-but-broken: a stat failure other than `NotFound` (e.g. an
112    /// unreadable parent) is itself an error, and a dangling symlink still
113    /// binds so the later URL read fails loudly. Only a genuinely absent
114    /// candidate leaves the local backend selected — a broken binding must
115    /// never silently become "not rendered".
116    pub fn resolved_from_env(&self) -> anyhow::Result<Self> {
117        self.resolve_with(|key| std::env::var_os(key))
118    }
119
120    /// The testable core of [`Self::resolved_from_env`]: the environment is
121    /// injected so resolution is exercised without mutating process state.
122    /// Public only so the app crate's layered-config tests can inject an
123    /// environment; not a public API surface.
124    #[doc(hidden)]
125    pub fn resolve_with(
126        &self,
127        env: impl Fn(&str) -> Option<std::ffi::OsString>,
128    ) -> anyhow::Result<Self> {
129        let credentials_dir = || env(Self::POSTGRES_CREDENTIALS_PATH_ENV).map(PathBuf::from);
130        let url_file = match self
131            .url_file
132            .clone()
133            .or_else(|| env(Self::RECORDS_URL_FILE_ENV).map(PathBuf::from))
134        {
135            Some(explicit) => Some(explicit),
136            None => match credentials_dir() {
137                Some(dir) => {
138                    let candidate = dir.join(Self::RECORDS_URL_FILE_NAME);
139                    // Directory fallback is opt-in by file presence: a shared
140                    // credentials dir that holds no records role must not turn
141                    // the records store Postgres-bound. Presence is lexical
142                    // (symlink_metadata, not is_file): a dangling symlink
143                    // still binds so the subsequent read fails closed, and a
144                    // stat error other than NotFound (ENOTDIR/EACCES on a
145                    // parent) is itself fatal — both are "rendered but
146                    // broken", never "not rendered".
147                    match std::fs::symlink_metadata(&candidate) {
148                        Ok(_) => Some(candidate),
149                        Err(e) if e.kind() == std::io::ErrorKind::NotFound => None,
150                        Err(e) => {
151                            return Err(anyhow::anyhow!(
152                                "records-role URL candidate at {} cannot be stat'ed ({e}); \
153                                 refusing to silently select the local backend",
154                                candidate.display()
155                            ));
156                        }
157                    }
158                }
159                None => None,
160            },
161        };
162        let root_cert_file = self
163            .root_cert_file
164            .clone()
165            .or_else(|| env(Self::RECORDS_SSLROOTCERT_FILE_ENV).map(PathBuf::from))
166            .or_else(|| credentials_dir().map(|dir| dir.join(Self::RDS_CA_FILE_NAME)));
167        Ok(Self {
168            url_file,
169            root_cert_file,
170            cell_id: self.cell_id.clone(),
171        })
172    }
173
174    /// Read and validate the records role's URL and CA-file bindings.
175    ///
176    /// The contract URL must use `postgresql`/`postgres`, name one nonempty DNS
177    /// host, and contain exactly one query pair `sslmode=verify-full`. After
178    /// validation, that value is translated to the pinned driver's supported
179    /// `require` mode; rustls supplies the CA and hostname verification that
180    /// implements the validated verify-full policy.
181    #[cfg(feature = "postgres")]
182    pub(crate) fn read_url(&self) -> anyhow::Result<ValidatedRdsUrl> {
183        let url_path = self
184            .url_file
185            .as_ref()
186            .ok_or_else(|| anyhow::anyhow!("RDS url_file not configured"))?;
187        let root_cert_path = self
188            .root_cert_file
189            .as_ref()
190            .ok_or_else(|| anyhow::anyhow!("RDS root_cert_file not configured"))?;
191
192        let url = std::fs::read_to_string(url_path)
193            .map_err(|e| anyhow::anyhow!("failed to read RDS url_file at {url_path:?}: {e}"))?;
194        let url = url.trim();
195        anyhow::ensure!(
196            !url.is_empty(),
197            "RDS url_file at {url_path:?} is empty — refusing to start with no backend"
198        );
199
200        let validated = Self::validate_url(url)
201            .map_err(|e| anyhow::anyhow!("RDS URL at {url_path:?} is nonconformant: {e}"))?;
202
203        std::fs::File::open(root_cert_path).map_err(|e| {
204            anyhow::anyhow!("RDS root_cert_file at {root_cert_path:?} is not readable: {e}")
205        })?;
206
207        Ok(validated)
208    }
209
210    /// Structurally validate the v1.1 URL and produce a driver-compatible URL.
211    /// The URL itself is never included in an error.
212    #[cfg(feature = "postgres")]
213    pub(crate) fn validate_url(url: &str) -> anyhow::Result<ValidatedRdsUrl> {
214        let mut parsed =
215            url::Url::parse(url).map_err(|e| anyhow::anyhow!("not a valid URL: {e}"))?;
216
217        anyhow::ensure!(
218            matches!(parsed.scheme(), "postgresql" | "postgres"),
219            "URL scheme must be 'postgresql' or 'postgres', got '{}'",
220            parsed.scheme()
221        );
222
223        let dns_hostname = match parsed.host() {
224            Some(url::Host::Domain(host)) if !host.is_empty() => {
225                let normalized = host.trim_end_matches('.').to_ascii_lowercase();
226                let loopback_name = ["local", "host"].concat();
227                let loopback_v4 = ["127", "0", "0", "1"].join(".");
228                anyhow::ensure!(
229                    normalized != loopback_name && normalized != loopback_v4,
230                    "URL host must not be a local loopback endpoint"
231                );
232                host.to_owned()
233            }
234            Some(url::Host::Ipv4(host)) => {
235                anyhow::ensure!(
236                    !host.is_loopback(),
237                    "URL host must not be a local loopback endpoint"
238                );
239                host.to_string()
240            }
241            Some(url::Host::Ipv6(host)) => {
242                anyhow::ensure!(
243                    !host.is_loopback(),
244                    "URL host must not be a local loopback endpoint"
245                );
246                host.to_string()
247            }
248            Some(url::Host::Domain(_)) | None => anyhow::bail!("URL is missing a nonempty host"),
249        };
250
251        let mut sslmode_values = Vec::new();
252        let mut driver_pairs = Vec::new();
253        for (key, value) in parsed.query_pairs() {
254            if key == "sslmode" {
255                sslmode_values.push(value.into_owned());
256                driver_pairs.push((key.into_owned(), "require".to_owned()));
257            } else {
258                driver_pairs.push((key.into_owned(), value.into_owned()));
259            }
260        }
261        anyhow::ensure!(
262            sslmode_values.len() == 1,
263            "URL must contain exactly one sslmode query parameter"
264        );
265        anyhow::ensure!(
266            sslmode_values[0] == "verify-full",
267            "sslmode must be exactly 'verify-full'"
268        );
269
270        parsed.query_pairs_mut().clear().extend_pairs(driver_pairs);
271        Ok(ValidatedRdsUrl {
272            driver_url: parsed.into(),
273            dns_hostname,
274        })
275    }
276
277    /// Return the explicit records CA-file path.
278    pub fn root_cert_file(&self) -> Option<&Path> {
279        self.root_cert_file.as_deref()
280    }
281}
282
283#[cfg(all(feature = "postgres", not(target_arch = "wasm32")))]
284impl RdsConfig {
285    /// Open the shared audited KV shell read-write (the app record store /
286    /// publisher path). Runs the idempotent schema migration; FATAL on
287    /// unavailable RDS — never a local fallback.
288    pub fn connect_kv(&self) -> anyhow::Result<crate::pgsql_kv::PgKv> {
289        let url = self.read_url()?;
290        let root_cert = self
291            .root_cert_file()
292            .ok_or_else(|| anyhow::anyhow!("RDS root_cert_file not configured"))?;
293        crate::pgsql_kv::PgKv::connect(&url, root_cert, &self.cell_id)
294    }
295
296    /// Open the KV shell READ-ONLY for resolver startup: no schema migration,
297    /// and an unprovisioned store fails closed (lost history is fatal, never
298    /// recreated at resolver bootstrap).
299    pub fn connect_kv_readonly(&self) -> anyhow::Result<crate::pgsql_kv::PgKv> {
300        let url = self.read_url()?;
301        let root_cert = self
302            .root_cert_file()
303            .ok_or_else(|| anyhow::anyhow!("RDS root_cert_file not configured"))?;
304        crate::pgsql_kv::PgKv::connect_readonly(&url, root_cert)
305    }
306
307    /// Open replay admission without creating checkpointed PDS state.
308    pub fn connect_replay_admission(&self) -> anyhow::Result<crate::pgsql_kv::PgKv> {
309        let url = self.read_url()?;
310        let root_cert = self
311            .root_cert_file()
312            .ok_or_else(|| anyhow::anyhow!("RDS root_cert_file not configured"))?;
313        crate::pgsql_kv::PgKv::connect_replay_admission(&url, root_cert)
314    }
315}
316
317#[cfg(test)]
318#[allow(clippy::unwrap_used, clippy::expect_used)]
319mod tests {
320    use super::*;
321
322    #[cfg(feature = "postgres")]
323    fn rds_fixture(url: &str) -> (tempfile::TempDir, RdsConfig) {
324        let dir = tempfile::TempDir::new().unwrap_or_else(|e| panic!("{e}"));
325        let url_file = dir.path().join("records-url");
326        let root_cert_file = dir.path().join("rds-ca.pem");
327        std::fs::write(&url_file, format!("{url}\n")).unwrap_or_else(|e| panic!("{e}"));
328        // RdsConfig validates readability; the connector performs PEM parsing.
329        std::fs::write(&root_cert_file, b"connector-validates-this-pem")
330            .unwrap_or_else(|e| panic!("{e}"));
331        let config = RdsConfig {
332            url_file: Some(url_file),
333            root_cert_file: Some(root_cert_file),
334            cell_id: "test-cell".to_owned(),
335        };
336        (dir, config)
337    }
338
339    /// Empty env lookup for `resolve_with` tests.
340    fn no_env(_: &str) -> Option<std::ffi::OsString> {
341        None
342    }
343
344    #[test]
345    fn rds_resolution_leaves_local_backend_when_unbound() {
346        let config = RdsConfig::default();
347        let resolved = config
348            .resolve_with(no_env)
349            .unwrap_or_else(|e| panic!("unbound resolution must not fail: {e}"));
350        assert!(!resolved.is_configured());
351        assert_eq!(resolved.root_cert_file, None);
352    }
353
354    #[test]
355    fn rds_resolution_binds_role_scoped_env_files() {
356        let config = RdsConfig::default();
357        let resolved = config
358            .resolve_with(|key| match key {
359                "HYPRSTREAM_RECORDS_URL_FILE" => Some("/run/cred/records-url".into()),
360                "HYPRSTREAM_RECORDS_SSLROOTCERT_FILE" => Some("/run/cred/rds-ca.pem".into()),
361                _ => None,
362            })
363            .unwrap_or_else(|e| panic!("scoped-env resolution must not fail: {e}"));
364        assert!(resolved.is_configured());
365        assert_eq!(
366            resolved.url_file.as_deref(),
367            Some(Path::new("/run/cred/records-url"))
368        );
369        assert_eq!(
370            resolved.root_cert_file.as_deref(),
371            Some(Path::new("/run/cred/rds-ca.pem"))
372        );
373    }
374
375    #[test]
376    fn rds_resolution_toml_overrides_env() {
377        let config = RdsConfig {
378            url_file: Some(PathBuf::from("/toml/records-url")),
379            root_cert_file: Some(PathBuf::from("/toml/rds-ca.pem")),
380            cell_id: "toml-cell".to_owned(),
381        };
382        let resolved = config
383            .resolve_with(|key| match key {
384                "HYPRSTREAM_RECORDS_URL_FILE" => Some("/env/records-url".into()),
385                "HYPRSTREAM_RECORDS_SSLROOTCERT_FILE" => Some("/env/rds-ca.pem".into()),
386                "HYPRSTREAM_POSTGRES_CREDENTIALS_PATH" => Some("/env".into()),
387                _ => None,
388            })
389            .unwrap_or_else(|e| panic!("TOML-pinned resolution must not fail: {e}"));
390        assert_eq!(
391            resolved.url_file.as_deref(),
392            Some(Path::new("/toml/records-url"))
393        );
394        assert_eq!(
395            resolved.root_cert_file.as_deref(),
396            Some(Path::new("/toml/rds-ca.pem"))
397        );
398        assert_eq!(resolved.cell_id, "toml-cell");
399    }
400
401    #[test]
402    fn rds_resolution_uses_credentials_dir_only_when_records_url_exists() {
403        let dir = tempfile::TempDir::new().unwrap_or_else(|e| panic!("{e}"));
404        let env = |key: &str| match key {
405            "HYPRSTREAM_POSTGRES_CREDENTIALS_PATH" => Some(dir.path().as_os_str().to_owned()),
406            _ => None,
407        };
408
409        // A credentials-role-only directory (no records-url) must NOT
410        // activate the records backend.
411        let config = RdsConfig::default();
412        let resolved = config
413            .resolve_with(env)
414            .unwrap_or_else(|e| panic!("absent records-url must resolve cleanly: {e}"));
415        assert!(
416            !resolved.is_configured(),
417            "a shared credentials dir without records-url stays on the local backend"
418        );
419
420        // Once metal renders the records role into the directory, the binding
421        // resolves — including the CA file at its rendered location.
422        std::fs::write(dir.path().join("records-url"), b"postgresql://x\n")
423            .unwrap_or_else(|e| panic!("{e}"));
424        let resolved = config
425            .resolve_with(env)
426            .unwrap_or_else(|e| panic!("rendered records-url must resolve: {e}"));
427        assert!(resolved.is_configured());
428        assert_eq!(
429            resolved.url_file.as_deref(),
430            Some(dir.path().join("records-url").as_path())
431        );
432        assert_eq!(
433            resolved.root_cert_file.as_deref(),
434            Some(dir.path().join("rds-ca.pem").as_path())
435        );
436    }
437
438    #[test]
439    fn rds_resolution_role_env_wins_over_credentials_dir() {
440        let dir = tempfile::TempDir::new().unwrap_or_else(|e| panic!("{e}"));
441        std::fs::write(dir.path().join("records-url"), b"postgresql://x\n")
442            .unwrap_or_else(|e| panic!("{e}"));
443        let config = RdsConfig::default();
444        let resolved = config
445            .resolve_with(|key| match key {
446                "HYPRSTREAM_RECORDS_URL_FILE" => Some("/scoped/records-url".into()),
447                "HYPRSTREAM_POSTGRES_CREDENTIALS_PATH" => Some(dir.path().as_os_str().to_owned()),
448                _ => None,
449            })
450            .unwrap_or_else(|e| panic!("scoped-env resolution must not fail: {e}"));
451        assert_eq!(
452            resolved.url_file.as_deref(),
453            Some(Path::new("/scoped/records-url")),
454            "the role-scoped env binding takes precedence over the shared directory"
455        );
456        // The CA still falls through to the rendered directory default.
457        assert_eq!(
458            resolved.root_cert_file.as_deref(),
459            Some(dir.path().join("rds-ca.pem").as_path())
460        );
461    }
462
463    #[cfg(unix)]
464    #[test]
465    fn rds_resolution_distinguishes_absent_dangling_and_unstatable_records_url() {
466        let dir = tempfile::TempDir::new().unwrap_or_else(|e| panic!("{e}"));
467        let env = |key: &str| match key {
468            "HYPRSTREAM_POSTGRES_CREDENTIALS_PATH" => Some(dir.path().as_os_str().to_owned()),
469            _ => None,
470        };
471        let config = RdsConfig::default();
472
473        // Genuinely absent → unbound (local backend), no error.
474        let resolved = config
475            .resolve_with(env)
476            .unwrap_or_else(|e| panic!("absent records-url must resolve cleanly: {e}"));
477        assert!(!resolved.is_configured());
478
479        // Dangling symlink → the binding still resolves (lexical presence),
480        // so the later URL read fails closed instead of silently keeping the
481        // local backend while an AZ peer runs RDS.
482        let dangling = dir.path().join("records-url");
483        std::os::unix::fs::symlink(dir.path().join("missing-target"), &dangling)
484            .unwrap_or_else(|e| panic!("{e}"));
485        let resolved = config
486            .resolve_with(env)
487            .unwrap_or_else(|e| panic!("dangling records-url must still resolve: {e}"));
488        assert!(
489            resolved.is_configured(),
490            "a dangling records-url is rendered-but-broken: it must bind so the read fails closed"
491        );
492
493        // A stat error other than NotFound (here ENOTDIR: the credentials
494        // path is a regular file) is fatal at resolution, never silently local.
495        let file_dir = tempfile::TempDir::new().unwrap_or_else(|e| panic!("{e}"));
496        let not_a_dir = file_dir.path().join("not-a-dir");
497        std::fs::write(&not_a_dir, b"x").unwrap_or_else(|e| panic!("{e}"));
498        let err = config
499            .resolve_with(|key| match key {
500                "HYPRSTREAM_POSTGRES_CREDENTIALS_PATH" => Some(not_a_dir.as_os_str().to_owned()),
501                _ => None,
502            })
503            .err()
504            .unwrap_or_else(|| panic!("an unstat-able records-url candidate must fail resolution"));
505        assert!(
506            err.to_string().contains("cannot be stat'ed"),
507            "the error must name the stat failure: {err}"
508        );
509    }
510
511    #[cfg(feature = "postgres")]
512    #[test]
513    fn rds_contract_accepts_exact_verify_full_and_translates_for_driver() {
514        let (_dir, config) = rds_fixture(
515            "postgresql://records:secret@db.internal.example/records?application_name=pds&sslmode=verify-full",
516        );
517        let validated = config
518            .read_url()
519            .unwrap_or_else(|e| panic!("valid records URL rejected: {e}"));
520
521        assert_eq!(validated.dns_hostname, "db.internal.example");
522        let parsed = url::Url::parse(&validated.driver_url)
523            .unwrap_or_else(|e| panic!("translated URL is invalid: {e}"));
524        let sslmodes: Vec<_> = parsed
525            .query_pairs()
526            .filter(|(key, _)| key == "sslmode")
527            .map(|(_, value)| value.into_owned())
528            .collect();
529        assert_eq!(sslmodes, ["require"]);
530    }
531
532    #[cfg(feature = "postgres")]
533    #[test]
534    fn rds_contract_matches_decoded_sslmode_query_keys() {
535        let (_dir, config) = rds_fixture(
536            "postgresql://records:secret@db.internal.example/records?ssl%6dode=verify-full",
537        );
538        assert!(config.read_url().is_ok());
539    }
540
541    #[cfg(feature = "postgres")]
542    #[test]
543    fn rds_contract_rejects_nonconforming_urls() {
544        let rejected = [
545            ("malformed", "not a URL"),
546            (
547                "wrong-scheme",
548                "https://db.internal.example/records?sslmode=verify-full",
549            ),
550            ("absent-host", "postgresql:///records?sslmode=verify-full"),
551            (
552                "canonical-ipv4-loopback",
553                "postgresql://127.0.0.1/records?sslmode=verify-full",
554            ),
555            (
556                "canonical-ipv6-loopback",
557                "postgresql://[::1]/records?sslmode=verify-full",
558            ),
559            (
560                "localhost",
561                "postgresql://localhost/records?sslmode=verify-full",
562            ),
563            ("absent-sslmode", "postgresql://db.internal.example/records"),
564            (
565                "disable",
566                "postgresql://db.internal.example/records?sslmode=disable",
567            ),
568            (
569                "allow",
570                "postgresql://db.internal.example/records?sslmode=allow",
571            ),
572            (
573                "prefer",
574                "postgresql://db.internal.example/records?sslmode=prefer",
575            ),
576            (
577                "require",
578                "postgresql://db.internal.example/records?sslmode=require",
579            ),
580            (
581                "verify-ca",
582                "postgresql://db.internal.example/records?sslmode=verify-ca",
583            ),
584            (
585                "duplicate",
586                "postgresql://db.internal.example/records?sslmode=verify-full&sslmode=verify-full",
587            ),
588            (
589                "conflict",
590                "postgresql://db.internal.example/records?sslmode=verify-full&sslmode=require",
591            ),
592            (
593                "decoded-duplicate",
594                "postgresql://db.internal.example/records?sslmode=verify-full&ssl%6dode=verify-full",
595            ),
596            (
597                "userinfo-marker-bypass",
598                "postgresql://user:sslmode=verify-full@db.internal.example/records",
599            ),
600        ];
601
602        for (case, url) in rejected {
603            let (_dir, config) = rds_fixture(url);
604            assert!(
605                config.read_url().is_err(),
606                "nonconforming case {case} was accepted"
607            );
608        }
609    }
610
611    #[cfg(feature = "postgres")]
612    #[test]
613    fn rds_contract_does_not_extend_loopback_rejection_to_other_ip_spellings() {
614        for url in [
615            "postgresql://192.0.2.10/records?sslmode=verify-full",
616            "postgresql://[2001:db8::10]/records?sslmode=verify-full",
617        ] {
618            let (_dir, config) = rds_fixture(url);
619            assert!(config.read_url().is_ok(), "relaxed contract rejected {url}");
620        }
621    }
622
623    #[cfg(feature = "postgres")]
624    #[test]
625    fn rds_contract_requires_explicit_readable_ca_file() {
626        let (_dir, mut config) = rds_fixture(
627            "postgres://records:secret@db.internal.example/records?sslmode=verify-full",
628        );
629        config.root_cert_file = None;
630        assert!(config.read_url().is_err());
631
632        config.root_cert_file = Some(std::path::PathBuf::from("/missing/records-rds-ca.pem"));
633        assert!(config.read_url().is_err());
634    }
635}