Skip to main content

vcon_server/
config.rs

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