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