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