1use std::collections::BTreeSet;
5use std::fmt;
6use std::net::SocketAddr;
7use std::path::{Path, PathBuf};
8use std::time::Duration;
9
10use serde::Deserialize;
11
12use crate::retention::Retention;
13
14#[derive(Debug, Clone, PartialEq, Eq)]
18pub struct Config {
19 pub listen: SocketAddr,
21 pub tls_cert: PathBuf,
23 pub tls_key: PathBuf,
25 pub data_dir: PathBuf,
27 pub master_key: PathBuf,
29 pub retention_default: Retention,
31 pub purge_interval: Duration,
33 pub rotation_warn: Duration,
36 pub body_limit: usize,
38 pub inflated_limit: u64,
40 pub read_timeout: Duration,
42 pub supported_critical: BTreeSet<String>,
44 pub mcp: crate::mcp::Limits,
46 pub storage: Storage,
48 pub export: Export,
50 pub catalog: CatalogStore,
52}
53
54#[derive(Debug, Clone, PartialEq, Eq, Default)]
56pub enum CatalogStore {
57 #[default]
59 Local,
60 Postgres(Box<PostgresSettings>),
62}
63
64#[derive(Debug, Clone, PartialEq, Eq)]
68pub struct PostgresSettings {
69 pub hosts: Vec<String>,
71 pub port: u16,
73 pub dbname: String,
75 pub user: String,
77 pub ca_file: Option<PathBuf>,
80 pub password_file: Option<PathBuf>,
82 pub client_cert_file: Option<PathBuf>,
84 pub client_key_file: Option<PathBuf>,
86 pub pool: u32,
88 pub connect_timeout: Duration,
90 pub statement_timeout: Duration,
92 pub lock_timeout: Duration,
94}
95
96#[derive(Debug, Clone, PartialEq, Eq, Default)]
98pub struct Export {
99 pub s3: Option<ExportS3>,
102}
103
104#[derive(Debug, Clone, PartialEq, Eq)]
108pub struct ExportS3 {
109 pub endpoint: Option<String>,
111 pub region: String,
113 pub path_style: bool,
115 pub access_key_id: Option<String>,
117 pub secret_access_key_file: Option<PathBuf>,
119 pub allow_http: bool,
121 pub ca_file: Option<PathBuf>,
124 pub timeout: Duration,
126}
127
128impl ExportS3 {
129 #[must_use]
131 pub fn for_bucket(&self, bucket: &str, prefix: &str) -> S3Settings {
132 S3Settings {
133 endpoint: self.endpoint.clone(),
134 region: self.region.clone(),
135 bucket: bucket.to_owned(),
136 prefix: prefix.to_owned(),
137 path_style: self.path_style,
138 access_key_id: self.access_key_id.clone(),
139 secret_access_key_file: self.secret_access_key_file.clone(),
140 allow_http: self.allow_http,
141 ca_file: self.ca_file.clone(),
142 allow_versioning: false,
143 timeout: self.timeout,
144 }
145 }
146}
147
148impl From<&S3Settings> for ExportS3 {
149 fn from(s: &S3Settings) -> ExportS3 {
151 ExportS3 {
152 endpoint: s.endpoint.clone(),
153 region: s.region.clone(),
154 path_style: s.path_style,
155 access_key_id: s.access_key_id.clone(),
156 secret_access_key_file: s.secret_access_key_file.clone(),
157 allow_http: s.allow_http,
158 ca_file: s.ca_file.clone(),
159 timeout: s.timeout,
160 }
161 }
162}
163
164#[derive(Debug, Clone, PartialEq, Eq)]
167#[must_use]
168pub struct StorageError(pub String);
169
170impl fmt::Display for StorageError {
171 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
172 f.write_str(&self.0)
173 }
174}
175
176impl std::error::Error for StorageError {}
177
178#[derive(Debug, Clone, PartialEq, Eq, Default)]
181pub struct Storage {
182 pub objects: ObjectStore,
184 pub parquet: Option<ParquetSettings>,
187}
188
189#[derive(Debug, Clone, Copy, PartialEq, Eq)]
191pub struct ParquetSettings {
192 pub pack_interval: Duration,
194 pub pack_limit: u64,
197 pub reader_grace: Duration,
200}
201
202pub const READER_GRACE: Duration = Duration::from_secs(900);
205
206pub const PACK_INTERVAL: Duration = Duration::from_secs(300);
208
209pub const PACK_LIMIT: u64 = 16 << 20;
212
213#[derive(Debug, Clone, PartialEq, Eq, Default)]
215pub enum ObjectStore {
216 #[default]
218 Local,
219 S3(S3Settings),
221}
222
223#[derive(Debug, Clone, PartialEq, Eq)]
225pub struct S3Settings {
226 pub endpoint: Option<String>,
228 pub region: String,
230 pub bucket: String,
232 pub prefix: String,
234 pub path_style: bool,
236 pub access_key_id: Option<String>,
238 pub secret_access_key_file: Option<PathBuf>,
240 pub allow_http: bool,
242 pub ca_file: Option<PathBuf>,
245 pub allow_versioning: bool,
247 pub timeout: Duration,
249}
250
251pub const PURGE_INTERVAL: Duration = Duration::from_secs(3600);
254
255pub const ROTATION_WARN: Duration = Duration::from_secs(30 * 86_400);
258
259pub const BODY_LIMIT: usize = 16 << 20;
264
265pub const INFLATED_LIMIT: u64 = 4 * BODY_LIMIT as u64;
269
270pub const READ_TIMEOUT: Duration = Duration::from_secs(60);
273
274#[derive(Debug, Clone, PartialEq, Eq)]
276pub struct ConfigError(pub String);
277
278impl fmt::Display for ConfigError {
279 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
280 f.write_str(&self.0)
281 }
282}
283
284impl std::error::Error for ConfigError {}
285
286pub fn load(path: &Path) -> Result<Config, ConfigError> {
293 let text = std::fs::read_to_string(path)
294 .map_err(|e| ConfigError(format!("{}: {e}", path.display())))?;
295 parse(&text)
296}
297
298pub fn parse(text: &str) -> Result<Config, ConfigError> {
306 let raw: Raw = toml::from_str(text).map_err(|e| ConfigError(e.to_string()))?;
307 let storage = storage(raw.storage)?;
308 let catalog = catalog(raw.catalog, &storage)?;
309 let retention_default = match raw.retention_default {
310 None => Retention::Years(7),
311 Some(text) => Retention::parse(&text).ok_or_else(|| {
312 ConfigError(format!(
313 "retention_default: {text:?} is not a period such as 7y, 18m or 90d"
314 ))
315 })?,
316 };
317 Ok(Config {
318 listen: raw.listen,
319 tls_cert: raw.tls.cert,
320 tls_key: raw.tls.key,
321 data_dir: raw.data_dir,
322 master_key: raw.master_key,
323 retention_default,
324 purge_interval: seconds("purge_interval", raw.purge_interval, PURGE_INTERVAL)?,
325 rotation_warn: seconds("rotation_warn", raw.rotation_warn, ROTATION_WARN)?,
326 body_limit: match raw.limits.body {
327 None => BODY_LIMIT,
328 Some(body) => usize::try_from(positive("limits.body", body)?)
329 .map_err(|_| ConfigError("limits.body is too large".to_owned()))?,
330 },
331 inflated_limit: match raw.limits.inflated {
332 None => INFLATED_LIMIT,
333 Some(inflated) => positive("limits.inflated", inflated)?,
334 },
335 read_timeout: seconds(
336 "limits.timeouts.read",
337 raw.limits.timeouts.read,
338 READ_TIMEOUT,
339 )?,
340 supported_critical: raw.supported_critical.into_iter().collect(),
341 mcp: mcp_limits(&raw.mcp)?,
342 storage,
343 export: Export {
344 s3: raw.export.s3.map(export_s3).transpose()?,
345 },
346 catalog,
347 })
348}
349
350fn mcp_limits(raw: &RawMcp) -> Result<crate::mcp::Limits, ConfigError> {
352 let default = crate::mcp::Limits::DEFAULT;
353 let narrow = |key: &str, value: u64| {
354 u32::try_from(positive(key, value)?).map_err(|_| ConfigError(format!("{key} is too large")))
355 };
356 Ok(crate::mcp::Limits {
357 calls_per_second: match raw.calls_per_second {
358 None => default.calls_per_second,
359 Some(value) => narrow("mcp.calls_per_second", value)?,
360 },
361 concurrent: match raw.concurrent {
362 None => default.concurrent,
363 Some(value) => narrow("mcp.concurrent", value)?,
364 },
365 response_bytes: match raw.response_bytes {
366 None => default.response_bytes,
367 Some(value) => usize::try_from(positive("mcp.response_bytes", value)?)
368 .map_err(|_| ConfigError("mcp.response_bytes is too large".to_owned()))?,
369 },
370 })
371}
372
373pub const S3_TIMEOUT: Duration = Duration::from_secs(30);
375
376fn storage(raw: RawStorage) -> Result<Storage, ConfigError> {
380 let objects = match (raw.objects.as_deref(), raw.s3) {
381 (None | Some("local"), None) => ObjectStore::Local,
382 (None | Some("local"), Some(_)) => {
383 return Err(ConfigError(
384 "storage.s3 is set but storage.objects is not \"s3\"".to_owned(),
385 ));
386 }
387 (Some("s3"), None) => {
388 return Err(ConfigError(
389 "storage.objects is \"s3\" but there is no storage.s3 table".to_owned(),
390 ));
391 }
392 (Some("s3"), Some(s3)) => ObjectStore::S3(s3_settings(s3)?),
393 (Some(other), _) => {
394 return Err(ConfigError(format!(
395 "storage.objects: {other:?} is not \"local\" or \"s3\""
396 )));
397 }
398 };
399 let parquet = match (&objects, raw.parquet) {
400 (_, None) => None,
401 (ObjectStore::S3(_), Some(p)) => Some(ParquetSettings {
402 pack_interval: seconds(
403 "storage.parquet.pack_interval",
404 p.pack_interval,
405 PACK_INTERVAL,
406 )?,
407 pack_limit: match p.pack_limit {
408 None => PACK_LIMIT,
409 Some(limit) => positive("storage.parquet.pack_limit", limit)?,
410 },
411 reader_grace: seconds("storage.parquet.reader_grace", p.reader_grace, READER_GRACE)?,
412 }),
413 (ObjectStore::Local, Some(_)) => {
414 return Err(ConfigError(
415 "storage.parquet packs the objects of a bucket, so it needs \
416 storage.objects = \"s3\""
417 .to_owned(),
418 ));
419 }
420 };
421 Ok(Storage { objects, parquet })
422}
423
424pub const POSTGRES_PORT: u16 = 5432;
426
427pub const POSTGRES_POOL: u32 = 16;
429
430pub const POSTGRES_CONNECT_TIMEOUT: Duration = Duration::from_secs(5);
433
434pub const POSTGRES_STATEMENT_TIMEOUT: Duration = Duration::from_secs(30);
436
437pub const POSTGRES_LOCK_TIMEOUT: Duration = Duration::from_secs(10);
439
440pub const POSTGRES_TIMEOUT_LIMIT: u64 = i32::MAX as u64 / 1000;
443
444pub const POSTGRES_NAME_LIMIT: usize = 63;
447
448fn catalog(raw: RawCatalog, storage: &Storage) -> Result<CatalogStore, ConfigError> {
451 match (raw.backend.as_deref(), raw.postgres) {
452 (None | Some("local"), None) => Ok(CatalogStore::Local),
453 (None | Some("local"), Some(_)) => Err(ConfigError(
454 "catalog.postgres is set but catalog.backend is not \"postgres\"".to_owned(),
455 )),
456 (Some("postgres"), None) => Err(ConfigError(
457 "catalog.backend is \"postgres\" but there is no catalog.postgres table".to_owned(),
458 )),
459 (Some("postgres"), Some(pg)) => {
460 if !matches!(storage.objects, ObjectStore::S3(_)) {
465 return Err(ConfigError(
466 "catalog.backend = \"postgres\" needs storage.objects = \"s3\": a catalog \
467 in PostgreSQL names objects that every server must be able to read"
468 .to_owned(),
469 ));
470 }
471 postgres_settings(pg).map(|pg| CatalogStore::Postgres(Box::new(pg)))
472 }
473 (Some(other), _) => Err(ConfigError(format!(
474 "catalog.backend: {other:?} is not \"local\" or \"postgres\""
475 ))),
476 }
477}
478
479fn postgres_settings(raw: RawPostgres) -> Result<PostgresSettings, ConfigError> {
480 const KEY: &str = "catalog.postgres";
481 if raw.hosts.is_empty() {
482 return Err(ConfigError(format!(
483 "{KEY}.hosts is empty; name at least one server"
484 )));
485 }
486 let mut seen = BTreeSet::new();
487 for host in &raw.hosts {
488 check_host(host).map_err(|why| ConfigError(format!("{KEY}.hosts: {host:?} {why}")))?;
489 if !seen.insert(host.to_ascii_lowercase()) {
490 return Err(ConfigError(format!("{KEY}.hosts names {host:?} twice")));
491 }
492 }
493 let port = match raw.port {
494 None => POSTGRES_PORT,
495 Some(port) => u16::try_from(positive(&format!("{KEY}.port"), port)?).map_err(|_| {
496 ConfigError(format!("{KEY}.port {port} is not a TCP port (1 to 65535)"))
497 })?,
498 };
499 check_name("dbname", &raw.dbname)?;
500 check_name("user", &raw.user)?;
501 for (name, path) in [
502 ("ca_file", &raw.ca_file),
503 ("password_file", &raw.password_file),
504 ("client_cert_file", &raw.client_cert_file),
505 ("client_key_file", &raw.client_key_file),
506 ] {
507 if path.as_ref().is_some_and(|p| p.as_os_str().is_empty()) {
508 return Err(ConfigError(format!("{KEY}.{name} is empty")));
509 }
510 }
511 match (&raw.client_cert_file, &raw.client_key_file) {
512 (Some(_), None) => {
513 return Err(ConfigError(format!(
514 "{KEY}.client_cert_file is set without {KEY}.client_key_file"
515 )));
516 }
517 (None, Some(_)) => {
518 return Err(ConfigError(format!(
519 "{KEY}.client_key_file is set without {KEY}.client_cert_file"
520 )));
521 }
522 _ => {}
523 }
524 if raw.password_file.is_none() && raw.client_cert_file.is_none() {
525 return Err(ConfigError(format!(
526 "set {KEY}.password_file, {KEY}.client_cert_file, or both: a server that asks for \
527 neither is not accepted"
528 )));
529 }
530 let pool = match raw.pool {
531 None => POSTGRES_POOL,
532 Some(pool) => u32::try_from(positive(&format!("{KEY}.pool"), pool)?)
533 .map_err(|_| ConfigError(format!("{KEY}.pool is too large")))?,
534 };
535 let limited = |name: &str, value: Option<u64>, default: Duration| {
536 let key = format!("{KEY}.{name}");
537 let value = seconds(&key, value, default)?;
538 if value.as_secs() > POSTGRES_TIMEOUT_LIMIT {
539 return Err(ConfigError(format!(
540 "{key} is more than {POSTGRES_TIMEOUT_LIMIT} seconds, the longest PostgreSQL holds"
541 )));
542 }
543 Ok(value)
544 };
545 Ok(PostgresSettings {
546 hosts: raw.hosts,
547 port,
548 dbname: raw.dbname,
549 user: raw.user,
550 ca_file: raw.ca_file,
551 password_file: raw.password_file,
552 client_cert_file: raw.client_cert_file,
553 client_key_file: raw.client_key_file,
554 pool,
555 connect_timeout: seconds(
556 &format!("{KEY}.connect_timeout"),
557 raw.connect_timeout,
558 POSTGRES_CONNECT_TIMEOUT,
559 )?,
560 statement_timeout: limited(
561 "statement_timeout",
562 raw.statement_timeout,
563 POSTGRES_STATEMENT_TIMEOUT,
564 )?,
565 lock_timeout: limited("lock_timeout", raw.lock_timeout, POSTGRES_LOCK_TIMEOUT)?,
566 })
567}
568
569fn check_name(key: &str, name: &str) -> Result<(), ConfigError> {
572 let refused = |why: &str| Err(ConfigError(format!("catalog.postgres.{key} {why}")));
573 if name.is_empty() {
574 return refused("is empty");
575 }
576 if name.contains('\0') {
577 return refused("holds a NUL character, which PostgreSQL names cannot");
578 }
579 if name.len() > POSTGRES_NAME_LIMIT {
580 return refused(&format!(
581 "is {} bytes; PostgreSQL would cut it to {POSTGRES_NAME_LIMIT} bytes and name \
582 another database or role",
583 name.len()
584 ));
585 }
586 Ok(())
587}
588
589fn check_host(host: &str) -> Result<(), String> {
592 if host.parse::<std::net::IpAddr>().is_ok() {
593 return Ok(());
594 }
595 if host.starts_with('/') {
596 return Err(
597 "is a Unix socket, which carries no TLS; the catalog is reached over TCP \
598 with TLS only"
599 .to_owned(),
600 );
601 }
602 if let Some(bare) = host.strip_prefix('[').and_then(|h| h.strip_suffix(']'))
603 && bare.parse::<std::net::Ipv6Addr>().is_ok()
604 {
605 return Err(format!(
606 "is written in brackets; write the address as {bare:?}"
607 ));
608 }
609 if host.is_empty() {
610 return Err("is empty".to_owned());
611 }
612 if !host.is_ascii() {
613 return Err("is not ASCII; write an internationalized name in its xn-- form".to_owned());
614 }
615 if host.contains(':') {
616 return Err(
617 "holds a colon; give the port in catalog.postgres.port, which every host uses"
618 .to_owned(),
619 );
620 }
621 if host.len() > 253 {
622 return Err("is longer than 253 characters, the longest DNS name".to_owned());
623 }
624 let good_label = |label: &str| {
625 (1..=63).contains(&label.len())
626 && !label.starts_with('-')
627 && !label.ends_with('-')
628 && label
629 .bytes()
630 .all(|b| b.is_ascii_alphanumeric() || b == b'-')
631 };
632 if !host.split('.').all(good_label) {
633 return Err(
634 "is not a DNS name: labels of 1 to 63 letters, digits and hyphens, joined by dots"
635 .to_owned(),
636 );
637 }
638 Ok(())
639}
640
641fn export_s3(raw: RawExportS3) -> Result<ExportS3, ConfigError> {
643 check_service(
644 "export.s3",
645 raw.endpoint.as_deref(),
646 raw.allow_http,
647 raw.ca_file.is_some(),
648 raw.access_key_id.is_some(),
649 raw.secret_access_key_file.is_some(),
650 )?;
651 Ok(ExportS3 {
652 endpoint: raw.endpoint,
653 region: raw.region,
654 path_style: raw.path_style,
655 access_key_id: raw.access_key_id,
656 secret_access_key_file: raw.secret_access_key_file,
657 allow_http: raw.allow_http,
658 ca_file: raw.ca_file,
659 timeout: seconds("export.s3.timeout", raw.timeout, S3_TIMEOUT)?,
660 })
661}
662
663fn check_service(
668 table: &str,
669 endpoint: Option<&str>,
670 allow_http: bool,
671 ca_file: bool,
672 access_key_id: bool,
673 secret_access_key_file: bool,
674) -> Result<(), ConfigError> {
675 if let Some(endpoint) = endpoint {
676 if endpoint.starts_with("http://") {
677 if ca_file {
678 return Err(ConfigError(format!(
679 "{table}.ca_file is set, but {table}.endpoint {endpoint:?} is plain \
680 HTTP, which uses no certificate"
681 )));
682 }
683 if !allow_http {
684 return Err(ConfigError(format!(
685 "{table}.endpoint {endpoint:?} is plain HTTP; set {table}.allow_http = \
686 true only for a test service on this host"
687 )));
688 }
689 } else if !endpoint.starts_with("https://") {
690 return Err(ConfigError(format!(
691 "{table}.endpoint {endpoint:?} is not an https:// URL"
692 )));
693 }
694 }
695 match (access_key_id, secret_access_key_file) {
696 (true, false) => Err(ConfigError(format!(
697 "{table}.access_key_id is set without {table}.secret_access_key_file"
698 ))),
699 (false, true) => Err(ConfigError(format!(
700 "{table}.secret_access_key_file is set without {table}.access_key_id"
701 ))),
702 _ => Ok(()),
703 }
704}
705
706fn s3_settings(raw: RawS3) -> Result<S3Settings, ConfigError> {
707 if raw.bucket.is_empty() {
708 return Err(ConfigError("storage.s3.bucket is empty".to_owned()));
709 }
710 if !raw.prefix.is_empty() && (raw.prefix.starts_with('/') || !raw.prefix.ends_with('/')) {
711 return Err(ConfigError(format!(
712 "storage.s3.prefix {:?} must not start with / and must end with /, \
713 such as \"server-a/\"",
714 raw.prefix
715 )));
716 }
717 check_service(
718 "storage.s3",
719 raw.endpoint.as_deref(),
720 raw.allow_http,
721 raw.ca_file.is_some(),
722 raw.access_key_id.is_some(),
723 raw.secret_access_key_file.is_some(),
724 )?;
725 Ok(S3Settings {
726 endpoint: raw.endpoint,
727 region: raw.region,
728 bucket: raw.bucket,
729 prefix: raw.prefix,
730 path_style: raw.path_style,
731 access_key_id: raw.access_key_id,
732 secret_access_key_file: raw.secret_access_key_file,
733 allow_http: raw.allow_http,
734 ca_file: raw.ca_file,
735 allow_versioning: raw.allow_versioning,
736 timeout: seconds("storage.s3.timeout", raw.timeout, S3_TIMEOUT)?,
737 })
738}
739
740fn positive(key: &str, value: u64) -> Result<u64, ConfigError> {
741 if value == 0 {
742 return Err(ConfigError(format!("{key} must be more than 0")));
743 }
744 Ok(value)
745}
746
747fn seconds(key: &str, value: Option<u64>, default: Duration) -> Result<Duration, ConfigError> {
749 match value {
750 None => Ok(default),
751 Some(value) => positive(key, value).map(Duration::from_secs),
752 }
753}
754
755#[derive(Deserialize)]
757#[serde(deny_unknown_fields)]
758struct Raw {
759 listen: SocketAddr,
760 tls: RawTls,
761 data_dir: PathBuf,
762 master_key: PathBuf,
763 retention_default: Option<String>,
764 purge_interval: Option<u64>,
765 rotation_warn: Option<u64>,
766 #[serde(default)]
767 limits: RawLimits,
768 #[serde(default)]
769 supported_critical: Vec<String>,
770 #[serde(default)]
771 mcp: RawMcp,
772 #[serde(default)]
773 storage: RawStorage,
774 #[serde(default)]
775 export: RawExport,
776 #[serde(default)]
777 catalog: RawCatalog,
778}
779
780#[derive(Default, Deserialize)]
781#[serde(deny_unknown_fields)]
782struct RawCatalog {
783 backend: Option<String>,
784 postgres: Option<RawPostgres>,
785}
786
787#[derive(Deserialize)]
788#[serde(deny_unknown_fields)]
789struct RawPostgres {
790 hosts: Vec<String>,
791 port: Option<u64>,
792 dbname: String,
793 user: String,
794 ca_file: Option<PathBuf>,
795 password_file: Option<PathBuf>,
796 client_cert_file: Option<PathBuf>,
797 client_key_file: Option<PathBuf>,
798 pool: Option<u64>,
799 connect_timeout: Option<u64>,
800 statement_timeout: Option<u64>,
801 lock_timeout: Option<u64>,
802}
803
804#[derive(Default, Deserialize)]
805#[serde(deny_unknown_fields)]
806struct RawExport {
807 s3: Option<RawExportS3>,
808}
809
810#[derive(Deserialize)]
811#[serde(deny_unknown_fields)]
812struct RawExportS3 {
813 endpoint: Option<String>,
814 region: String,
815 #[serde(default)]
816 path_style: bool,
817 access_key_id: Option<String>,
818 secret_access_key_file: Option<PathBuf>,
819 #[serde(default)]
820 allow_http: bool,
821 ca_file: Option<PathBuf>,
822 timeout: Option<u64>,
823}
824
825#[derive(Default, Deserialize)]
826#[serde(deny_unknown_fields)]
827struct RawStorage {
828 objects: Option<String>,
829 s3: Option<RawS3>,
830 parquet: Option<RawParquet>,
831}
832
833#[derive(Deserialize)]
834#[serde(deny_unknown_fields)]
835struct RawParquet {
836 pack_interval: Option<u64>,
837 pack_limit: Option<u64>,
838 reader_grace: Option<u64>,
839}
840
841#[derive(Deserialize)]
842#[serde(deny_unknown_fields)]
843struct RawS3 {
844 endpoint: Option<String>,
845 region: String,
846 bucket: String,
847 #[serde(default)]
848 prefix: String,
849 #[serde(default)]
850 path_style: bool,
851 access_key_id: Option<String>,
852 secret_access_key_file: Option<PathBuf>,
853 #[serde(default)]
854 allow_http: bool,
855 ca_file: Option<PathBuf>,
856 #[serde(default)]
857 allow_versioning: bool,
858 timeout: Option<u64>,
859}
860
861#[derive(Default, Deserialize)]
862#[serde(deny_unknown_fields)]
863struct RawMcp {
864 calls_per_second: Option<u64>,
865 concurrent: Option<u64>,
866 response_bytes: Option<u64>,
867}
868
869#[derive(Deserialize)]
870#[serde(deny_unknown_fields)]
871struct RawTls {
872 cert: PathBuf,
873 key: PathBuf,
874}
875
876#[derive(Default, Deserialize)]
877#[serde(deny_unknown_fields)]
878struct RawLimits {
879 body: Option<u64>,
880 inflated: Option<u64>,
881 #[serde(default)]
882 timeouts: RawTimeouts,
883}
884
885#[derive(Default, Deserialize)]
886#[serde(deny_unknown_fields)]
887struct RawTimeouts {
888 read: Option<u64>,
889}
890
891#[cfg(test)]
892mod tests {
893 use super::*;
894
895 const FULL: &str = r#"
896listen = "127.0.0.1:8443"
897data_dir = "/var/lib/vcon-server"
898master_key = "/etc/vcon-server/master.key"
899retention_default = "18m"
900purge_interval = 1800
901rotation_warn = 604800
902supported_critical = ["known", "other"]
903
904[tls]
905cert = "/etc/vcon-server/cert.pem"
906key = "/etc/vcon-server/key.pem"
907
908[limits]
909body = 10485760
910inflated = 104857600
911
912[limits.timeouts]
913read = 30
914
915[mcp]
916calls_per_second = 20
917concurrent = 8
918response_bytes = 262144
919
920[storage]
921objects = "s3"
922
923[storage.s3]
924endpoint = "https://objects.example.com:9000"
925region = "eu-west-1"
926bucket = "vcon"
927prefix = "server-a/"
928path_style = true
929access_key_id = "vcon-server"
930secret_access_key_file = "/etc/vcon-server/s3.secret"
931allow_http = true
932ca_file = "/etc/vcon-server/s3-ca.pem"
933allow_versioning = true
934timeout = 60
935
936[storage.parquet]
937pack_interval = 600
938pack_limit = 8388608
939reader_grace = 1800
940
941[export.s3]
942endpoint = "https://analytics.example.com"
943region = "eu-west-2"
944path_style = true
945access_key_id = "vcon-export"
946secret_access_key_file = "/etc/vcon-server/export.secret"
947allow_http = true
948ca_file = "/etc/vcon-server/export-ca.pem"
949timeout = 120
950
951[catalog]
952backend = "postgres"
953
954[catalog.postgres]
955hosts = ["db1.example.com", "192.0.2.10", "2001:db8::10"]
956port = 6432
957dbname = "vcon"
958user = "vcon_app"
959ca_file = "/etc/vcon-server/pg-ca.pem"
960password_file = "/etc/vcon-server/postgres.password"
961client_cert_file = "/etc/vcon-server/pg-client.pem"
962client_key_file = "/etc/vcon-server/pg-client.key"
963pool = 8
964connect_timeout = 10
965statement_timeout = 60
966lock_timeout = 20
967"#;
968
969 #[test]
970 fn a_full_configuration_is_read() {
971 assert_eq!(
972 parse(FULL),
973 Ok(Config {
974 listen: "127.0.0.1:8443".parse().expect("address"),
975 tls_cert: "/etc/vcon-server/cert.pem".into(),
976 tls_key: "/etc/vcon-server/key.pem".into(),
977 data_dir: "/var/lib/vcon-server".into(),
978 master_key: "/etc/vcon-server/master.key".into(),
979 retention_default: Retention::Months(18),
980 purge_interval: Duration::from_secs(1800),
981 rotation_warn: Duration::from_secs(604_800),
982 body_limit: 10_485_760,
983 inflated_limit: 104_857_600,
984 read_timeout: Duration::from_secs(30),
985 supported_critical: ["known", "other"].map(String::from).into(),
986 mcp: crate::mcp::Limits {
987 calls_per_second: 20,
988 concurrent: 8,
989 response_bytes: 262_144,
990 },
991 storage: Storage {
992 objects: ObjectStore::S3(S3Settings {
993 endpoint: Some("https://objects.example.com:9000".to_owned()),
994 region: "eu-west-1".to_owned(),
995 bucket: "vcon".to_owned(),
996 prefix: "server-a/".to_owned(),
997 path_style: true,
998 access_key_id: Some("vcon-server".to_owned()),
999 secret_access_key_file: Some("/etc/vcon-server/s3.secret".into()),
1000 allow_http: true,
1001 ca_file: Some("/etc/vcon-server/s3-ca.pem".into()),
1002 allow_versioning: true,
1003 timeout: Duration::from_secs(60),
1004 }),
1005 parquet: Some(ParquetSettings {
1006 pack_interval: Duration::from_secs(600),
1007 pack_limit: 8_388_608,
1008 reader_grace: Duration::from_secs(1800),
1009 }),
1010 },
1011 export: Export {
1012 s3: Some(ExportS3 {
1013 endpoint: Some("https://analytics.example.com".to_owned()),
1014 region: "eu-west-2".to_owned(),
1015 path_style: true,
1016 access_key_id: Some("vcon-export".to_owned()),
1017 secret_access_key_file: Some("/etc/vcon-server/export.secret".into()),
1018 allow_http: true,
1019 ca_file: Some("/etc/vcon-server/export-ca.pem".into()),
1020 timeout: Duration::from_secs(120),
1021 }),
1022 },
1023 catalog: CatalogStore::Postgres(Box::new(PostgresSettings {
1024 hosts: ["db1.example.com", "192.0.2.10", "2001:db8::10"]
1025 .map(String::from)
1026 .into(),
1027 port: 6432,
1028 dbname: "vcon".to_owned(),
1029 user: "vcon_app".to_owned(),
1030 ca_file: Some("/etc/vcon-server/pg-ca.pem".into()),
1031 password_file: Some("/etc/vcon-server/postgres.password".into()),
1032 client_cert_file: Some("/etc/vcon-server/pg-client.pem".into()),
1033 client_key_file: Some("/etc/vcon-server/pg-client.key".into()),
1034 pool: 8,
1035 connect_timeout: Duration::from_secs(10),
1036 statement_timeout: Duration::from_secs(60),
1037 lock_timeout: Duration::from_secs(20),
1038 })),
1039 }),
1040 "every key the file writes is read into its field"
1041 );
1042 }
1043
1044 #[test]
1045 fn retention_and_supported_extensions_have_defaults() {
1046 let text = FULL
1047 .replace("retention_default = \"18m\"\n", "")
1048 .replace("supported_critical = [\"known\", \"other\"]\n", "");
1049 let config = parse(&text).expect("parses");
1050 assert_eq!(
1051 config.retention_default,
1052 Retention::Years(7),
1053 "with no retention_default, vCons are kept seven years"
1054 );
1055 assert_eq!(
1056 config.supported_critical,
1057 BTreeSet::new(),
1058 "with no supported_critical, no extension is supported"
1059 );
1060 }
1061
1062 const LEAST: &str = r#"
1064listen = "127.0.0.1:8443"
1065data_dir = "/var/lib/vcon-server"
1066master_key = "/etc/vcon-server/master.key"
1067
1068[tls]
1069cert = "/etc/vcon-server/cert.pem"
1070key = "/etc/vcon-server/key.pem"
1071"#;
1072
1073 #[test]
1074 fn periods_and_limits_have_defaults() {
1075 let config = parse(LEAST).expect("parses");
1076 assert_eq!(
1077 config.purge_interval,
1078 Duration::from_secs(3600),
1079 "the purge sweep runs hourly by default"
1080 );
1081 assert_eq!(
1082 config.rotation_warn,
1083 Duration::from_secs(30 * 86_400),
1084 "an overdue rotation is warned of after 30 days by default"
1085 );
1086 assert_eq!(
1087 config.body_limit,
1088 16 << 20,
1089 "a body may be 16 MiB by default"
1090 );
1091 assert_eq!(
1092 config.inflated_limit,
1093 64 << 20,
1094 "a body may inflate to 64 MiB by default"
1095 );
1096 assert_eq!(
1097 config.read_timeout,
1098 Duration::from_secs(60),
1099 "a request has 60 seconds to arrive by default"
1100 );
1101 assert_eq!(
1102 config.mcp,
1103 crate::mcp::Limits::DEFAULT,
1104 "with no [mcp] table, the MCP endpoint takes its default limits"
1105 );
1106 }
1107
1108 #[test]
1111 fn each_limit_defaults_alone() {
1112 let base = parse(FULL).expect("parses");
1113 for (line, default) in [
1114 (
1115 "body = 10485760\n",
1116 Config {
1117 body_limit: 16 << 20,
1118 ..base.clone()
1119 },
1120 ),
1121 (
1122 "inflated = 104857600\n",
1123 Config {
1124 inflated_limit: 64 << 20,
1125 ..base.clone()
1126 },
1127 ),
1128 (
1129 "read = 30\n",
1130 Config {
1131 read_timeout: Duration::from_secs(60),
1132 ..base.clone()
1133 },
1134 ),
1135 (
1136 "purge_interval = 1800\n",
1137 Config {
1138 purge_interval: Duration::from_secs(3600),
1139 ..base.clone()
1140 },
1141 ),
1142 (
1143 "rotation_warn = 604800\n",
1144 Config {
1145 rotation_warn: Duration::from_secs(30 * 86_400),
1146 ..base.clone()
1147 },
1148 ),
1149 (
1150 "[limits.timeouts]\nread = 30\n",
1151 Config {
1152 read_timeout: Duration::from_secs(60),
1153 ..base.clone()
1154 },
1155 ),
1156 (
1157 "calls_per_second = 20\n",
1158 Config {
1159 mcp: crate::mcp::Limits {
1160 calls_per_second: 100,
1161 ..base.mcp
1162 },
1163 ..base.clone()
1164 },
1165 ),
1166 (
1167 "concurrent = 8\n",
1168 Config {
1169 mcp: crate::mcp::Limits {
1170 concurrent: 100,
1171 ..base.mcp
1172 },
1173 ..base.clone()
1174 },
1175 ),
1176 (
1177 "response_bytes = 262144\n",
1178 Config {
1179 mcp: crate::mcp::Limits {
1180 response_bytes: 1 << 20,
1181 ..base.mcp
1182 },
1183 ..base.clone()
1184 },
1185 ),
1186 ] {
1187 assert!(FULL.contains(line), "{line}");
1188 assert_eq!(parse(&FULL.replace(line, "")), Ok(default), "{line}");
1189 }
1190 }
1191
1192 #[test]
1195 fn the_full_file_sets_no_value_equal_to_its_default() {
1196 let (full, least) = (parse(FULL).expect("full"), parse(LEAST).expect("least"));
1197 assert_ne!(
1198 full.purge_interval, least.purge_interval,
1199 "FULL writes purge_interval as a value other than its default"
1200 );
1201 assert_ne!(
1202 full.rotation_warn, least.rotation_warn,
1203 "FULL writes rotation_warn as a value other than its default"
1204 );
1205 assert_ne!(
1206 full.body_limit, least.body_limit,
1207 "FULL writes limits.body as a value other than its default"
1208 );
1209 assert_ne!(
1210 full.inflated_limit, least.inflated_limit,
1211 "FULL writes limits.inflated as a value other than its default"
1212 );
1213 assert_ne!(
1214 full.read_timeout, least.read_timeout,
1215 "FULL writes limits.timeouts.read as a value other than its default"
1216 );
1217 assert_ne!(
1218 full.mcp.calls_per_second, least.mcp.calls_per_second,
1219 "FULL writes mcp.calls_per_second as a value other than its default"
1220 );
1221 assert_ne!(
1222 full.mcp.concurrent, least.mcp.concurrent,
1223 "FULL writes mcp.concurrent as a value other than its default"
1224 );
1225 assert_ne!(
1226 full.mcp.response_bytes, least.mcp.response_bytes,
1227 "FULL writes mcp.response_bytes as a value other than its default"
1228 );
1229 assert_ne!(
1230 full.storage, least.storage,
1231 "FULL writes storage.objects as a value other than its default"
1232 );
1233 let parquet = full.storage.parquet.expect("FULL has storage.parquet");
1234 let least_parquet = parquet_least();
1235 for (key, differs) in [
1236 (
1237 "storage.parquet.pack_interval",
1238 parquet.pack_interval != least_parquet.pack_interval,
1239 ),
1240 (
1241 "storage.parquet.pack_limit",
1242 parquet.pack_limit != least_parquet.pack_limit,
1243 ),
1244 (
1245 "storage.parquet.reader_grace",
1246 parquet.reader_grace != least_parquet.reader_grace,
1247 ),
1248 ] {
1249 assert!(
1250 differs,
1251 "FULL writes {key} as a value other than its default"
1252 );
1253 }
1254 let ObjectStore::S3(s3) = full.storage.objects else {
1255 panic!("FULL keeps its objects in S3")
1256 };
1257 let least_s3 = s3_least();
1258 for (key, differs) in [
1259 ("storage.s3.endpoint", s3.endpoint != least_s3.endpoint),
1260 ("storage.s3.prefix", s3.prefix != least_s3.prefix),
1261 (
1262 "storage.s3.path_style",
1263 s3.path_style != least_s3.path_style,
1264 ),
1265 (
1266 "storage.s3.access_key_id",
1267 s3.access_key_id != least_s3.access_key_id,
1268 ),
1269 (
1270 "storage.s3.secret_access_key_file",
1271 s3.secret_access_key_file != least_s3.secret_access_key_file,
1272 ),
1273 (
1274 "storage.s3.allow_http",
1275 s3.allow_http != least_s3.allow_http,
1276 ),
1277 ("storage.s3.ca_file", s3.ca_file != least_s3.ca_file),
1278 (
1279 "storage.s3.allow_versioning",
1280 s3.allow_versioning != least_s3.allow_versioning,
1281 ),
1282 ("storage.s3.timeout", s3.timeout != least_s3.timeout),
1283 ] {
1284 assert!(
1285 differs,
1286 "FULL writes {key} as a value other than its default"
1287 );
1288 }
1289 let export = full.export.s3.expect("FULL has export.s3");
1290 let least_export = parse(&format!("{LEAST}\n[export.s3]\nregion = \"us-east-1\"\n"))
1291 .expect("least export")
1292 .export
1293 .s3
1294 .expect("export.s3");
1295 for (key, differs) in [
1296 (
1297 "export.s3.endpoint",
1298 export.endpoint != least_export.endpoint,
1299 ),
1300 ("export.s3.region", export.region != least_export.region),
1301 (
1302 "export.s3.path_style",
1303 export.path_style != least_export.path_style,
1304 ),
1305 (
1306 "export.s3.access_key_id",
1307 export.access_key_id != least_export.access_key_id,
1308 ),
1309 (
1310 "export.s3.secret_access_key_file",
1311 export.secret_access_key_file != least_export.secret_access_key_file,
1312 ),
1313 (
1314 "export.s3.allow_http",
1315 export.allow_http != least_export.allow_http,
1316 ),
1317 ("export.s3.ca_file", export.ca_file != least_export.ca_file),
1318 ("export.s3.timeout", export.timeout != least_export.timeout),
1319 ] {
1320 assert!(
1321 differs,
1322 "FULL writes {key} as a value other than its default"
1323 );
1324 }
1325 assert_ne!(
1326 full.catalog, least.catalog,
1327 "FULL writes catalog.backend as a value other than its default"
1328 );
1329 let CatalogStore::Postgres(pg) = full.catalog else {
1330 panic!("FULL keeps its catalogs in PostgreSQL")
1331 };
1332 let least_pg = catalog::postgres_least();
1333 for (key, differs) in [
1334 ("catalog.postgres.port", pg.port != least_pg.port),
1335 ("catalog.postgres.ca_file", pg.ca_file != least_pg.ca_file),
1336 (
1337 "catalog.postgres.password_file",
1338 pg.password_file != least_pg.password_file,
1339 ),
1340 (
1341 "catalog.postgres.client_cert_file",
1342 pg.client_cert_file != least_pg.client_cert_file,
1343 ),
1344 (
1345 "catalog.postgres.client_key_file",
1346 pg.client_key_file != least_pg.client_key_file,
1347 ),
1348 ("catalog.postgres.pool", pg.pool != least_pg.pool),
1349 (
1350 "catalog.postgres.connect_timeout",
1351 pg.connect_timeout != least_pg.connect_timeout,
1352 ),
1353 (
1354 "catalog.postgres.statement_timeout",
1355 pg.statement_timeout != least_pg.statement_timeout,
1356 ),
1357 (
1358 "catalog.postgres.lock_timeout",
1359 pg.lock_timeout != least_pg.lock_timeout,
1360 ),
1361 ] {
1362 assert!(
1363 differs,
1364 "FULL writes {key} as a value other than its default"
1365 );
1366 }
1367 }
1368
1369 fn s3_least() -> S3Settings {
1371 let text = format!(
1372 "{LEAST}\n[storage]\nobjects = \"s3\"\n[storage.s3]\nregion = \"us-east-1\"\nbucket = \"vcon\"\n"
1373 );
1374 match parse(&text)
1375 .expect("the least S3 configuration reads")
1376 .storage
1377 .objects
1378 {
1379 ObjectStore::S3(s3) => s3,
1380 ObjectStore::Local => panic!("objects = \"s3\" keeps the objects in S3"),
1381 }
1382 }
1383
1384 #[test]
1385 fn without_a_storage_table_everything_is_local() {
1386 assert_eq!(
1387 parse(LEAST).expect("parses").storage,
1388 Storage {
1389 objects: ObjectStore::Local,
1390 parquet: None,
1391 },
1392 "a file written before storage backends keeps its meaning"
1393 );
1394 }
1395
1396 fn parquet_least() -> ParquetSettings {
1398 let text = format!(
1399 "{LEAST}\n[storage]\nobjects = \"s3\"\n[storage.s3]\nregion = \"us-east-1\"\n\
1400 bucket = \"vcon\"\n[storage.parquet]\n"
1401 );
1402 parse(&text)
1403 .expect("the least Parquet configuration reads")
1404 .storage
1405 .parquet
1406 .expect("an empty [storage.parquet] turns Parquet storage on")
1407 }
1408
1409 #[test]
1410 fn parquet_settings_have_defaults() {
1411 assert_eq!(
1412 parquet_least(),
1413 ParquetSettings {
1414 pack_interval: PACK_INTERVAL,
1415 pack_limit: PACK_LIMIT,
1416 reader_grace: READER_GRACE,
1417 },
1418 "an empty table takes every default"
1419 );
1420 assert_eq!(READER_GRACE, Duration::from_secs(900), "15 minutes");
1421 assert_eq!(PACK_INTERVAL, Duration::from_secs(300), "five minutes");
1422 assert_eq!(PACK_LIMIT, 16 << 20, "16 MiB");
1423 }
1424
1425 #[test]
1426 fn s3_settings_have_defaults() {
1427 assert_eq!(
1428 s3_least(),
1429 S3Settings {
1430 endpoint: None,
1431 region: "us-east-1".to_owned(),
1432 bucket: "vcon".to_owned(),
1433 prefix: String::new(),
1434 path_style: false,
1435 access_key_id: None,
1436 secret_access_key_file: None,
1437 allow_http: false,
1438 ca_file: None,
1439 allow_versioning: false,
1440 timeout: Duration::from_secs(30),
1441 },
1442 "only region and bucket are required"
1443 );
1444 }
1445
1446 #[test]
1450 fn export_s3_settings_are_read_and_checked_as_storage_s3_is() {
1451 let export = |extra: &str| format!("{LEAST}\n[export.s3]\nregion = \"us-east-1\"\n{extra}");
1452 assert_eq!(
1453 parse(LEAST).expect("least").export,
1454 Export::default(),
1455 "no table"
1456 );
1457 assert_eq!(
1458 parse(&export("")).expect("least export").export.s3,
1459 Some(ExportS3 {
1460 endpoint: None,
1461 region: "us-east-1".to_owned(),
1462 path_style: false,
1463 access_key_id: None,
1464 secret_access_key_file: None,
1465 allow_http: false,
1466 ca_file: None,
1467 timeout: S3_TIMEOUT,
1468 }),
1469 "only region is required"
1470 );
1471 for (extra, key) in [
1472 (
1473 "endpoint = \"http://127.0.0.1:9000\"\n",
1474 "export.s3.allow_http",
1475 ),
1476 ("endpoint = \"objects.example.com\"\n", "export.s3.endpoint"),
1477 (
1478 "access_key_id = \"vcon\"\n",
1479 "export.s3.secret_access_key_file",
1480 ),
1481 (
1482 "secret_access_key_file = \"/s\"\n",
1483 "export.s3.access_key_id",
1484 ),
1485 ("timeout = 0\n", "export.s3.timeout"),
1486 (
1487 "endpoint = \"http://127.0.0.1:9000\"\nallow_http = true\nca_file = \"/c.pem\"\n",
1488 "export.s3.ca_file",
1489 ),
1490 ("bucket = \"vcon\"\n", "bucket"),
1491 ("prefix = \"a/\"\n", "prefix"),
1492 ("allow_versioning = true\n", "allow_versioning"),
1493 ] {
1494 let ConfigError(message) = parse(&export(extra)).expect_err(extra);
1495 assert!(message.contains(key), "{extra}: {message}");
1496 }
1497 assert!(
1498 parse(&format!("{LEAST}\n[export.s3]\n"))
1499 .expect_err("no region")
1500 .0
1501 .contains("region"),
1502 "region is required"
1503 );
1504 }
1505
1506 #[test]
1509 fn an_export_service_names_its_bucket_and_prefix() {
1510 let full = parse(FULL).expect("full");
1511 let export = full.export.s3.expect("export.s3");
1512 let s = export.for_bucket("reports", "vcon/");
1513 assert_eq!(
1514 (s.bucket.as_str(), s.prefix.as_str()),
1515 ("reports", "vcon/"),
1516 "the target's bucket and prefix"
1517 );
1518 assert_eq!(s.endpoint, export.endpoint, "the export's endpoint");
1519 assert_eq!(s.region, export.region, "the export's region");
1520 assert_eq!(
1521 s.access_key_id, export.access_key_id,
1522 "the export's access key id"
1523 );
1524 assert_eq!(
1525 s.secret_access_key_file, export.secret_access_key_file,
1526 "the export's secret file"
1527 );
1528 assert_eq!(s.ca_file, export.ca_file, "the export's CA file");
1529 assert_eq!(
1530 (s.path_style, s.allow_http),
1531 (true, true),
1532 "FULL sets path_style and allow_http"
1533 );
1534 assert_eq!(s.timeout, Duration::from_secs(120), "the export's timeout");
1535 assert!(!s.allow_versioning, "never read for an export");
1536 let ObjectStore::S3(storage) = full.storage.objects else {
1537 panic!("FULL keeps its objects in S3")
1538 };
1539 let from = ExportS3::from(&storage).for_bucket(&storage.bucket, &storage.prefix);
1540 assert_eq!(
1541 from,
1542 S3Settings {
1543 allow_versioning: false,
1544 ..storage
1545 },
1546 "storage.s3's service and keys, whole"
1547 );
1548 }
1549
1550 #[test]
1551 fn s3_settings_that_do_not_hold_together_are_named() {
1552 let s3 = |extra: &str| {
1553 format!(
1554 "{LEAST}\n[storage]\nobjects = \"s3\"\n[storage.s3]\nregion = \"us-east-1\"\nbucket = \"vcon\"\n{extra}"
1555 )
1556 };
1557 for (text, key) in [
1558 (
1559 format!("{LEAST}\n[storage]\nobjects = \"s3\"\n"),
1560 "storage.s3",
1561 ),
1562 (
1563 format!("{LEAST}\n[storage]\nobjects = \"s3\"\n[storage.s3]\nbucket = \"vcon\"\n"),
1564 "region",
1565 ),
1566 (
1567 format!(
1568 "{LEAST}\n[storage]\nobjects = \"s3\"\n[storage.s3]\nregion = \"us-east-1\"\n"
1569 ),
1570 "bucket",
1571 ),
1572 (
1573 s3("endpoint = \"http://127.0.0.1:9000\"\n"),
1574 "storage.s3.allow_http",
1575 ),
1576 (
1577 s3("endpoint = \"objects.example.com\"\n"),
1578 "storage.s3.endpoint",
1579 ),
1580 (
1581 s3("access_key_id = \"vcon-server\"\n"),
1582 "storage.s3.secret_access_key_file",
1583 ),
1584 (
1585 s3("secret_access_key_file = \"/etc/vcon-server/s3.secret\"\n"),
1586 "storage.s3.access_key_id",
1587 ),
1588 (s3("timeout = 0\n"), "storage.s3.timeout"),
1589 (
1590 s3(
1591 "endpoint = \"http://127.0.0.1:9000\"\nallow_http = true\nca_file = \"/etc/vcon-server/s3-ca.pem\"\n",
1592 ),
1593 "storage.s3.ca_file",
1594 ),
1595 (s3("prefix = \"/server-a/\"\n"), "storage.s3.prefix"),
1596 (s3("prefix = \"server-a\"\n"), "storage.s3.prefix"),
1597 (
1598 s3("bucket = \"\"\n").replace("bucket = \"vcon\"\n", ""),
1599 "storage.s3.bucket",
1600 ),
1601 (
1602 format!("{LEAST}\n[storage]\nobjects = \"tape\"\n"),
1603 "objects",
1604 ),
1605 (format!("{LEAST}\n[storage.parquet]\n"), "storage.parquet"),
1606 (
1607 format!("{LEAST}\n[storage]\nobjects = \"local\"\n[storage.parquet]\n"),
1608 "storage.parquet",
1609 ),
1610 (
1611 s3("[storage.parquet]\npack_interval = 0\n"),
1612 "storage.parquet.pack_interval",
1613 ),
1614 (
1615 s3("[storage.parquet]\npack_limit = 0\n"),
1616 "storage.parquet.pack_limit",
1617 ),
1618 (
1619 s3("[storage.parquet]\nreader_grace = 0\n"),
1620 "storage.parquet.reader_grace",
1621 ),
1622 (
1623 format!(
1624 "{LEAST}\n[storage]\nobjects = \"local\"\n[storage.s3]\nregion = \"us-east-1\"\nbucket = \"vcon\"\n"
1625 ),
1626 "storage.s3",
1627 ),
1628 ] {
1629 let error = parse(&text).expect_err(key);
1630 assert!(error.0.contains(key), "the error names {key}: {error}");
1631 }
1632 }
1633
1634 #[test]
1635 fn an_http_endpoint_reads_when_allowed() {
1636 let text = format!(
1637 "{LEAST}\n[storage]\nobjects = \"s3\"\n[storage.s3]\nregion = \"us-east-1\"\nbucket = \"vcon\"\nendpoint = \"http://127.0.0.1:9000\"\nallow_http = true\n"
1638 );
1639 assert!(
1640 parse(&text).is_ok(),
1641 "allow_http lets a test container's plain endpoint through"
1642 );
1643 }
1644
1645 #[test]
1647 fn every_missing_key_without_a_default_is_named() {
1648 for (line, key) in [
1649 ("listen = \"127.0.0.1:8443\"\n", "listen"),
1650 ("data_dir = \"/var/lib/vcon-server\"\n", "data_dir"),
1651 (
1652 "master_key = \"/etc/vcon-server/master.key\"\n",
1653 "master_key",
1654 ),
1655 ("cert = \"/etc/vcon-server/cert.pem\"\n", "cert"),
1656 ("key = \"/etc/vcon-server/key.pem\"\n", "key"),
1657 ] {
1658 assert!(FULL.contains(line), "{line}");
1659 let error = parse(&FULL.replace(line, "")).expect_err(key);
1660 assert!(error.0.contains(&format!("`{key}`")), "{key}: {error}");
1661 }
1662 }
1663
1664 #[test]
1665 fn an_unknown_key_is_named() {
1666 for (text, key) in [
1667 (format!("colour = \"blue\"\n{FULL}"), "colour"),
1668 (FULL.replace("read = 30", "read = 30\nwrite = 30"), "write"),
1669 (FULL.replace("[tls]", "[tls]\nca = \"x\""), "ca"),
1670 (
1671 FULL.replace("[mcp]", "[mcp]\nresources = true"),
1672 "resources",
1673 ),
1674 ] {
1675 let error = parse(&text).expect_err(key);
1676 assert!(error.0.contains(&format!("`{key}`")), "{key}: {error}");
1677 }
1678 }
1679
1680 #[test]
1681 fn a_bad_value_is_named() {
1682 for (from, to, key) in [
1683 ("\"127.0.0.1:8443\"", "\"localhost\"", "listen"),
1684 ("\"18m\"", "\"7w\"", "retention_default"),
1685 (
1686 "purge_interval = 1800",
1687 "purge_interval = 0",
1688 "purge_interval",
1689 ),
1690 (
1691 "rotation_warn = 604800",
1692 "rotation_warn = 0",
1693 "rotation_warn",
1694 ),
1695 ("body = 10485760", "body = 0", "limits.body"),
1696 ("inflated = 104857600", "inflated = 0", "limits.inflated"),
1697 (
1698 "calls_per_second = 20",
1699 "calls_per_second = 0",
1700 "mcp.calls_per_second",
1701 ),
1702 ("concurrent = 8", "concurrent = 0", "mcp.concurrent"),
1703 (
1704 "response_bytes = 262144",
1705 "response_bytes = 0",
1706 "mcp.response_bytes",
1707 ),
1708 (
1709 "concurrent = 8",
1710 "concurrent = 4294967296",
1711 "mcp.concurrent",
1712 ),
1713 ("read = 30", "read = 0", "limits.timeouts.read"),
1714 ("read = 30", "read = -1", "read"),
1715 ] {
1716 let error = parse(&FULL.replace(from, to)).expect_err(key);
1717 assert!(error.0.contains(key), "{key}: {error}");
1718 }
1719 }
1720
1721 mod site_page {
1725 use super::*;
1726
1727 fn page(name: &str) -> String {
1728 let path = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
1729 .join("../../website/content/docs")
1730 .join(name);
1731 std::fs::read_to_string(&path).unwrap_or_else(|e| panic!("{}: {e}", path.display()))
1732 }
1733
1734 fn keys(table: &toml::Table, prefix: &str, out: &mut Vec<String>) {
1736 for (key, value) in table {
1737 let name = format!("{prefix}{key}");
1738 match value {
1739 toml::Value::Table(inner) => keys(inner, &format!("{name}."), out),
1740 _ => out.push(name),
1741 }
1742 }
1743 }
1744
1745 fn row<'a>(text: &'a str, key: &str) -> &'a str {
1747 let start = format!("| `{key}` |");
1748 let mut rows = text.lines().filter(|l| l.starts_with(&start));
1749 let row = rows.next().unwrap_or_else(|| panic!("no row for {key}"));
1750 assert!(rows.next().is_none(), "two rows for {key}");
1751 row
1752 }
1753
1754 #[test]
1755 fn every_key_is_listed_with_its_default() {
1756 let text = page("configuration.md");
1757 let defaults = parse(LEAST).expect("least");
1758 let mut all = Vec::new();
1759 keys(&FULL.parse::<toml::Table>().expect("toml"), "", &mut all);
1760 assert_eq!(all.len(), 51, "{all:?}");
1761 let pg = catalog::postgres_least();
1762 for key in all {
1763 let default = match key.as_str() {
1764 "listen" | "data_dir" | "master_key" | "tls.cert" | "tls.key" => {
1765 "required".to_owned()
1766 }
1767 "retention_default" => format!("`{}`", defaults.retention_default),
1768 "purge_interval" => format!("`{}`", defaults.purge_interval.as_secs()),
1769 "rotation_warn" => format!("`{}`", defaults.rotation_warn.as_secs()),
1770 "limits.body" => format!("`{}`", defaults.body_limit),
1771 "limits.inflated" => format!("`{}`", defaults.inflated_limit),
1772 "limits.timeouts.read" => format!("`{}`", defaults.read_timeout.as_secs()),
1773 "mcp.calls_per_second" => format!("`{}`", defaults.mcp.calls_per_second),
1774 "mcp.concurrent" => format!("`{}`", defaults.mcp.concurrent),
1775 "mcp.response_bytes" => format!("`{}`", defaults.mcp.response_bytes),
1776 "storage.objects" => "`local`".to_owned(),
1777 "storage.s3.region" | "storage.s3.bucket" => "required with `s3`".to_owned(),
1778 "storage.s3.endpoint"
1779 | "storage.s3.access_key_id"
1780 | "storage.s3.secret_access_key_file"
1781 | "storage.s3.ca_file" => "none".to_owned(),
1782 "storage.s3.prefix" => "empty".to_owned(),
1783 "storage.s3.path_style" => format!("`{}`", s3_least().path_style),
1784 "storage.s3.allow_http" => format!("`{}`", s3_least().allow_http),
1785 "storage.s3.allow_versioning" => {
1786 format!("`{}`", s3_least().allow_versioning)
1787 }
1788 "storage.s3.timeout" => format!("`{}`", s3_least().timeout.as_secs()),
1789 "storage.parquet.pack_interval" => {
1790 format!("`{}`", parquet_least().pack_interval.as_secs())
1791 }
1792 "storage.parquet.pack_limit" => format!("`{}`", parquet_least().pack_limit),
1793 "storage.parquet.reader_grace" => {
1794 format!("`{}`", parquet_least().reader_grace.as_secs())
1795 }
1796 "export.s3.region" => "required with `export.s3`".to_owned(),
1797 "export.s3.endpoint"
1798 | "export.s3.access_key_id"
1799 | "export.s3.secret_access_key_file"
1800 | "export.s3.ca_file" => "none".to_owned(),
1801 "export.s3.path_style" => format!("`{}`", s3_least().path_style),
1802 "export.s3.allow_http" => format!("`{}`", s3_least().allow_http),
1803 "export.s3.timeout" => format!("`{}`", S3_TIMEOUT.as_secs()),
1804 "catalog.backend" => "`local`".to_owned(),
1805 "catalog.postgres.hosts"
1806 | "catalog.postgres.dbname"
1807 | "catalog.postgres.user" => "required with `postgres`".to_owned(),
1808 "catalog.postgres.ca_file"
1809 | "catalog.postgres.password_file"
1810 | "catalog.postgres.client_cert_file"
1811 | "catalog.postgres.client_key_file" => "none".to_owned(),
1812 "catalog.postgres.port" => format!("`{}`", pg.port),
1813 "catalog.postgres.pool" => format!("`{}`", pg.pool),
1814 "catalog.postgres.connect_timeout" => {
1815 format!("`{}`", pg.connect_timeout.as_secs())
1816 }
1817 "catalog.postgres.statement_timeout" => {
1818 format!("`{}`", pg.statement_timeout.as_secs())
1819 }
1820 "catalog.postgres.lock_timeout" => {
1821 format!("`{}`", pg.lock_timeout.as_secs())
1822 }
1823 "supported_critical" => {
1824 assert!(
1825 defaults.supported_critical.is_empty(),
1826 "the page says none, which holds only while the default is empty"
1827 );
1828 "none".to_owned()
1829 }
1830 other => panic!("a key this test does not know: {other}"),
1831 };
1832 let row = row(&text, &key);
1833 let last = row
1834 .trim_end_matches('|')
1835 .rsplit('|')
1836 .next()
1837 .expect("a last cell")
1838 .trim();
1839 assert!(
1840 last.starts_with(&default),
1841 "{key}: `{last}` is not {default}"
1842 );
1843 }
1844 }
1845
1846 #[test]
1848 fn every_fixed_limit_is_listed_with_its_value() {
1849 let text = page("configuration.md");
1850 for (limit, value) in [
1851 ("Signed layers in one body", vcon::read::MAX_SIGNED_LAYERS),
1852 (
1853 "Arrays and objects open at once",
1854 vcon::read::MAX_JSON_DEPTH,
1855 ),
1856 ] {
1857 let start = format!("| {limit} |");
1858 let rows: Vec<&str> = text.lines().filter(|l| l.starts_with(&start)).collect();
1859 assert_eq!(rows.len(), 1, "one row for {limit}");
1860 let cell = rows[0].split('|').nth(2).expect("a value cell").trim();
1861 assert_eq!(cell, format!("`{value}`"), "{limit}");
1862 }
1863 }
1864
1865 #[test]
1866 fn every_example_file_on_the_site_reads() {
1867 let mut examples = 0;
1868 for name in [
1869 "configuration.md",
1870 "getting-started.md",
1871 "container.md",
1872 "postgres-catalog.md",
1873 ] {
1874 let text = page(name);
1875 for block in text.split("```toml\n").skip(1) {
1876 let toml = block.split("```").next().expect("a block");
1877 parse(toml).unwrap_or_else(|e| panic!("{name}: {e}\n{toml}"));
1878 examples += 1;
1879 }
1880 }
1881 assert_eq!(
1882 examples, 7,
1883 "four on the configuration page, one each on getting started, the \
1884 container page and the PostgreSQL catalog page, so a block the split misses \
1885 is caught"
1886 );
1887 }
1888 }
1889
1890 mod catalog {
1893 use super::*;
1894
1895 pub(super) fn postgres_text() -> String {
1899 format!(
1900 "{LEAST}\n[storage]\nobjects = \"s3\"\n\n[storage.s3]\nregion = \"us-east-1\"\n\
1901 bucket = \"vcon\"\n\n[catalog]\nbackend = \"postgres\"\n\n[catalog.postgres]\n\
1902 hosts = [\"db1.example.com\"]\ndbname = \"vcon\"\nuser = \"vcon_app\"\n\
1903 password_file = \"/etc/vcon-server/pg.password\"\n"
1904 )
1905 }
1906
1907 fn edited(from: &str, to: &str) -> String {
1909 let text = postgres_text();
1910 assert!(text.contains(from), "the least text holds {from:?}");
1911 text.replace(from, to)
1912 }
1913
1914 fn with(line: &str) -> String {
1916 format!("{}{line}\n", postgres_text())
1917 }
1918
1919 fn postgres(text: &str) -> PostgresSettings {
1921 match parse(text)
1922 .unwrap_or_else(|e| panic!("{e}\n{text}"))
1923 .catalog
1924 {
1925 CatalogStore::Postgres(pg) => *pg,
1926 CatalogStore::Local => panic!("backend = \"postgres\" keeps the catalogs there"),
1927 }
1928 }
1929
1930 pub(super) fn postgres_least() -> PostgresSettings {
1932 postgres(&postgres_text())
1933 }
1934
1935 fn refused(text: &str) -> String {
1937 parse(text).expect_err(text).0
1938 }
1939
1940 mod success {
1941 use super::*;
1942
1943 #[test]
1944 fn a_postgres_catalog_is_read_with_its_defaults() {
1945 assert_eq!(
1946 postgres_least(),
1947 PostgresSettings {
1948 hosts: vec!["db1.example.com".to_owned()],
1949 port: 5432,
1950 dbname: "vcon".to_owned(),
1951 user: "vcon_app".to_owned(),
1952 ca_file: None,
1953 password_file: Some("/etc/vcon-server/pg.password".into()),
1954 client_cert_file: None,
1955 client_key_file: None,
1956 pool: 16,
1957 connect_timeout: Duration::from_secs(5),
1958 statement_timeout: Duration::from_secs(30),
1959 lock_timeout: Duration::from_secs(10),
1960 },
1961 "only hosts, dbname, user and a way to log in are required"
1962 );
1963 }
1964
1965 #[test]
1966 fn without_a_catalog_table_the_catalogs_are_local() {
1967 assert_eq!(
1968 parse(LEAST).expect("parses").catalog,
1969 CatalogStore::Local,
1970 "a file written before the PostgreSQL catalog keeps its meaning"
1971 );
1972 }
1973
1974 #[test]
1975 fn backend_local_is_the_local_catalog() {
1976 let text = format!("{LEAST}\n[catalog]\nbackend = \"local\"\n");
1977 assert_eq!(
1978 parse(&text).expect("parses").catalog,
1979 CatalogStore::Local,
1980 "\"local\" names the default"
1981 );
1982 }
1983
1984 #[test]
1985 fn a_client_certificate_alone_is_enough_to_log_in() {
1986 let text = edited(
1987 "password_file = \"/etc/vcon-server/pg.password\"\n",
1988 "client_cert_file = \"/c.pem\"\nclient_key_file = \"/c.key\"\n",
1989 );
1990 let pg = postgres(&text);
1991 assert_eq!(
1992 (pg.password_file, pg.client_cert_file, pg.client_key_file),
1993 (None, Some("/c.pem".into()), Some("/c.key".into())),
1994 "a certificate and its key, with no password"
1995 );
1996 }
1997
1998 #[test]
1999 fn a_password_and_a_client_certificate_are_read_together() {
2000 let pg = postgres(&with(
2001 "client_cert_file = \"/c.pem\"\nclient_key_file = \"/c.key\"",
2002 ));
2003 assert!(
2004 pg.password_file.is_some() && pg.client_cert_file.is_some(),
2005 "both ways of logging in, as pg_hba.conf's clientcert=verify-full asks"
2006 );
2007 }
2008
2009 #[test]
2010 fn several_hosts_are_kept_in_their_order() {
2011 let text = edited(
2012 "hosts = [\"db1.example.com\"]",
2013 "hosts = [\"db2.example.com\", \"db1.example.com\", \"192.0.2.10\"]",
2014 );
2015 assert_eq!(
2016 postgres(&text).hosts,
2017 ["db2.example.com", "db1.example.com", "192.0.2.10"],
2018 "tried in the order written"
2019 );
2020 }
2021
2022 #[test]
2023 fn parquet_storage_with_a_postgres_catalog_is_read() {
2024 let text = edited(
2025 "bucket = \"vcon\"\n",
2026 "bucket = \"vcon\"\n\n[storage.parquet]\n",
2027 );
2028 let config = parse(&text).expect("parses");
2029 assert!(
2030 config.storage.parquet.is_some()
2031 && matches!(config.catalog, CatalogStore::Postgres(_)),
2032 "Parquet files in the bucket and the catalogs in PostgreSQL"
2033 );
2034 }
2035 }
2036
2037 mod failure {
2038 use super::*;
2039
2040 fn refused_naming(text: &str, names: &[&str]) {
2042 let message = refused(text);
2043 for name in names {
2044 assert!(message.contains(name), "names {name}: {message}");
2045 }
2046 }
2047
2048 #[test]
2049 fn an_unknown_backend_is_named() {
2050 refused_naming(
2051 &edited("backend = \"postgres\"", "backend = \"mysql\""),
2052 &["catalog.backend", "\"mysql\""],
2053 );
2054 }
2055
2056 #[test]
2057 fn a_postgres_table_without_the_postgres_backend_is_refused() {
2058 refused_naming(
2059 &edited("backend = \"postgres\"", "backend = \"local\""),
2060 &["catalog.postgres", "catalog.backend"],
2061 );
2062 }
2063
2064 #[test]
2065 fn the_postgres_backend_without_its_table_is_refused() {
2066 let text = format!(
2067 "{LEAST}\n[storage]\nobjects = \"s3\"\n[storage.s3]\nregion = \"us-east-1\"\n\
2068 bucket = \"vcon\"\n[catalog]\nbackend = \"postgres\"\n"
2069 );
2070 refused_naming(&text, &["catalog.postgres"]);
2071 }
2072
2073 #[test]
2074 fn a_postgres_catalog_with_local_objects_is_refused() {
2075 let text = format!(
2076 "{LEAST}\n[catalog]\nbackend = \"postgres\"\n[catalog.postgres]\n\
2077 hosts = [\"db1.example.com\"]\ndbname = \"vcon\"\nuser = \"vcon_app\"\n\
2078 password_file = \"/p\"\n"
2079 );
2080 refused_naming(&text, &["catalog.backend", "storage.objects", "\"s3\""]);
2081 }
2082
2083 #[test]
2084 fn an_empty_host_list_is_refused() {
2085 refused_naming(
2086 &edited("hosts = [\"db1.example.com\"]", "hosts = []"),
2087 &["catalog.postgres.hosts"],
2088 );
2089 }
2090
2091 #[test]
2092 fn an_empty_host_name_is_refused() {
2093 refused_naming(
2094 &edited("hosts = [\"db1.example.com\"]", "hosts = [\"\"]"),
2095 &["catalog.postgres.hosts"],
2096 );
2097 }
2098
2099 #[test]
2100 fn a_host_that_is_not_a_dns_name_is_refused() {
2101 for host in [
2102 "db_1.example.com",
2103 "db..example.com",
2104 "-db.example.com",
2105 "db .example.com",
2106 ] {
2107 refused_naming(
2108 &edited("\"db1.example.com\"", &format!("{host:?}")),
2109 &["catalog.postgres.hosts", host],
2110 );
2111 }
2112 }
2113
2114 #[test]
2115 fn a_missing_host_list_is_named() {
2116 refused_naming(&edited("hosts = [\"db1.example.com\"]\n", ""), &["hosts"]);
2117 }
2118
2119 #[test]
2120 fn a_port_of_zero_is_refused() {
2121 refused_naming(&with("port = 0"), &["catalog.postgres.port"]);
2122 }
2123
2124 #[test]
2125 fn a_port_above_65535_is_refused() {
2126 refused_naming(&with("port = 65536"), &["catalog.postgres.port"]);
2127 }
2128
2129 #[test]
2130 fn an_empty_database_name_is_refused() {
2131 refused_naming(
2132 &edited("dbname = \"vcon\"", "dbname = \"\""),
2133 &["catalog.postgres.dbname"],
2134 );
2135 }
2136
2137 #[test]
2138 fn a_missing_database_name_is_named() {
2139 refused_naming(&edited("dbname = \"vcon\"\n", ""), &["dbname"]);
2140 }
2141
2142 #[test]
2143 fn an_empty_user_is_refused() {
2144 refused_naming(
2145 &edited("user = \"vcon_app\"", "user = \"\""),
2146 &["catalog.postgres.user"],
2147 );
2148 }
2149
2150 #[test]
2151 fn a_missing_user_is_named() {
2152 refused_naming(&edited("user = \"vcon_app\"\n", ""), &["user"]);
2153 }
2154
2155 #[test]
2156 fn no_password_and_no_client_certificate_is_refused() {
2157 refused_naming(
2158 &edited("password_file = \"/etc/vcon-server/pg.password\"\n", ""),
2159 &[
2160 "catalog.postgres.password_file",
2161 "catalog.postgres.client_cert_file",
2162 ],
2163 );
2164 }
2165
2166 #[test]
2167 fn a_client_certificate_without_its_key_is_refused() {
2168 refused_naming(
2169 &with("client_cert_file = \"/c.pem\""),
2170 &["catalog.postgres.client_key_file"],
2171 );
2172 }
2173
2174 #[test]
2175 fn a_client_key_without_its_certificate_is_refused() {
2176 refused_naming(
2177 &with("client_key_file = \"/c.key\""),
2178 &["catalog.postgres.client_cert_file"],
2179 );
2180 }
2181
2182 #[test]
2183 fn an_empty_file_name_is_refused() {
2184 for (key, text) in [
2185 ("ca_file", with("ca_file = \"\"")),
2186 (
2187 "password_file",
2188 edited("\"/etc/vcon-server/pg.password\"", "\"\""),
2189 ),
2190 (
2191 "client_cert_file",
2192 with("client_cert_file = \"\"\nclient_key_file = \"/c.key\""),
2193 ),
2194 (
2195 "client_key_file",
2196 with("client_cert_file = \"/c.pem\"\nclient_key_file = \"\""),
2197 ),
2198 ] {
2199 refused_naming(&text, &[&format!("catalog.postgres.{key}")]);
2200 }
2201 }
2202
2203 #[test]
2204 fn a_pool_of_zero_is_refused() {
2205 refused_naming(&with("pool = 0"), &["catalog.postgres.pool"]);
2206 }
2207
2208 #[test]
2209 fn a_pool_too_large_to_count_is_refused() {
2210 refused_naming(&with("pool = 4294967296"), &["catalog.postgres.pool"]);
2211 }
2212
2213 #[test]
2214 fn a_connect_timeout_of_zero_is_refused() {
2215 refused_naming(
2216 &with("connect_timeout = 0"),
2217 &["catalog.postgres.connect_timeout"],
2218 );
2219 }
2220
2221 #[test]
2222 fn a_statement_timeout_of_zero_is_refused() {
2223 refused_naming(
2224 &with("statement_timeout = 0"),
2225 &["catalog.postgres.statement_timeout"],
2226 );
2227 }
2228
2229 #[test]
2230 fn a_lock_timeout_of_zero_is_refused() {
2231 refused_naming(
2232 &with("lock_timeout = 0"),
2233 &["catalog.postgres.lock_timeout"],
2234 );
2235 }
2236
2237 #[test]
2239 fn an_sslmode_key_is_an_unknown_key() {
2240 refused_naming(&with("sslmode = \"disable\""), &["`sslmode`"]);
2241 }
2242
2243 #[test]
2244 fn an_unknown_key_in_the_catalog_table_is_named() {
2245 refused_naming(
2246 &edited(
2247 "backend = \"postgres\"",
2248 "backend = \"postgres\"\nreplicas = 2",
2249 ),
2250 &["`replicas`"],
2251 );
2252 }
2253 }
2254
2255 mod edge {
2256 use super::*;
2257
2258 fn host_text(host: &str) -> String {
2259 edited("\"db1.example.com\"", &format!("{host:?}"))
2260 }
2261
2262 #[test]
2263 fn ipv6_hosts_are_read() {
2264 for host in ["2001:db8::10", "::1", "2001:db8:0:0:0:0:0:10"] {
2265 assert_eq!(
2266 postgres(&host_text(host)).hosts,
2267 [host],
2268 "an IPv6 address is a host as written"
2269 );
2270 }
2271 }
2272
2273 #[test]
2274 fn a_bracketed_ipv6_host_is_refused_with_its_bare_form() {
2275 let message = refused(&host_text("[2001:db8::10]"));
2276 assert!(
2277 message.contains("catalog.postgres.hosts")
2278 && message.contains("\"2001:db8::10\""),
2279 "names the key and the form to write: {message}"
2280 );
2281 }
2282
2283 #[test]
2286 fn a_unix_socket_host_is_refused_because_tls_is_required() {
2287 let message = refused(&host_text("/var/run/postgresql"));
2288 assert!(
2289 message.contains("catalog.postgres.hosts")
2290 && message.contains("Unix socket")
2291 && message.contains("TLS"),
2292 "says why: {message}"
2293 );
2294 }
2295
2296 #[test]
2297 fn a_unicode_host_name_is_refused_with_a_pointer_to_its_ascii_form() {
2298 let message = refused(&host_text("bücher.example.com"));
2299 assert!(
2300 message.contains("catalog.postgres.hosts") && message.contains("xn--"),
2301 "an internationalized name is written in its xn-- form: {message}"
2302 );
2303 }
2304
2305 #[test]
2306 fn an_ascii_form_of_a_unicode_host_name_is_read() {
2307 assert_eq!(
2308 postgres(&host_text("xn--bcher-kva.example.com")).hosts,
2309 ["xn--bcher-kva.example.com"],
2310 "the xn-- form is a DNS name"
2311 );
2312 }
2313
2314 #[test]
2315 fn unicode_database_and_role_names_are_read() {
2316 let text = edited("dbname = \"vcon\"", "dbname = \"vcon_数据\"")
2317 .replace("user = \"vcon_app\"", "user = \"vcon_ünï\"");
2318 let pg = postgres(&text);
2319 assert_eq!(
2320 (pg.dbname.as_str(), pg.user.as_str()),
2321 ("vcon_数据", "vcon_ünï"),
2322 "PostgreSQL names may hold any character but NUL"
2323 );
2324 }
2325
2326 #[test]
2329 fn a_name_of_63_bytes_is_read_and_one_of_64_refused() {
2330 let at_limit = "数".repeat(21);
2331 assert_eq!(at_limit.len(), 63, "21 three-byte characters");
2332 for key in ["dbname", "user"] {
2333 let line = |name: &str| format!("{key} = \"{name}\"");
2334 let from = if key == "dbname" {
2335 "dbname = \"vcon\""
2336 } else {
2337 "user = \"vcon_app\""
2338 };
2339 let pg = postgres(&edited(from, &line(&at_limit)));
2340 let read = if key == "dbname" { pg.dbname } else { pg.user };
2341 assert_eq!(read, at_limit, "{key}: 63 bytes is PostgreSQL's limit");
2342 let message = refused(&edited(from, &line(&format!("{at_limit}a"))));
2343 assert!(
2344 message.contains(&format!("catalog.postgres.{key}"))
2345 && message.contains("63 bytes"),
2346 "{key}: {message}"
2347 );
2348 }
2349 }
2350
2351 #[test]
2352 fn a_nul_in_a_name_is_refused() {
2353 for (from, to, key) in [
2354 ("dbname = \"vcon\"", "dbname = \"vc\\u0000on\"", "dbname"),
2355 ("user = \"vcon_app\"", "user = \"vcon\\u0000\"", "user"),
2356 ] {
2357 let message = refused(&edited(from, to));
2358 assert!(
2359 message.contains(&format!("catalog.postgres.{key}"))
2360 && message.contains("NUL"),
2361 "{key}: {message}"
2362 );
2363 }
2364 }
2365
2366 #[test]
2367 fn the_first_and_last_ports_are_read() {
2368 for port in [1, 65535] {
2369 assert_eq!(
2370 u64::from(postgres(&with(&format!("port = {port}"))).port),
2371 port,
2372 "every TCP port but 0"
2373 );
2374 }
2375 }
2376
2377 #[test]
2380 fn timeouts_at_the_postgresql_limit_are_read_and_one_past_refused() {
2381 for key in ["statement_timeout", "lock_timeout"] {
2382 let pg = postgres(&with(&format!("{key} = 2147483")));
2383 let read = if key == "statement_timeout" {
2384 pg.statement_timeout
2385 } else {
2386 pg.lock_timeout
2387 };
2388 assert_eq!(read, Duration::from_secs(2_147_483), "{key} at the limit");
2389 let message = refused(&with(&format!("{key} = 2147484")));
2390 assert!(
2391 message.contains(&format!("catalog.postgres.{key}"))
2392 && message.contains("2147483"),
2393 "{key}: {message}"
2394 );
2395 }
2396 }
2397
2398 #[test]
2399 fn a_one_second_connect_timeout_is_read() {
2400 assert_eq!(
2401 postgres(&with("connect_timeout = 1")).connect_timeout,
2402 Duration::from_secs(1),
2403 "the shortest timeout"
2404 );
2405 }
2406
2407 #[test]
2408 fn the_same_host_twice_is_refused() {
2409 let message = refused(&edited(
2410 "hosts = [\"db1.example.com\"]",
2411 "hosts = [\"db1.example.com\", \"DB1.example.com\"]",
2412 ));
2413 assert!(
2414 message.contains("catalog.postgres.hosts") && message.contains("twice"),
2415 "a DNS name in any case is one host: {message}"
2416 );
2417 }
2418
2419 #[test]
2420 fn a_dns_label_of_63_characters_is_read_and_one_of_64_refused() {
2421 let label = "a".repeat(63);
2422 let host = format!("{label}.example.com");
2423 assert_eq!(
2424 postgres(&host_text(&host)).hosts,
2425 [host],
2426 "63 is the DNS limit"
2427 );
2428 let message = refused(&host_text(&format!("a{label}.example.com")));
2429 assert!(message.contains("catalog.postgres.hosts"), "{message}");
2430 }
2431
2432 #[test]
2433 fn a_host_name_of_more_than_253_characters_is_refused() {
2434 let label = "a".repeat(63);
2435 let at_limit = format!("{label}.{label}.{label}.{}", "a".repeat(61));
2436 assert_eq!(at_limit.len(), 253, "four labels");
2437 assert_eq!(
2438 postgres(&host_text(&at_limit)).hosts,
2439 std::slice::from_ref(&at_limit),
2440 "253 characters is the DNS limit"
2441 );
2442 let message = refused(&host_text(&format!("a{at_limit}")));
2443 assert!(message.contains("catalog.postgres.hosts"), "{message}");
2444 }
2445
2446 #[test]
2447 fn a_port_written_in_a_host_is_refused_with_the_port_key_named() {
2448 let message = refused(&host_text("db1.example.com:5432"));
2449 assert!(
2450 message.contains("catalog.postgres.hosts")
2451 && message.contains("catalog.postgres.port"),
2452 "the port has its own key: {message}"
2453 );
2454 }
2455 }
2456 }
2457
2458 #[test]
2459 fn a_missing_file_is_named() {
2460 let error = load(Path::new("/nonexistent/vcon-server.toml")).expect_err("missing");
2461 assert!(error.0.contains("/nonexistent/vcon-server.toml"), "{error}");
2462 }
2463}