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::api::ConnectionLimits;
13use crate::retention::Retention;
14use crate::session::Origin;
15
16#[derive(Debug, Clone, PartialEq, Eq)]
20pub struct Config {
21 pub listen: SocketAddr,
23 pub tls_cert: PathBuf,
25 pub tls_key: PathBuf,
27 pub data_dir: PathBuf,
29 pub master_key: PathBuf,
31 pub retention_default: Retention,
33 pub purge_interval: Duration,
35 pub rotation_warn: Duration,
38 pub body_limit: usize,
40 pub inflated_limit: u64,
42 pub read_timeout: Duration,
44 pub connection: ConnectionLimits,
49 pub supported_critical: BTreeSet<String>,
51 pub mcp: crate::mcp::Limits,
53 pub reports: crate::api::ReportLimits,
57 pub storage: Storage,
59 pub export: Export,
61 pub catalog: CatalogStore,
63 pub operator: Option<Operator>,
66 pub public_origin: Option<Origin>,
70 pub keys_no_expiry: bool,
73}
74
75#[derive(Debug, Clone, PartialEq, Eq)]
79pub struct Operator {
80 pub listen: SocketAddr,
82 pub tls_cert: PathBuf,
85 pub tls_key: PathBuf,
88 pub public_origin: Option<Origin>,
92}
93
94#[must_use]
99pub fn same_socket(a: SocketAddr, b: SocketAddr) -> bool {
100 a.port() == b.port()
101 && a.port() != 0
102 && (a.ip() == b.ip()
103 || (a.is_ipv4() == b.is_ipv4() && (a.ip().is_unspecified() || b.ip().is_unspecified())))
104}
105
106#[derive(Debug, Clone, PartialEq, Eq, Default)]
108pub enum CatalogStore {
109 #[default]
111 Local,
112 Postgres(Box<PostgresSettings>),
114}
115
116#[derive(Debug, Clone, PartialEq, Eq)]
120pub struct PostgresSettings {
121 pub hosts: Vec<String>,
123 pub port: u16,
125 pub dbname: String,
127 pub user: String,
129 pub ca_file: Option<PathBuf>,
132 pub password_file: Option<PathBuf>,
134 pub client_cert_file: Option<PathBuf>,
136 pub client_key_file: Option<PathBuf>,
138 pub pool: u32,
140 pub connect_timeout: Duration,
142 pub statement_timeout: Duration,
144 pub lock_timeout: Duration,
146}
147
148#[derive(Debug, Clone, PartialEq, Eq, Default)]
150pub struct Export {
151 pub s3: Option<ExportS3>,
154}
155
156#[derive(Debug, Clone, PartialEq, Eq)]
160pub struct ExportS3 {
161 pub endpoint: Option<String>,
163 pub region: String,
165 pub path_style: bool,
167 pub access_key_id: Option<String>,
169 pub secret_access_key_file: Option<PathBuf>,
171 pub allow_http: bool,
173 pub ca_file: Option<PathBuf>,
176 pub timeout: Duration,
178}
179
180impl ExportS3 {
181 #[must_use]
183 pub fn for_bucket(&self, bucket: &str, prefix: &str) -> S3Settings {
184 S3Settings {
185 endpoint: self.endpoint.clone(),
186 region: self.region.clone(),
187 bucket: bucket.to_owned(),
188 prefix: prefix.to_owned(),
189 path_style: self.path_style,
190 access_key_id: self.access_key_id.clone(),
191 secret_access_key_file: self.secret_access_key_file.clone(),
192 allow_http: self.allow_http,
193 ca_file: self.ca_file.clone(),
194 allow_versioning: false,
195 timeout: self.timeout,
196 }
197 }
198}
199
200impl From<&S3Settings> for ExportS3 {
201 fn from(s: &S3Settings) -> ExportS3 {
203 ExportS3 {
204 endpoint: s.endpoint.clone(),
205 region: s.region.clone(),
206 path_style: s.path_style,
207 access_key_id: s.access_key_id.clone(),
208 secret_access_key_file: s.secret_access_key_file.clone(),
209 allow_http: s.allow_http,
210 ca_file: s.ca_file.clone(),
211 timeout: s.timeout,
212 }
213 }
214}
215
216#[derive(Debug, Clone, PartialEq, Eq)]
219#[must_use]
220pub struct StorageError(pub String);
221
222impl fmt::Display for StorageError {
223 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
224 f.write_str(&self.0)
225 }
226}
227
228impl std::error::Error for StorageError {}
229
230#[derive(Debug, Clone, PartialEq, Eq, Default)]
233pub struct Storage {
234 pub objects: ObjectStore,
236 pub parquet: Option<ParquetSettings>,
239}
240
241#[derive(Debug, Clone, Copy, PartialEq, Eq)]
243pub struct ParquetSettings {
244 pub pack_interval: Duration,
246 pub pack_limit: u64,
249 pub reader_grace: Duration,
252}
253
254pub const READER_GRACE: Duration = Duration::from_secs(900);
257
258pub const PACK_INTERVAL: Duration = Duration::from_secs(300);
260
261pub const PACK_LIMIT: u64 = 16 << 20;
264
265#[derive(Debug, Clone, PartialEq, Eq, Default)]
267pub enum ObjectStore {
268 #[default]
270 Local,
271 S3(S3Settings),
273}
274
275#[derive(Debug, Clone, PartialEq, Eq)]
277pub struct S3Settings {
278 pub endpoint: Option<String>,
280 pub region: String,
282 pub bucket: String,
284 pub prefix: String,
286 pub path_style: bool,
288 pub access_key_id: Option<String>,
290 pub secret_access_key_file: Option<PathBuf>,
292 pub allow_http: bool,
294 pub ca_file: Option<PathBuf>,
297 pub allow_versioning: bool,
299 pub timeout: Duration,
301}
302
303pub const PURGE_INTERVAL: Duration = Duration::from_secs(3600);
306
307pub const ROTATION_WARN: Duration = Duration::from_secs(30 * 86_400);
310
311pub const BODY_LIMIT: usize = 16 << 20;
316
317pub const INFLATED_LIMIT: u64 = 4 * BODY_LIMIT as u64;
321
322pub const READ_TIMEOUT: Duration = Duration::from_secs(60);
325
326#[derive(Debug, Clone, PartialEq, Eq)]
328pub struct ConfigError(pub String);
329
330impl fmt::Display for ConfigError {
331 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
332 f.write_str(&self.0)
333 }
334}
335
336impl std::error::Error for ConfigError {}
337
338pub fn load(path: &Path) -> Result<Config, ConfigError> {
345 let text = std::fs::read_to_string(path)
346 .map_err(|e| ConfigError(format!("{}: {e}", path.display())))?;
347 parse(&text)
348}
349
350pub fn parse(text: &str) -> Result<Config, ConfigError> {
358 let raw: Raw = toml::from_str(text).map_err(|e| ConfigError(e.to_string()))?;
359 let storage = storage(raw.storage)?;
360 let catalog = catalog(raw.catalog, &storage)?;
361 let retention_default = match raw.retention_default {
362 None => Retention::Years(7),
363 Some(text) => Retention::parse(&text).ok_or_else(|| {
364 ConfigError(format!(
365 "retention_default: {text:?} is not a period such as 7y, 18m or 90d"
366 ))
367 })?,
368 };
369 let tls = (raw.tls.cert, raw.tls.key);
370 let public_origin = origin("public_origin", raw.public_origin)?;
371 Ok(Config {
372 listen: raw.listen,
373 tls_cert: tls.0.clone(),
374 tls_key: tls.1.clone(),
375 data_dir: raw.data_dir,
376 master_key: raw.master_key,
377 retention_default,
378 purge_interval: seconds("purge_interval", raw.purge_interval, PURGE_INTERVAL)?,
379 rotation_warn: seconds("rotation_warn", raw.rotation_warn, ROTATION_WARN)?,
380 body_limit: match raw.limits.body {
381 None => BODY_LIMIT,
382 Some(body) => usize::try_from(positive("limits.body", body)?)
383 .map_err(|_| ConfigError("limits.body is too large".to_owned()))?,
384 },
385 inflated_limit: match raw.limits.inflated {
386 None => INFLATED_LIMIT,
387 Some(inflated) => positive("limits.inflated", inflated)?,
388 },
389 read_timeout: seconds(
390 "limits.timeouts.read",
391 raw.limits.timeouts.read,
392 READ_TIMEOUT,
393 )?,
394 connection: connection_limits(&raw.limits)?,
395 supported_critical: raw.supported_critical.into_iter().collect(),
396 mcp: mcp_limits(&raw.mcp)?,
397 reports: report_limits(&raw.limits)?,
398 storage,
399 export: Export {
400 s3: raw.export.s3.map(export_s3).transpose()?,
401 },
402 catalog,
403 operator: operator(raw.operator, raw.listen, &tls, public_origin.as_ref())?,
404 public_origin,
405 keys_no_expiry: raw.keys.no_expiry.unwrap_or(true),
406 })
407}
408
409fn origin(key: &str, raw: Option<String>) -> Result<Option<Origin>, ConfigError> {
411 raw.map(|text| {
412 Origin::parse(&text).ok_or_else(|| {
413 ConfigError(format!(
414 "{key}: {text:?} is not an origin: write https://, a host in lower case and, \
415 unless it is 443, a port, with nothing after, such as https://vcon.example.com"
416 ))
417 })
418 })
419 .transpose()
420}
421
422fn operator(
424 raw: Option<RawOperator>,
425 listen: SocketAddr,
426 tls: &(PathBuf, PathBuf),
427 tenant_origin: Option<&Origin>,
428) -> Result<Option<Operator>, ConfigError> {
429 let Some(raw) = raw else {
430 return Ok(None);
431 };
432 if same_socket(raw.listen, listen) {
433 return Err(ConfigError(format!(
434 "operator.listen: {} is the socket `listen` takes ({listen}); the operator listener \
435 needs an address or port of its own",
436 raw.listen
437 )));
438 }
439 let (tls_cert, tls_key) = match raw.tls {
440 Some(own) => (own.cert, own.key),
441 None => tls.clone(),
442 };
443 let public_origin = origin("operator.public_origin", raw.public_origin)?;
444 if let (Some(own), Some(tenant)) = (&public_origin, tenant_origin)
447 && own.host() == tenant.host()
448 {
449 return Err(ConfigError(format!(
450 "operator.public_origin: {own} has the host of `public_origin` ({tenant}); a browser \
451 keeps a session cookie by host and not by port, so the operator listener needs a \
452 host name of its own"
453 )));
454 }
455 Ok(Some(Operator {
456 listen: raw.listen,
457 tls_cert,
458 tls_key,
459 public_origin,
460 }))
461}
462
463fn mcp_limits(raw: &RawMcp) -> Result<crate::mcp::Limits, ConfigError> {
465 let default = crate::mcp::Limits::DEFAULT;
466 let narrow = |key: &str, value: u64| {
467 u32::try_from(positive(key, value)?).map_err(|_| ConfigError(format!("{key} is too large")))
468 };
469 Ok(crate::mcp::Limits {
470 calls_per_second: match raw.calls_per_second {
471 None => default.calls_per_second,
472 Some(value) => narrow("mcp.calls_per_second", value)?,
473 },
474 concurrent: match raw.concurrent {
475 None => default.concurrent,
476 Some(value) => narrow("mcp.concurrent", value)?,
477 },
478 response_bytes: match raw.response_bytes {
479 None => default.response_bytes,
480 Some(value) => usize::try_from(positive("mcp.response_bytes", value)?)
481 .map_err(|_| ConfigError("mcp.response_bytes is too large".to_owned()))?,
482 },
483 })
484}
485
486pub const S3_TIMEOUT: Duration = Duration::from_secs(30);
488
489fn storage(raw: RawStorage) -> Result<Storage, ConfigError> {
493 let objects = match (raw.objects.as_deref(), raw.s3) {
494 (None | Some("local"), None) => ObjectStore::Local,
495 (None | Some("local"), Some(_)) => {
496 return Err(ConfigError(
497 "storage.s3 is set but storage.objects is not \"s3\"".to_owned(),
498 ));
499 }
500 (Some("s3"), None) => {
501 return Err(ConfigError(
502 "storage.objects is \"s3\" but there is no storage.s3 table".to_owned(),
503 ));
504 }
505 (Some("s3"), Some(s3)) => ObjectStore::S3(s3_settings(s3)?),
506 (Some(other), _) => {
507 return Err(ConfigError(format!(
508 "storage.objects: {other:?} is not \"local\" or \"s3\""
509 )));
510 }
511 };
512 let parquet = match (&objects, raw.parquet) {
513 (_, None) => None,
514 (ObjectStore::S3(_), Some(p)) => Some(ParquetSettings {
515 pack_interval: seconds(
516 "storage.parquet.pack_interval",
517 p.pack_interval,
518 PACK_INTERVAL,
519 )?,
520 pack_limit: match p.pack_limit {
521 None => PACK_LIMIT,
522 Some(limit) => positive("storage.parquet.pack_limit", limit)?,
523 },
524 reader_grace: seconds("storage.parquet.reader_grace", p.reader_grace, READER_GRACE)?,
525 }),
526 (ObjectStore::Local, Some(_)) => {
527 return Err(ConfigError(
528 "storage.parquet packs the objects of a bucket, so it needs \
529 storage.objects = \"s3\""
530 .to_owned(),
531 ));
532 }
533 };
534 Ok(Storage { objects, parquet })
535}
536
537pub const POSTGRES_PORT: u16 = 5432;
539
540pub const POSTGRES_POOL: u32 = 16;
542
543pub const POSTGRES_CONNECT_TIMEOUT: Duration = Duration::from_secs(5);
546
547pub const POSTGRES_STATEMENT_TIMEOUT: Duration = Duration::from_secs(30);
549
550pub const POSTGRES_LOCK_TIMEOUT: Duration = Duration::from_secs(10);
552
553pub const POSTGRES_TIMEOUT_LIMIT: u64 = i32::MAX as u64 / 1000;
556
557pub const POSTGRES_NAME_LIMIT: usize = 63;
560
561fn catalog(raw: RawCatalog, storage: &Storage) -> Result<CatalogStore, ConfigError> {
564 match (raw.backend.as_deref(), raw.postgres) {
565 (None | Some("local"), None) => Ok(CatalogStore::Local),
566 (None | Some("local"), Some(_)) => Err(ConfigError(
567 "catalog.postgres is set but catalog.backend is not \"postgres\"".to_owned(),
568 )),
569 (Some("postgres"), None) => Err(ConfigError(
570 "catalog.backend is \"postgres\" but there is no catalog.postgres table".to_owned(),
571 )),
572 (Some("postgres"), Some(pg)) => {
573 if !matches!(storage.objects, ObjectStore::S3(_)) {
578 return Err(ConfigError(
579 "catalog.backend = \"postgres\" needs storage.objects = \"s3\": a catalog \
580 in PostgreSQL names objects that every server must be able to read"
581 .to_owned(),
582 ));
583 }
584 postgres_settings(pg).map(|pg| CatalogStore::Postgres(Box::new(pg)))
585 }
586 (Some(other), _) => Err(ConfigError(format!(
587 "catalog.backend: {other:?} is not \"local\" or \"postgres\""
588 ))),
589 }
590}
591
592fn postgres_settings(raw: RawPostgres) -> Result<PostgresSettings, ConfigError> {
593 const KEY: &str = "catalog.postgres";
594 if raw.hosts.is_empty() {
595 return Err(ConfigError(format!(
596 "{KEY}.hosts is empty; name at least one server"
597 )));
598 }
599 let mut seen = BTreeSet::new();
600 for host in &raw.hosts {
601 check_host(host).map_err(|why| ConfigError(format!("{KEY}.hosts: {host:?} {why}")))?;
602 if !seen.insert(host.to_ascii_lowercase()) {
603 return Err(ConfigError(format!("{KEY}.hosts names {host:?} twice")));
604 }
605 }
606 let port = match raw.port {
607 None => POSTGRES_PORT,
608 Some(port) => u16::try_from(positive(&format!("{KEY}.port"), port)?).map_err(|_| {
609 ConfigError(format!("{KEY}.port {port} is not a TCP port (1 to 65535)"))
610 })?,
611 };
612 check_name("dbname", &raw.dbname)?;
613 check_name("user", &raw.user)?;
614 for (name, path) in [
615 ("ca_file", &raw.ca_file),
616 ("password_file", &raw.password_file),
617 ("client_cert_file", &raw.client_cert_file),
618 ("client_key_file", &raw.client_key_file),
619 ] {
620 if path.as_ref().is_some_and(|p| p.as_os_str().is_empty()) {
621 return Err(ConfigError(format!("{KEY}.{name} is empty")));
622 }
623 }
624 match (&raw.client_cert_file, &raw.client_key_file) {
625 (Some(_), None) => {
626 return Err(ConfigError(format!(
627 "{KEY}.client_cert_file is set without {KEY}.client_key_file"
628 )));
629 }
630 (None, Some(_)) => {
631 return Err(ConfigError(format!(
632 "{KEY}.client_key_file is set without {KEY}.client_cert_file"
633 )));
634 }
635 _ => {}
636 }
637 if raw.password_file.is_none() && raw.client_cert_file.is_none() {
638 return Err(ConfigError(format!(
639 "set {KEY}.password_file, {KEY}.client_cert_file, or both: a server that asks for \
640 neither is not accepted"
641 )));
642 }
643 let pool = match raw.pool {
644 None => POSTGRES_POOL,
645 Some(pool) => u32::try_from(positive(&format!("{KEY}.pool"), pool)?)
646 .map_err(|_| ConfigError(format!("{KEY}.pool is too large")))?,
647 };
648 let limited = |name: &str, value: Option<u64>, default: Duration| {
649 let key = format!("{KEY}.{name}");
650 let value = seconds(&key, value, default)?;
651 if value.as_secs() > POSTGRES_TIMEOUT_LIMIT {
652 return Err(ConfigError(format!(
653 "{key} is more than {POSTGRES_TIMEOUT_LIMIT} seconds, the longest PostgreSQL holds"
654 )));
655 }
656 Ok(value)
657 };
658 Ok(PostgresSettings {
659 hosts: raw.hosts,
660 port,
661 dbname: raw.dbname,
662 user: raw.user,
663 ca_file: raw.ca_file,
664 password_file: raw.password_file,
665 client_cert_file: raw.client_cert_file,
666 client_key_file: raw.client_key_file,
667 pool,
668 connect_timeout: seconds(
669 &format!("{KEY}.connect_timeout"),
670 raw.connect_timeout,
671 POSTGRES_CONNECT_TIMEOUT,
672 )?,
673 statement_timeout: limited(
674 "statement_timeout",
675 raw.statement_timeout,
676 POSTGRES_STATEMENT_TIMEOUT,
677 )?,
678 lock_timeout: limited("lock_timeout", raw.lock_timeout, POSTGRES_LOCK_TIMEOUT)?,
679 })
680}
681
682fn check_name(key: &str, name: &str) -> Result<(), ConfigError> {
685 let refused = |why: &str| Err(ConfigError(format!("catalog.postgres.{key} {why}")));
686 if name.is_empty() {
687 return refused("is empty");
688 }
689 if name.contains('\0') {
690 return refused("holds a NUL character, which PostgreSQL names cannot");
691 }
692 if name.len() > POSTGRES_NAME_LIMIT {
693 return refused(&format!(
694 "is {} bytes; PostgreSQL would cut it to {POSTGRES_NAME_LIMIT} bytes and name \
695 another database or role",
696 name.len()
697 ));
698 }
699 Ok(())
700}
701
702fn check_host(host: &str) -> Result<(), String> {
705 if host.parse::<std::net::IpAddr>().is_ok() {
706 return Ok(());
707 }
708 if host.starts_with('/') {
709 return Err(
710 "is a Unix socket, which carries no TLS; the catalog is reached over TCP \
711 with TLS only"
712 .to_owned(),
713 );
714 }
715 if let Some(bare) = host.strip_prefix('[').and_then(|h| h.strip_suffix(']'))
716 && bare.parse::<std::net::Ipv6Addr>().is_ok()
717 {
718 return Err(format!(
719 "is written in brackets; write the address as {bare:?}"
720 ));
721 }
722 if host.is_empty() {
723 return Err("is empty".to_owned());
724 }
725 if !host.is_ascii() {
726 return Err("is not ASCII; write an internationalized name in its xn-- form".to_owned());
727 }
728 if host.contains(':') {
729 return Err(
730 "holds a colon; give the port in catalog.postgres.port, which every host uses"
731 .to_owned(),
732 );
733 }
734 if host.len() > 253 {
735 return Err("is longer than 253 characters, the longest DNS name".to_owned());
736 }
737 let good_label = |label: &str| {
738 (1..=63).contains(&label.len())
739 && !label.starts_with('-')
740 && !label.ends_with('-')
741 && label
742 .bytes()
743 .all(|b| b.is_ascii_alphanumeric() || b == b'-')
744 };
745 if !host.split('.').all(good_label) {
746 return Err(
747 "is not a DNS name: labels of 1 to 63 letters, digits and hyphens, joined by dots"
748 .to_owned(),
749 );
750 }
751 Ok(())
752}
753
754fn export_s3(raw: RawExportS3) -> Result<ExportS3, ConfigError> {
756 check_service(
757 "export.s3",
758 raw.endpoint.as_deref(),
759 raw.allow_http,
760 raw.ca_file.is_some(),
761 raw.access_key_id.is_some(),
762 raw.secret_access_key_file.is_some(),
763 )?;
764 Ok(ExportS3 {
765 endpoint: raw.endpoint,
766 region: raw.region,
767 path_style: raw.path_style,
768 access_key_id: raw.access_key_id,
769 secret_access_key_file: raw.secret_access_key_file,
770 allow_http: raw.allow_http,
771 ca_file: raw.ca_file,
772 timeout: seconds("export.s3.timeout", raw.timeout, S3_TIMEOUT)?,
773 })
774}
775
776fn check_service(
781 table: &str,
782 endpoint: Option<&str>,
783 allow_http: bool,
784 ca_file: bool,
785 access_key_id: bool,
786 secret_access_key_file: bool,
787) -> Result<(), ConfigError> {
788 if let Some(endpoint) = endpoint {
789 if endpoint.starts_with("http://") {
790 if ca_file {
791 return Err(ConfigError(format!(
792 "{table}.ca_file is set, but {table}.endpoint {endpoint:?} is plain \
793 HTTP, which uses no certificate"
794 )));
795 }
796 if !allow_http {
797 return Err(ConfigError(format!(
798 "{table}.endpoint {endpoint:?} is plain HTTP; set {table}.allow_http = \
799 true only for a test service on this host"
800 )));
801 }
802 } else if !endpoint.starts_with("https://") {
803 return Err(ConfigError(format!(
804 "{table}.endpoint {endpoint:?} is not an https:// URL"
805 )));
806 }
807 }
808 match (access_key_id, secret_access_key_file) {
809 (true, false) => Err(ConfigError(format!(
810 "{table}.access_key_id is set without {table}.secret_access_key_file"
811 ))),
812 (false, true) => Err(ConfigError(format!(
813 "{table}.secret_access_key_file is set without {table}.access_key_id"
814 ))),
815 _ => Ok(()),
816 }
817}
818
819fn s3_settings(raw: RawS3) -> Result<S3Settings, ConfigError> {
820 if raw.bucket.is_empty() {
821 return Err(ConfigError("storage.s3.bucket is empty".to_owned()));
822 }
823 if !raw.prefix.is_empty() && (raw.prefix.starts_with('/') || !raw.prefix.ends_with('/')) {
824 return Err(ConfigError(format!(
825 "storage.s3.prefix {:?} must not start with / and must end with /, \
826 such as \"server-a/\"",
827 raw.prefix
828 )));
829 }
830 check_service(
831 "storage.s3",
832 raw.endpoint.as_deref(),
833 raw.allow_http,
834 raw.ca_file.is_some(),
835 raw.access_key_id.is_some(),
836 raw.secret_access_key_file.is_some(),
837 )?;
838 Ok(S3Settings {
839 endpoint: raw.endpoint,
840 region: raw.region,
841 bucket: raw.bucket,
842 prefix: raw.prefix,
843 path_style: raw.path_style,
844 access_key_id: raw.access_key_id,
845 secret_access_key_file: raw.secret_access_key_file,
846 allow_http: raw.allow_http,
847 ca_file: raw.ca_file,
848 allow_versioning: raw.allow_versioning,
849 timeout: seconds("storage.s3.timeout", raw.timeout, S3_TIMEOUT)?,
850 })
851}
852
853fn positive(key: &str, value: u64) -> Result<u64, ConfigError> {
854 if value == 0 {
855 return Err(ConfigError(format!("{key} must be more than 0")));
856 }
857 Ok(value)
858}
859
860pub const CONNECTION_LIMIT_MAX: u64 = 3600;
864
865pub const CSP_REPORTS_MAX: u64 = 6000;
869
870fn report_limits(limits: &RawLimits) -> Result<crate::api::ReportLimits, ConfigError> {
876 let default = crate::api::ReportLimits::DEFAULT;
877 let read = |key: &str, value: Option<u64>, default: u32| -> Result<u32, ConfigError> {
878 let Some(value) = value else {
879 return Ok(default);
880 };
881 let value = positive(key, value)?;
882 u32::try_from(value)
883 .ok()
884 .filter(|_| value <= CSP_REPORTS_MAX)
885 .ok_or_else(|| {
886 ConfigError(format!(
887 "{key} must be at most {CSP_REPORTS_MAX}, and is {value}"
888 ))
889 })
890 };
891 let per_minute = read("limits.csp_reports", limits.csp_reports, default.per_minute)?;
892 let per_address = read(
895 "limits.csp_reports_per_address",
896 limits.csp_reports_per_address,
897 default.per_address.min(per_minute),
898 )?;
899 if per_address > per_minute {
900 return Err(ConfigError(format!(
901 "limits.csp_reports_per_address ({per_address}) must be at most limits.csp_reports ({per_minute})"
902 )));
903 }
904 Ok(crate::api::ReportLimits {
905 per_minute,
906 per_address,
907 })
908}
909
910pub const CONNECTIONS_MAX: u64 = 65_536;
913
914fn connections(value: Option<u64>, default: usize) -> Result<usize, ConfigError> {
917 let Some(value) = value else {
918 return Ok(default);
919 };
920 let value = positive("limits.connections", value)?;
921 usize::try_from(value)
922 .ok()
923 .filter(|_| value <= CONNECTIONS_MAX)
924 .ok_or_else(|| {
925 ConfigError(format!(
926 "limits.connections must be at most {CONNECTIONS_MAX}, and is {value}"
927 ))
928 })
929}
930
931fn connection_limits(limits: &RawLimits) -> Result<ConnectionLimits, ConfigError> {
934 let raw = &limits.timeouts;
935 let default = ConnectionLimits::default();
936 let limit = |key: &str, value: Option<u64>, default: Duration| {
937 let limit = seconds(key, value, default)?;
938 if limit.as_secs() > CONNECTION_LIMIT_MAX {
939 return Err(ConfigError(format!(
940 "{key} must be at most {CONNECTION_LIMIT_MAX} seconds, and is {}",
941 limit.as_secs()
942 )));
943 }
944 Ok(limit)
945 };
946 Ok(ConnectionLimits {
947 handshake: limit(
948 "limits.timeouts.handshake",
949 raw.handshake,
950 default.handshake,
951 )?,
952 first_head: limit(
953 "limits.timeouts.first_head",
954 raw.first_head,
955 default.first_head,
956 )?,
957 head: limit("limits.timeouts.head", raw.head, default.head)?,
958 idle: limit("limits.timeouts.idle", raw.idle, default.idle)?,
959 goodbye: default.goodbye,
960 accept_pause: default.accept_pause,
961 max: connections(limits.connections, default.max)?,
962 })
963}
964
965fn seconds(key: &str, value: Option<u64>, default: Duration) -> Result<Duration, ConfigError> {
967 match value {
968 None => Ok(default),
969 Some(value) => positive(key, value).map(Duration::from_secs),
970 }
971}
972
973#[derive(Deserialize)]
975#[serde(deny_unknown_fields)]
976struct Raw {
977 listen: SocketAddr,
978 tls: RawTls,
979 data_dir: PathBuf,
980 master_key: PathBuf,
981 retention_default: Option<String>,
982 purge_interval: Option<u64>,
983 rotation_warn: Option<u64>,
984 #[serde(default)]
985 limits: RawLimits,
986 #[serde(default)]
987 supported_critical: Vec<String>,
988 #[serde(default)]
989 mcp: RawMcp,
990 #[serde(default)]
991 storage: RawStorage,
992 #[serde(default)]
993 export: RawExport,
994 #[serde(default)]
995 catalog: RawCatalog,
996 operator: Option<RawOperator>,
997 public_origin: Option<String>,
998 #[serde(default)]
999 keys: RawKeys,
1000}
1001
1002#[derive(Default, Deserialize)]
1004#[serde(deny_unknown_fields)]
1005struct RawKeys {
1006 no_expiry: Option<bool>,
1007}
1008
1009#[derive(Deserialize)]
1010#[serde(deny_unknown_fields)]
1011struct RawOperator {
1012 listen: SocketAddr,
1013 tls: Option<RawTls>,
1014 public_origin: Option<String>,
1015}
1016
1017#[derive(Default, Deserialize)]
1018#[serde(deny_unknown_fields)]
1019struct RawCatalog {
1020 backend: Option<String>,
1021 postgres: Option<RawPostgres>,
1022}
1023
1024#[derive(Deserialize)]
1025#[serde(deny_unknown_fields)]
1026struct RawPostgres {
1027 hosts: Vec<String>,
1028 port: Option<u64>,
1029 dbname: String,
1030 user: String,
1031 ca_file: Option<PathBuf>,
1032 password_file: Option<PathBuf>,
1033 client_cert_file: Option<PathBuf>,
1034 client_key_file: Option<PathBuf>,
1035 pool: Option<u64>,
1036 connect_timeout: Option<u64>,
1037 statement_timeout: Option<u64>,
1038 lock_timeout: Option<u64>,
1039}
1040
1041#[derive(Default, Deserialize)]
1042#[serde(deny_unknown_fields)]
1043struct RawExport {
1044 s3: Option<RawExportS3>,
1045}
1046
1047#[derive(Deserialize)]
1048#[serde(deny_unknown_fields)]
1049struct RawExportS3 {
1050 endpoint: Option<String>,
1051 region: String,
1052 #[serde(default)]
1053 path_style: bool,
1054 access_key_id: Option<String>,
1055 secret_access_key_file: Option<PathBuf>,
1056 #[serde(default)]
1057 allow_http: bool,
1058 ca_file: Option<PathBuf>,
1059 timeout: Option<u64>,
1060}
1061
1062#[derive(Default, Deserialize)]
1063#[serde(deny_unknown_fields)]
1064struct RawStorage {
1065 objects: Option<String>,
1066 s3: Option<RawS3>,
1067 parquet: Option<RawParquet>,
1068}
1069
1070#[derive(Deserialize)]
1071#[serde(deny_unknown_fields)]
1072struct RawParquet {
1073 pack_interval: Option<u64>,
1074 pack_limit: Option<u64>,
1075 reader_grace: Option<u64>,
1076}
1077
1078#[derive(Deserialize)]
1079#[serde(deny_unknown_fields)]
1080struct RawS3 {
1081 endpoint: Option<String>,
1082 region: String,
1083 bucket: String,
1084 #[serde(default)]
1085 prefix: String,
1086 #[serde(default)]
1087 path_style: bool,
1088 access_key_id: Option<String>,
1089 secret_access_key_file: Option<PathBuf>,
1090 #[serde(default)]
1091 allow_http: bool,
1092 ca_file: Option<PathBuf>,
1093 #[serde(default)]
1094 allow_versioning: bool,
1095 timeout: Option<u64>,
1096}
1097
1098#[derive(Default, Deserialize)]
1099#[serde(deny_unknown_fields)]
1100struct RawMcp {
1101 calls_per_second: Option<u64>,
1102 concurrent: Option<u64>,
1103 response_bytes: Option<u64>,
1104}
1105
1106#[derive(Deserialize)]
1107#[serde(deny_unknown_fields)]
1108struct RawTls {
1109 cert: PathBuf,
1110 key: PathBuf,
1111}
1112
1113#[derive(Default, Deserialize)]
1114#[serde(deny_unknown_fields)]
1115struct RawLimits {
1116 body: Option<u64>,
1117 inflated: Option<u64>,
1118 connections: Option<u64>,
1119 csp_reports: Option<u64>,
1120 csp_reports_per_address: Option<u64>,
1121 #[serde(default)]
1122 timeouts: RawTimeouts,
1123}
1124
1125#[derive(Default, Deserialize)]
1126#[serde(deny_unknown_fields)]
1127struct RawTimeouts {
1128 read: Option<u64>,
1129 handshake: Option<u64>,
1130 first_head: Option<u64>,
1131 head: Option<u64>,
1132 idle: Option<u64>,
1133}
1134
1135#[cfg(test)]
1136mod tests {
1137 use super::*;
1138
1139 const FULL: &str = r#"
1140listen = "127.0.0.1:8443"
1141data_dir = "/var/lib/vcon-server"
1142master_key = "/etc/vcon-server/master.key"
1143retention_default = "18m"
1144purge_interval = 1800
1145rotation_warn = 604800
1146supported_critical = ["known", "other"]
1147public_origin = "https://vcon.example.com"
1148
1149[tls]
1150cert = "/etc/vcon-server/cert.pem"
1151key = "/etc/vcon-server/key.pem"
1152
1153[operator]
1154listen = "127.0.0.1:8444"
1155public_origin = "https://ops.example.com:8444"
1156
1157[operator.tls]
1158cert = "/etc/vcon-server/operator-cert.pem"
1159key = "/etc/vcon-server/operator-key.pem"
1160
1161[keys]
1162no_expiry = false
1163
1164[limits]
1165body = 10485760
1166inflated = 104857600
1167connections = 64
1168csp_reports = 300
1169csp_reports_per_address = 30
1170
1171[limits.timeouts]
1172read = 30
1173handshake = 5
1174first_head = 15
1175head = 20
1176idle = 90
1177
1178[mcp]
1179calls_per_second = 20
1180concurrent = 8
1181response_bytes = 262144
1182
1183[storage]
1184objects = "s3"
1185
1186[storage.s3]
1187endpoint = "https://objects.example.com:9000"
1188region = "eu-west-1"
1189bucket = "vcon"
1190prefix = "server-a/"
1191path_style = true
1192access_key_id = "vcon-server"
1193secret_access_key_file = "/etc/vcon-server/s3.secret"
1194allow_http = true
1195ca_file = "/etc/vcon-server/s3-ca.pem"
1196allow_versioning = true
1197timeout = 60
1198
1199[storage.parquet]
1200pack_interval = 600
1201pack_limit = 8388608
1202reader_grace = 1800
1203
1204[export.s3]
1205endpoint = "https://analytics.example.com"
1206region = "eu-west-2"
1207path_style = true
1208access_key_id = "vcon-export"
1209secret_access_key_file = "/etc/vcon-server/export.secret"
1210allow_http = true
1211ca_file = "/etc/vcon-server/export-ca.pem"
1212timeout = 120
1213
1214[catalog]
1215backend = "postgres"
1216
1217[catalog.postgres]
1218hosts = ["db1.example.com", "192.0.2.10", "2001:db8::10"]
1219port = 6432
1220dbname = "vcon"
1221user = "vcon_app"
1222ca_file = "/etc/vcon-server/pg-ca.pem"
1223password_file = "/etc/vcon-server/postgres.password"
1224client_cert_file = "/etc/vcon-server/pg-client.pem"
1225client_key_file = "/etc/vcon-server/pg-client.key"
1226pool = 8
1227connect_timeout = 10
1228statement_timeout = 60
1229lock_timeout = 20
1230"#;
1231
1232 #[test]
1233 fn a_full_configuration_is_read() {
1234 assert_eq!(
1235 parse(FULL),
1236 Ok(Config {
1237 listen: "127.0.0.1:8443".parse().expect("address"),
1238 tls_cert: "/etc/vcon-server/cert.pem".into(),
1239 tls_key: "/etc/vcon-server/key.pem".into(),
1240 data_dir: "/var/lib/vcon-server".into(),
1241 master_key: "/etc/vcon-server/master.key".into(),
1242 retention_default: Retention::Months(18),
1243 purge_interval: Duration::from_secs(1800),
1244 rotation_warn: Duration::from_secs(604_800),
1245 body_limit: 10_485_760,
1246 inflated_limit: 104_857_600,
1247 read_timeout: Duration::from_secs(30),
1248 connection: ConnectionLimits {
1249 handshake: Duration::from_secs(5),
1250 first_head: Duration::from_secs(15),
1251 head: Duration::from_secs(20),
1252 idle: Duration::from_secs(90),
1253 goodbye: Duration::from_secs(5),
1254 accept_pause: Duration::from_secs(1),
1255 max: 64,
1256 },
1257 supported_critical: ["known", "other"].map(String::from).into(),
1258 mcp: crate::mcp::Limits {
1259 calls_per_second: 20,
1260 concurrent: 8,
1261 response_bytes: 262_144,
1262 },
1263 reports: crate::api::ReportLimits {
1264 per_minute: 300,
1265 per_address: 30,
1266 },
1267 storage: Storage {
1268 objects: ObjectStore::S3(S3Settings {
1269 endpoint: Some("https://objects.example.com:9000".to_owned()),
1270 region: "eu-west-1".to_owned(),
1271 bucket: "vcon".to_owned(),
1272 prefix: "server-a/".to_owned(),
1273 path_style: true,
1274 access_key_id: Some("vcon-server".to_owned()),
1275 secret_access_key_file: Some("/etc/vcon-server/s3.secret".into()),
1276 allow_http: true,
1277 ca_file: Some("/etc/vcon-server/s3-ca.pem".into()),
1278 allow_versioning: true,
1279 timeout: Duration::from_secs(60),
1280 }),
1281 parquet: Some(ParquetSettings {
1282 pack_interval: Duration::from_secs(600),
1283 pack_limit: 8_388_608,
1284 reader_grace: Duration::from_secs(1800),
1285 }),
1286 },
1287 export: Export {
1288 s3: Some(ExportS3 {
1289 endpoint: Some("https://analytics.example.com".to_owned()),
1290 region: "eu-west-2".to_owned(),
1291 path_style: true,
1292 access_key_id: Some("vcon-export".to_owned()),
1293 secret_access_key_file: Some("/etc/vcon-server/export.secret".into()),
1294 allow_http: true,
1295 ca_file: Some("/etc/vcon-server/export-ca.pem".into()),
1296 timeout: Duration::from_secs(120),
1297 }),
1298 },
1299 catalog: CatalogStore::Postgres(Box::new(PostgresSettings {
1300 hosts: ["db1.example.com", "192.0.2.10", "2001:db8::10"]
1301 .map(String::from)
1302 .into(),
1303 port: 6432,
1304 dbname: "vcon".to_owned(),
1305 user: "vcon_app".to_owned(),
1306 ca_file: Some("/etc/vcon-server/pg-ca.pem".into()),
1307 password_file: Some("/etc/vcon-server/postgres.password".into()),
1308 client_cert_file: Some("/etc/vcon-server/pg-client.pem".into()),
1309 client_key_file: Some("/etc/vcon-server/pg-client.key".into()),
1310 pool: 8,
1311 connect_timeout: Duration::from_secs(10),
1312 statement_timeout: Duration::from_secs(60),
1313 lock_timeout: Duration::from_secs(20),
1314 })),
1315 operator: Some(Operator {
1316 listen: "127.0.0.1:8444".parse().expect("address"),
1317 tls_cert: "/etc/vcon-server/operator-cert.pem".into(),
1318 tls_key: "/etc/vcon-server/operator-key.pem".into(),
1319 public_origin: Origin::parse("https://ops.example.com:8444"),
1320 }),
1321 public_origin: Origin::parse("https://vcon.example.com"),
1322 keys_no_expiry: false,
1323 }),
1324 "every key the file writes is read into its field"
1325 );
1326 }
1327
1328 mod operator_listener {
1329 use super::*;
1330
1331 fn with(table: &str) -> String {
1333 format!("{LEAST}\n{table}")
1334 }
1335
1336 fn address(text: &str) -> SocketAddr {
1337 text.parse().expect("an address")
1338 }
1339
1340 #[test]
1341 fn without_the_table_there_is_no_operator_listener() {
1342 assert_eq!(
1343 parse(LEAST).expect("parses").operator,
1344 None,
1345 "one listener, as before the table existed"
1346 );
1347 }
1348
1349 #[test]
1350 fn the_table_with_its_address_alone_takes_the_servers_certificate_and_key() {
1351 let config = parse(&with("[operator]\nlisten = \"127.0.0.1:8444\"\n")).expect("parses");
1352 assert_eq!(
1353 config.operator,
1354 Some(Operator {
1355 listen: address("127.0.0.1:8444"),
1356 tls_cert: "/etc/vcon-server/cert.pem".into(),
1357 tls_key: "/etc/vcon-server/key.pem".into(),
1358 public_origin: None,
1359 }),
1360 "tls.cert and tls.key serve both listeners"
1361 );
1362 }
1363
1364 #[test]
1365 fn the_table_may_name_a_certificate_and_key_of_its_own() {
1366 let config = parse(&with(
1367 "[operator]\nlisten = \"127.0.0.1:8444\"\n\n[operator.tls]\n\
1368 cert = \"/etc/vcon-server/ops.pem\"\nkey = \"/etc/vcon-server/ops.key\"\n",
1369 ))
1370 .expect("parses");
1371 assert_eq!(
1372 config.operator,
1373 Some(Operator {
1374 listen: address("127.0.0.1:8444"),
1375 tls_cert: "/etc/vcon-server/ops.pem".into(),
1376 tls_key: "/etc/vcon-server/ops.key".into(),
1377 public_origin: None,
1378 }),
1379 "the operator listener's own pair"
1380 );
1381 assert_eq!(
1382 config.tls_cert,
1383 PathBuf::from("/etc/vcon-server/cert.pem"),
1384 "the tenant listener keeps its own"
1385 );
1386 }
1387
1388 #[test]
1389 fn the_table_leaves_every_other_key_as_it_was() {
1390 let without = parse(LEAST).expect("parses");
1391 let with = parse(&with("[operator]\nlisten = \"127.0.0.1:8444\"\n")).expect("parses");
1392 assert_eq!(
1393 Config {
1394 operator: None,
1395 ..with
1396 },
1397 without,
1398 "only the operator member differs"
1399 );
1400 }
1401
1402 #[test]
1403 fn the_operator_listener_may_be_on_any_address_the_operator_chooses() {
1404 for listen in [
1405 "127.0.0.1:8444",
1406 "[::1]:8444",
1407 "192.0.2.10:8444",
1408 "[2001:db8::10]:8444",
1409 "0.0.0.0:8444",
1410 "127.0.0.1:0",
1411 ] {
1412 let config =
1413 parse(&with(&format!("[operator]\nlisten = \"{listen}\"\n"))).expect(listen);
1414 assert_eq!(
1415 config.operator.expect("an operator listener").listen,
1416 address(listen),
1417 "{listen}"
1418 );
1419 }
1420 }
1421
1422 #[test]
1423 fn the_same_port_on_another_address_is_another_socket() {
1424 for (tenant, operator) in [
1425 ("192.0.2.10:8443", "127.0.0.1:8443"),
1426 ("127.0.0.1:8443", "[::1]:8443"),
1427 ("0.0.0.0:8443", "[::1]:8443"),
1428 ] {
1429 let text = with(&format!("[operator]\nlisten = \"{operator}\"\n")).replace(
1430 "127.0.0.1:8443\"\ndata_dir",
1431 &format!("{tenant}\"\ndata_dir"),
1432 );
1433 assert!(
1434 parse(&text).is_ok(),
1435 "{tenant} and {operator}: {:?}",
1436 parse(&text)
1437 );
1438 }
1439 }
1440
1441 #[test]
1442 fn port_zero_twice_is_two_sockets() {
1443 let text = with("[operator]\nlisten = \"127.0.0.1:0\"\n")
1444 .replace("127.0.0.1:8443", "127.0.0.1:0");
1445 let config = parse(&text).expect("parses");
1446 assert_eq!(config.listen, address("127.0.0.1:0"), "the tenant listener");
1447 assert_eq!(
1448 config.operator.expect("an operator listener").listen,
1449 address("127.0.0.1:0"),
1450 "the operator listener"
1451 );
1452 }
1453
1454 #[test]
1455 fn the_table_without_its_address_is_refused_by_name() {
1456 for table in [
1457 "[operator]\n",
1458 "[operator.tls]\ncert = \"a.pem\"\nkey = \"a.key\"\n",
1459 ] {
1460 let error = parse(&with(table)).expect_err("no address");
1461 assert!(error.0.contains("`listen`"), "{table}: {error}");
1462 }
1463 }
1464
1465 #[test]
1466 fn the_tenant_listeners_own_socket_is_refused() {
1467 let error =
1468 parse(&with("[operator]\nlisten = \"127.0.0.1:8443\"\n")).expect_err("one socket");
1469 assert_eq!(
1470 error.0,
1471 "operator.listen: 127.0.0.1:8443 is the socket `listen` takes (127.0.0.1:8443); \
1472 the operator listener needs an address or port of its own",
1473 "the refusal names both keys and both addresses"
1474 );
1475 }
1476
1477 #[test]
1478 fn a_socket_the_tenant_listener_covers_is_refused() {
1479 for (tenant, operator) in [
1480 ("0.0.0.0:8443", "127.0.0.1:8443"),
1481 ("127.0.0.1:8443", "0.0.0.0:8443"),
1482 ("[::]:8443", "[::1]:8443"),
1483 ("[2001:db8::10]:8443", "[::]:8443"),
1484 ] {
1485 let text = with(&format!("[operator]\nlisten = \"{operator}\"\n")).replace(
1486 "127.0.0.1:8443\"\ndata_dir",
1487 &format!("{tenant}\"\ndata_dir"),
1488 );
1489 let error = parse(&text).expect_err("one socket");
1490 assert!(
1491 error.0.starts_with("operator.listen: "),
1492 "{tenant} and {operator}: {error}"
1493 );
1494 }
1495 }
1496
1497 #[test]
1498 fn an_address_that_is_not_one_is_refused_by_name() {
1499 for listen in ["localhost:8444", "127.0.0.1", "8444", "", "127.0.0.1:99999"] {
1500 let error = parse(&with(&format!("[operator]\nlisten = \"{listen}\"\n")))
1501 .expect_err(listen);
1502 assert!(error.0.contains("listen"), "{listen}: {error}");
1503 }
1504 }
1505
1506 #[test]
1507 fn an_address_of_the_wrong_type_is_refused() {
1508 for value in ["8444", "true", "[\"127.0.0.1:8444\"]"] {
1509 let error =
1510 parse(&with(&format!("[operator]\nlisten = {value}\n"))).expect_err(value);
1511 assert!(error.0.contains("listen"), "{value}: {error}");
1512 }
1513 }
1514
1515 #[test]
1516 fn an_unknown_key_in_the_table_is_refused_by_name() {
1517 for (table, key) in [
1518 (
1519 "[operator]\nlisten = \"127.0.0.1:8444\"\nport = 8444\n",
1520 "port",
1521 ),
1522 (
1523 "[operator]\nlisten = \"127.0.0.1:8444\"\n[operator.tls]\ncert = \"a\"\nkey = \"b\"\nca = \"c\"\n",
1524 "ca",
1525 ),
1526 (
1527 "[operator]\nlisten = \"127.0.0.1:8444\"\n[operator.limits]\nbody = 1\n",
1528 "limits",
1529 ),
1530 ] {
1531 let error = parse(&with(table)).expect_err(key);
1532 assert!(error.0.contains(&format!("`{key}`")), "{key}: {error}");
1533 }
1534 }
1535
1536 #[test]
1537 fn half_a_certificate_and_key_pair_is_refused_by_the_missing_half() {
1538 for (given, missing) in [("cert", "key"), ("key", "cert")] {
1539 let table = format!(
1540 "[operator]\nlisten = \"127.0.0.1:8444\"\n[operator.tls]\n{given} = \"a.pem\"\n"
1541 );
1542 let error = parse(&with(&table)).expect_err(missing);
1543 assert!(
1544 error.0.contains(&format!("`{missing}`")),
1545 "{given} alone: {error}"
1546 );
1547 }
1548 }
1549
1550 #[test]
1551 fn the_table_written_twice_is_refused() {
1552 let table = "[operator]\nlisten = \"127.0.0.1:8444\"\n[operator]\nlisten = \"127.0.0.1:8445\"\n";
1553 assert!(parse(&with(table)).is_err(), "TOML takes a table once");
1554 }
1555
1556 #[test]
1557 fn operator_as_a_value_and_not_a_table_is_refused() {
1558 let text = format!("operator = \"127.0.0.1:8444\"\n{LEAST}");
1559 let error = parse(&text).expect_err("not a table");
1560 assert!(error.0.contains("operator"), "{error}");
1561 }
1562
1563 #[test]
1564 fn two_addresses_are_one_socket_only_on_one_port_and_one_address() {
1565 let same = [
1566 ("127.0.0.1:8443", "127.0.0.1:8443"),
1567 ("0.0.0.0:8443", "127.0.0.1:8443"),
1568 ("192.0.2.10:8443", "0.0.0.0:8443"),
1569 ("[::]:8443", "[2001:db8::10]:8443"),
1570 ("[::1]:8443", "[::1]:8443"),
1571 ("0.0.0.0:8443", "0.0.0.0:8443"),
1572 ];
1573 for (a, b) in same {
1574 assert!(same_socket(address(a), address(b)), "{a} and {b}");
1575 assert!(same_socket(address(b), address(a)), "{b} and {a}");
1576 }
1577 let different = [
1578 ("127.0.0.1:8443", "127.0.0.1:8444"),
1579 ("127.0.0.1:8443", "192.0.2.10:8443"),
1580 ("0.0.0.0:8443", "0.0.0.0:8444"),
1581 ("127.0.0.1:8443", "[::1]:8443"),
1582 ("0.0.0.0:8443", "[::1]:8443"),
1583 ("127.0.0.1:0", "127.0.0.1:0"),
1584 ("0.0.0.0:0", "127.0.0.1:0"),
1585 ];
1586 for (a, b) in different {
1587 assert!(!same_socket(address(a), address(b)), "{a} and {b}");
1588 assert!(!same_socket(address(b), address(a)), "{b} and {a}");
1589 }
1590 }
1591 }
1592
1593 mod key_expiry {
1595 use super::*;
1596
1597 fn with(table: &str) -> Result<Config, ConfigError> {
1598 parse(&format!("{LEAST}\n{table}"))
1599 }
1600
1601 #[test]
1602 fn without_the_key_a_key_may_be_made_with_no_expiry() {
1603 assert!(
1604 parse(LEAST).expect("parses").keys_no_expiry,
1605 "the default allows it"
1606 );
1607 }
1608
1609 #[test]
1610 fn the_key_is_read_as_written() {
1611 for (text, want) in [("true", true), ("false", false)] {
1612 let config = with(&format!("[keys]\nno_expiry = {text}\n")).expect("parses");
1613 assert_eq!(config.keys_no_expiry, want, "no_expiry = {text}");
1614 }
1615 }
1616
1617 #[test]
1618 fn an_empty_table_leaves_the_default() {
1619 assert!(
1620 with("[keys]\n").expect("parses").keys_no_expiry,
1621 "a table with no key"
1622 );
1623 }
1624
1625 #[test]
1626 fn a_value_that_is_not_a_boolean_is_refused() {
1627 for text in ["\"false\"", "0", "1", "[]", "90"] {
1628 let error = with(&format!("[keys]\nno_expiry = {text}\n")).expect_err(text);
1629 assert!(error.0.contains("no_expiry"), "{text}: {error}");
1630 }
1631 }
1632
1633 #[test]
1634 fn another_key_in_the_table_is_refused() {
1635 let error = with("[keys]\ndefault_days = 30\n").expect_err("an unknown key");
1636 assert!(error.0.contains("default_days"), "{error}");
1637 }
1638
1639 #[test]
1640 fn the_key_outside_its_table_is_refused() {
1641 let error = parse(&format!("no_expiry = false\n{LEAST}")).expect_err("the wrong place");
1642 assert!(error.0.contains("no_expiry"), "{error}");
1643 }
1644 }
1645
1646 mod public_origins {
1647 use super::*;
1648 use crate::session::Origin;
1649
1650 const OPERATOR: &str = "[operator]\nlisten = \"127.0.0.1:8444\"\n";
1651
1652 fn with(tenant: Option<&str>, operator: &str) -> Result<Config, ConfigError> {
1655 let first = tenant.map_or_else(String::new, |o| format!("public_origin = {o}\n"));
1656 parse(&format!("{first}{LEAST}\n{OPERATOR}{operator}"))
1657 }
1658
1659 fn origin(text: &str) -> Option<Origin> {
1660 Some(Origin::parse(text).expect("an origin"))
1661 }
1662
1663 fn operators(config: &Config) -> Option<Origin> {
1664 config
1665 .operator
1666 .as_ref()
1667 .expect("an operator listener")
1668 .public_origin
1669 .clone()
1670 }
1671
1672 #[test]
1675 fn without_the_keys_no_listener_has_a_public_origin() {
1676 let config = with(None, "").expect("parses");
1677 assert_eq!(config.public_origin, None, "sessions are off on `listen`");
1678 assert_eq!(operators(&config), None, "and on `operator.listen`");
1679 assert_eq!(
1680 parse(LEAST).expect("parses").public_origin,
1681 None,
1682 "the least"
1683 );
1684 }
1685
1686 #[test]
1687 fn public_origin_is_the_tenant_listener_s() {
1688 let config = with(Some("\"https://vcon.example.com\""), "").expect("parses");
1689 assert_eq!(
1690 config.public_origin,
1691 origin("https://vcon.example.com"),
1692 "the tenant listener's"
1693 );
1694 assert_eq!(operators(&config), None, "the operator listener has none");
1695 }
1696
1697 #[test]
1698 fn operator_public_origin_is_the_operator_listener_s() {
1699 let config = with(
1700 Some("\"https://vcon.example.com\""),
1701 "public_origin = \"https://ops.example.com:8444\"\n",
1702 )
1703 .expect("parses");
1704 assert_eq!(
1705 config.public_origin,
1706 origin("https://vcon.example.com"),
1707 "the tenant listener's"
1708 );
1709 assert_eq!(
1710 operators(&config),
1711 origin("https://ops.example.com:8444"),
1712 "the operator listener's"
1713 );
1714 }
1715
1716 #[test]
1717 fn a_server_with_one_listener_takes_public_origin_alone() {
1718 let text = format!("public_origin = \"https://vcon.example.com:8443\"\n{LEAST}");
1719 let config = parse(&text).expect("parses");
1720 assert_eq!(
1721 config.public_origin,
1722 origin("https://vcon.example.com:8443"),
1723 "the one listener's"
1724 );
1725 assert_eq!(config.operator, None, "no operator listener");
1726 }
1727
1728 #[test]
1731 fn a_public_origin_that_is_not_https_and_a_host_is_refused_by_its_key() {
1732 for bad in [
1733 "http://vcon.example.com",
1734 "https://vcon.example.com/",
1735 "https://vcon.example.com/console",
1736 "vcon.example.com",
1737 "https://Vcon.example.com",
1738 "",
1739 ] {
1740 let error = with(Some(&format!("{bad:?}")), "").expect_err(bad);
1741 assert!(
1742 error.0.starts_with("public_origin: ") && error.0.contains(bad),
1743 "{error}"
1744 );
1745 }
1746 }
1747
1748 #[test]
1749 fn an_operator_public_origin_that_is_not_an_origin_is_refused_by_its_key() {
1750 let error = with(None, "public_origin = \"https://ops.example.com/admin\"\n")
1751 .expect_err("a path");
1752 assert!(
1753 error.0.starts_with("operator.public_origin: "),
1754 "the key is named: {error}"
1755 );
1756 }
1757
1758 #[test]
1759 fn two_public_origins_on_one_host_are_refused_whatever_their_ports() {
1760 for (tenant, operator) in [
1761 ("https://vcon.example.com", "https://vcon.example.com"),
1762 ("https://vcon.example.com", "https://vcon.example.com:8444"),
1763 (
1764 "https://vcon.example.com:8443",
1765 "https://vcon.example.com:8444",
1766 ),
1767 ("https://[2001:db8::7]:8443", "https://[2001:db8::7]:8444"),
1768 ] {
1769 let error = with(
1770 Some(&format!("{tenant:?}")),
1771 &format!("public_origin = {operator:?}\n"),
1772 )
1773 .expect_err("one host");
1774 assert!(
1775 error.0.starts_with("operator.public_origin: ") && error.0.contains("host"),
1776 "{tenant} and {operator}: {error}"
1777 );
1778 }
1779 }
1780
1781 #[test]
1782 fn a_public_origin_that_is_not_a_string_is_refused() {
1783 assert!(with(Some("8443"), "").is_err(), "a number");
1784 assert!(
1785 with(Some("[\"https://a.example.com\"]"), "").is_err(),
1786 "a list"
1787 );
1788 assert!(with(None, "public_origin = true\n").is_err(), "a flag");
1789 }
1790
1791 #[test]
1794 fn the_operator_listener_may_have_a_public_origin_when_the_tenant_s_has_none() {
1795 let config =
1796 with(None, "public_origin = \"https://ops.example.com\"\n").expect("parses");
1797 assert_eq!(config.public_origin, None, "sessions off for tenants");
1798 assert_eq!(
1799 operators(&config),
1800 origin("https://ops.example.com"),
1801 "the operator listener's"
1802 );
1803 }
1804
1805 #[test]
1806 fn two_public_origins_on_two_hosts_may_share_a_port() {
1807 let config = with(
1808 Some("\"https://vcon.example.com:8443\""),
1809 "public_origin = \"https://ops.example.com:8443\"\n",
1810 )
1811 .expect("two hosts");
1812 assert_eq!(
1813 operators(&config),
1814 origin("https://ops.example.com:8443"),
1815 "the operator listener's"
1816 );
1817 }
1818
1819 #[test]
1820 fn a_public_origin_may_be_an_address_or_localhost() {
1821 for text in [
1822 "https://localhost:8443",
1823 "https://192.0.2.7:8443",
1824 "https://[2001:db8::7]:8443",
1825 ] {
1826 let config = with(Some(&format!("{text:?}")), "").expect(text);
1827 assert_eq!(config.public_origin, origin(text), "{text}");
1828 }
1829 }
1830
1831 #[test]
1832 fn a_host_that_is_another_s_prefix_is_another_host() {
1833 let config = with(
1834 Some("\"https://vcon.example.com\""),
1835 "public_origin = \"https://vcon.example.com.example.net\"\n",
1836 )
1837 .expect("two hosts");
1838 assert_eq!(
1839 operators(&config),
1840 origin("https://vcon.example.com.example.net"),
1841 "the operator listener's"
1842 );
1843 }
1844 }
1845
1846 mod connection_limits {
1847 use super::*;
1848
1849 fn with(timeouts: &str) -> Result<Config, ConfigError> {
1850 parse(&format!("{LEAST}\n[limits.timeouts]\n{timeouts}"))
1851 }
1852
1853 #[test]
1854 fn the_defaults_are_ten_seconds_thirty_thirty_and_two_minutes_idle() {
1855 let config = parse(LEAST).expect("parses");
1856 assert_eq!(
1857 config.connection,
1858 ConnectionLimits {
1859 handshake: Duration::from_secs(10),
1860 first_head: Duration::from_secs(30),
1861 head: Duration::from_secs(30),
1862 idle: Duration::from_secs(120),
1863 goodbye: Duration::from_secs(5),
1864 accept_pause: Duration::from_secs(1),
1865 max: 512,
1866 },
1867 "with no [limits.timeouts] table"
1868 );
1869 assert_eq!(
1870 config.connection,
1871 ConnectionLimits::default(),
1872 "the defaults serve applies without a configuration"
1873 );
1874 }
1875
1876 #[test]
1877 fn each_key_sets_its_own_limit_and_no_other() {
1878 let default = ConnectionLimits::default();
1879 for (line, expected) in [
1880 (
1881 "handshake = 3",
1882 ConnectionLimits {
1883 handshake: Duration::from_secs(3),
1884 ..default
1885 },
1886 ),
1887 (
1888 "first_head = 7",
1889 ConnectionLimits {
1890 first_head: Duration::from_secs(7),
1891 ..default
1892 },
1893 ),
1894 (
1895 "head = 75",
1896 ConnectionLimits {
1897 head: Duration::from_secs(75),
1898 ..default
1899 },
1900 ),
1901 (
1902 "idle = 300",
1903 ConnectionLimits {
1904 idle: Duration::from_secs(300),
1905 ..default
1906 },
1907 ),
1908 ] {
1909 let config = with(line).expect(line);
1910 assert_eq!(config.connection, expected, "{line}");
1911 assert_eq!(
1912 config.read_timeout, READ_TIMEOUT,
1913 "{line}: the body limit is its own key"
1914 );
1915 }
1916 }
1917
1918 #[test]
1919 fn the_four_keys_together_are_all_read() {
1920 let config = with("handshake = 2\nfirst_head = 4\nhead = 6\nread = 8\nidle = 10")
1921 .expect("parses");
1922 assert_eq!(
1923 (
1924 config.connection.handshake,
1925 config.connection.first_head,
1926 config.connection.head,
1927 config.read_timeout,
1928 config.connection.idle,
1929 ),
1930 (
1931 Duration::from_secs(2),
1932 Duration::from_secs(4),
1933 Duration::from_secs(6),
1934 Duration::from_secs(8),
1935 Duration::from_secs(10),
1936 ),
1937 "each key in its own member"
1938 );
1939 }
1940
1941 #[test]
1942 fn an_idle_connection_is_kept_two_minutes_unless_told() {
1943 assert_eq!(
1944 parse(LEAST).expect("parses").connection.idle,
1945 Duration::from_secs(120),
1946 "with no [limits.timeouts] table"
1947 );
1948 assert_eq!(
1949 with("head = 5").expect("parses").connection.idle,
1950 Duration::from_secs(120),
1951 "with a table that does not say"
1952 );
1953 }
1954
1955 #[test]
1956 fn the_idle_limit_may_be_shorter_than_the_head_limit_and_longer() {
1957 for (idle, head) in [(1, 3600), (3600, 1), (30, 30)] {
1960 let config = with(&format!("idle = {idle}\nhead = {head}")).expect("parses");
1961 assert_eq!(
1962 (config.connection.idle, config.connection.head),
1963 (Duration::from_secs(idle), Duration::from_secs(head)),
1964 "idle {idle}, head {head}"
1965 );
1966 }
1967 }
1968
1969 #[test]
1970 fn the_wait_after_a_connection_is_told_to_close_has_no_key() {
1971 let error = with("goodbye = 2").expect_err("no such key");
1972 assert!(error.0.contains("`goodbye`"), "{error}");
1973 assert_eq!(
1974 with("idle = 9").expect("parses").connection.goodbye,
1975 Duration::from_secs(5),
1976 "five seconds whatever the keys say"
1977 );
1978 }
1979
1980 #[test]
1981 fn one_second_and_one_hour_are_the_bounds_and_both_are_taken() {
1982 for key in ["handshake", "first_head", "head", "idle"] {
1983 for seconds in [1, CONNECTION_LIMIT_MAX] {
1984 assert!(
1985 with(&format!("{key} = {seconds}")).is_ok(),
1986 "{key} = {seconds}"
1987 );
1988 }
1989 }
1990 }
1991
1992 #[test]
1993 fn zero_is_refused_by_name() {
1994 for key in ["handshake", "first_head", "head", "idle"] {
1995 let error = with(&format!("{key} = 0")).expect_err(key);
1996 assert_eq!(
1997 error.0,
1998 format!("limits.timeouts.{key} must be more than 0"),
1999 "{key}"
2000 );
2001 }
2002 }
2003
2004 #[test]
2005 fn more_than_an_hour_is_refused_by_name_with_the_bound() {
2006 for key in ["handshake", "first_head", "head", "idle"] {
2007 for seconds in [3601_u64, 86_400, u64::from(u32::MAX)] {
2008 let error = with(&format!("{key} = {seconds}")).expect_err(key);
2009 assert_eq!(
2010 error.0,
2011 format!(
2012 "limits.timeouts.{key} must be at most 3600 seconds, and is {seconds}"
2013 ),
2014 "{key} = {seconds}"
2015 );
2016 }
2017 }
2018 }
2019
2020 #[test]
2021 fn a_value_that_is_not_whole_seconds_is_refused() {
2022 for key in ["handshake", "first_head", "head", "idle"] {
2023 for value in ["-1", "1.5", "\"10\"", "true", "[10]"] {
2024 let error = with(&format!("{key} = {value}")).expect_err(key);
2025 assert!(error.0.contains(key), "{key} = {value}: {error}");
2026 }
2027 }
2028 }
2029
2030 #[test]
2031 fn the_wait_after_a_failed_accept_has_no_key() {
2032 let error = with("accept_pause = 2").expect_err("no such key");
2033 assert!(error.0.contains("`accept_pause`"), "{error}");
2034 }
2035
2036 fn with_limit(line: &str) -> Result<Config, ConfigError> {
2038 parse(&format!("{LEAST}\n[limits]\n{line}\n"))
2039 }
2040
2041 #[test]
2042 fn a_listener_takes_120_reports_a_minute_and_20_from_one_address_unless_told() {
2043 let reports = parse(LEAST).expect("parses").reports;
2044 assert_eq!(
2045 (reports.per_minute, reports.per_address),
2046 (120, 20),
2047 "the defaults"
2048 );
2049 assert_eq!(reports, crate::api::ReportLimits::DEFAULT, "the gate's own");
2050 }
2051
2052 #[test]
2053 fn both_report_limits_are_read() {
2054 let reports = with_limit("csp_reports = 300\ncsp_reports_per_address = 30")
2055 .expect("parses")
2056 .reports;
2057 assert_eq!(
2058 (reports.per_minute, reports.per_address),
2059 (300, 30),
2060 "as written"
2061 );
2062 }
2063
2064 #[test]
2065 fn the_minutes_number_alone_is_read_and_one_addresss_stays() {
2066 let reports = with_limit("csp_reports = 500").expect("parses").reports;
2067 assert_eq!(
2068 (reports.per_minute, reports.per_address),
2069 (500, 20),
2070 "one key"
2071 );
2072 }
2073
2074 #[test]
2075 fn one_addresss_number_alone_is_read_and_the_minutes_stays() {
2076 let reports = with_limit("csp_reports_per_address = 7")
2077 .expect("parses")
2078 .reports;
2079 assert_eq!(
2080 (reports.per_minute, reports.per_address),
2081 (120, 7),
2082 "one key"
2083 );
2084 }
2085
2086 #[test]
2087 fn a_minutes_number_under_20_lowers_one_addresss_default_with_it() {
2088 let reports = with_limit("csp_reports = 5").expect("parses").reports;
2089 assert_eq!(
2090 (reports.per_minute, reports.per_address),
2091 (5, 5),
2092 "never more than all"
2093 );
2094 }
2095
2096 #[test]
2097 fn the_bounds_of_the_report_limits_are_taken() {
2098 let least = with_limit("csp_reports = 1\ncsp_reports_per_address = 1")
2099 .expect("the least")
2100 .reports;
2101 assert_eq!((least.per_minute, least.per_address), (1, 1), "the least");
2102 let most = with_limit("csp_reports = 6000\ncsp_reports_per_address = 6000")
2103 .expect("the most")
2104 .reports;
2105 assert_eq!(
2106 (most.per_minute, most.per_address),
2107 (6000, 6000),
2108 "the most"
2109 );
2110 }
2111
2112 #[test]
2113 fn the_report_limits_change_no_other_limit() {
2114 let config = with_limit("csp_reports = 300").expect("parses");
2115 let base = parse(LEAST).expect("parses");
2116 assert_eq!(config.connection, base.connection, "the connection limits");
2117 assert_eq!(config.body_limit, base.body_limit, "the body limit");
2118 }
2119
2120 #[test]
2121 fn no_reports_at_all_is_refused_by_name() {
2122 for key in ["csp_reports", "csp_reports_per_address"] {
2123 let error = with_limit(&format!("{key} = 0")).expect_err("zero");
2124 assert_eq!(
2125 error.0,
2126 format!("limits.{key} must be more than 0"),
2127 "{key}"
2128 );
2129 }
2130 }
2131
2132 #[test]
2133 fn more_reports_than_6000_is_refused_by_name_with_the_bound() {
2134 for key in ["csp_reports", "csp_reports_per_address"] {
2135 for value in [6001_u64, 1_000_000, u64::from(u32::MAX) + 1] {
2136 let error = with_limit(&format!("{key} = {value}")).expect_err("too many");
2137 assert_eq!(
2138 error.0,
2139 format!("limits.{key} must be at most 6000, and is {value}"),
2140 "{key} = {value}"
2141 );
2142 }
2143 }
2144 }
2145
2146 #[test]
2147 fn more_from_one_address_than_from_all_is_refused_with_both_numbers() {
2148 let error =
2149 with_limit("csp_reports = 10\ncsp_reports_per_address = 11").expect_err("more");
2150 assert_eq!(
2151 error.0,
2152 "limits.csp_reports_per_address (11) must be at most limits.csp_reports (10)",
2153 "the two numbers"
2154 );
2155 let error =
2156 with_limit("csp_reports_per_address = 121").expect_err("more than the default");
2157 assert!(
2158 error
2159 .0
2160 .contains("(121) must be at most limits.csp_reports (120)"),
2161 "{error}"
2162 );
2163 }
2164
2165 #[test]
2166 fn a_report_limit_that_is_not_a_whole_number_is_refused() {
2167 for key in ["csp_reports", "csp_reports_per_address"] {
2168 for value in ["-1", "1.5", "\"ten\"", "true"] {
2169 let error = with_limit(&format!("{key} = {value}")).expect_err(value);
2170 assert!(error.0.contains(key), "{key} = {value}: {error}");
2171 }
2172 }
2173 }
2174
2175 #[test]
2176 fn a_report_limit_written_outside_the_limits_table_is_refused() {
2177 let error = parse(&format!("{LEAST}\ncsp_reports = 5\n")).expect_err("the wrong table");
2178 assert!(error.0.contains("csp_reports"), "{error}");
2179 }
2180
2181 #[test]
2182 fn a_listener_holds_512_connections_at_once_unless_told() {
2183 assert_eq!(
2184 parse(LEAST).expect("parses").connection.max,
2185 512,
2186 "with no [limits] table"
2187 );
2188 assert_eq!(
2189 with_limit("body = 1024").expect("parses").connection.max,
2190 512,
2191 "with a [limits] table that does not say"
2192 );
2193 }
2194
2195 #[test]
2196 fn the_most_connections_at_once_is_read_and_changes_no_other_limit() {
2197 let config = with_limit("connections = 2000").expect("parses");
2198 assert_eq!(
2199 config.connection,
2200 ConnectionLimits {
2201 max: 2000,
2202 ..ConnectionLimits::default()
2203 },
2204 "only the most at once differs"
2205 );
2206 }
2207
2208 #[test]
2209 fn one_connection_and_65536_are_the_bounds_and_both_are_taken() {
2210 for connections in [1_usize, 65_536] {
2211 assert_eq!(
2212 with_limit(&format!("connections = {connections}"))
2213 .expect("parses")
2214 .connection
2215 .max,
2216 connections,
2217 "{connections}"
2218 );
2219 }
2220 }
2221
2222 #[test]
2223 fn no_connections_at_all_is_refused_by_name() {
2224 let error = with_limit("connections = 0").expect_err("zero");
2225 assert_eq!(
2226 error.0, "limits.connections must be more than 0",
2227 "a listener that takes no connection serves nothing"
2228 );
2229 }
2230
2231 #[test]
2232 fn more_connections_than_65536_is_refused_by_name_with_the_bound() {
2233 for connections in [65_537_u64, 1_000_000, u64::from(u32::MAX)] {
2234 let error =
2235 with_limit(&format!("connections = {connections}")).expect_err("too many");
2236 assert_eq!(
2237 error.0,
2238 format!("limits.connections must be at most 65536, and is {connections}"),
2239 "{connections}"
2240 );
2241 }
2242 }
2243
2244 #[test]
2245 fn a_number_of_connections_that_is_not_a_whole_number_is_refused() {
2246 for value in ["-1", "1.5", "\"512\"", "true", "[512]"] {
2247 let error = with_limit(&format!("connections = {value}")).expect_err(value);
2248 assert!(error.0.contains("connections"), "{value}: {error}");
2249 }
2250 }
2251 }
2252
2253 #[test]
2254 fn retention_and_supported_extensions_have_defaults() {
2255 let text = FULL
2256 .replace("retention_default = \"18m\"\n", "")
2257 .replace("supported_critical = [\"known\", \"other\"]\n", "");
2258 let config = parse(&text).expect("parses");
2259 assert_eq!(
2260 config.retention_default,
2261 Retention::Years(7),
2262 "with no retention_default, vCons are kept seven years"
2263 );
2264 assert_eq!(
2265 config.supported_critical,
2266 BTreeSet::new(),
2267 "with no supported_critical, no extension is supported"
2268 );
2269 }
2270
2271 const LEAST: &str = r#"
2273listen = "127.0.0.1:8443"
2274data_dir = "/var/lib/vcon-server"
2275master_key = "/etc/vcon-server/master.key"
2276
2277[tls]
2278cert = "/etc/vcon-server/cert.pem"
2279key = "/etc/vcon-server/key.pem"
2280"#;
2281
2282 #[test]
2283 fn periods_and_limits_have_defaults() {
2284 let config = parse(LEAST).expect("parses");
2285 assert_eq!(
2286 config.purge_interval,
2287 Duration::from_secs(3600),
2288 "the purge sweep runs hourly by default"
2289 );
2290 assert_eq!(
2291 config.rotation_warn,
2292 Duration::from_secs(30 * 86_400),
2293 "an overdue rotation is warned of after 30 days by default"
2294 );
2295 assert_eq!(
2296 config.body_limit,
2297 16 << 20,
2298 "a body may be 16 MiB by default"
2299 );
2300 assert_eq!(
2301 config.inflated_limit,
2302 64 << 20,
2303 "a body may inflate to 64 MiB by default"
2304 );
2305 assert_eq!(
2306 config.read_timeout,
2307 Duration::from_secs(60),
2308 "a request has 60 seconds to arrive by default"
2309 );
2310 assert_eq!(
2311 config.mcp,
2312 crate::mcp::Limits::DEFAULT,
2313 "with no [mcp] table, the MCP endpoint takes its default limits"
2314 );
2315 }
2316
2317 #[test]
2320 fn each_limit_defaults_alone() {
2321 let base = parse(FULL).expect("parses");
2322 for (line, default) in [
2323 (
2324 "body = 10485760\n",
2325 Config {
2326 body_limit: 16 << 20,
2327 ..base.clone()
2328 },
2329 ),
2330 (
2331 "inflated = 104857600\n",
2332 Config {
2333 inflated_limit: 64 << 20,
2334 ..base.clone()
2335 },
2336 ),
2337 (
2338 "read = 30\n",
2339 Config {
2340 read_timeout: Duration::from_secs(60),
2341 ..base.clone()
2342 },
2343 ),
2344 (
2345 "purge_interval = 1800\n",
2346 Config {
2347 purge_interval: Duration::from_secs(3600),
2348 ..base.clone()
2349 },
2350 ),
2351 (
2352 "rotation_warn = 604800\n",
2353 Config {
2354 rotation_warn: Duration::from_secs(30 * 86_400),
2355 ..base.clone()
2356 },
2357 ),
2358 (
2359 "[limits.timeouts]\nread = 30\nhandshake = 5\nfirst_head = 15\nhead = 20\nidle = 90\n",
2360 Config {
2361 read_timeout: Duration::from_secs(60),
2362 connection: ConnectionLimits {
2363 max: base.connection.max,
2364 ..ConnectionLimits::default()
2365 },
2366 ..base.clone()
2367 },
2368 ),
2369 (
2370 "connections = 64\n",
2371 Config {
2372 connection: ConnectionLimits {
2373 max: 512,
2374 ..base.connection
2375 },
2376 ..base.clone()
2377 },
2378 ),
2379 (
2380 "handshake = 5\n",
2381 Config {
2382 connection: ConnectionLimits {
2383 handshake: Duration::from_secs(10),
2384 ..base.connection
2385 },
2386 ..base.clone()
2387 },
2388 ),
2389 (
2390 "first_head = 15\n",
2391 Config {
2392 connection: ConnectionLimits {
2393 first_head: Duration::from_secs(30),
2394 ..base.connection
2395 },
2396 ..base.clone()
2397 },
2398 ),
2399 (
2400 "head = 20\n",
2401 Config {
2402 connection: ConnectionLimits {
2403 head: Duration::from_secs(30),
2404 ..base.connection
2405 },
2406 ..base.clone()
2407 },
2408 ),
2409 (
2410 "idle = 90\n",
2411 Config {
2412 connection: ConnectionLimits {
2413 idle: Duration::from_secs(120),
2414 ..base.connection
2415 },
2416 ..base.clone()
2417 },
2418 ),
2419 (
2420 "calls_per_second = 20\n",
2421 Config {
2422 mcp: crate::mcp::Limits {
2423 calls_per_second: 100,
2424 ..base.mcp
2425 },
2426 ..base.clone()
2427 },
2428 ),
2429 (
2430 "concurrent = 8\n",
2431 Config {
2432 mcp: crate::mcp::Limits {
2433 concurrent: 100,
2434 ..base.mcp
2435 },
2436 ..base.clone()
2437 },
2438 ),
2439 (
2440 "response_bytes = 262144\n",
2441 Config {
2442 mcp: crate::mcp::Limits {
2443 response_bytes: 1 << 20,
2444 ..base.mcp
2445 },
2446 ..base.clone()
2447 },
2448 ),
2449 ] {
2450 assert!(FULL.contains(line), "{line}");
2451 assert_eq!(parse(&FULL.replace(line, "")), Ok(default), "{line}");
2452 }
2453 }
2454
2455 #[test]
2458 fn the_full_file_sets_no_value_equal_to_its_default() {
2459 let (full, least) = (parse(FULL).expect("full"), parse(LEAST).expect("least"));
2460 assert_ne!(
2461 full.purge_interval, least.purge_interval,
2462 "FULL writes purge_interval as a value other than its default"
2463 );
2464 assert_ne!(
2465 full.rotation_warn, least.rotation_warn,
2466 "FULL writes rotation_warn as a value other than its default"
2467 );
2468 assert_ne!(
2469 full.body_limit, least.body_limit,
2470 "FULL writes limits.body as a value other than its default"
2471 );
2472 assert_ne!(
2473 full.inflated_limit, least.inflated_limit,
2474 "FULL writes limits.inflated as a value other than its default"
2475 );
2476 assert_ne!(
2477 full.read_timeout, least.read_timeout,
2478 "FULL writes limits.timeouts.read as a value other than its default"
2479 );
2480 assert_ne!(
2481 full.mcp.calls_per_second, least.mcp.calls_per_second,
2482 "FULL writes mcp.calls_per_second as a value other than its default"
2483 );
2484 assert_ne!(
2485 full.mcp.concurrent, least.mcp.concurrent,
2486 "FULL writes mcp.concurrent as a value other than its default"
2487 );
2488 assert_ne!(
2489 full.mcp.response_bytes, least.mcp.response_bytes,
2490 "FULL writes mcp.response_bytes as a value other than its default"
2491 );
2492 assert_ne!(
2493 full.storage, least.storage,
2494 "FULL writes storage.objects as a value other than its default"
2495 );
2496 let parquet = full.storage.parquet.expect("FULL has storage.parquet");
2497 let least_parquet = parquet_least();
2498 for (key, differs) in [
2499 (
2500 "storage.parquet.pack_interval",
2501 parquet.pack_interval != least_parquet.pack_interval,
2502 ),
2503 (
2504 "storage.parquet.pack_limit",
2505 parquet.pack_limit != least_parquet.pack_limit,
2506 ),
2507 (
2508 "storage.parquet.reader_grace",
2509 parquet.reader_grace != least_parquet.reader_grace,
2510 ),
2511 ] {
2512 assert!(
2513 differs,
2514 "FULL writes {key} as a value other than its default"
2515 );
2516 }
2517 let ObjectStore::S3(s3) = full.storage.objects else {
2518 panic!("FULL keeps its objects in S3")
2519 };
2520 let least_s3 = s3_least();
2521 for (key, differs) in [
2522 ("storage.s3.endpoint", s3.endpoint != least_s3.endpoint),
2523 ("storage.s3.prefix", s3.prefix != least_s3.prefix),
2524 (
2525 "storage.s3.path_style",
2526 s3.path_style != least_s3.path_style,
2527 ),
2528 (
2529 "storage.s3.access_key_id",
2530 s3.access_key_id != least_s3.access_key_id,
2531 ),
2532 (
2533 "storage.s3.secret_access_key_file",
2534 s3.secret_access_key_file != least_s3.secret_access_key_file,
2535 ),
2536 (
2537 "storage.s3.allow_http",
2538 s3.allow_http != least_s3.allow_http,
2539 ),
2540 ("storage.s3.ca_file", s3.ca_file != least_s3.ca_file),
2541 (
2542 "storage.s3.allow_versioning",
2543 s3.allow_versioning != least_s3.allow_versioning,
2544 ),
2545 ("storage.s3.timeout", s3.timeout != least_s3.timeout),
2546 ] {
2547 assert!(
2548 differs,
2549 "FULL writes {key} as a value other than its default"
2550 );
2551 }
2552 let export = full.export.s3.expect("FULL has export.s3");
2553 let least_export = parse(&format!("{LEAST}\n[export.s3]\nregion = \"us-east-1\"\n"))
2554 .expect("least export")
2555 .export
2556 .s3
2557 .expect("export.s3");
2558 for (key, differs) in [
2559 (
2560 "export.s3.endpoint",
2561 export.endpoint != least_export.endpoint,
2562 ),
2563 ("export.s3.region", export.region != least_export.region),
2564 (
2565 "export.s3.path_style",
2566 export.path_style != least_export.path_style,
2567 ),
2568 (
2569 "export.s3.access_key_id",
2570 export.access_key_id != least_export.access_key_id,
2571 ),
2572 (
2573 "export.s3.secret_access_key_file",
2574 export.secret_access_key_file != least_export.secret_access_key_file,
2575 ),
2576 (
2577 "export.s3.allow_http",
2578 export.allow_http != least_export.allow_http,
2579 ),
2580 ("export.s3.ca_file", export.ca_file != least_export.ca_file),
2581 ("export.s3.timeout", export.timeout != least_export.timeout),
2582 ] {
2583 assert!(
2584 differs,
2585 "FULL writes {key} as a value other than its default"
2586 );
2587 }
2588 assert_ne!(
2589 full.catalog, least.catalog,
2590 "FULL writes catalog.backend as a value other than its default"
2591 );
2592 let CatalogStore::Postgres(pg) = full.catalog else {
2593 panic!("FULL keeps its catalogs in PostgreSQL")
2594 };
2595 let least_pg = catalog::postgres_least();
2596 for (key, differs) in [
2597 ("catalog.postgres.port", pg.port != least_pg.port),
2598 ("catalog.postgres.ca_file", pg.ca_file != least_pg.ca_file),
2599 (
2600 "catalog.postgres.password_file",
2601 pg.password_file != least_pg.password_file,
2602 ),
2603 (
2604 "catalog.postgres.client_cert_file",
2605 pg.client_cert_file != least_pg.client_cert_file,
2606 ),
2607 (
2608 "catalog.postgres.client_key_file",
2609 pg.client_key_file != least_pg.client_key_file,
2610 ),
2611 ("catalog.postgres.pool", pg.pool != least_pg.pool),
2612 (
2613 "catalog.postgres.connect_timeout",
2614 pg.connect_timeout != least_pg.connect_timeout,
2615 ),
2616 (
2617 "catalog.postgres.statement_timeout",
2618 pg.statement_timeout != least_pg.statement_timeout,
2619 ),
2620 (
2621 "catalog.postgres.lock_timeout",
2622 pg.lock_timeout != least_pg.lock_timeout,
2623 ),
2624 ] {
2625 assert!(
2626 differs,
2627 "FULL writes {key} as a value other than its default"
2628 );
2629 }
2630 }
2631
2632 fn s3_least() -> S3Settings {
2634 let text = format!(
2635 "{LEAST}\n[storage]\nobjects = \"s3\"\n[storage.s3]\nregion = \"us-east-1\"\nbucket = \"vcon\"\n"
2636 );
2637 match parse(&text)
2638 .expect("the least S3 configuration reads")
2639 .storage
2640 .objects
2641 {
2642 ObjectStore::S3(s3) => s3,
2643 ObjectStore::Local => panic!("objects = \"s3\" keeps the objects in S3"),
2644 }
2645 }
2646
2647 #[test]
2648 fn without_a_storage_table_everything_is_local() {
2649 assert_eq!(
2650 parse(LEAST).expect("parses").storage,
2651 Storage {
2652 objects: ObjectStore::Local,
2653 parquet: None,
2654 },
2655 "a file written before storage backends keeps its meaning"
2656 );
2657 }
2658
2659 fn parquet_least() -> ParquetSettings {
2661 let text = format!(
2662 "{LEAST}\n[storage]\nobjects = \"s3\"\n[storage.s3]\nregion = \"us-east-1\"\n\
2663 bucket = \"vcon\"\n[storage.parquet]\n"
2664 );
2665 parse(&text)
2666 .expect("the least Parquet configuration reads")
2667 .storage
2668 .parquet
2669 .expect("an empty [storage.parquet] turns Parquet storage on")
2670 }
2671
2672 #[test]
2673 fn parquet_settings_have_defaults() {
2674 assert_eq!(
2675 parquet_least(),
2676 ParquetSettings {
2677 pack_interval: PACK_INTERVAL,
2678 pack_limit: PACK_LIMIT,
2679 reader_grace: READER_GRACE,
2680 },
2681 "an empty table takes every default"
2682 );
2683 assert_eq!(READER_GRACE, Duration::from_secs(900), "15 minutes");
2684 assert_eq!(PACK_INTERVAL, Duration::from_secs(300), "five minutes");
2685 assert_eq!(PACK_LIMIT, 16 << 20, "16 MiB");
2686 }
2687
2688 #[test]
2689 fn s3_settings_have_defaults() {
2690 assert_eq!(
2691 s3_least(),
2692 S3Settings {
2693 endpoint: None,
2694 region: "us-east-1".to_owned(),
2695 bucket: "vcon".to_owned(),
2696 prefix: String::new(),
2697 path_style: false,
2698 access_key_id: None,
2699 secret_access_key_file: None,
2700 allow_http: false,
2701 ca_file: None,
2702 allow_versioning: false,
2703 timeout: Duration::from_secs(30),
2704 },
2705 "only region and bucket are required"
2706 );
2707 }
2708
2709 #[test]
2713 fn export_s3_settings_are_read_and_checked_as_storage_s3_is() {
2714 let export = |extra: &str| format!("{LEAST}\n[export.s3]\nregion = \"us-east-1\"\n{extra}");
2715 assert_eq!(
2716 parse(LEAST).expect("least").export,
2717 Export::default(),
2718 "no table"
2719 );
2720 assert_eq!(
2721 parse(&export("")).expect("least export").export.s3,
2722 Some(ExportS3 {
2723 endpoint: None,
2724 region: "us-east-1".to_owned(),
2725 path_style: false,
2726 access_key_id: None,
2727 secret_access_key_file: None,
2728 allow_http: false,
2729 ca_file: None,
2730 timeout: S3_TIMEOUT,
2731 }),
2732 "only region is required"
2733 );
2734 for (extra, key) in [
2735 (
2736 "endpoint = \"http://127.0.0.1:9000\"\n",
2737 "export.s3.allow_http",
2738 ),
2739 ("endpoint = \"objects.example.com\"\n", "export.s3.endpoint"),
2740 (
2741 "access_key_id = \"vcon\"\n",
2742 "export.s3.secret_access_key_file",
2743 ),
2744 (
2745 "secret_access_key_file = \"/s\"\n",
2746 "export.s3.access_key_id",
2747 ),
2748 ("timeout = 0\n", "export.s3.timeout"),
2749 (
2750 "endpoint = \"http://127.0.0.1:9000\"\nallow_http = true\nca_file = \"/c.pem\"\n",
2751 "export.s3.ca_file",
2752 ),
2753 ("bucket = \"vcon\"\n", "bucket"),
2754 ("prefix = \"a/\"\n", "prefix"),
2755 ("allow_versioning = true\n", "allow_versioning"),
2756 ] {
2757 let ConfigError(message) = parse(&export(extra)).expect_err(extra);
2758 assert!(message.contains(key), "{extra}: {message}");
2759 }
2760 assert!(
2761 parse(&format!("{LEAST}\n[export.s3]\n"))
2762 .expect_err("no region")
2763 .0
2764 .contains("region"),
2765 "region is required"
2766 );
2767 }
2768
2769 #[test]
2772 fn an_export_service_names_its_bucket_and_prefix() {
2773 let full = parse(FULL).expect("full");
2774 let export = full.export.s3.expect("export.s3");
2775 let s = export.for_bucket("reports", "vcon/");
2776 assert_eq!(
2777 (s.bucket.as_str(), s.prefix.as_str()),
2778 ("reports", "vcon/"),
2779 "the target's bucket and prefix"
2780 );
2781 assert_eq!(s.endpoint, export.endpoint, "the export's endpoint");
2782 assert_eq!(s.region, export.region, "the export's region");
2783 assert_eq!(
2784 s.access_key_id, export.access_key_id,
2785 "the export's access key id"
2786 );
2787 assert_eq!(
2788 s.secret_access_key_file, export.secret_access_key_file,
2789 "the export's secret file"
2790 );
2791 assert_eq!(s.ca_file, export.ca_file, "the export's CA file");
2792 assert_eq!(
2793 (s.path_style, s.allow_http),
2794 (true, true),
2795 "FULL sets path_style and allow_http"
2796 );
2797 assert_eq!(s.timeout, Duration::from_secs(120), "the export's timeout");
2798 assert!(!s.allow_versioning, "never read for an export");
2799 let ObjectStore::S3(storage) = full.storage.objects else {
2800 panic!("FULL keeps its objects in S3")
2801 };
2802 let from = ExportS3::from(&storage).for_bucket(&storage.bucket, &storage.prefix);
2803 assert_eq!(
2804 from,
2805 S3Settings {
2806 allow_versioning: false,
2807 ..storage
2808 },
2809 "storage.s3's service and keys, whole"
2810 );
2811 }
2812
2813 #[test]
2814 fn s3_settings_that_do_not_hold_together_are_named() {
2815 let s3 = |extra: &str| {
2816 format!(
2817 "{LEAST}\n[storage]\nobjects = \"s3\"\n[storage.s3]\nregion = \"us-east-1\"\nbucket = \"vcon\"\n{extra}"
2818 )
2819 };
2820 for (text, key) in [
2821 (
2822 format!("{LEAST}\n[storage]\nobjects = \"s3\"\n"),
2823 "storage.s3",
2824 ),
2825 (
2826 format!("{LEAST}\n[storage]\nobjects = \"s3\"\n[storage.s3]\nbucket = \"vcon\"\n"),
2827 "region",
2828 ),
2829 (
2830 format!(
2831 "{LEAST}\n[storage]\nobjects = \"s3\"\n[storage.s3]\nregion = \"us-east-1\"\n"
2832 ),
2833 "bucket",
2834 ),
2835 (
2836 s3("endpoint = \"http://127.0.0.1:9000\"\n"),
2837 "storage.s3.allow_http",
2838 ),
2839 (
2840 s3("endpoint = \"objects.example.com\"\n"),
2841 "storage.s3.endpoint",
2842 ),
2843 (
2844 s3("access_key_id = \"vcon-server\"\n"),
2845 "storage.s3.secret_access_key_file",
2846 ),
2847 (
2848 s3("secret_access_key_file = \"/etc/vcon-server/s3.secret\"\n"),
2849 "storage.s3.access_key_id",
2850 ),
2851 (s3("timeout = 0\n"), "storage.s3.timeout"),
2852 (
2853 s3(
2854 "endpoint = \"http://127.0.0.1:9000\"\nallow_http = true\nca_file = \"/etc/vcon-server/s3-ca.pem\"\n",
2855 ),
2856 "storage.s3.ca_file",
2857 ),
2858 (s3("prefix = \"/server-a/\"\n"), "storage.s3.prefix"),
2859 (s3("prefix = \"server-a\"\n"), "storage.s3.prefix"),
2860 (
2861 s3("bucket = \"\"\n").replace("bucket = \"vcon\"\n", ""),
2862 "storage.s3.bucket",
2863 ),
2864 (
2865 format!("{LEAST}\n[storage]\nobjects = \"tape\"\n"),
2866 "objects",
2867 ),
2868 (format!("{LEAST}\n[storage.parquet]\n"), "storage.parquet"),
2869 (
2870 format!("{LEAST}\n[storage]\nobjects = \"local\"\n[storage.parquet]\n"),
2871 "storage.parquet",
2872 ),
2873 (
2874 s3("[storage.parquet]\npack_interval = 0\n"),
2875 "storage.parquet.pack_interval",
2876 ),
2877 (
2878 s3("[storage.parquet]\npack_limit = 0\n"),
2879 "storage.parquet.pack_limit",
2880 ),
2881 (
2882 s3("[storage.parquet]\nreader_grace = 0\n"),
2883 "storage.parquet.reader_grace",
2884 ),
2885 (
2886 format!(
2887 "{LEAST}\n[storage]\nobjects = \"local\"\n[storage.s3]\nregion = \"us-east-1\"\nbucket = \"vcon\"\n"
2888 ),
2889 "storage.s3",
2890 ),
2891 ] {
2892 let error = parse(&text).expect_err(key);
2893 assert!(error.0.contains(key), "the error names {key}: {error}");
2894 }
2895 }
2896
2897 #[test]
2898 fn an_http_endpoint_reads_when_allowed() {
2899 let text = format!(
2900 "{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"
2901 );
2902 assert!(
2903 parse(&text).is_ok(),
2904 "allow_http lets a test container's plain endpoint through"
2905 );
2906 }
2907
2908 #[test]
2910 fn every_missing_key_without_a_default_is_named() {
2911 for (line, key) in [
2912 ("listen = \"127.0.0.1:8443\"\n", "listen"),
2913 ("data_dir = \"/var/lib/vcon-server\"\n", "data_dir"),
2914 (
2915 "master_key = \"/etc/vcon-server/master.key\"\n",
2916 "master_key",
2917 ),
2918 ("cert = \"/etc/vcon-server/cert.pem\"\n", "cert"),
2919 ("key = \"/etc/vcon-server/key.pem\"\n", "key"),
2920 ] {
2921 assert!(FULL.contains(line), "{line}");
2922 let error = parse(&FULL.replace(line, "")).expect_err(key);
2923 assert!(error.0.contains(&format!("`{key}`")), "{key}: {error}");
2924 }
2925 }
2926
2927 #[test]
2928 fn an_unknown_key_is_named() {
2929 for (text, key) in [
2930 (format!("colour = \"blue\"\n{FULL}"), "colour"),
2931 (FULL.replace("read = 30", "read = 30\nwrite = 30"), "write"),
2932 (FULL.replace("[tls]", "[tls]\nca = \"x\""), "ca"),
2933 (
2934 FULL.replace("[mcp]", "[mcp]\nresources = true"),
2935 "resources",
2936 ),
2937 ] {
2938 let error = parse(&text).expect_err(key);
2939 assert!(error.0.contains(&format!("`{key}`")), "{key}: {error}");
2940 }
2941 }
2942
2943 #[test]
2944 fn a_bad_value_is_named() {
2945 for (from, to, key) in [
2946 ("\"127.0.0.1:8443\"", "\"localhost\"", "listen"),
2947 ("\"18m\"", "\"7w\"", "retention_default"),
2948 (
2949 "purge_interval = 1800",
2950 "purge_interval = 0",
2951 "purge_interval",
2952 ),
2953 (
2954 "rotation_warn = 604800",
2955 "rotation_warn = 0",
2956 "rotation_warn",
2957 ),
2958 ("body = 10485760", "body = 0", "limits.body"),
2959 ("inflated = 104857600", "inflated = 0", "limits.inflated"),
2960 ("connections = 64", "connections = 0", "limits.connections"),
2961 (
2962 "connections = 64",
2963 "connections = 65537",
2964 "limits.connections",
2965 ),
2966 (
2967 "calls_per_second = 20",
2968 "calls_per_second = 0",
2969 "mcp.calls_per_second",
2970 ),
2971 ("concurrent = 8", "concurrent = 0", "mcp.concurrent"),
2972 (
2973 "response_bytes = 262144",
2974 "response_bytes = 0",
2975 "mcp.response_bytes",
2976 ),
2977 (
2978 "concurrent = 8",
2979 "concurrent = 4294967296",
2980 "mcp.concurrent",
2981 ),
2982 ("read = 30", "read = 0", "limits.timeouts.read"),
2983 ("read = 30", "read = -1", "read"),
2984 (
2985 "handshake = 5",
2986 "handshake = 0",
2987 "limits.timeouts.handshake",
2988 ),
2989 (
2990 "handshake = 5",
2991 "handshake = 3601",
2992 "limits.timeouts.handshake",
2993 ),
2994 ("handshake = 5", "handshake = \"5s\"", "handshake"),
2995 (
2996 "first_head = 15",
2997 "first_head = 0",
2998 "limits.timeouts.first_head",
2999 ),
3000 (
3001 "first_head = 15",
3002 "first_head = 3601",
3003 "limits.timeouts.first_head",
3004 ),
3005 ("first_head = 15", "first_head = 1.5", "first_head"),
3006 ("\nhead = 20", "\nhead = 0", "limits.timeouts.head"),
3007 ("\nhead = 20", "\nhead = 3601", "limits.timeouts.head"),
3008 ("\nhead = 20", "\nhead = 18446744073709551615", "head"),
3009 ("idle = 90", "idle = 0", "limits.timeouts.idle"),
3010 ("idle = 90", "idle = 3601", "limits.timeouts.idle"),
3011 ("idle = 90", "idle = \"2m\"", "idle"),
3012 ] {
3013 let error = parse(&FULL.replace(from, to)).expect_err(key);
3014 assert!(error.0.contains(key), "{key}: {error}");
3015 }
3016 }
3017
3018 mod site_page {
3022 use super::*;
3023
3024 fn page(name: &str) -> String {
3025 let path = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
3026 .join("../../website/content/docs")
3027 .join(name);
3028 std::fs::read_to_string(&path).unwrap_or_else(|e| panic!("{}: {e}", path.display()))
3029 }
3030
3031 pub(super) fn keys(table: &toml::Table, prefix: &str, out: &mut Vec<String>) {
3033 for (key, value) in table {
3034 let name = format!("{prefix}{key}");
3035 match value {
3036 toml::Value::Table(inner) => keys(inner, &format!("{name}."), out),
3037 _ => out.push(name),
3038 }
3039 }
3040 }
3041
3042 fn row<'a>(text: &'a str, key: &str) -> &'a str {
3044 let start = format!("| `{key}` |");
3045 let mut rows = text.lines().filter(|l| l.starts_with(&start));
3046 let row = rows.next().unwrap_or_else(|| panic!("no row for {key}"));
3047 assert!(rows.next().is_none(), "two rows for {key}");
3048 row
3049 }
3050
3051 #[test]
3052 fn every_key_is_listed_with_its_default() {
3053 let text = page("configuration.md");
3054 let mut all = Vec::new();
3055 keys(&FULL.parse::<toml::Table>().expect("toml"), "", &mut all);
3056 assert_eq!(all.len(), 64, "{all:?}");
3057 for key in all {
3058 let default = default_text(&key)
3059 .unwrap_or_else(|| panic!("a key this test does not know: {key}"));
3060 let row = row(&text, &key);
3061 let last = row
3062 .trim_end_matches('|')
3063 .rsplit('|')
3064 .next()
3065 .expect("a last cell")
3066 .trim();
3067 assert!(
3068 last.starts_with(&default),
3069 "{key}: `{last}` is not {default}"
3070 );
3071 }
3072 }
3073
3074 pub(super) fn default_text(key: &str) -> Option<String> {
3079 let defaults = parse(LEAST).expect("least");
3080 let pg = catalog::postgres_least();
3081 Some(match key {
3082 "listen" | "data_dir" | "master_key" | "tls.cert" | "tls.key" => {
3083 "required".to_owned()
3084 }
3085 "operator.listen" => "none: `listen` serves both".to_owned(),
3086 "operator.tls.cert" => "`tls.cert`".to_owned(),
3087 "operator.tls.key" => "`tls.key`".to_owned(),
3088 "public_origin" | "operator.public_origin" => {
3089 assert_eq!(defaults.public_origin, None, "the page says none");
3090 "none: the listener serves no session".to_owned()
3091 }
3092 "retention_default" => format!("`{}`", defaults.retention_default),
3093 "purge_interval" => format!("`{}`", defaults.purge_interval.as_secs()),
3094 "rotation_warn" => format!("`{}`", defaults.rotation_warn.as_secs()),
3095 "limits.body" => format!("`{}`", defaults.body_limit),
3096 "limits.inflated" => format!("`{}`", defaults.inflated_limit),
3097 "limits.connections" => format!("`{}`", defaults.connection.max),
3098 "limits.csp_reports" => format!("`{}`", defaults.reports.per_minute),
3099 "limits.csp_reports_per_address" => {
3100 format!("`{}`", defaults.reports.per_address)
3101 }
3102 "limits.timeouts.read" => format!("`{}`", defaults.read_timeout.as_secs()),
3103 "limits.timeouts.handshake" => {
3104 format!("`{}`", defaults.connection.handshake.as_secs())
3105 }
3106 "limits.timeouts.first_head" => {
3107 format!("`{}`", defaults.connection.first_head.as_secs())
3108 }
3109 "limits.timeouts.head" => format!("`{}`", defaults.connection.head.as_secs()),
3110 "limits.timeouts.idle" => format!("`{}`", defaults.connection.idle.as_secs()),
3111 "keys.no_expiry" => format!("`{}`", defaults.keys_no_expiry),
3112 "mcp.calls_per_second" => format!("`{}`", defaults.mcp.calls_per_second),
3113 "mcp.concurrent" => format!("`{}`", defaults.mcp.concurrent),
3114 "mcp.response_bytes" => format!("`{}`", defaults.mcp.response_bytes),
3115 "storage.objects" => "`local`".to_owned(),
3116 "storage.s3.region" | "storage.s3.bucket" => "required with `s3`".to_owned(),
3117 "storage.s3.endpoint"
3118 | "storage.s3.access_key_id"
3119 | "storage.s3.secret_access_key_file"
3120 | "storage.s3.ca_file" => "none".to_owned(),
3121 "storage.s3.prefix" => "empty".to_owned(),
3122 "storage.s3.path_style" => format!("`{}`", s3_least().path_style),
3123 "storage.s3.allow_http" => format!("`{}`", s3_least().allow_http),
3124 "storage.s3.allow_versioning" => {
3125 format!("`{}`", s3_least().allow_versioning)
3126 }
3127 "storage.s3.timeout" => format!("`{}`", s3_least().timeout.as_secs()),
3128 "storage.parquet.pack_interval" => {
3129 format!("`{}`", parquet_least().pack_interval.as_secs())
3130 }
3131 "storage.parquet.pack_limit" => format!("`{}`", parquet_least().pack_limit),
3132 "storage.parquet.reader_grace" => {
3133 format!("`{}`", parquet_least().reader_grace.as_secs())
3134 }
3135 "export.s3.region" => "required with `export.s3`".to_owned(),
3136 "export.s3.endpoint"
3137 | "export.s3.access_key_id"
3138 | "export.s3.secret_access_key_file"
3139 | "export.s3.ca_file" => "none".to_owned(),
3140 "export.s3.path_style" => format!("`{}`", s3_least().path_style),
3141 "export.s3.allow_http" => format!("`{}`", s3_least().allow_http),
3142 "export.s3.timeout" => format!("`{}`", S3_TIMEOUT.as_secs()),
3143 "catalog.backend" => "`local`".to_owned(),
3144 "catalog.postgres.hosts" | "catalog.postgres.dbname" | "catalog.postgres.user" => {
3145 "required with `postgres`".to_owned()
3146 }
3147 "catalog.postgres.ca_file"
3148 | "catalog.postgres.password_file"
3149 | "catalog.postgres.client_cert_file"
3150 | "catalog.postgres.client_key_file" => "none".to_owned(),
3151 "catalog.postgres.port" => format!("`{}`", pg.port),
3152 "catalog.postgres.pool" => format!("`{}`", pg.pool),
3153 "catalog.postgres.connect_timeout" => {
3154 format!("`{}`", pg.connect_timeout.as_secs())
3155 }
3156 "catalog.postgres.statement_timeout" => {
3157 format!("`{}`", pg.statement_timeout.as_secs())
3158 }
3159 "catalog.postgres.lock_timeout" => {
3160 format!("`{}`", pg.lock_timeout.as_secs())
3161 }
3162 "supported_critical" => {
3163 assert!(
3164 defaults.supported_critical.is_empty(),
3165 "the page says none, which holds only while the default is empty"
3166 );
3167 "none".to_owned()
3168 }
3169 _ => return None,
3170 })
3171 }
3172
3173 #[test]
3175 fn every_fixed_limit_is_listed_with_its_value() {
3176 let text = page("configuration.md");
3177 for (limit, value) in [
3178 ("Signed layers in one body", vcon::read::MAX_SIGNED_LAYERS),
3179 (
3180 "Arrays and objects open at once",
3181 vcon::read::MAX_JSON_DEPTH,
3182 ),
3183 ] {
3184 let start = format!("| {limit} |");
3185 let rows: Vec<&str> = text.lines().filter(|l| l.starts_with(&start)).collect();
3186 assert_eq!(rows.len(), 1, "one row for {limit}");
3187 let cell = rows[0].split('|').nth(2).expect("a value cell").trim();
3188 assert_eq!(cell, format!("`{value}`"), "{limit}");
3189 }
3190 }
3191
3192 #[test]
3193 fn every_example_file_on_the_site_reads() {
3194 let mut examples = 0;
3195 for name in [
3196 "configuration.md",
3197 "getting-started.md",
3198 "container.md",
3199 "postgres-catalog.md",
3200 ] {
3201 let text = page(name);
3202 for block in text.split("```toml\n").skip(1) {
3203 let toml = block.split("```").next().expect("a block");
3204 parse(toml).unwrap_or_else(|e| panic!("{name}: {e}\n{toml}"));
3205 examples += 1;
3206 }
3207 }
3208 assert_eq!(
3209 examples, 7,
3210 "four on the configuration page, one each on getting started, the \
3211 container page and the PostgreSQL catalog page, so a block the split misses \
3212 is caught"
3213 );
3214 }
3215 }
3216
3217 mod catalog {
3220 use super::*;
3221
3222 pub(super) fn postgres_text() -> String {
3226 format!(
3227 "{LEAST}\n[storage]\nobjects = \"s3\"\n\n[storage.s3]\nregion = \"us-east-1\"\n\
3228 bucket = \"vcon\"\n\n[catalog]\nbackend = \"postgres\"\n\n[catalog.postgres]\n\
3229 hosts = [\"db1.example.com\"]\ndbname = \"vcon\"\nuser = \"vcon_app\"\n\
3230 password_file = \"/etc/vcon-server/pg.password\"\n"
3231 )
3232 }
3233
3234 fn edited(from: &str, to: &str) -> String {
3236 let text = postgres_text();
3237 assert!(text.contains(from), "the least text holds {from:?}");
3238 text.replace(from, to)
3239 }
3240
3241 fn with(line: &str) -> String {
3243 format!("{}{line}\n", postgres_text())
3244 }
3245
3246 fn postgres(text: &str) -> PostgresSettings {
3248 match parse(text)
3249 .unwrap_or_else(|e| panic!("{e}\n{text}"))
3250 .catalog
3251 {
3252 CatalogStore::Postgres(pg) => *pg,
3253 CatalogStore::Local => panic!("backend = \"postgres\" keeps the catalogs there"),
3254 }
3255 }
3256
3257 pub(super) fn postgres_least() -> PostgresSettings {
3259 postgres(&postgres_text())
3260 }
3261
3262 fn refused(text: &str) -> String {
3264 parse(text).expect_err(text).0
3265 }
3266
3267 mod success {
3268 use super::*;
3269
3270 #[test]
3271 fn a_postgres_catalog_is_read_with_its_defaults() {
3272 assert_eq!(
3273 postgres_least(),
3274 PostgresSettings {
3275 hosts: vec!["db1.example.com".to_owned()],
3276 port: 5432,
3277 dbname: "vcon".to_owned(),
3278 user: "vcon_app".to_owned(),
3279 ca_file: None,
3280 password_file: Some("/etc/vcon-server/pg.password".into()),
3281 client_cert_file: None,
3282 client_key_file: None,
3283 pool: 16,
3284 connect_timeout: Duration::from_secs(5),
3285 statement_timeout: Duration::from_secs(30),
3286 lock_timeout: Duration::from_secs(10),
3287 },
3288 "only hosts, dbname, user and a way to log in are required"
3289 );
3290 }
3291
3292 #[test]
3293 fn without_a_catalog_table_the_catalogs_are_local() {
3294 assert_eq!(
3295 parse(LEAST).expect("parses").catalog,
3296 CatalogStore::Local,
3297 "a file written before the PostgreSQL catalog keeps its meaning"
3298 );
3299 }
3300
3301 #[test]
3302 fn backend_local_is_the_local_catalog() {
3303 let text = format!("{LEAST}\n[catalog]\nbackend = \"local\"\n");
3304 assert_eq!(
3305 parse(&text).expect("parses").catalog,
3306 CatalogStore::Local,
3307 "\"local\" names the default"
3308 );
3309 }
3310
3311 #[test]
3312 fn a_client_certificate_alone_is_enough_to_log_in() {
3313 let text = edited(
3314 "password_file = \"/etc/vcon-server/pg.password\"\n",
3315 "client_cert_file = \"/c.pem\"\nclient_key_file = \"/c.key\"\n",
3316 );
3317 let pg = postgres(&text);
3318 assert_eq!(
3319 (pg.password_file, pg.client_cert_file, pg.client_key_file),
3320 (None, Some("/c.pem".into()), Some("/c.key".into())),
3321 "a certificate and its key, with no password"
3322 );
3323 }
3324
3325 #[test]
3326 fn a_password_and_a_client_certificate_are_read_together() {
3327 let pg = postgres(&with(
3328 "client_cert_file = \"/c.pem\"\nclient_key_file = \"/c.key\"",
3329 ));
3330 assert!(
3331 pg.password_file.is_some() && pg.client_cert_file.is_some(),
3332 "both ways of logging in, as pg_hba.conf's clientcert=verify-full asks"
3333 );
3334 }
3335
3336 #[test]
3337 fn several_hosts_are_kept_in_their_order() {
3338 let text = edited(
3339 "hosts = [\"db1.example.com\"]",
3340 "hosts = [\"db2.example.com\", \"db1.example.com\", \"192.0.2.10\"]",
3341 );
3342 assert_eq!(
3343 postgres(&text).hosts,
3344 ["db2.example.com", "db1.example.com", "192.0.2.10"],
3345 "tried in the order written"
3346 );
3347 }
3348
3349 #[test]
3350 fn parquet_storage_with_a_postgres_catalog_is_read() {
3351 let text = edited(
3352 "bucket = \"vcon\"\n",
3353 "bucket = \"vcon\"\n\n[storage.parquet]\n",
3354 );
3355 let config = parse(&text).expect("parses");
3356 assert!(
3357 config.storage.parquet.is_some()
3358 && matches!(config.catalog, CatalogStore::Postgres(_)),
3359 "Parquet files in the bucket and the catalogs in PostgreSQL"
3360 );
3361 }
3362 }
3363
3364 mod failure {
3365 use super::*;
3366
3367 fn refused_naming(text: &str, names: &[&str]) {
3369 let message = refused(text);
3370 for name in names {
3371 assert!(message.contains(name), "names {name}: {message}");
3372 }
3373 }
3374
3375 #[test]
3376 fn an_unknown_backend_is_named() {
3377 refused_naming(
3378 &edited("backend = \"postgres\"", "backend = \"mysql\""),
3379 &["catalog.backend", "\"mysql\""],
3380 );
3381 }
3382
3383 #[test]
3384 fn a_postgres_table_without_the_postgres_backend_is_refused() {
3385 refused_naming(
3386 &edited("backend = \"postgres\"", "backend = \"local\""),
3387 &["catalog.postgres", "catalog.backend"],
3388 );
3389 }
3390
3391 #[test]
3392 fn the_postgres_backend_without_its_table_is_refused() {
3393 let text = format!(
3394 "{LEAST}\n[storage]\nobjects = \"s3\"\n[storage.s3]\nregion = \"us-east-1\"\n\
3395 bucket = \"vcon\"\n[catalog]\nbackend = \"postgres\"\n"
3396 );
3397 refused_naming(&text, &["catalog.postgres"]);
3398 }
3399
3400 #[test]
3401 fn a_postgres_catalog_with_local_objects_is_refused() {
3402 let text = format!(
3403 "{LEAST}\n[catalog]\nbackend = \"postgres\"\n[catalog.postgres]\n\
3404 hosts = [\"db1.example.com\"]\ndbname = \"vcon\"\nuser = \"vcon_app\"\n\
3405 password_file = \"/p\"\n"
3406 );
3407 refused_naming(&text, &["catalog.backend", "storage.objects", "\"s3\""]);
3408 }
3409
3410 #[test]
3411 fn an_empty_host_list_is_refused() {
3412 refused_naming(
3413 &edited("hosts = [\"db1.example.com\"]", "hosts = []"),
3414 &["catalog.postgres.hosts"],
3415 );
3416 }
3417
3418 #[test]
3419 fn an_empty_host_name_is_refused() {
3420 refused_naming(
3421 &edited("hosts = [\"db1.example.com\"]", "hosts = [\"\"]"),
3422 &["catalog.postgres.hosts"],
3423 );
3424 }
3425
3426 #[test]
3427 fn a_host_that_is_not_a_dns_name_is_refused() {
3428 for host in [
3429 "db_1.example.com",
3430 "db..example.com",
3431 "-db.example.com",
3432 "db .example.com",
3433 ] {
3434 refused_naming(
3435 &edited("\"db1.example.com\"", &format!("{host:?}")),
3436 &["catalog.postgres.hosts", host],
3437 );
3438 }
3439 }
3440
3441 #[test]
3442 fn a_missing_host_list_is_named() {
3443 refused_naming(&edited("hosts = [\"db1.example.com\"]\n", ""), &["hosts"]);
3444 }
3445
3446 #[test]
3447 fn a_port_of_zero_is_refused() {
3448 refused_naming(&with("port = 0"), &["catalog.postgres.port"]);
3449 }
3450
3451 #[test]
3452 fn a_port_above_65535_is_refused() {
3453 refused_naming(&with("port = 65536"), &["catalog.postgres.port"]);
3454 }
3455
3456 #[test]
3457 fn an_empty_database_name_is_refused() {
3458 refused_naming(
3459 &edited("dbname = \"vcon\"", "dbname = \"\""),
3460 &["catalog.postgres.dbname"],
3461 );
3462 }
3463
3464 #[test]
3465 fn a_missing_database_name_is_named() {
3466 refused_naming(&edited("dbname = \"vcon\"\n", ""), &["dbname"]);
3467 }
3468
3469 #[test]
3470 fn an_empty_user_is_refused() {
3471 refused_naming(
3472 &edited("user = \"vcon_app\"", "user = \"\""),
3473 &["catalog.postgres.user"],
3474 );
3475 }
3476
3477 #[test]
3478 fn a_missing_user_is_named() {
3479 refused_naming(&edited("user = \"vcon_app\"\n", ""), &["user"]);
3480 }
3481
3482 #[test]
3483 fn no_password_and_no_client_certificate_is_refused() {
3484 refused_naming(
3485 &edited("password_file = \"/etc/vcon-server/pg.password\"\n", ""),
3486 &[
3487 "catalog.postgres.password_file",
3488 "catalog.postgres.client_cert_file",
3489 ],
3490 );
3491 }
3492
3493 #[test]
3494 fn a_client_certificate_without_its_key_is_refused() {
3495 refused_naming(
3496 &with("client_cert_file = \"/c.pem\""),
3497 &["catalog.postgres.client_key_file"],
3498 );
3499 }
3500
3501 #[test]
3502 fn a_client_key_without_its_certificate_is_refused() {
3503 refused_naming(
3504 &with("client_key_file = \"/c.key\""),
3505 &["catalog.postgres.client_cert_file"],
3506 );
3507 }
3508
3509 #[test]
3510 fn an_empty_file_name_is_refused() {
3511 for (key, text) in [
3512 ("ca_file", with("ca_file = \"\"")),
3513 (
3514 "password_file",
3515 edited("\"/etc/vcon-server/pg.password\"", "\"\""),
3516 ),
3517 (
3518 "client_cert_file",
3519 with("client_cert_file = \"\"\nclient_key_file = \"/c.key\""),
3520 ),
3521 (
3522 "client_key_file",
3523 with("client_cert_file = \"/c.pem\"\nclient_key_file = \"\""),
3524 ),
3525 ] {
3526 refused_naming(&text, &[&format!("catalog.postgres.{key}")]);
3527 }
3528 }
3529
3530 #[test]
3531 fn a_pool_of_zero_is_refused() {
3532 refused_naming(&with("pool = 0"), &["catalog.postgres.pool"]);
3533 }
3534
3535 #[test]
3536 fn a_pool_too_large_to_count_is_refused() {
3537 refused_naming(&with("pool = 4294967296"), &["catalog.postgres.pool"]);
3538 }
3539
3540 #[test]
3541 fn a_connect_timeout_of_zero_is_refused() {
3542 refused_naming(
3543 &with("connect_timeout = 0"),
3544 &["catalog.postgres.connect_timeout"],
3545 );
3546 }
3547
3548 #[test]
3549 fn a_statement_timeout_of_zero_is_refused() {
3550 refused_naming(
3551 &with("statement_timeout = 0"),
3552 &["catalog.postgres.statement_timeout"],
3553 );
3554 }
3555
3556 #[test]
3557 fn a_lock_timeout_of_zero_is_refused() {
3558 refused_naming(
3559 &with("lock_timeout = 0"),
3560 &["catalog.postgres.lock_timeout"],
3561 );
3562 }
3563
3564 #[test]
3566 fn an_sslmode_key_is_an_unknown_key() {
3567 refused_naming(&with("sslmode = \"disable\""), &["`sslmode`"]);
3568 }
3569
3570 #[test]
3571 fn an_unknown_key_in_the_catalog_table_is_named() {
3572 refused_naming(
3573 &edited(
3574 "backend = \"postgres\"",
3575 "backend = \"postgres\"\nreplicas = 2",
3576 ),
3577 &["`replicas`"],
3578 );
3579 }
3580 }
3581
3582 mod edge {
3583 use super::*;
3584
3585 fn host_text(host: &str) -> String {
3586 edited("\"db1.example.com\"", &format!("{host:?}"))
3587 }
3588
3589 #[test]
3590 fn ipv6_hosts_are_read() {
3591 for host in ["2001:db8::10", "::1", "2001:db8:0:0:0:0:0:10"] {
3592 assert_eq!(
3593 postgres(&host_text(host)).hosts,
3594 [host],
3595 "an IPv6 address is a host as written"
3596 );
3597 }
3598 }
3599
3600 #[test]
3601 fn a_bracketed_ipv6_host_is_refused_with_its_bare_form() {
3602 let message = refused(&host_text("[2001:db8::10]"));
3603 assert!(
3604 message.contains("catalog.postgres.hosts")
3605 && message.contains("\"2001:db8::10\""),
3606 "names the key and the form to write: {message}"
3607 );
3608 }
3609
3610 #[test]
3613 fn a_unix_socket_host_is_refused_because_tls_is_required() {
3614 let message = refused(&host_text("/var/run/postgresql"));
3615 assert!(
3616 message.contains("catalog.postgres.hosts")
3617 && message.contains("Unix socket")
3618 && message.contains("TLS"),
3619 "says why: {message}"
3620 );
3621 }
3622
3623 #[test]
3624 fn a_unicode_host_name_is_refused_with_a_pointer_to_its_ascii_form() {
3625 let message = refused(&host_text("bücher.example.com"));
3626 assert!(
3627 message.contains("catalog.postgres.hosts") && message.contains("xn--"),
3628 "an internationalized name is written in its xn-- form: {message}"
3629 );
3630 }
3631
3632 #[test]
3633 fn an_ascii_form_of_a_unicode_host_name_is_read() {
3634 assert_eq!(
3635 postgres(&host_text("xn--bcher-kva.example.com")).hosts,
3636 ["xn--bcher-kva.example.com"],
3637 "the xn-- form is a DNS name"
3638 );
3639 }
3640
3641 #[test]
3642 fn unicode_database_and_role_names_are_read() {
3643 let text = edited("dbname = \"vcon\"", "dbname = \"vcon_数据\"")
3644 .replace("user = \"vcon_app\"", "user = \"vcon_ünï\"");
3645 let pg = postgres(&text);
3646 assert_eq!(
3647 (pg.dbname.as_str(), pg.user.as_str()),
3648 ("vcon_数据", "vcon_ünï"),
3649 "PostgreSQL names may hold any character but NUL"
3650 );
3651 }
3652
3653 #[test]
3656 fn a_name_of_63_bytes_is_read_and_one_of_64_refused() {
3657 let at_limit = "数".repeat(21);
3658 assert_eq!(at_limit.len(), 63, "21 three-byte characters");
3659 for key in ["dbname", "user"] {
3660 let line = |name: &str| format!("{key} = \"{name}\"");
3661 let from = if key == "dbname" {
3662 "dbname = \"vcon\""
3663 } else {
3664 "user = \"vcon_app\""
3665 };
3666 let pg = postgres(&edited(from, &line(&at_limit)));
3667 let read = if key == "dbname" { pg.dbname } else { pg.user };
3668 assert_eq!(read, at_limit, "{key}: 63 bytes is PostgreSQL's limit");
3669 let message = refused(&edited(from, &line(&format!("{at_limit}a"))));
3670 assert!(
3671 message.contains(&format!("catalog.postgres.{key}"))
3672 && message.contains("63 bytes"),
3673 "{key}: {message}"
3674 );
3675 }
3676 }
3677
3678 #[test]
3679 fn a_nul_in_a_name_is_refused() {
3680 for (from, to, key) in [
3681 ("dbname = \"vcon\"", "dbname = \"vc\\u0000on\"", "dbname"),
3682 ("user = \"vcon_app\"", "user = \"vcon\\u0000\"", "user"),
3683 ] {
3684 let message = refused(&edited(from, to));
3685 assert!(
3686 message.contains(&format!("catalog.postgres.{key}"))
3687 && message.contains("NUL"),
3688 "{key}: {message}"
3689 );
3690 }
3691 }
3692
3693 #[test]
3694 fn the_first_and_last_ports_are_read() {
3695 for port in [1, 65535] {
3696 assert_eq!(
3697 u64::from(postgres(&with(&format!("port = {port}"))).port),
3698 port,
3699 "every TCP port but 0"
3700 );
3701 }
3702 }
3703
3704 #[test]
3707 fn timeouts_at_the_postgresql_limit_are_read_and_one_past_refused() {
3708 for key in ["statement_timeout", "lock_timeout"] {
3709 let pg = postgres(&with(&format!("{key} = 2147483")));
3710 let read = if key == "statement_timeout" {
3711 pg.statement_timeout
3712 } else {
3713 pg.lock_timeout
3714 };
3715 assert_eq!(read, Duration::from_secs(2_147_483), "{key} at the limit");
3716 let message = refused(&with(&format!("{key} = 2147484")));
3717 assert!(
3718 message.contains(&format!("catalog.postgres.{key}"))
3719 && message.contains("2147483"),
3720 "{key}: {message}"
3721 );
3722 }
3723 }
3724
3725 #[test]
3726 fn a_one_second_connect_timeout_is_read() {
3727 assert_eq!(
3728 postgres(&with("connect_timeout = 1")).connect_timeout,
3729 Duration::from_secs(1),
3730 "the shortest timeout"
3731 );
3732 }
3733
3734 #[test]
3735 fn the_same_host_twice_is_refused() {
3736 let message = refused(&edited(
3737 "hosts = [\"db1.example.com\"]",
3738 "hosts = [\"db1.example.com\", \"DB1.example.com\"]",
3739 ));
3740 assert!(
3741 message.contains("catalog.postgres.hosts") && message.contains("twice"),
3742 "a DNS name in any case is one host: {message}"
3743 );
3744 }
3745
3746 #[test]
3747 fn a_dns_label_of_63_characters_is_read_and_one_of_64_refused() {
3748 let label = "a".repeat(63);
3749 let host = format!("{label}.example.com");
3750 assert_eq!(
3751 postgres(&host_text(&host)).hosts,
3752 [host],
3753 "63 is the DNS limit"
3754 );
3755 let message = refused(&host_text(&format!("a{label}.example.com")));
3756 assert!(message.contains("catalog.postgres.hosts"), "{message}");
3757 }
3758
3759 #[test]
3760 fn a_host_name_of_more_than_253_characters_is_refused() {
3761 let label = "a".repeat(63);
3762 let at_limit = format!("{label}.{label}.{label}.{}", "a".repeat(61));
3763 assert_eq!(at_limit.len(), 253, "four labels");
3764 assert_eq!(
3765 postgres(&host_text(&at_limit)).hosts,
3766 std::slice::from_ref(&at_limit),
3767 "253 characters is the DNS limit"
3768 );
3769 let message = refused(&host_text(&format!("a{at_limit}")));
3770 assert!(message.contains("catalog.postgres.hosts"), "{message}");
3771 }
3772
3773 #[test]
3774 fn a_port_written_in_a_host_is_refused_with_the_port_key_named() {
3775 let message = refused(&host_text("db1.example.com:5432"));
3776 assert!(
3777 message.contains("catalog.postgres.hosts")
3778 && message.contains("catalog.postgres.port"),
3779 "the port has its own key: {message}"
3780 );
3781 }
3782 }
3783 }
3784
3785 #[test]
3786 fn a_missing_file_is_named() {
3787 let error = load(Path::new("/nonexistent/vcon-server.toml")).expect_err("missing");
3788 assert!(error.0.contains("/nonexistent/vcon-server.toml"), "{error}");
3789 }
3790
3791 mod contract {
3801 use super::*;
3802 use std::collections::BTreeMap;
3803
3804 const WRITE: &str = "VCON_SERVER_WRITE_CONTRACT";
3807
3808 const REGENERATE: &str =
3810 "VCON_SERVER_WRITE_CONTRACT=1 cargo test -p vcon-server --lib config::tests::contract";
3811
3812 const SNAPSHOT: &str = "contract/config.json";
3814
3815 const ALWAYS: &str = "always";
3817 const WITH_TABLE: &str = "with its table";
3819 const NO: &str = "no";
3821
3822 fn root() -> std::path::PathBuf {
3823 std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../..")
3824 }
3825
3826 fn type_name(value: &toml::Value) -> String {
3830 match value {
3831 toml::Value::String(_) => "string".to_owned(),
3832 toml::Value::Integer(_) => "integer".to_owned(),
3833 toml::Value::Float(_) => "float".to_owned(),
3834 toml::Value::Boolean(_) => "boolean".to_owned(),
3835 toml::Value::Datetime(_) => "datetime".to_owned(),
3836 toml::Value::Table(_) => "table".to_owned(),
3837 toml::Value::Array(items) => {
3838 let mut kinds = items.iter().map(type_name);
3839 match kinds.next() {
3840 Some(first) if kinds.all(|k| k == first) => format!("array of {first}"),
3841 _ => "array".to_owned(),
3842 }
3843 }
3844 }
3845 }
3846
3847 fn without(table: &toml::Table, key: &str) -> toml::Table {
3849 let mut out = table.clone();
3850 let (head, rest) = key
3851 .split_once('.')
3852 .map_or((key, None), |(h, r)| (h, Some(r)));
3853 match rest {
3854 None => {
3855 out.remove(head);
3856 }
3857 Some(rest) => {
3858 if let Some(toml::Value::Table(inner)) = out.get_mut(head) {
3859 *inner = without(inner, rest);
3860 }
3861 }
3862 }
3863 out
3864 }
3865
3866 fn has(table: &toml::Table, key: &str) -> bool {
3868 lookup(table, key).is_some()
3869 }
3870
3871 fn required(
3877 key: &str,
3878 full: &toml::Table,
3879 least: &toml::Table,
3880 load: impl Fn(&str) -> Result<(), String>,
3881 ) -> &'static str {
3882 if has(least, key) {
3883 return ALWAYS;
3884 }
3885 let text = toml::to_string(&without(full, key)).expect("a table writes as TOML");
3886 let leaf = key.rsplit('.').next().unwrap_or(key);
3887 match load(&text) {
3888 Err(e) if e.contains(&format!("missing field `{leaf}`")) => WITH_TABLE,
3889 _ => NO,
3890 }
3891 }
3892
3893 struct Entry {
3895 key: String,
3896 kind: String,
3897 required: &'static str,
3898 default: Option<String>,
3899 }
3900
3901 fn render(entries: &[Entry]) -> String {
3905 let keys: BTreeMap<&str, serde_json::Value> = entries
3906 .iter()
3907 .map(|e| {
3908 let default = if e.required == NO {
3909 e.default.clone()
3910 } else {
3911 None
3912 };
3913 let entry: BTreeMap<&str, serde_json::Value> = [
3914 ("default", serde_json::json!(default)),
3915 ("required", serde_json::json!(e.required)),
3916 ("type", serde_json::json!(e.kind)),
3917 ]
3918 .into_iter()
3919 .collect();
3920 (e.key.as_str(), serde_json::json!(entry))
3921 })
3922 .collect();
3923 let mut text =
3924 serde_json::to_string_pretty(&serde_json::json!({ "keys": keys })).expect("JSON");
3925 text.push('\n');
3926 text
3927 }
3928
3929 fn stale(file: &str, now: &str) -> String {
3932 snapshot::stale(
3933 SNAPSHOT,
3934 "the configuration code reads",
3935 REGENERATE,
3936 file,
3937 now,
3938 )
3939 }
3940
3941 mod snapshot {
3943 include!("../tests/support/contract_snapshot.rs");
3944 }
3945
3946 fn dotted(table: &toml::Table) -> Vec<String> {
3948 let mut all = Vec::new();
3949 super::site_page::keys(table, "", &mut all);
3950 all.sort();
3951 all
3952 }
3953
3954 fn loads(text: &str) -> Result<(), String> {
3955 parse(text).map(|_| ()).map_err(|e| e.0)
3956 }
3957
3958 fn entries_now() -> Vec<Entry> {
3961 let full: toml::Table = FULL.parse().expect("FULL is TOML");
3962 let least: toml::Table = LEAST.parse().expect("LEAST is TOML");
3963 dotted(&full)
3964 .into_iter()
3965 .map(|key| {
3966 let value = lookup(&full, &key).expect("a key of FULL");
3967 let required = required(&key, &full, &least, loads);
3968 let default = super::site_page::default_text(&key)
3969 .unwrap_or_else(|| panic!("no default rule for {key}"));
3970 Entry {
3971 kind: type_name(value),
3972 required,
3973 default: Some(default),
3974 key,
3975 }
3976 })
3977 .collect()
3978 }
3979
3980 fn lookup<'a>(table: &'a toml::Table, key: &str) -> Option<&'a toml::Value> {
3982 let (head, rest) = key
3983 .split_once('.')
3984 .map_or((key, None), |(h, r)| (h, Some(r)));
3985 match (table.get(head)?, rest) {
3986 (value, None) => Some(value),
3987 (toml::Value::Table(inner), Some(rest)) => lookup(inner, rest),
3988 _ => None,
3989 }
3990 }
3991
3992 fn snapshot_now() -> String {
3993 render(&entries_now())
3994 }
3995
3996 fn snapshot_json() -> serde_json::Value {
3997 serde_json::from_str(&snapshot_now()).expect("the rendered snapshot is JSON")
3998 }
3999
4000 fn table(text: &str) -> toml::Table {
4001 text.parse().expect("TOML")
4002 }
4003
4004 #[test]
4007 fn the_snapshot_is_what_the_code_reads() {
4008 let now = snapshot_now();
4009 let path = root().join(SNAPSHOT);
4010 if std::env::var_os(WRITE).is_some() {
4011 std::fs::create_dir_all(path.parent().expect("a parent")).expect("contract/");
4012 std::fs::write(&path, &now).expect("the snapshot is written");
4013 return;
4014 }
4015 let file = std::fs::read_to_string(&path).unwrap_or_default();
4016 assert!(file == now, "{}", stale(&file, &now));
4017 }
4018
4019 #[test]
4020 fn every_key_of_the_full_file_is_in_the_snapshot() {
4021 let d = snapshot_json();
4022 let keys = d["keys"].as_object().expect("a keys object");
4023 assert_eq!(keys.len(), 64, "FULL sets 64 keys: {keys:?}");
4024 assert!(
4025 keys.contains_key("catalog.postgres.lock_timeout"),
4026 "a nested key is dotted"
4027 );
4028 }
4029
4030 #[test]
4031 fn the_keys_of_the_least_file_are_always_required() {
4032 let d = snapshot_json();
4033 for key in ["listen", "data_dir", "master_key", "tls.cert", "tls.key"] {
4034 assert_eq!(d["keys"][key]["required"], ALWAYS, "{key} is in LEAST");
4035 }
4036 }
4037
4038 #[test]
4039 fn exactly_these_keys_are_required() {
4040 let d = snapshot_json();
4041 let found: BTreeMap<String, String> = d["keys"]
4042 .as_object()
4043 .expect("a keys object")
4044 .iter()
4045 .filter(|(_, v)| v["required"] != NO)
4046 .map(|(k, v)| (k.clone(), v["required"].as_str().expect("text").to_owned()))
4047 .collect();
4048 let expected: BTreeMap<String, String> = [
4049 ("catalog.postgres.dbname", WITH_TABLE),
4050 ("catalog.postgres.hosts", WITH_TABLE),
4051 ("catalog.postgres.user", WITH_TABLE),
4052 ("data_dir", ALWAYS),
4053 ("export.s3.region", WITH_TABLE),
4054 ("listen", ALWAYS),
4055 ("master_key", ALWAYS),
4056 ("operator.listen", WITH_TABLE),
4057 ("operator.tls.cert", WITH_TABLE),
4058 ("operator.tls.key", WITH_TABLE),
4059 ("storage.s3.bucket", WITH_TABLE),
4060 ("storage.s3.region", WITH_TABLE),
4061 ("tls.cert", ALWAYS),
4062 ("tls.key", ALWAYS),
4063 ]
4064 .into_iter()
4065 .map(|(k, v)| (k.to_owned(), v.to_owned()))
4066 .collect();
4067 assert_eq!(
4068 found, expected,
4069 "the keys a file must set, read by loading FULL without each"
4070 );
4071 }
4072
4073 #[test]
4074 fn a_default_is_the_one_the_page_states() {
4075 let d = snapshot_json();
4076 assert_eq!(
4077 d["keys"]["purge_interval"]["default"], "`3600`",
4078 "hourly by default"
4079 );
4080 assert_eq!(
4081 d["keys"]["storage.objects"]["default"], "`local`",
4082 "local objects by default"
4083 );
4084 assert_eq!(
4085 d["keys"]["storage.s3.prefix"]["default"], "empty",
4086 "no prefix by default"
4087 );
4088 }
4089
4090 #[test]
4091 fn types_are_read_from_the_full_file() {
4092 let d = snapshot_json();
4093 for (key, kind) in [
4094 ("listen", "string"),
4095 ("purge_interval", "integer"),
4096 ("keys.no_expiry", "boolean"),
4097 ("supported_critical", "array of string"),
4098 ("catalog.postgres.hosts", "array of string"),
4099 ] {
4100 assert_eq!(d["keys"][key]["type"], kind, "{key}");
4101 }
4102 }
4103
4104 #[test]
4105 fn rendering_twice_gives_the_same_text() {
4106 assert_eq!(snapshot_now(), snapshot_now(), "one build has one snapshot");
4107 }
4108
4109 #[test]
4110 fn the_rendered_snapshot_is_the_shape_contract_diff_reads() {
4111 let d = snapshot_json();
4112 let keys = d["keys"].as_object().expect("a keys object");
4113 for (key, entry) in keys {
4114 let members: Vec<&String> = entry.as_object().expect("an object").keys().collect();
4115 assert_eq!(
4116 members,
4117 ["default", "required", "type"],
4118 "{key}: members in name order"
4119 );
4120 assert!(entry["type"].is_string(), "{key}: a type");
4121 assert!(
4122 [ALWAYS, WITH_TABLE, NO].contains(&entry["required"].as_str().unwrap_or("")),
4123 "{key}: one of the three required states"
4124 );
4125 assert!(
4126 entry["default"].is_string() || entry["default"].is_null(),
4127 "{key}: a default is text or null"
4128 );
4129 }
4130 assert!(
4131 snapshot_now().ends_with("}\n"),
4132 "the file ends with a newline"
4133 );
4134 }
4135
4136 #[test]
4137 fn a_value_type_names_each_toml_kind() {
4138 let t =
4139 table("s = \"x\"\ni = 1\nf = 1.5\nb = true\nd = 1979-05-27\nt = {}\na = [1, 2]\n");
4140 for (key, kind) in [
4141 ("s", "string"),
4142 ("i", "integer"),
4143 ("f", "float"),
4144 ("b", "boolean"),
4145 ("d", "datetime"),
4146 ("t", "table"),
4147 ("a", "array of integer"),
4148 ] {
4149 assert_eq!(type_name(&t[key]), kind, "{key}");
4150 }
4151 }
4152
4153 #[test]
4154 fn a_key_is_removed_from_its_nested_table() {
4155 let t = table("[a.b]\nc = 1\nd = 2\n");
4156 let left = without(&t, "a.b.c");
4157 assert!(!has(&left, "a.b.c"), "the key is gone");
4158 assert!(has(&left, "a.b.d"), "its neighbor stays");
4159 }
4160
4161 #[test]
4164 fn a_stale_snapshot_names_the_command_that_writes_it() {
4165 let message = stale("{\n \"keys\": {}\n}\n", "{\n \"keys\": {\"a\": 1}\n}\n");
4166 assert!(message.contains(REGENERATE), "names the command: {message}");
4167 assert!(message.contains("line 2"), "names the line: {message}");
4168 assert!(message.contains(SNAPSHOT), "names the file: {message}");
4169 }
4170
4171 #[test]
4172 fn a_missing_snapshot_names_the_command_that_writes_it() {
4173 let message = stale("", "{\n}\n");
4174 assert!(
4175 message.contains("line 1"),
4176 "the first line differs: {message}"
4177 );
4178 assert!(
4179 message.contains("(none)"),
4180 "the file has no line: {message}"
4181 );
4182 assert!(message.contains(REGENERATE), "names the command: {message}");
4183 }
4184
4185 #[test]
4186 fn a_snapshot_with_a_line_too_many_is_stale_at_that_line() {
4187 let message = stale("{\n}\nx\n", "{\n}\n");
4188 assert!(
4189 message.contains("line 3"),
4190 "the third line is extra: {message}"
4191 );
4192 assert!(
4193 message.contains("`x` in the file"),
4194 "quotes the extra line: {message}"
4195 );
4196 }
4197
4198 #[test]
4199 fn the_stability_page_names_the_command_and_the_message() {
4200 let page = std::fs::read_to_string(root().join("website/content/docs/stability.md"))
4201 .expect("stability.md");
4202 assert!(page.contains(REGENERATE), "the page shows `{REGENERATE}`");
4203 let message = stale("", "x");
4204 let head = message.split(';').next().expect("a first part");
4205 assert!(page.contains(head), "the page names the message `{head}`");
4206 }
4207
4208 #[test]
4209 fn a_key_no_default_rule_knows_has_none() {
4210 assert_eq!(
4211 super::site_page::default_text("no_such_key"),
4212 None,
4213 "a new key needs its row in the rule, and the snapshot test says so"
4214 );
4215 }
4216
4217 #[test]
4218 fn a_key_whose_removal_is_a_missing_field_is_required_with_its_table() {
4219 let full = table("[t]\nneeded = 1\nfree = 2\n");
4220 let least = table("");
4221 let load = |text: &str| {
4222 if text.contains("needed") {
4223 Ok(())
4224 } else {
4225 Err("missing field `needed`".to_owned())
4226 }
4227 };
4228 assert_eq!(
4229 required("t.needed", &full, &least, load),
4230 WITH_TABLE,
4231 "removing it fails"
4232 );
4233 assert_eq!(
4234 required("t.free", &full, &least, load),
4235 NO,
4236 "removing it loads"
4237 );
4238 }
4239
4240 #[test]
4241 fn a_key_whose_removal_breaks_another_rule_is_not_required() {
4242 let full = table("[t]\npair_a = 1\npair_b = 2\n");
4243 let refused = |_: &str| Err("`t.pair_a` needs `t.pair_b`".to_owned());
4244 assert_eq!(
4245 required("t.pair_b", &full, &table(""), refused),
4246 NO,
4247 "a rule between keys"
4248 );
4249 let other = |_: &str| Err("missing field `pair_c`".to_owned());
4250 assert_eq!(
4251 required("t.pair_b", &full, &table(""), other),
4252 NO,
4253 "another key is missing"
4254 );
4255 }
4256
4257 #[test]
4258 fn removing_a_credential_or_the_backend_from_the_full_file_is_not_required() {
4259 let d = snapshot_json();
4260 for key in [
4261 "catalog.backend",
4262 "storage.objects",
4263 "storage.s3.access_key_id",
4264 "catalog.postgres.client_key_file",
4265 ] {
4266 assert_eq!(
4267 d["keys"][key]["required"], NO,
4268 "{key}: a rule between keys, not a missing field"
4269 );
4270 }
4271 }
4272
4273 #[test]
4274 fn a_key_of_the_least_file_is_required_always_even_if_it_loads_without() {
4275 let full = table("a = 1\nb = 2\n");
4276 let least = table("a = 1\n");
4277 assert_eq!(
4278 required("a", &full, &least, |_| Ok(())),
4279 ALWAYS,
4280 "LEAST decides"
4281 );
4282 let missing = |_: &str| Err("missing field `b`".to_owned());
4283 assert_eq!(
4284 required("b", &full, &least, missing),
4285 WITH_TABLE,
4286 "FULL decides"
4287 );
4288 }
4289
4290 #[test]
4291 fn a_required_key_has_no_default_in_the_snapshot() {
4292 let text = render(&[Entry {
4293 key: "listen".to_owned(),
4294 kind: "string".to_owned(),
4295 required: ALWAYS,
4296 default: Some("required".to_owned()),
4297 }]);
4298 let d: serde_json::Value = serde_json::from_str(&text).expect("JSON");
4299 assert!(d["keys"]["listen"]["default"].is_null(), "required: {text}");
4300 }
4301
4302 #[test]
4303 fn a_missing_key_is_not_had() {
4304 let t = table("[a]\nb = 1\n");
4305 assert!(!has(&t, "a.c"), "no such key");
4306 assert!(!has(&t, "b"), "no such top-level key");
4307 assert!(!has(&t, "a.b.c"), "a value is not a table");
4308 }
4309
4310 #[test]
4313 fn operator_listen_is_required_with_its_table_though_the_page_says_none() {
4314 let d = snapshot_json();
4315 assert_eq!(
4316 d["keys"]["operator.listen"]["required"], WITH_TABLE,
4317 "RawOperator needs it"
4318 );
4319 assert!(
4320 d["keys"]["operator.listen"]["default"].is_null(),
4321 "so it has no default"
4322 );
4323 }
4324
4325 #[test]
4326 fn keys_are_in_name_order() {
4327 let text = snapshot_now();
4328 let d: serde_json::Value = serde_json::from_str(&text).expect("JSON");
4329 let keys: Vec<&String> = d["keys"].as_object().expect("keys").keys().collect();
4330 let mut sorted = keys.clone();
4331 sorted.sort();
4332 assert_eq!(keys, sorted, "name order");
4333 let at = |k: &str| text.find(&format!("\"{k}\"")).expect("in the text");
4334 assert!(
4335 at("catalog.backend") < at("listen"),
4336 "the text is in name order too"
4337 );
4338 }
4339
4340 #[test]
4341 fn removing_the_only_key_of_a_table_leaves_the_table() {
4342 let t = table("[a]\nb = 1\n");
4343 let left = without(&t, "a.b");
4344 assert!(
4345 matches!(left.get("a"), Some(toml::Value::Table(inner)) if inner.is_empty()),
4346 "{left:?}"
4347 );
4348 }
4349
4350 #[test]
4351 fn removing_a_key_that_is_not_there_changes_nothing() {
4352 let t = table("a = 1\n");
4353 assert_eq!(without(&t, "b.c"), t, "nothing to remove");
4354 assert_eq!(without(&t, "a.b"), t, "a value has no keys");
4355 }
4356
4357 #[test]
4358 fn an_array_of_mixed_or_no_items_is_an_array() {
4359 let t = table("m = [1, \"x\"]\ne = []\nn = [[1], [2]]\n");
4360 assert_eq!(type_name(&t["m"]), "array", "mixed items");
4361 assert_eq!(type_name(&t["e"]), "array", "no items");
4362 assert_eq!(
4363 type_name(&t["n"]),
4364 "array of array of integer",
4365 "nested arrays"
4366 );
4367 }
4368
4369 #[test]
4370 fn a_key_with_a_default_of_none_keeps_that_text() {
4371 let d = snapshot_json();
4372 assert_eq!(
4373 d["keys"]["storage.s3.endpoint"]["default"], "none",
4374 "no endpoint: the AWS one"
4375 );
4376 assert_eq!(
4377 d["keys"]["operator.tls.cert"]["required"], WITH_TABLE,
4378 "with [operator.tls]"
4379 );
4380 }
4381
4382 #[test]
4383 fn a_default_from_a_constant_is_in_backticks() {
4384 let d = snapshot_json();
4385 assert_eq!(d["keys"]["export.s3.timeout"]["required"], NO, "optional");
4386 assert!(
4387 d["keys"]["export.s3.timeout"]["default"]
4388 .as_str()
4389 .is_some_and(|s| s.starts_with('`')),
4390 "a value in backticks: {}",
4391 d["keys"]["export.s3.timeout"]["default"]
4392 );
4393 }
4394
4395 #[test]
4396 fn the_full_file_without_an_optional_key_still_loads() {
4397 let full = table(FULL);
4398 let text = toml::to_string(&without(&full, "limits.timeouts.idle")).expect("TOML");
4399 assert_eq!(loads(&text), Ok(()), "an optional key may be left out");
4400 assert!(!text.contains("idle"), "the key is gone: {text}");
4401 }
4402 }
4403}