1use serde::{Deserialize, Serialize};
11use std::path::{Path, PathBuf};
12
13#[derive(Debug, Clone, Default, Serialize, Deserialize)]
35pub struct RdsConfig {
36 #[serde(default)]
40 pub url_file: Option<PathBuf>,
41
42 #[serde(default)]
46 pub root_cert_file: Option<PathBuf>,
47
48 #[serde(default = "default_rds_cell_id")]
52 pub cell_id: String,
53}
54
55#[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 pub const RECORDS_URL_FILE_ENV: &'static str = "HYPRSTREAM_RECORDS_URL_FILE";
90 pub const RECORDS_SSLROOTCERT_FILE_ENV: &'static str = "HYPRSTREAM_RECORDS_SSLROOTCERT_FILE";
92 pub const POSTGRES_CREDENTIALS_PATH_ENV: &'static str = "HYPRSTREAM_POSTGRES_CREDENTIALS_PATH";
95 const RECORDS_URL_FILE_NAME: &'static str = "records-url";
97 const RDS_CA_FILE_NAME: &'static str = "rds-ca.pem";
98
99 pub fn is_configured(&self) -> bool {
101 self.url_file.is_some()
102 }
103
104 pub fn resolved_from_env(&self) -> anyhow::Result<Self> {
117 self.resolve_with(|key| std::env::var_os(key))
118 }
119
120 #[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 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 #[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 #[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 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 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 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 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 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 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 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 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 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 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 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 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(¬_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}