Skip to main content

boatramp_node/
config.rs

1//! Local configuration files (RON).
2//!
3//! Two distinct files, split by audience:
4//!
5//! - **`project.cfg`** — one per project folder, read by the client commands
6//!   (`sync`, `build`, `bundle`, `validate`): where/how to publish, the optional
7//!   build/bundle steps, and the deploy-scoped `routing` config that is folded
8//!   into the immutable deployment manifest. See [`ProjectConfig`].
9//! - **`boatramp.cfg`** — the server daemon config, read by `serve`:
10//!   `serve` / `handlers` / `cluster`. See [`ServerConfig`].
11//!
12//! Both are RON; a missing file yields the default config.
13
14use std::collections::BTreeMap;
15use std::net::SocketAddr;
16use std::path::{Path, PathBuf};
17
18use boatramp_core::config::DeployConfig;
19use serde::Deserialize;
20
21/// RON parse options shared by both loaders: `implicit_some` lets optional fields
22/// be written as bare values (`server: "..."`, not `Some("...")`). `pub` so the
23/// binary (which re-exports this module) can parse a manifest with the same
24/// options after the module moved into this crate.
25pub fn ron_options() -> ron::Options {
26    ron::Options::default().with_default_extension(ron::extensions::Extensions::IMPLICIT_SOME)
27}
28
29/// A failure loading or parsing a local config file (`project.cfg` / `boatramp.cfg`).
30#[derive(Debug, thiserror::Error)]
31pub enum ConfigError {
32    /// Wraps an underlying error with the file path it came from.
33    #[error("{path}: {source}")]
34    File {
35        path: String,
36        #[source]
37        source: Box<Self>,
38    },
39    /// The RON document failed to parse.
40    #[error("invalid config syntax: {0}")]
41    Ron(#[from] ron::error::SpannedError),
42    /// The `routing` section failed its compile-check.
43    #[error("routing: {0}")]
44    Routing(#[from] boatramp_core::ConfigError),
45    /// Reading the file failed (other than not-found, which yields defaults).
46    #[error(transparent)]
47    Io(#[from] std::io::Error),
48    /// An environment-variable override could not be parsed (bad number/bool).
49    #[error("environment variable {var}: {reason}")]
50    Env {
51        /// The offending `BOATRAMP_*` variable. Owned because some names are built
52        /// dynamically (the keyed `databases` map, whose members aren't known at
53        /// compile time).
54        var: String,
55        /// Why the value was rejected.
56        reason: String,
57    },
58    /// A `handlers.bindings.sql.databases` binding name is not a safe URL path
59    /// segment — it is threaded verbatim into `/api/sql/{db}/…` and `--db`, so an
60    /// empty/`//`-collapsing or path-separator-bearing name is refused at load
61    /// (fail-closed) rather than emitting a malformed control-plane path.
62    #[error("SQL database binding {name:?}: {reason}{cure}")]
63    InvalidDbName {
64        /// The offending binding name (the `databases` map key).
65        name: String,
66        /// Why it was rejected (from the canonical validator).
67        reason: &'static str,
68        /// A trailing remediation hint (empty unless this is the legacy empty-name
69        /// default case, where it points at the `default` cure).
70        cure: &'static str,
71    },
72}
73
74/// Project configuration, loaded from `project.cfg` (RON) in the project folder.
75///
76/// Read by the client commands (`sync`, `build`, `bundle`, `validate`).
77/// Everything is optional; a missing file is the default.
78#[derive(Debug, Default, Deserialize)]
79#[serde(default)]
80pub struct ProjectConfig {
81    /// Where and how to publish this project.
82    pub publish: PublishConfig,
83    /// Optional build step run before `sync`.
84    pub build: Option<BuildConfig>,
85    /// Optional embedded-bundler step (`bundler` feature).
86    pub bundle: Option<BundleConfig>,
87    /// Deploy-scoped routing/handlers config. Folded into the deployment
88    /// manifest at `sync` (so it is atomic with the content and rolls back with
89    /// it). The bulk of a project's config — redirects, rewrites, headers,
90    /// handlers, consumers, crons, streams.
91    pub routing: DeployConfig,
92}
93
94impl ProjectConfig {
95    /// Parse a `project.cfg` document (RON). The `routing` section is
96    /// compile-checked (route patterns, cron schedules, imports) so a bad config
97    /// fails fast.
98    pub fn parse(text: &str) -> Result<Self, ConfigError> {
99        let config: Self = ron_options().from_str(text)?;
100        config.routing.compile_check()?;
101        Ok(config)
102    }
103
104    /// Load from `path` (RON). A missing file yields the default config.
105    pub fn load(path: &Path) -> Result<Self, ConfigError> {
106        match std::fs::read_to_string(path) {
107            Ok(contents) => Self::parse(&contents).map_err(|err| ConfigError::File {
108                path: path.display().to_string(),
109                source: Box::new(err),
110            }),
111            Err(err) if err.kind() == std::io::ErrorKind::NotFound => Ok(Self::default()),
112            Err(err) => Err(err.into()),
113        }
114    }
115}
116
117/// Server daemon configuration, loaded from `boatramp.cfg` (RON). Read by
118/// `boatramp serve`; flags/env override the `serve` values.
119#[derive(Debug, Default, Deserialize)]
120#[serde(default)]
121pub struct ServerConfig {
122    /// Server defaults for `serve` (flag/env override these).
123    pub serve: Option<ServeConfig>,
124    /// Server-side handler runtime config (which backend serves each binding),
125    /// consumed only with the `handlers` feature.
126    pub handlers: Option<HandlersConfig>,
127    /// Self-hosted cluster mode (consumed only with the `cluster` feature).
128    pub cluster: Option<ClusterConfig>,
129    /// Opt-in **compute** backends. Present ⇒ this node
130    /// runs compute workloads via the backends it can offer; absent ⇒ no compute
131    /// (the reconcile loop stays a no-op).
132    pub compute: Option<ComputeConfig>,
133    /// Operator security posture (the hardening knobs): a profile
134    /// preset + overrides, resolved at startup. Absent ⇒ the strict
135    /// `multi-tenant` default. Operator-only — never part of site config.
136    pub security: Option<boatramp_core::security::SecurityConfig>,
137    /// Secrets-at-rest envelope. Absent ⇒ private
138    /// keys stored cleartext in the (replicated) control plane.
139    pub secrets: Option<SecretsConfig>,
140}
141
142/// `secrets` section — envelope encryption for private keys at rest.
143#[cfg_attr(not(feature = "cluster"), allow(dead_code))]
144#[derive(Debug, Clone, Default, Deserialize)]
145#[serde(default, deny_unknown_fields)]
146pub struct SecretsConfig {
147    /// Backend: `"local"` (machine-local AES-256-GCM KEK) or `"vault"` (Vault
148    /// Transit). Empty/other ⇒ no wrapping. In a cluster a local KEK must be the
149    /// **same file on every node** (wrapped certs replicate); Vault avoids that.
150    pub envelope: String,
151    /// Local-KEK key file (`envelope = "local"`). Default
152    /// `<data-dir>/secrets/kek`. Auto-generated `0600` if absent.
153    pub kek_file: Option<PathBuf>,
154    /// Vault Transit config (`envelope = "vault"`).
155    pub vault: Option<VaultSecretsConfig>,
156}
157
158/// Vault Transit settings for `envelope = "vault"`. The token is read from the
159/// environment (`token_env`), never stored in the config file.
160#[cfg_attr(not(all(feature = "cluster", feature = "acme-dns")), allow(dead_code))]
161#[derive(Debug, Clone, Deserialize)]
162#[serde(deny_unknown_fields)]
163pub struct VaultSecretsConfig {
164    /// Vault address, e.g. `https://vault:8200`.
165    pub addr: String,
166    /// Transit key name to wrap under.
167    pub key: String,
168    /// Environment variable holding the Vault token (default `VAULT_TOKEN`).
169    #[serde(default = "default_vault_token_env")]
170    pub token_env: String,
171}
172
173fn default_vault_token_env() -> String {
174    "VAULT_TOKEN".to_string()
175}
176
177impl Default for VaultSecretsConfig {
178    fn default() -> Self {
179        Self {
180            addr: String::new(),
181            key: String::new(),
182            token_env: default_vault_token_env(),
183        }
184    }
185}
186
187/// The RESERVED compute-workload name prefix (#501 Stage B LOW-2). boatramp DERIVES the
188/// per-project managed-database server workloads with this prefix
189/// (`boatramp_storage::tenant_provision::DERIVED_MANAGED_DB_PREFIX`), so an operator must
190/// NOT name a static `[handlers].bindings.sql.databases.*.compute` workload with it — a
191/// collision could shadow / alias a derived managed server. Screened fail-closed at
192/// config load ([`ServerConfig::validate_sql_db_names`]). Kept as a literal here (not the
193/// `boatramp-storage` const) so the screen holds on a build without the sql engine
194/// features; the two must stay in sync (a single source of truth would couple config
195/// loading to the optional storage dep).
196const RESERVED_MANAGED_DB_COMPUTE_PREFIX: &str = "bramp-db-";
197
198impl ServerConfig {
199    /// Parse a `boatramp.cfg` document (RON). Db-binding names declared in the file
200    /// are validated here (the same fail-closed check `load` re-runs after the env
201    /// merge), so a file-only config path — e.g. `boatramp cloudflare` rendering, or
202    /// the operator-resources loader — is guarded even without going through `load`.
203    pub fn parse(text: &str) -> Result<Self, ConfigError> {
204        let config: Self = ron_options().from_str(text)?;
205        config.validate_sql_db_names()?;
206        Ok(config)
207    }
208
209    /// Load from `path` (RON), then layer `BOATRAMP_*` environment overrides on
210    /// top. A missing file yields the default config, so `serve` can be configured
211    /// entirely from the environment (12-factor deployments where dropping a
212    /// `boatramp.cfg` is awkward — fly.io / Cloudflare / containers).
213    pub fn load(path: &Path) -> Result<Self, ConfigError> {
214        let mut config = match std::fs::read_to_string(path) {
215            Ok(contents) => Self::parse(&contents).map_err(|err| ConfigError::File {
216                path: path.display().to_string(),
217                source: Box::new(err),
218            })?,
219            Err(err) if err.kind() == std::io::ErrorKind::NotFound => Self::default(),
220            Err(err) => return Err(err.into()),
221        };
222        config.apply_env_overrides(&EnvSource::Process)?;
223        Ok(config)
224    }
225
226    /// Layer `BOATRAMP_*` environment overrides onto the loaded config for the
227    /// `compute`, `security`, and handler-`sql` sections — the operational knobs
228    /// that were previously reachable only through the `boatramp.cfg` file.
229    ///
230    /// **Precedence: env overrides file.** This matches the existing `serve`
231    /// section (its `#[arg(long, env = …)]` flags already let an env var win over
232    /// the file value), keeping the resolution rule uniform. A set variable
233    /// updates the field even when the file also set it; an unset variable leaves
234    /// the file (or built-in default) untouched. When a section is absent from the
235    /// file but any of its variables are set, the section is materialised from its
236    /// defaults first — so no config file is required to configure it.
237    ///
238    /// `source` supplies the variables (the process environment in production; an
239    /// explicit map in tests), so this stays a pure function of its inputs.
240    fn apply_env_overrides(&mut self, source: &EnvSource) -> Result<(), ConfigError> {
241        // --- compute ---------------------------------------------------------
242        // Materialise `[compute]` only if at least one of its variables is set, so
243        // an unset environment leaves an absent section absent (⇒ no compute).
244        if source.any(COMPUTE_ENV_VARS) {
245            let compute = self.compute.get_or_insert_with(ComputeConfig::default);
246            if let Some(v) = source.get("BOATRAMP_COMPUTE_BRIDGE") {
247                compute.bridge = v;
248            }
249            if let Some(v) = source.get("BOATRAMP_COMPUTE_SUBNET") {
250                compute.subnet = v;
251            }
252            if let Some(v) = source.parse("BOATRAMP_COMPUTE_VCPUS")? {
253                compute.vcpus = v;
254            }
255            if let Some(v) = source.parse("BOATRAMP_COMPUTE_MEM_MIB")? {
256                compute.mem_mib = v;
257            }
258            if let Some(v) = source.get("BOATRAMP_COMPUTE_REGION") {
259                compute.region = Some(v);
260            }
261            if let Some(v) = source.get("BOATRAMP_COMPUTE_SQL_SHIM_URL") {
262                compute.sql_shim_url = Some(v);
263            }
264            // The two shared-kernel enums have no `FromStr`, only a serde
265            // `rename_all = "lowercase"`; map their variants by that same spelling.
266            if let Some(v) = source.parse_enum(
267                "BOATRAMP_COMPUTE_MANAGED_DB_PRIVILEGE",
268                &[
269                    ("rootless", ManagedDbPrivilege::Rootless),
270                    ("caps", ManagedDbPrivilege::Caps),
271                ],
272            )? {
273                compute.managed_db_privilege = v;
274            }
275            if let Some(v) = source.parse_enum(
276                "BOATRAMP_COMPUTE_DOCKER_ENDPOINT",
277                &[
278                    ("published", boatramp_docker::DockerEndpoint::Published),
279                    ("bridge", boatramp_docker::DockerEndpoint::Bridge),
280                ],
281            )? {
282                compute.docker_endpoint = v;
283            }
284            if let Some(v) = source.parse_enum(
285                "BOATRAMP_COMPUTE_DOCKER_VOLUME_MODE",
286                &[
287                    ("named", boatramp_docker::DockerVolumeMode::Named),
288                    ("bind", boatramp_docker::DockerVolumeMode::Bind),
289                ],
290            )? {
291                compute.docker_volume_mode = v;
292            }
293            // Kernel trust anchors — comma-separated lists. These are
294            // security-critical: they are the trust anchor for the posture-scaled
295            // kernel bar, so a value here decides which kernels a `multi-tenant`
296            // node will boot. In a 12-factor deployment the environment IS the
297            // operator's trusted config source (a fly.toml `[env]` is committed the
298            // same as a file), so they are exposed here — but an operator should
299            // know the environment is *more* visible than a file (it leaks through
300            // `/proc/<pid>/environ` and is inherited by every subprocess), so a
301            // file remains the better home for them when one is available.
302            if let Some(v) = source.parse_list("BOATRAMP_COMPUTE_KERNEL_SIGNING_PUBKEYS") {
303                compute.kernel_signing_pubkeys = v;
304            }
305            if let Some(v) = source.parse_list("BOATRAMP_COMPUTE_KERNEL_ALLOWED_HASHES") {
306                compute.kernel_allowed_hashes = v;
307            }
308            // Internal DNS (per-project service discovery on the bridge gateway).
309            if let Some(v) = source.parse_bool("BOATRAMP_COMPUTE_INTERNAL_DNS")? {
310                compute.internal_dns = v;
311            }
312            if let Some(v) = source.get("BOATRAMP_COMPUTE_DNS_UPSTREAM") {
313                compute.dns_upstream = v;
314            }
315            if let Some(v) = source.get("BOATRAMP_COMPUTE_DNS_DOMAIN") {
316                compute.dns_domain = v;
317            }
318        }
319
320        // --- security --------------------------------------------------------
321        // Always materialise `[security]` when any knob is set: an absent section
322        // resolves to the strict `multi-tenant` default, and an env override then
323        // layers over that exactly as a file `overrides` block would.
324        if source.any(SECURITY_ENV_VARS) {
325            let security = self
326                .security
327                .get_or_insert_with(boatramp_core::security::SecurityConfig::default);
328            if let Some(v) = source.get("BOATRAMP_SECURITY_PROFILE") {
329                security.profile = Some(v);
330            }
331            let o = &mut security.overrides;
332            if let Some(v) =
333                source.parse_bool("BOATRAMP_SECURITY_ALLOW_UNAUTHENTICATED_PUBLIC_BIND")?
334            {
335                o.allow_unauthenticated_public_bind = Some(v);
336            }
337            if let Some(v) = source.parse("BOATRAMP_SECURITY_MAX_UPLOAD_BYTES")? {
338                o.max_upload_bytes = Some(v);
339            }
340            if let Some(v) = source.parse_bool("BOATRAMP_SECURITY_ALLOW_SITE_UNIX_UPSTREAMS")? {
341                o.allow_site_unix_upstreams = Some(v);
342            }
343            if let Some(v) = source.parse_bool("BOATRAMP_SECURITY_ALLOW_SITE_PRIVATE_UPSTREAMS")? {
344                o.allow_site_private_upstreams = Some(v);
345            }
346            if let Some(v) = source.parse_bool("BOATRAMP_SECURITY_ALLOW_GUEST_PRIVATE_EGRESS")? {
347                o.allow_guest_private_egress = Some(v);
348            }
349            if let Some(v) = source.parse_bool("BOATRAMP_SECURITY_ALLOW_GUEST_SELF_EGRESS")? {
350                o.allow_guest_self_egress = Some(v);
351            }
352            if let Some(v) = source.parse_bool("BOATRAMP_SECURITY_ALLOW_GUEST_EGRESS_EXTRA_CA")? {
353                o.allow_guest_egress_extra_ca = Some(v);
354            }
355            if let Some(v) = source.parse("BOATRAMP_SECURITY_MAX_HANDLER_BLOB_BYTES")? {
356                o.max_handler_blob_bytes = Some(v);
357            }
358            if let Some(v) = source.parse("BOATRAMP_SECURITY_MAX_COMPONENT_BYTES")? {
359                o.max_component_bytes = Some(v);
360            }
361            if let Some(v) = source.parse_bool("BOATRAMP_SECURITY_OIDC_REQUIRE_AUDIENCE")? {
362                o.oidc_require_audience = Some(v);
363            }
364            if let Some(v) = source.parse_bool("BOATRAMP_SECURITY_DOMAIN_VERIFY_ALLOW_PRIVATE")? {
365                o.domain_verify_allow_private = Some(v);
366            }
367            if let Some(v) = source.parse_bool("BOATRAMP_SECURITY_DOMAIN_VERIFY_SELF_SERVE")? {
368                o.domain_verify_self_serve = Some(v);
369            }
370            if let Some(v) = source.parse_bool("BOATRAMP_SECURITY_ALLOW_SHARED_KERNEL_COMPUTE")? {
371                o.allow_shared_kernel_compute = Some(v);
372            }
373            if let Some(v) = source.parse_bool("BOATRAMP_SECURITY_ALLOW_COMPUTE_EXEC")? {
374                o.allow_compute_exec = Some(v);
375            }
376            if let Some(v) = source.parse_bool("BOATRAMP_SECURITY_RATELIMIT_FAIL_OPEN")? {
377                o.ratelimit_fail_open = Some(v);
378            }
379            if let Some(v) = source.parse_bool("BOATRAMP_SECURITY_ALLOW_IMPLICIT_ROUTING")? {
380                o.allow_implicit_routing = Some(v);
381            }
382            if let Some(v) = source.parse_bool("BOATRAMP_SECURITY_REQUIRE_POP")? {
383                o.require_pop = Some(v);
384            }
385            if let Some(v) = source.parse_bool("BOATRAMP_SECURITY_REQUIRE_DOMAIN_VERIFICATION")? {
386                o.require_domain_verification = Some(v);
387            }
388            if let Some(v) = source.parse_bool("BOATRAMP_SECURITY_ALLOW_ENV_SECRET_REFS")? {
389                o.allow_env_secret_refs = Some(v);
390            }
391            // The multi-tenant sub-knobs (Gap 4b): previously file-only, now env-settable so a
392            // 12-factor deployment can tune tenancy isolation + guest capability minting without a
393            // `boatramp.cfg`. Fleet-scoped (a per-project override still lives in the config file).
394            if let Some(v) = source.parse_bool("BOATRAMP_SECURITY_REQUIRE_TENANCY_DECLARATION")? {
395                o.require_tenancy_declaration = Some(v);
396            }
397            if let Some(v) = source.parse_bool("BOATRAMP_SECURITY_ALLOW_CROSS_TENANT_DB")? {
398                o.allow_cross_tenant_db = Some(v);
399            }
400            if let Some(v) = source.parse_bool("BOATRAMP_SECURITY_ALLOW_GUEST_MINT_CAPABILITY")? {
401                o.allow_guest_mint_capability = Some(v);
402            }
403            if let Some(v) = source.parse("BOATRAMP_SECURITY_MAX_GUEST_CAPABILITY_TTL_SECS")? {
404                o.max_guest_capability_ttl_secs = Some(v);
405            }
406            // Remaining guest-feature knobs — env parity for a 12-factor fleet that runs env-only
407            // (no `boatramp.cfg`). Each preset defaults these OFF under `multi-tenant`, so an
408            // env-only multi-tenant deployment had no lever to opt a guest feature back on. The
409            // override field + `apply()` + `explain()` already exist for every one; only the env
410            // mapping was missing (`allow_guest_email` regressed prod SMTP on the P48 cutover).
411            if let Some(v) = source.parse_bool("BOATRAMP_SECURITY_ALLOW_GUEST_EMAIL")? {
412                o.allow_guest_email = Some(v);
413            }
414            if let Some(v) = source.parse_bool("BOATRAMP_SECURITY_ALLOW_GUEST_ADMIN_DOMAINS")? {
415                o.allow_guest_admin_domains = Some(v);
416            }
417            if let Some(v) = source.parse_bool("BOATRAMP_SECURITY_ALLOW_GUEST_ADMIN_EMAIL")? {
418                o.allow_guest_admin_email = Some(v);
419            }
420            if let Some(v) = source.parse_bool("BOATRAMP_SECURITY_ALLOW_GUEST_ADMIN_SITE")? {
421                o.allow_guest_admin_site = Some(v);
422            }
423            if let Some(v) = source.parse_bool("BOATRAMP_SECURITY_ALLOW_GUEST_ADMIN_SECRETS")? {
424                o.allow_guest_admin_secrets = Some(v);
425            }
426        }
427
428        // --- handler sql (`handlers.bindings.sql`) ---------------------------
429        // Materialise the nested `handlers.bindings.sql` chain only when a `sql`
430        // variable is set, so an unset environment doesn't conjure an empty
431        // handlers section. The variables mirror the config path
432        // (`BOATRAMP_HANDLERS_SQL_*`) and cover the cluster-vs-single-node knobs;
433        // secrets stay indirected via `*_TOKEN_ENV` names, never the token itself.
434        if source.any(SQL_ENV_VARS) {
435            let handlers = self.handlers.get_or_insert_with(HandlersConfig::default);
436            let sql = handlers
437                .bindings
438                .sql
439                .get_or_insert_with(SqlBindingConfig::default);
440            if let Some(v) = source.get("BOATRAMP_HANDLERS_SQL_DIR") {
441                sql.dir = Some(PathBuf::from(v));
442            }
443            if let Some(v) = source.get("BOATRAMP_HANDLERS_SQL_URL") {
444                sql.url = Some(v);
445            }
446            if let Some(v) = source.get("BOATRAMP_HANDLERS_SQL_ADMIN_URL") {
447                sql.admin_url = Some(v);
448            }
449            if let Some(v) = source.get("BOATRAMP_HANDLERS_SQL_REPLICA_URL") {
450                sql.replica_url = Some(v);
451            }
452            if let Some(v) = source.get("BOATRAMP_HANDLERS_SQL_TOKEN_ENV") {
453                sql.token_env = Some(v);
454            }
455            if let Some(v) = source.get("BOATRAMP_HANDLERS_SQL_ADMIN_TOKEN_ENV") {
456                sql.admin_token_env = Some(v);
457            }
458            if let Some(v) = source.get("BOATRAMP_HANDLERS_SQL_PREVIEW_MODE") {
459                sql.preview_mode = Some(v);
460            }
461            if let Some(v) = source.get("BOATRAMP_HANDLERS_SQL_PREVIEW_INIT") {
462                sql.preview_init = Some(PathBuf::from(v));
463            }
464            if let Some(v) = source.parse("BOATRAMP_HANDLERS_SQL_DEPROVISION_GRACE_SECS")? {
465                sql.deprovision_grace_secs = Some(v);
466            }
467        }
468
469        // --- handler sql external databases (`handlers.bindings.sql.databases`) ---
470        // The bring-your-own / managed-compute DB map, keyed by name. There is no
471        // config file to enumerate the members, so the member names are discovered
472        // from the environment: any `BOATRAMP_HANDLERS_SQL_DB_<NAME>_<FIELD>`
473        // variable declares database `<NAME>`. Each env-declared DB is merged into
474        // (overriding, per field, by key) whatever the file already declared under
475        // that name — the same env-over-file precedence as the scalars.
476        //
477        // The default database (the binding a handler opens as `sql.open("")`) is
478        // addressed by the reserved `DEFAULT` token, which can't appear as a literal
479        // in a variable name: `BOATRAMP_HANDLERS_SQL_DB_DEFAULT_KIND` populates the
480        // reserved [`DEFAULT_DB_NAME`](boatramp_core::project::DEFAULT_DB_NAME) key
481        // (`"default"`). As of v0.5.0 this is a real, path-segment-safe name (never the
482        // empty string), so the binding is addressable as `--db default` and every
483        // db-name ingress carries a valid URL path segment. The guest-facing
484        // `sql.open("")` contract is preserved by aliasing `"" ⇄ "default"` at the
485        // backend-resolution boundary — external bindings are a pure label over their
486        // connection params, so the renamed binding points at the SAME physical DB.
487        if source.any_with_prefix(SQL_DB_ENV_PREFIX) {
488            let handlers = self.handlers.get_or_insert_with(HandlersConfig::default);
489            let sql = handlers
490                .bindings
491                .sql
492                .get_or_insert_with(SqlBindingConfig::default);
493            for name in source.sql_database_names() {
494                // `DEFAULT` is the reserved token for the default database; it maps to
495                // the reserved real name `"default"` (v0.5.0; was the empty string).
496                let key = if name == "DEFAULT" {
497                    boatramp_core::project::DEFAULT_DB_NAME.to_string()
498                } else {
499                    name.clone()
500                };
501                let db = sql.databases.entry(key).or_default();
502                let prefix = format!("{SQL_DB_ENV_PREFIX}{name}_");
503                if let Some(v) = source.get(&format!("{prefix}KIND")) {
504                    db.kind = v;
505                }
506                if let Some(v) = source.get(&format!("{prefix}URL_ENV")) {
507                    db.url_env = v;
508                }
509                if let Some(v) = source.get(&format!("{prefix}READ_URL_ENV")) {
510                    db.read_url_env = Some(v);
511                }
512                if let Some(v) = source.get(&format!("{prefix}COMPUTE")) {
513                    db.compute = Some(v);
514                }
515                if let Some(v) = source.get(&format!("{prefix}DATABASE")) {
516                    db.database = Some(v);
517                }
518                if let Some(v) = source.get(&format!("{prefix}USER")) {
519                    db.user = Some(v);
520                }
521                if let Some(v) = source.get(&format!("{prefix}PASSWORD_ENV")) {
522                    db.password_env = Some(v);
523                }
524                if let Some(v) = source.parse(&format!("{prefix}POOL_MAX"))? {
525                    db.pool_max = Some(v);
526                }
527                if let Some(v) = source.parse_bool(&format!("{prefix}READ_ONLY"))? {
528                    db.read_only = v;
529                }
530                if let Some(v) = source.parse_bool(&format!("{prefix}ALLOW_PREVIEW"))? {
531                    db.allow_preview = v;
532                }
533                if let Some(v) = source.parse(&format!("{prefix}CONNECT_TIMEOUT_SECS"))? {
534                    db.connect_timeout_secs = Some(v);
535                }
536                if let Some(v) = source.get(&format!("{prefix}IMAGE")) {
537                    db.image = Some(v);
538                }
539                if let Some(v) = source.parse(&format!("{prefix}VOLUME_SIZE_MIB"))? {
540                    db.volume_size_mib = Some(v);
541                }
542                if let Some(v) = source.parse(&format!("{prefix}STARTUP_GRACE_SECS"))? {
543                    db.startup_grace_secs = Some(v);
544                }
545                if let Some(v) = source.parse_enum(
546                    &format!("{prefix}TENANT"),
547                    &[
548                        ("single", TenantIsolation::Single),
549                        ("shared", TenantIsolation::Shared),
550                    ],
551                )? {
552                    db.tenant = v;
553                }
554                if let Some(v) = source.parse_enum(
555                    &format!("{prefix}TENANT_SCOPE"),
556                    &[
557                        ("project", TenantScope::Project),
558                        ("site", TenantScope::Site),
559                    ],
560                )? {
561                    db.tenant_scope = v;
562                }
563                if let Some(v) = source.parse_bool(&format!("{prefix}RLS_SESSION"))? {
564                    db.rls_session = v;
565                }
566                if let Some(v) = source.get(&format!("{prefix}TENANT_GUC")) {
567                    db.tenant_guc = Some(v);
568                }
569                if let Some(v) = source.get(&format!("{prefix}SESSION_GUC")) {
570                    db.session_guc = Some(v);
571                }
572                if let Some(v) = source.get(&format!("{prefix}TENANT_ALL_MARKER")) {
573                    db.tenant_all_marker = Some(v);
574                }
575            }
576        }
577
578        // --- secrets (`[secrets]`) -------------------------------------------
579        // Envelope encryption for private keys at rest. `kek_file` holds a *path*
580        // (never key material) and the Vault token stays indirected via
581        // `token_env` (a variable name, not the token). Materialise the nested
582        // `vault` sub-config only when a vault variable is set.
583        if source.any(SECRETS_ENV_VARS) {
584            let secrets = self.secrets.get_or_insert_with(SecretsConfig::default);
585            if let Some(v) = source.get("BOATRAMP_SECRETS_ENVELOPE") {
586                secrets.envelope = v;
587            }
588            if let Some(v) = source.get("BOATRAMP_SECRETS_KEK_FILE") {
589                secrets.kek_file = Some(PathBuf::from(v));
590            }
591            if source.any(SECRETS_VAULT_ENV_VARS) {
592                let vault = secrets
593                    .vault
594                    .get_or_insert_with(VaultSecretsConfig::default);
595                if let Some(v) = source.get("BOATRAMP_SECRETS_VAULT_ADDR") {
596                    vault.addr = v;
597                }
598                if let Some(v) = source.get("BOATRAMP_SECRETS_VAULT_KEY") {
599                    vault.key = v;
600                }
601                if let Some(v) = source.get("BOATRAMP_SECRETS_VAULT_TOKEN_ENV") {
602                    vault.token_env = v;
603                }
604            }
605        }
606
607        // --- cluster (`[cluster]`) -------------------------------------------
608        // The self-hosted cluster section's own fields. The founding/joining
609        // *actions* already have their own `serve` flags with env
610        // (`BOATRAMP_CLUSTER_INIT` / `_JOIN` / `_ADVERTISE_ADDR`); those are
611        // distinct from — and not duplicated by — the `[cluster]` section fields
612        // exposed here. `join_token` keeps a secret out of plain sight via the
613        // usual `env:VAR` / `path:/file` prefix, so the env holds the *reference*,
614        // not the token. `ClusterConfig` has no `Default` (a founder needs at least
615        // a `listen`), so a `BOATRAMP_CLUSTER_LISTEN` is required to materialise an
616        // absent section from the environment.
617        if source.any(CLUSTER_ENV_VARS) {
618            // Materialise an absent section only if a bind address is supplied;
619            // otherwise there is no valid `ClusterConfig` to build (it has no
620            // `Default` — a node must know where to bind its mesh). When the file
621            // already declared `[cluster]`, its `listen` stands and the other env
622            // fields layer over it even without `BOATRAMP_CLUSTER_LISTEN`.
623            let listen = source.parse::<SocketAddr>("BOATRAMP_CLUSTER_LISTEN")?;
624            if self.cluster.is_none()
625                && let Some(listen) = listen
626            {
627                self.cluster = Some(ClusterConfig {
628                    listen,
629                    root_pubkeys: Vec::new(),
630                    seeds: Vec::new(),
631                    join_token: None,
632                    store_dir: None,
633                    mesh: None,
634                });
635            }
636            if let Some(cluster) = self.cluster.as_mut() {
637                // A `listen` override applies to an already-present section too (a
638                // freshly materialised one already carries it).
639                if let Some(v) = listen {
640                    cluster.listen = v;
641                }
642                if let Some(v) = source.parse_list("BOATRAMP_CLUSTER_ROOT_PUBKEYS") {
643                    cluster.root_pubkeys = v;
644                }
645                if let Some(v) = source.parse_list("BOATRAMP_CLUSTER_SEEDS") {
646                    cluster.seeds = v;
647                }
648                if let Some(v) = source.get("BOATRAMP_CLUSTER_JOIN_TOKEN") {
649                    cluster.join_token = Some(v);
650                }
651                if let Some(v) = source.get("BOATRAMP_CLUSTER_STORE_DIR") {
652                    cluster.store_dir = Some(PathBuf::from(v));
653                }
654                if source.any(CLUSTER_MESH_ENV_VARS) {
655                    let mesh = cluster.mesh.get_or_insert_with(MeshConfig::default);
656                    if let Some(v) = source.get("BOATRAMP_CLUSTER_MESH_KEY_FILE") {
657                        mesh.key_file = Some(PathBuf::from(v));
658                    }
659                    if let Some(v) = source.get("BOATRAMP_CLUSTER_MESH_KEY_ROTATION") {
660                        mesh.key_rotation = Some(v);
661                    }
662                    if let Some(v) = source.get("BOATRAMP_CLUSTER_MESH_JOIN_TOKEN_TTL") {
663                        mesh.join_token_ttl = Some(v);
664                    }
665                    if let Some(v) =
666                        source.parse_bool("BOATRAMP_CLUSTER_MESH_GATE_CLIENT_WRITES")?
667                    {
668                        mesh.gate_client_writes = Some(v);
669                    }
670                }
671            }
672        }
673
674        // Fail closed on any db-binding name that is not a safe URL path segment.
675        // Runs on the fully merged (file + env) `databases` map, so it catches a name
676        // from either source — and (crucially) the legacy empty-string default key,
677        // which is no longer produced by the `DEFAULT` token but could still be
678        // written literally in a `boatramp.cfg` file.
679        self.validate_sql_db_names()?;
680        Ok(())
681    }
682
683    /// Validate every configured `handlers.bindings.sql.databases` binding name
684    /// through the one canonical [`validate_resource_name`](boatramp_core::project::validate_resource_name)
685    /// (`kind = "database"`). A db-binding name is threaded verbatim into the
686    /// control-plane URL (`/api/sql/{db}/…`, `/api/migrate/{db}/…`) and the CLI
687    /// `--db`, so it must be a non-empty, path-segment-safe identifier — the same rule
688    /// project/site/function names already pass. The empty-string legacy default key
689    /// gets a targeted cure pointing at the reserved `default` name.
690    ///
691    /// Also screens each binding's `compute` field against the
692    /// [`RESERVED_MANAGED_DB_COMPUTE_PREFIX`] (#501 Stage B LOW-2): the `bramp-db-`
693    /// prefix is reserved for the derived per-project managed-DB server workloads, so an
694    /// operator may not point a static BYO binding at a `bramp-db-…` workload.
695    fn validate_sql_db_names(&self) -> Result<(), ConfigError> {
696        let Some(databases) = self
697            .handlers
698            .as_ref()
699            .and_then(|h| h.bindings.sql.as_ref())
700            .map(|s| &s.databases)
701        else {
702            return Ok(());
703        };
704        for (name, db) in databases {
705            if let Err(err) = boatramp_core::project::validate_resource_name("database", name) {
706                // The empty-string case is the pre-v0.5.0 default binding key: point
707                // at the cure (name it `default`, or set nothing and let the reserved
708                // `DEFAULT` token map to `default` automatically).
709                let cure = if name.is_empty() {
710                    " — name your default binding `default` (or set \
711                     BOATRAMP_HANDLERS_SQL_DB_DEFAULT_*, which now maps to `default` \
712                     automatically); see the v0.5.0 CHANGELOG"
713                } else {
714                    ""
715                };
716                return Err(ConfigError::InvalidDbName {
717                    name: err.value,
718                    reason: err.reason,
719                    cure,
720                });
721            }
722            // #501 Stage B LOW-2: the `bramp-db-` compute-workload prefix is RESERVED for
723            // the derived per-project managed-DB server workloads
724            // (`boatramp_storage::tenant_provision::DERIVED_MANAGED_DB_PREFIX`). An operator
725            // must not point a static BYO binding at a `compute` workload with that prefix —
726            // it could shadow / alias a derived managed server. Screen it fail-closed at
727            // config load (cheap: a `starts_with` on an already-parsed field).
728            if let Some(compute) = db.compute.as_deref()
729                && compute.starts_with(RESERVED_MANAGED_DB_COMPUTE_PREFIX)
730            {
731                return Err(ConfigError::InvalidDbName {
732                    name: compute.to_string(),
733                    reason: "the `bramp-db-` compute-workload prefix is reserved for \
734                             boatramp-derived managed-database servers",
735                    cure: " — rename the `compute` workload to not start with `bramp-db-`",
736                });
737            }
738        }
739        Ok(())
740    }
741}
742
743/// The `BOATRAMP_*` variables that populate the `[compute]` section. Kept as one
744/// list so [`ServerConfig::apply_env_overrides`] can decide whether to materialise
745/// an absent section without repeating the names.
746const COMPUTE_ENV_VARS: &[&str] = &[
747    "BOATRAMP_COMPUTE_BRIDGE",
748    "BOATRAMP_COMPUTE_SUBNET",
749    "BOATRAMP_COMPUTE_VCPUS",
750    "BOATRAMP_COMPUTE_MEM_MIB",
751    "BOATRAMP_COMPUTE_REGION",
752    "BOATRAMP_COMPUTE_SQL_SHIM_URL",
753    "BOATRAMP_COMPUTE_MANAGED_DB_PRIVILEGE",
754    "BOATRAMP_COMPUTE_DOCKER_ENDPOINT",
755    "BOATRAMP_COMPUTE_DOCKER_VOLUME_MODE",
756    "BOATRAMP_COMPUTE_KERNEL_SIGNING_PUBKEYS",
757    "BOATRAMP_COMPUTE_KERNEL_ALLOWED_HASHES",
758    "BOATRAMP_COMPUTE_INTERNAL_DNS",
759    "BOATRAMP_COMPUTE_DNS_UPSTREAM",
760    "BOATRAMP_COMPUTE_DNS_DOMAIN",
761];
762
763/// The `BOATRAMP_*` variables that populate the `[security]` section.
764const SECURITY_ENV_VARS: &[&str] = &[
765    "BOATRAMP_SECURITY_PROFILE",
766    "BOATRAMP_SECURITY_ALLOW_UNAUTHENTICATED_PUBLIC_BIND",
767    "BOATRAMP_SECURITY_MAX_UPLOAD_BYTES",
768    "BOATRAMP_SECURITY_ALLOW_SITE_UNIX_UPSTREAMS",
769    "BOATRAMP_SECURITY_ALLOW_SITE_PRIVATE_UPSTREAMS",
770    "BOATRAMP_SECURITY_ALLOW_GUEST_PRIVATE_EGRESS",
771    "BOATRAMP_SECURITY_ALLOW_GUEST_SELF_EGRESS",
772    "BOATRAMP_SECURITY_ALLOW_GUEST_EGRESS_EXTRA_CA",
773    "BOATRAMP_SECURITY_MAX_HANDLER_BLOB_BYTES",
774    "BOATRAMP_SECURITY_MAX_COMPONENT_BYTES",
775    "BOATRAMP_SECURITY_OIDC_REQUIRE_AUDIENCE",
776    "BOATRAMP_SECURITY_DOMAIN_VERIFY_ALLOW_PRIVATE",
777    "BOATRAMP_SECURITY_DOMAIN_VERIFY_SELF_SERVE",
778    "BOATRAMP_SECURITY_ALLOW_SHARED_KERNEL_COMPUTE",
779    "BOATRAMP_SECURITY_ALLOW_COMPUTE_EXEC",
780    "BOATRAMP_SECURITY_RATELIMIT_FAIL_OPEN",
781    "BOATRAMP_SECURITY_ALLOW_IMPLICIT_ROUTING",
782    "BOATRAMP_SECURITY_REQUIRE_POP",
783    "BOATRAMP_SECURITY_REQUIRE_DOMAIN_VERIFICATION",
784    "BOATRAMP_SECURITY_ALLOW_ENV_SECRET_REFS",
785    "BOATRAMP_SECURITY_REQUIRE_TENANCY_DECLARATION",
786    "BOATRAMP_SECURITY_ALLOW_CROSS_TENANT_DB",
787    "BOATRAMP_SECURITY_ALLOW_GUEST_MINT_CAPABILITY",
788    "BOATRAMP_SECURITY_MAX_GUEST_CAPABILITY_TTL_SECS",
789    "BOATRAMP_SECURITY_ALLOW_GUEST_EMAIL",
790    "BOATRAMP_SECURITY_ALLOW_GUEST_ADMIN_DOMAINS",
791    "BOATRAMP_SECURITY_ALLOW_GUEST_ADMIN_EMAIL",
792    "BOATRAMP_SECURITY_ALLOW_GUEST_ADMIN_SITE",
793    "BOATRAMP_SECURITY_ALLOW_GUEST_ADMIN_SECRETS",
794];
795
796/// The `BOATRAMP_*` variables that populate `handlers.bindings.sql`.
797const SQL_ENV_VARS: &[&str] = &[
798    "BOATRAMP_HANDLERS_SQL_DIR",
799    "BOATRAMP_HANDLERS_SQL_URL",
800    "BOATRAMP_HANDLERS_SQL_ADMIN_URL",
801    "BOATRAMP_HANDLERS_SQL_REPLICA_URL",
802    "BOATRAMP_HANDLERS_SQL_TOKEN_ENV",
803    "BOATRAMP_HANDLERS_SQL_ADMIN_TOKEN_ENV",
804    "BOATRAMP_HANDLERS_SQL_PREVIEW_MODE",
805    "BOATRAMP_HANDLERS_SQL_PREVIEW_INIT",
806    "BOATRAMP_HANDLERS_SQL_DEPROVISION_GRACE_SECS",
807];
808
809/// The fixed prefix of a keyed `handlers.bindings.sql.databases` variable —
810/// `BOATRAMP_HANDLERS_SQL_DB_<NAME>_<FIELD>`. Member names aren't known ahead of
811/// time (there is no config file to enumerate them), so they are discovered by
812/// scanning the environment for this prefix.
813const SQL_DB_ENV_PREFIX: &str = "BOATRAMP_HANDLERS_SQL_DB_";
814
815/// The recognised `_<FIELD>` suffixes of a `databases` variable, ordered so a
816/// name-isolating strip matches the **longest** suffix first (`_READ_URL_ENV`
817/// before `_URL_ENV`). Each mirrors a field of [`ExternalDatabaseConfig`].
818const SQL_DB_FIELD_SUFFIXES: &[&str] = &[
819    "_STARTUP_GRACE_SECS",
820    "_CONNECT_TIMEOUT_SECS",
821    // `_SESSION_GUC` / `_TENANT_GUC` / `_TENANT_ALL_MARKER` before `_TENANT`/`_TENANT_SCOPE`
822    // (longest-first name isolation).
823    "_SESSION_GUC",
824    "_TENANT_ALL_MARKER",
825    "_TENANT_GUC",
826    "_VOLUME_SIZE_MIB",
827    "_READ_URL_ENV",
828    "_PASSWORD_ENV",
829    "_ALLOW_PREVIEW",
830    "_URL_ENV",
831    "_DATABASE",
832    "_READ_ONLY",
833    "_POOL_MAX",
834    "_RLS_SESSION",
835    "_TENANT_SCOPE",
836    "_COMPUTE",
837    "_TENANT",
838    "_IMAGE",
839    "_KIND",
840    "_USER",
841];
842
843/// The `BOATRAMP_*` variables that populate the `[secrets]` section (excluding the
844/// nested `vault` sub-config, gated separately by [`SECRETS_VAULT_ENV_VARS`]).
845const SECRETS_ENV_VARS: &[&str] = &[
846    "BOATRAMP_SECRETS_ENVELOPE",
847    "BOATRAMP_SECRETS_KEK_FILE",
848    "BOATRAMP_SECRETS_VAULT_ADDR",
849    "BOATRAMP_SECRETS_VAULT_KEY",
850    "BOATRAMP_SECRETS_VAULT_TOKEN_ENV",
851];
852
853/// The `BOATRAMP_*` variables that populate the nested `[secrets.vault]` sub-config.
854const SECRETS_VAULT_ENV_VARS: &[&str] = &[
855    "BOATRAMP_SECRETS_VAULT_ADDR",
856    "BOATRAMP_SECRETS_VAULT_KEY",
857    "BOATRAMP_SECRETS_VAULT_TOKEN_ENV",
858];
859
860/// The `BOATRAMP_*` variables that populate the `[cluster]` section fields (the
861/// section's own config, distinct from the founding/joining *action* flags
862/// `BOATRAMP_CLUSTER_INIT` / `_JOIN` / `_ADVERTISE_ADDR`, which are `serve` clap
863/// args and are deliberately not listed here).
864const CLUSTER_ENV_VARS: &[&str] = &[
865    "BOATRAMP_CLUSTER_LISTEN",
866    "BOATRAMP_CLUSTER_ROOT_PUBKEYS",
867    "BOATRAMP_CLUSTER_SEEDS",
868    "BOATRAMP_CLUSTER_JOIN_TOKEN",
869    "BOATRAMP_CLUSTER_STORE_DIR",
870    "BOATRAMP_CLUSTER_MESH_KEY_FILE",
871    "BOATRAMP_CLUSTER_MESH_KEY_ROTATION",
872    "BOATRAMP_CLUSTER_MESH_JOIN_TOKEN_TTL",
873    "BOATRAMP_CLUSTER_MESH_GATE_CLIENT_WRITES",
874];
875
876/// The `BOATRAMP_*` variables that populate the nested `[cluster.mesh]` sub-config.
877const CLUSTER_MESH_ENV_VARS: &[&str] = &[
878    "BOATRAMP_CLUSTER_MESH_KEY_FILE",
879    "BOATRAMP_CLUSTER_MESH_KEY_ROTATION",
880    "BOATRAMP_CLUSTER_MESH_JOIN_TOKEN_TTL",
881    "BOATRAMP_CLUSTER_MESH_GATE_CLIENT_WRITES",
882];
883
884/// Where env-override values come from: the real process environment, or an
885/// explicit map for a deterministic unit test. Keeping the lookup behind this enum
886/// lets [`ServerConfig::apply_env_overrides`] be tested without touching (racy,
887/// process-global) `std::env`.
888enum EnvSource {
889    /// The live process environment (`std::env::var`).
890    Process,
891    /// A fixed name→value map (tests only).
892    #[cfg(test)]
893    Map(BTreeMap<String, String>),
894}
895
896impl EnvSource {
897    /// The value of `var`, if set to a non-empty string. An empty value is treated
898    /// as unset so an accidental `VAR=` doesn't clobber a file value with `""`.
899    fn get(&self, var: &str) -> Option<String> {
900        let raw = match self {
901            Self::Process => std::env::var(var).ok(),
902            #[cfg(test)]
903            Self::Map(m) => m.get(var).cloned(),
904        };
905        raw.filter(|v| !v.is_empty())
906    }
907
908    /// Whether any of `vars` is set (to a non-empty value).
909    fn any(&self, vars: &[&str]) -> bool {
910        vars.iter().any(|v| self.get(v).is_some())
911    }
912
913    /// Whether any variable whose name starts with `prefix` is set (to a
914    /// non-empty value). Used to decide whether to materialise a keyed map (the
915    /// `databases` env scheme) whose member names aren't known ahead of time.
916    fn any_with_prefix(&self, prefix: &str) -> bool {
917        self.names()
918            .any(|name| name.starts_with(prefix) && self.get(&name).is_some())
919    }
920
921    /// The full set of variable names visible to this source. Used to discover the
922    /// keyed-map member names from the environment (there is no config file to
923    /// enumerate them). Returned owned so it doesn't borrow the process env.
924    fn names(&self) -> Box<dyn Iterator<Item = String> + '_> {
925        match self {
926            Self::Process => Box::new(std::env::vars().map(|(k, _)| k)),
927            #[cfg(test)]
928            Self::Map(m) => Box::new(m.keys().cloned()),
929        }
930    }
931
932    /// Parse `var` as one of a fixed set of string-mapped variants, mapping an
933    /// unknown value to a clear [`ConfigError::Env`] that names the variable and
934    /// the accepted values. Used for the config enums that have no `FromStr`
935    /// (their only string mapping is a serde `rename_all`). `Ok(None)` when unset.
936    fn parse_enum<T: Copy>(
937        &self,
938        var: &str,
939        variants: &[(&str, T)],
940    ) -> Result<Option<T>, ConfigError> {
941        match self.get(var) {
942            Some(raw) => {
943                let lower = raw.trim().to_ascii_lowercase();
944                variants
945                    .iter()
946                    .find(|(name, _)| *name == lower)
947                    .map(|(_, v)| Some(*v))
948                    .ok_or_else(|| ConfigError::Env {
949                        var: var.to_string(),
950                        reason: format!(
951                            "expected one of {}, got {raw:?}",
952                            variants
953                                .iter()
954                                .map(|(n, _)| *n)
955                                .collect::<Vec<_>>()
956                                .join("/")
957                        ),
958                    })
959            }
960            None => Ok(None),
961        }
962    }
963
964    /// The distinct `<NAME>` tokens of every `BOATRAMP_HANDLERS_SQL_DB_<NAME>_<FIELD>`
965    /// variable that is set. The name is everything between the fixed prefix and the
966    /// *last* `_<FIELD>` segment, so a database name may itself contain underscores
967    /// (the field suffix is one of a known set). Returned sorted + de-duplicated so
968    /// the map is built deterministically.
969    fn sql_database_names(&self) -> Vec<String> {
970        let mut names: Vec<String> = self
971            .names()
972            .filter(|n| n.starts_with(SQL_DB_ENV_PREFIX) && self.get(n).is_some())
973            .filter_map(|n| {
974                let rest = n.strip_prefix(SQL_DB_ENV_PREFIX)?;
975                // Strip the recognised field suffix to isolate `<NAME>`. The suffixes
976                // are matched longest-first so `READ_URL_ENV` wins over `URL_ENV`.
977                SQL_DB_FIELD_SUFFIXES
978                    .iter()
979                    .find_map(|suffix| rest.strip_suffix(suffix))
980                    .filter(|name| !name.is_empty())
981                    .map(str::to_string)
982            })
983            .collect();
984        names.sort();
985        names.dedup();
986        names
987    }
988
989    /// Parse `var` as a **comma-separated** list of non-empty trimmed items, e.g.
990    /// the kernel trust anchors. A single value (no comma) yields a one-element
991    /// list. Empty items are dropped so a trailing comma or doubled separator is
992    /// tolerated. `Ok(None)` when unset; `Some(Vec::new())` never happens (an
993    /// all-empty value is treated as unset by [`Self::get`]).
994    fn parse_list(&self, var: &str) -> Option<Vec<String>> {
995        self.get(var).map(|raw| {
996            raw.split(',')
997                .map(str::trim)
998                .filter(|s| !s.is_empty())
999                .map(str::to_string)
1000                .collect()
1001        })
1002    }
1003
1004    /// Parse `var` as any [`FromStr`](std::str::FromStr) type (numbers), mapping a
1005    /// parse failure to a clear [`ConfigError::Env`]. `Ok(None)` when the variable
1006    /// is unset.
1007    fn parse<T>(&self, var: &str) -> Result<Option<T>, ConfigError>
1008    where
1009        T: std::str::FromStr,
1010        T::Err: std::fmt::Display,
1011    {
1012        match self.get(var) {
1013            Some(raw) => raw.parse::<T>().map(Some).map_err(|e| ConfigError::Env {
1014                var: var.to_string(),
1015                reason: e.to_string(),
1016            }),
1017            None => Ok(None),
1018        }
1019    }
1020
1021    /// Parse `var` as a boolean, accepting the common truthy/falsey spellings
1022    /// (`true`/`false`, `1`/`0`, `yes`/`no`, `on`/`off`) case-insensitively so an
1023    /// operator isn't surprised by a strict `true`-only parse. `Ok(None)` when
1024    /// unset.
1025    fn parse_bool(&self, var: &str) -> Result<Option<bool>, ConfigError> {
1026        match self.get(var) {
1027            Some(raw) => match raw.trim().to_ascii_lowercase().as_str() {
1028                "true" | "1" | "yes" | "on" => Ok(Some(true)),
1029                "false" | "0" | "no" | "off" => Ok(Some(false)),
1030                other => Err(ConfigError::Env {
1031                    var: var.to_string(),
1032                    reason: format!("expected a boolean (true/false), got {other:?}"),
1033                }),
1034            },
1035            None => Ok(None),
1036        }
1037    }
1038}
1039
1040/// How a **managed database** (PLAN-managed-compute-sql) runs its stock image on a
1041/// shared-kernel backend, whose entrypoint would otherwise fail under the dropped-`ALL`
1042/// hardening. `rootless` (the default) needs no capabilities and works under any
1043/// posture; `caps` is the fallback for an image that won't run rootless.
1044#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Deserialize)]
1045#[serde(rename_all = "lowercase")]
1046pub enum ManagedDbPrivilege {
1047    /// Run the DB as its image's user (`999:999` for the official postgres/mysql
1048    /// images) against a pre-owned volume — no added capabilities, any posture.
1049    #[default]
1050    Rootless,
1051    /// Add the minimal capability set the entrypoint needs (`CHOWN`, `DAC_OVERRIDE`,
1052    /// `FOWNER`, `SETUID`, `SETGID`). Honored only under the single-tenant posture.
1053    Caps,
1054}
1055
1056/// `compute` section — opt-in compute backends. Present
1057/// ⇒ `serve` registers the backends this node can offer and advertises them to
1058/// the scheduler; backends are capability-detected (container on Linux, remote
1059/// docker when a daemon is reachable, VMM when `/dev/kvm` exists).
1060#[derive(Debug, Clone, Deserialize)]
1061#[serde(default, deny_unknown_fields)]
1062pub struct ComputeConfig {
1063    /// Bridge the container veths / VM taps attach to (default `br-boatramp`).
1064    pub bridge: String,
1065    /// Guest IP subnet (default `10.0.0.0/24`).
1066    pub subnet: String,
1067    /// vCPUs this node advertises as schedulable (`0` ⇒ detect from the host).
1068    pub vcpus: u32,
1069    /// Memory (MiB) this node advertises as schedulable (`0` ⇒ a 1 GiB default).
1070    pub mem_mib: u32,
1071    /// **Static** kernel-signing public keys (`"<alg>:<hex>"`) — the trust anchor
1072    /// for the posture-scaled kernel bar. Under `multi-tenant`, a dynamically-
1073    /// selected default kernel must carry a signature verifying against one of
1074    /// these. Host-access-gated (never in the KV tier); changing it needs a
1075    /// restart. Empty ⇒ no kernel may be signed-verified (strict posture then
1076    /// accepts none).
1077    pub kernel_signing_pubkeys: Vec<String>,
1078    /// **Static** allow-list of kernel content hashes (sha256 hex) a dynamic
1079    /// default may select under `multi-tenant`. Host-access-gated. Empty ⇒ no
1080    /// kernel is allow-listed.
1081    pub kernel_allowed_hashes: Vec<String>,
1082    /// This node's **region** tag (FA-8). Advertised on the compute `Node` so a
1083    /// gateway routing to a `compute:`-backed workload with `--lb nearest` sends
1084    /// each request to the nearest replica by its node's region — no manual
1085    /// `--region` map. `None` ⇒ region-agnostic.
1086    pub region: Option<String>,
1087    /// How the remote-Docker backend reports a workload's reachable endpoint.
1088    /// `published` (default) publishes the container port on `127.0.0.1:<ephemeral>`
1089    /// so a host-native `serve` reaches it on any daemon (incl. Docker Desktop /
1090    /// macOS, where the bridge IP is not host-routable); `bridge` routes to the
1091    /// container bridge IP directly (only when `serve` shares the daemon's network).
1092    pub docker_endpoint: boatramp_docker::DockerEndpoint,
1093    /// How the remote-Docker backend backs a workload's persistent volumes.
1094    /// `named` (default) attaches a daemon-managed `docker volume` by name (portable
1095    /// across daemons + Docker Desktop / macOS); `bind` bind-mounts a host directory
1096    /// under `<data_dir>/compute/volumes/<name>` (local daemon only).
1097    pub docker_volume_mode: boatramp_docker::DockerVolumeMode,
1098    /// Guest-reachable base URL of the compute **sql-shim** (PLAN-compute-bindings) —
1099    /// e.g. `http://10.0.0.1:8081` (the compute bridge gateway) or the docker bridge
1100    /// gateway. Set ⇒ a workload's `--bind sql` reaches the managed database through a
1101    /// listener bound on `0.0.0.0:<port>`. `None` (default) ⇒ compute sql bindings off.
1102    #[serde(default, skip_serializing_if = "Option::is_none")]
1103    #[cfg_attr(not(feature = "handlers"), allow(dead_code))]
1104    pub sql_shim_url: Option<String>,
1105    /// Privilege strategy for a managed database's stock image on a shared-kernel
1106    /// backend (see [`ManagedDbPrivilege`]). `rootless` by default.
1107    #[serde(default)]
1108    #[cfg_attr(not(feature = "handlers"), allow(dead_code))]
1109    pub managed_db_privilege: ManagedDbPrivilege,
1110    /// Per-project **internal DNS** (service discovery): run a lightweight resolver
1111    /// on the bridge gateway so a guest can reach peers by name (`<workload>` /
1112    /// `<workload>.<project>.<dns_domain>`) instead of a numeric IP, scoped to its
1113    /// own project. Default **on** — it activates only when the container backend +
1114    /// bridge come up, so a node without them is unaffected. `false` disables it and
1115    /// leaves each image's own `/etc/resolv.conf`.
1116    #[serde(default = "default_internal_dns")]
1117    pub internal_dns: bool,
1118    /// The upstream resolver the internal DNS forwards non-internal queries to
1119    /// (external names + non-`A`/`AAAA` types), so the resolver is the guest's single
1120    /// nameserver. `"host:port"`; default `1.1.1.1:53`.
1121    #[serde(default = "default_dns_upstream")]
1122    pub dns_upstream: String,
1123    /// The internal DNS suffix names live under (`<workload>.<project>.<dns_domain>`);
1124    /// also the `search` domain written into each container's resolv.conf. Default
1125    /// `boatramp.internal`.
1126    #[serde(default = "default_dns_domain")]
1127    pub dns_domain: String,
1128}
1129
1130/// Default for [`ComputeConfig::internal_dns`] — on (activates only with the
1131/// container backend + bridge).
1132fn default_internal_dns() -> bool {
1133    true
1134}
1135
1136/// Default upstream resolver for [`ComputeConfig::dns_upstream`].
1137fn default_dns_upstream() -> String {
1138    "1.1.1.1:53".to_string()
1139}
1140
1141/// Default internal DNS suffix for [`ComputeConfig::dns_domain`].
1142fn default_dns_domain() -> String {
1143    boatramp_container::dns::DEFAULT_INTERNAL_DOMAIN.to_string()
1144}
1145
1146/// The built-in **boatramp kernel-signing public key** (`es256:…`), whose private
1147/// half lives as the `KERNEL_SIGNING_KEY` Actions secret in
1148/// [`BoatRamp/boatramp-vmlinux`](https://github.com/BoatRamp/boatramp-vmlinux).
1149/// Shipped as a default trust anchor so the first-party signed `boatramp-vmlinux`
1150/// verifies out of the box under the strict posture. An operator can replace
1151/// `kernel_signing_pubkeys` to trust only their own keys.
1152pub const BOATRAMP_KERNEL_SIGNING_PUBKEY: &str =
1153    "es256:02c4e4af2e9cba6ba6745c513f193622e6674a8b2d0187ebea5612f5b46a7eade4";
1154
1155/// The first-party signed-kernel content hashes trusted under the **strict**
1156/// posture, for this build's **guest arch**. The guest arch mirrors the host: an
1157/// x86_64 host boots x86_64 KVM guests (the embedded VMM); an Apple-silicon host
1158/// boots aarch64 guests (the Virtualization.framework `vmm-vz` backend). An x86_64
1159/// kernel can't boot an aarch64 VM (and vice versa), so each arch trusts only its
1160/// own signed `boatramp-vmlinux-<arch>` releases. Bump on each new signed release.
1161///
1162/// The **relaxed** (single-tenant) posture ignores this list — it verifies only the
1163/// content-hash pin — so an operator-supplied kernel boots there regardless of arch.
1164fn default_allowed_kernel_hashes() -> Vec<String> {
1165    #[cfg(target_arch = "x86_64")]
1166    {
1167        vec![
1168            // v0.2.0 minimal Firecracker 6.1-config kernel: boots under the
1169            // firecracker-*binary* backend (ACPI device discovery) but NOT the
1170            // in-process embedded VMM. Kept trusted so operators on the currently
1171            // published release don't fail strict verification.
1172            "cf1e590a9e642be3667131ca35fbf390378a457d8908169d2a169608e299d974".to_string(),
1173            // Same kernel + CONFIG_VIRTIO_MMIO_CMDLINE_DEVICES=y (flake `#vmlinux`),
1174            // so the embedded VMM binds its virtio-block root over the cmdline
1175            // transport. Reproducible build output (deterministic nix build,
1176            // verified on KVM); the next signed boatramp-vmlinux release — which
1177            // reuses this flake — publishes + signs it, gated by
1178            // `vmlinux-release-boot.yml`.
1179            "d0dc2098ab2a2a3c1bc72ab61dc85d9e464d798d7e55b6b80525db5ca2f00c5a".to_string(),
1180        ]
1181    }
1182    #[cfg(target_arch = "aarch64")]
1183    {
1184        vec![
1185            // `boatramp-vmlinux-aarch64` v0.2.3 (the Virtualization.framework guest
1186            // kernel, flake `#vmlinux` on aarch64-linux — a raw arm64 `Image`). This
1187            // release enables the generic PCIe host + virtio-pci so the guest actually
1188            // discovers VZ's virtio disk/net/console (the earlier v0.2.2 `be95fb0d…`
1189            // built with `CONFIG_PCI` off never booted under VZ and is dropped). This
1190            // is the hash of the **published, ES256-signed** release asset (signed by
1191            // BOATRAMP_KERNEL_SIGNING_PUBKEY), so a selected `compute.default_kernel`
1192            // clears the strict bar out of the box; the boot + scale-to-zero round-trip
1193            // was validated against this exact published kernel. NOTE: unlike x86_64,
1194            // the aarch64 build is not currently bit-reproducible across build hosts
1195            // (same config + size, different build metadata), so pin/verify against the
1196            // published `.sha256`/`.sig`, not a local rebuild. Bump on each new release.
1197            "d785a48d754e65a4630443301f1fb84cb69cf882336d3cf37055e437b3d8e21f".to_string(),
1198        ]
1199    }
1200    #[cfg(not(any(target_arch = "x86_64", target_arch = "aarch64")))]
1201    {
1202        Vec::new()
1203    }
1204}
1205
1206impl Default for ComputeConfig {
1207    fn default() -> Self {
1208        Self {
1209            bridge: "br-boatramp".to_string(),
1210            subnet: "10.0.0.0/24".to_string(),
1211            vcpus: 0,
1212            mem_mib: 0,
1213            kernel_signing_pubkeys: vec![BOATRAMP_KERNEL_SIGNING_PUBKEY.to_string()],
1214            kernel_allowed_hashes: default_allowed_kernel_hashes(),
1215            region: None,
1216            docker_endpoint: boatramp_docker::DockerEndpoint::default(),
1217            docker_volume_mode: boatramp_docker::DockerVolumeMode::default(),
1218            sql_shim_url: None,
1219            managed_db_privilege: ManagedDbPrivilege::default(),
1220            internal_dns: default_internal_dns(),
1221            dns_upstream: default_dns_upstream(),
1222            dns_domain: default_dns_domain(),
1223        }
1224    }
1225}
1226
1227/// `cluster` section — self-hosted **cluster mode**. Parsed in
1228/// every build so config files stay portable; only *consumed* when the `cluster`
1229/// feature is compiled in (`boatramp serve --mode cluster`).
1230#[cfg_attr(not(feature = "cluster"), allow(dead_code))]
1231#[derive(Debug, Clone, Deserialize)]
1232pub struct ClusterConfig {
1233    /// Address to bind this node's Raft **peer mesh** on (the `/raft/*` +
1234    /// `/stream/*` endpoints) — distinct from the public `serve.addr`.
1235    pub listen: SocketAddr,
1236    /// The cluster **root anchor set** — the `es256:`/`ed25519:`-tagged public
1237    /// keys that define this cluster's identity (a cluster *is* its root key).
1238    /// Every join/trust decision verifies against this set. Empty ⇒ falls back to
1239    /// `serve.auth_root_public_key` (the single-anchor default). A *set* enables
1240    /// make-before-break root rotation.
1241    #[serde(default)]
1242    pub root_pubkeys: Vec<String>,
1243    /// **Seeds** — control-plane addresses of existing cluster members
1244    /// (`host:port`), any of which can admit this node. Present ⇒ this node
1245    /// **joins** (redeems its `join_token`); absent + no durable state + explicit
1246    /// `--cluster-init` ⇒ it **founds**. There is no peer map: members are learned
1247    /// from the root-signed join response.
1248    #[serde(default)]
1249    pub seeds: Vec<String>,
1250    /// The single-use bearer **join token** used when `seeds` are set. Keeps the
1251    /// secret out of the file via a prefix: `env:VAR`, `path:/file`, or an inline
1252    /// literal. Usually supplied via `serve --cluster-join <ticket>` instead.
1253    #[serde(default)]
1254    pub join_token: Option<String>,
1255    /// Directory for this node's **durable** Raft log/state store (node-local;
1256    /// distinct from the replicated control plane). Default
1257    /// `<data-dir>/raft`.
1258    #[serde(default)]
1259    pub store_dir: Option<PathBuf>,
1260    /// Mesh identity + TLS settings. Absent ⇒ defaults (identity key
1261    /// auto-generated under `<data-dir>/mesh/identity.key`).
1262    #[serde(default)]
1263    pub mesh: Option<MeshConfig>,
1264}
1265
1266/// `[cluster.mesh]` — mesh identity + TLS knobs.
1267#[cfg_attr(not(feature = "cluster"), allow(dead_code))]
1268#[derive(Debug, Clone, Default, Deserialize)]
1269#[serde(default, deny_unknown_fields)]
1270pub struct MeshConfig {
1271    /// Path to this node's Ed25519 identity key (PKCS#8 DER, `0600`,
1272    /// auto-generated). Default `<data-dir>/mesh/identity.key`.
1273    pub key_file: Option<PathBuf>,
1274    /// Automatic key-rotation cadence (e.g. `"30d"`); `None` = manual only.
1275    /// Consumed by the rotation loop.
1276    pub key_rotation: Option<String>,
1277    /// TTL for a single-use join token (e.g. `"1h"`).
1278    pub join_token_ttl: Option<String>,
1279    /// Gate mesh `client-write`s behind a control-plane **cluster-write
1280    /// capability**, so a trusted peer can't inject arbitrary
1281    /// control-plane writes on mesh trust alone. Requires the token root
1282    /// **private** key on every node (each mints + presents its own capability);
1283    /// default `false`.
1284    pub gate_client_writes: Option<bool>,
1285}
1286
1287/// `handlers` section — server-side handler runtime config (read by `serve`).
1288/// Parsed in every build (so config files stay portable), but only *consumed*
1289/// when the `handlers` feature is compiled in.
1290#[cfg_attr(not(feature = "handlers"), allow(dead_code))]
1291#[derive(Debug, Clone, Default, Deserialize)]
1292#[serde(default)]
1293pub struct HandlersConfig {
1294    /// `handlers.bindings` — which backend serves each handler binding.
1295    pub bindings: BindingsConfig,
1296    /// Use the wasmtime **pooling** instance allocator: faster
1297    /// instantiation at the cost of a large up-front virtual-memory reservation.
1298    /// Off by default — opt in and benchmark for your workload.
1299    pub pooling: bool,
1300    /// Engine-wide **safety max** on a *connection-bearing* invocation (a site
1301    /// handler or a synchronous function/webhook invoke), milliseconds. A route
1302    /// or function may declare a *lower* timeout, never a higher one. Kept tight
1303    /// on purpose: a client, proxy, and the shared request pool are all blocked
1304    /// while a sync handler runs. Absent ⇒ 10s (the historical default). This is
1305    /// a node safety ceiling, not a per-invocation budget, and is distinct from
1306    /// a per-site `max_timeout_ms`.
1307    pub sync_max_timeout_ms: Option<u64>,
1308    /// Engine-wide safety max on a *durable async* invocation — the drain that
1309    /// runs `?mode=async` calls, workflow steps, cron/queue/blob triggers, and
1310    /// `wasi:messaging` consumers, milliseconds. No client is connected and the
1311    /// work is retried + dead-lettered, so this can be far larger than the sync
1312    /// ceiling: it is what lets a legitimately long background job (e.g. an LLM
1313    /// generation) declare and actually get minutes of runtime. Absent ⇒ 15
1314    /// minutes. Runs on its own concurrency budget (`async_max_concurrency`), so
1315    /// a long job never starves live traffic.
1316    pub async_max_timeout_ms: Option<u64>,
1317    /// Max concurrent in-flight *async-lane* invocations, kept separate from the
1318    /// (larger) request pool so a burst of long background jobs can't exhaust the
1319    /// slots live site traffic needs. Absent ⇒ 8.
1320    pub async_max_concurrency: Option<usize>,
1321    /// Optional CPU **fuel** ceiling for an async-lane invocation. A large async
1322    /// timeout bounds only wall-clock; without a fuel bound a CPU-bound guest can
1323    /// spin for the whole window. Absent ⇒ unmetered (same as the sync default).
1324    pub async_max_fuel: Option<u64>,
1325    /// **Relaxed messaging-publish durability** — the max number of published
1326    /// messages that may be acknowledged from the in-memory buffer BEFORE a durable
1327    /// checkpoint is forced. **Absent / `0` ⇒ strong durability (the default):**
1328    /// every `publish()` returns only after the message is crash-durable — a
1329    /// *stronger* guarantee than NATS JetStream's default sync publish. Set `N > 0`
1330    /// to opt a node into fast-ack (publish returns on the buffer insert, ~10µs
1331    /// instead of ~one flush interval), at the cost of a **bounded loss window: up
1332    /// to `N` acknowledged-but-unflushed messages are lost on a process crash / OOM
1333    /// / SIGKILL / power loss** before the next flush. Affects ONLY the messaging
1334    /// bus publish path — control-plane, auth, and consumer ack/redelivery
1335    /// durability are unaffected. Single-node only (cluster durability is
1336    /// replication). A node with `N > 0` logs a warning at startup.
1337    pub messaging_max_unflushed_msgs: Option<usize>,
1338    /// **Event-driven delivery — safety-net reconcile cadence** (ms). The coarse timer the delivery
1339    /// drainer falls back to when no fast-path wake fires: it drains the durable ready-set and fires
1340    /// lease-expiry redelivery via the per-message due-heap, so a dropped wake or a time-based
1341    /// visibility never stalls delivery beyond this interval. It never scans idle topics (an idle
1342    /// fleet costs ~0). Absent ⇒ ~2 s. Lower for tighter redelivery latency at more wakeups; raise to
1343    /// quiet a large idle fleet further.
1344    pub messaging_safetynet_interval_ms: Option<u64>,
1345    /// **Event-driven delivery — ready-set rebuild cadence** (ms). The long-cadence self-heal that
1346    /// re-derives the ready-set from the authoritative message index — recovering a marker lost to a
1347    /// crash between the index write and the ready write, pruning a stale marker, and self-populating
1348    /// a fresh/upgraded node's ready-set. This is the one full-ish scan, so it runs rarely. Absent ⇒
1349    /// ~30 s. The correctness backstop for the ready-set (a lost marker costs at most one rebuild
1350    /// interval of latency, never a lost message).
1351    pub messaging_readyset_rebuild_interval_ms: Option<u64>,
1352    /// Max wall-clock for a *streaming-lane* response (a `#[handler(stream)]`
1353    /// route — SSE, chunked, agent token streaming), milliseconds. A client is
1354    /// connected but the body is written incrementally over seconds-to-minutes,
1355    /// so this is far larger than the sync ceiling. Runs on its own concurrency
1356    /// budget (`streaming_max_concurrency`), isolated from both the fast request
1357    /// pool and the async drain. Absent ⇒ 15 minutes.
1358    pub streaming_max_timeout_ms: Option<u64>,
1359    /// Max concurrent in-flight *streaming-lane* responses, kept separate from the
1360    /// request pool and the async drain so a burst of long-lived streams starves
1361    /// neither. Absent ⇒ 64.
1362    pub streaming_max_concurrency: Option<usize>,
1363    /// Optional CPU **fuel** ceiling for a streaming-lane response. Absent ⇒
1364    /// unmetered (a stream is I/O-bound on the client, not CPU-bound).
1365    pub streaming_max_fuel: Option<u64>,
1366    /// Optional ceiling on a guest's **outbound** `wasi:http` call — the connect
1367    /// and time-to-first-byte wait — milliseconds, independent of the invocation
1368    /// timeout, so a hung upstream is bounded on its own terms. The streaming
1369    /// (between-bytes) timeout is left at wasmtime's default so a slow token
1370    /// stream is not cut mid-flight. Absent ⇒ wasmtime's default.
1371    pub outbound_timeout_ms: Option<u64>,
1372}
1373
1374/// `handlers.bindings` — per-binding backend configuration. kv/blob reuse the
1375/// server's own KV/Storage backends (per-site prefixed); `sql` is the single
1376/// libsql backend, whose single-node-vs-cluster split is the only choice.
1377#[cfg_attr(not(feature = "handlers"), allow(dead_code))]
1378#[derive(Debug, Clone, Default, Deserialize)]
1379#[serde(default)]
1380pub struct BindingsConfig {
1381    /// `handlers.bindings.sql` — libsql settings. Absent ⇒ single-node,
1382    /// per-site embedded files under `<data-dir>/handlers-sql`.
1383    pub sql: Option<SqlBindingConfig>,
1384}
1385
1386/// libsql settings for the handler `sql` binding — the single SQL backend. Each
1387/// site gets a real database boundary (an embedded file per site, or a sqld
1388/// namespace per site), never schema separation (which arbitrary guest SQL
1389/// escapes). Setting `url` switches from single-node to a shared sqld cluster;
1390/// everything else stays identical.
1391#[cfg_attr(not(feature = "handlers"), allow(dead_code))]
1392#[derive(Debug, Clone, Default, Deserialize)]
1393#[serde(default)]
1394pub struct SqlBindingConfig {
1395    /// Single-node: root directory for the per-site embedded database files
1396    /// (default `<data-dir>/handlers-sql`). Ignored when `url` is set.
1397    pub dir: Option<PathBuf>,
1398    /// Cluster: base sqld data URL (e.g. `http://sqld:8080`). When set, each
1399    /// site is a sqld namespace addressed as a subdomain of this URL; `admin_url`
1400    /// is then required.
1401    pub url: Option<String>,
1402    /// Cluster: sqld admin API base URL (e.g. `http://sqld:9090`) for creating
1403    /// per-site namespaces. Required when `url` is set.
1404    pub admin_url: Option<String>,
1405    /// Cluster: optional sqld **read-replica** data URL. When set, handlers'
1406    /// read-only `sql` transactions (`open-read-only`) route to this endpoint
1407    /// while writes stay on `url` (reads → replicas, writes → primary).
1408    /// Reads may lag (eventually consistent). Ignored in
1409    /// single-node mode (no `url`).
1410    pub replica_url: Option<String>,
1411    /// Name of the env var holding the sqld data auth token (optional; never
1412    /// the token itself in-file).
1413    pub token_env: Option<String>,
1414    /// Name of the env var holding the sqld admin API auth key (optional).
1415    pub admin_token_env: Option<String>,
1416    /// How preview deployments get their SQL database: `empty` (default — a
1417    /// fresh isolated db), `branch` (a consistent copy of the site's live db;
1418    /// single-node only), or `shared` (the site's live db). See
1419    /// `boatramp_core::sql::PreviewSqlMode`.
1420    pub preview_mode: Option<String>,
1421    /// Path to an idempotent SQL script run when an `empty` preview database is
1422    /// first opened (e.g. schema/seed). Ignored in `branch`/`shared` modes.
1423    pub preview_init: Option<PathBuf>,
1424    /// `handlers.bindings.sql.databases` — external **bring-your-own** databases,
1425    /// each opened by name via `sql.open("<name>")`. An operator-configured
1426    /// Postgres/MySQL whose *isolation is the operator's* (it's their database),
1427    /// so these bypass the per-site libsql boundary and are reachable by any
1428    /// handler/function granted the `sql` binding. Needs the `sql-postgres` /
1429    /// `sql-mysql` build feature for the engine. A name here shadows the same
1430    /// name on the managed libsql default.
1431    pub databases: BTreeMap<String, ExternalDatabaseConfig>,
1432    /// **Soft-delete grace window** for a per-tenant managed database, in seconds
1433    /// (env `BOATRAMP_HANDLERS_SQL_DEPROVISION_GRACE_SECS`). When a project/site is
1434    /// deleted, a **Shared + Postgres** tenant is *soft*-deleted (its database is
1435    /// renamed aside and its role disabled) and stays recoverable for this long
1436    /// before a reaper hard-drops it — see
1437    /// [`tenant_sql`](crate::tenant_sql). `None` ⇒ the 7-day default
1438    /// (`DEFAULT_DEPROVISION_GRACE_SECS`); `0` ⇒ disable the soft path (immediate,
1439    /// irreversible hard drop everywhere). MySQL and all `Single` tenants always
1440    /// hard-drop immediately (the engine/cell can't be renamed aside safely), so this
1441    /// knob only affects the Shared-Postgres cell.
1442    pub deprovision_grace_secs: Option<u64>,
1443    /// **Trusted-extension allowlist** for the owner-gated schema-migration surface — the ONLY
1444    /// Postgres extensions a migration `Extension` step may enable (a name not here is refused
1445    /// fail-closed). A raw `sql` migration step may not `CREATE EXTENSION` at all, so this list is
1446    /// the single, operator-controlled gate on which extensions a project can install via
1447    /// migrations. Empty / `None` ⇒ no extension may be enabled through a migration (the safest
1448    /// default). Keep it tight (e.g. `["pgcrypto", "uuid-ossp", "citext"]`); an entry like
1449    /// `dblink`/`postgres_fdw` deliberately widens cross-database reach, so add those only knowingly.
1450    pub migrate_trusted_extensions: Option<Vec<String>>,
1451    /// **Per-project declared-database COUNT ceiling** (#501 Stage B MEDIUM-1 — the
1452    /// disk-exhaustion / errno-28 guard). The maximum number of `databases:` entries a
1453    /// single project may declare; a declare that would exceed it is refused fail-closed
1454    /// (a 422-class error). Each declared DB eagerly provisions a 10–200 GiB volume, so
1455    /// without this a `Project·Admin` could declare an unbounded number and exhaust the
1456    /// node's disk. `None` ⇒ the built-in default
1457    /// (`apply_db_caps::DEFAULT_MAX_DECLARED_DATABASES_PER_PROJECT`, 16); `0` ⇒ declaring
1458    /// any managed database is disabled on this node.
1459    pub max_declared_databases: Option<usize>,
1460    /// **Per-project aggregate declared-VOLUME ceiling**, in MiB (#501 Stage B
1461    /// MEDIUM-1). The maximum SUM of `volume_size_mib` across all of a project's declared
1462    /// databases; a declare whose incoming volume would push the project's total past
1463    /// this is refused fail-closed. `None` ⇒ the built-in default
1464    /// (`apply_db_caps::DEFAULT_MAX_DECLARED_VOLUME_MIB`, 512 GiB); `0` ⇒ disable managed
1465    /// declarations on this node (the aggregate can never fit a non-zero volume).
1466    pub max_declared_volume_mib: Option<u64>,
1467}
1468
1469/// One external SQL database for the handler `sql` binding. Its **source** is one
1470/// of two mutually-exclusive forms:
1471///  - `url_env` — a **bring-your-own** database: the connection URL is a secret,
1472///    named indirectly by an env var (never written in the config file).
1473///  - `compute` — a database **boatramp runs** as a compute workload: boatramp
1474///    derives the connection from the workload's live endpoint (host\:port) plus
1475///    the `database`/`user`/`password_env` here, so there is no URL to hand-map and
1476///    it follows the workload across restarts (PLAN-managed-compute-sql).
1477#[cfg_attr(not(feature = "handlers"), allow(dead_code))]
1478#[derive(Debug, Clone, Default, Deserialize)]
1479#[serde(default)]
1480pub struct ExternalDatabaseConfig {
1481    /// Engine: `postgres` (aliases `postgresql`/`pg`), `mysql` (alias
1482    /// `mariadb`), or `libsql` (aliases `sqlite`/`sqlite3`) — the embedded
1483    /// SQLite-compatible engine (single-node file, or a remote sqld primary via
1484    /// `url_env`). A `libsql` entry needs neither `compute` nor an external URL for
1485    /// the single-node case: it names an on-disk file via [`path`](Self::path).
1486    pub kind: String,
1487    /// Name of the env var holding the connection URL (e.g.
1488    /// `postgres://user:pw@host/db`). Required unless `compute` is set — or, for a
1489    /// single-node `libsql` database, unless `path` is set (an embedded file needs
1490    /// no URL/secret).
1491    pub url_env: String,
1492    /// Optional env var holding a **read-replica** connection URL. When set,
1493    /// `open-read-only` transactions route there; writes stay on `url_env`.
1494    pub read_url_env: Option<String>,
1495    /// Optional env var holding a **DDL/migration** connection URL for the
1496    /// **owner-role analog** of the schema-migration surface — a login that is
1497    /// DDL-capable *and distinct from the runtime binding user* (`user` /
1498    /// `url_env`). Its whole purpose is to keep migration DDL off the runtime
1499    /// tenant identity, mirroring the Postgres owner-role split (Postgres mints a
1500    /// per-tenant non-superuser owner role automatically; MySQL has no such role
1501    /// model, so the DDL identity must be supplied explicitly).
1502    ///
1503    /// **MySQL:** required to run schema migrations. Point it at an admin/DDL
1504    /// login (e.g. `mysql://root:…@host/db` or a purpose-made `_migrate` grant
1505    /// with `CREATE, ALTER, DROP, INDEX, REFERENCES` on the schema) that is **not**
1506    /// the runtime `user`. If it is unset (or resolves to the same identity as the
1507    /// runtime binding), migrate **refuses** fail-closed rather than run owner-DDL
1508    /// as the runtime tenant user — there is no owner/runtime split to fall back
1509    /// on. Ignored by the normal handler `sql` path; read only by the migration
1510    /// runner.
1511    ///
1512    /// **Postgres:** ignored — the per-project non-superuser owner role +
1513    /// its sealed credential are minted automatically at provision, so no
1514    /// operator-supplied DDL URL is needed (a set value is harmless and unused).
1515    pub migration_url_env: Option<String>,
1516    /// The name of a **compute workload** (a Postgres/MySQL server boatramp runs)
1517    /// to source this database from, instead of `url_env`. boatramp resolves the
1518    /// workload's live endpoint and builds the connection. Mutually exclusive with
1519    /// `url_env`.
1520    ///
1521    /// **Reserved prefix (#501 Stage B LOW-2):** do NOT name a static workload with the
1522    /// `bramp-db-` prefix — it is reserved for the per-project managed-database servers
1523    /// boatramp derives for declarative `databases:` entries
1524    /// (`boatramp_storage::tenant_provision::DERIVED_MANAGED_DB_PREFIX`). A `bramp-db-…`
1525    /// value here is refused fail-closed at config load
1526    /// ([`ConfigError::InvalidDbName`](crate::config::ConfigError::InvalidDbName)).
1527    pub compute: Option<String>,
1528    /// The database name inside the compute-backed server (non-secret).
1529    pub database: Option<String>,
1530    /// The connecting user for the compute-backed server (non-secret).
1531    pub user: Option<String>,
1532    /// Env var holding the password for `user` on the compute-backed server.
1533    /// **Omit to let boatramp fully manage the credential** (PLAN-managed-compute-sql
1534    /// Phase 2): it generates a strong password once, seals it with the `[secrets]`
1535    /// envelope, injects it into the DB workload's server-init env at launch, and
1536    /// connects the handler with it — the operator sets no DB secret at all. Set it
1537    /// only to bring your own password for the compute-backed server.
1538    pub password_env: Option<String>,
1539    /// Maximum pooled connections (default 8).
1540    pub pool_max: Option<u32>,
1541    /// Open every transaction `READ ONLY` (the engine rejects writes) — for a
1542    /// database functions should only read.
1543    pub read_only: bool,
1544    /// Permit **preview** deployments to reach this database. Default `false`: a
1545    /// preview is refused, so it can never touch the operator's live external DB.
1546    pub allow_preview: bool,
1547    /// Connection/acquire timeout in seconds (default 10).
1548    pub connect_timeout_secs: Option<u64>,
1549    /// The stock OCI image for a **managed co-located** database (`compute` set, no
1550    /// `password_env`). When omitted, boatramp auto-registers the workload from the
1551    /// engine's default image (`pgvector/pgvector:pg16` for postgres, `mysql:8.0`
1552    /// for mysql). Ignored for a bring-your-own (`url_env`) database.
1553    pub image: Option<String>,
1554    /// The persistent data-volume size in MiB for a **managed co-located** database
1555    /// (default 10240 = 10 GiB). Ignored for a bring-your-own database.
1556    pub volume_size_mib: Option<u32>,
1557    /// Startup grace (seconds) for a **managed co-located** database: how long a
1558    /// freshly launched server has to finish its first `initdb` before the reconcile
1559    /// loop treats a still-unhealthy replica as a broken launch to stop + relaunch.
1560    /// When set it overrides the engine default the synthesizer picks (Postgres 60,
1561    /// MySQL 120). Omit to use that default. Ignored for a bring-your-own database.
1562    pub startup_grace_secs: Option<u32>,
1563    /// **Isolation mechanism** for a compute-backed managed database (2×2 axis 1).
1564    /// `single` (default) — a *dedicated* database server (its own container) per
1565    /// tenant; `shared` — *one* server hosting a permission-separated database + role
1566    /// per tenant. Ignored for a bring-your-own (`url_env`) database.
1567    pub tenant: TenantIsolation,
1568    /// **Tenant grain** for a compute-backed managed database (2×2 axis 2). `project`
1569    /// (default) — a tenant is a project; `site` — a tenant is a site. A tenant may
1570    /// hold several databases (one per binding that names it); it gets one login role
1571    /// and sealed credential per (tenant, server), granted on all its own databases
1572    /// and none of another tenant's. The reserved `default` project uses the plain
1573    /// configured name, so a single-tenant install is just one ordinary database.
1574    pub tenant_scope: TenantScope,
1575    /// **Opt-in** (default `false`): inject the request's `boatramp.project` /
1576    /// `boatramp.site` into the SQL session at each transaction start (Postgres
1577    /// `set_config` GUC, MySQL session var), so hand-written **native RLS** policies
1578    /// can key on them per-request. The GraphQL data connector's row-level policy is
1579    /// claim-sourced and needs nothing here; this is for hand-rolled RLS on the plain
1580    /// `sql.open` path (Postgres — the engine with native row-level security).
1581    ///
1582    /// # Trust model — read before relying on this for isolation
1583    ///
1584    /// `rls_session` **provides** the request's tenant to the SQL session for an app's
1585    /// RLS to key on. It is **not** a general hostile-guest boundary:
1586    ///
1587    /// - The reserved keys (`boatramp.*` / `@boatramp_*`) are **protected** from guest
1588    ///   override — a handler statement that tries to `set_config('boatramp.…', …)` /
1589    ///   `SET boatramp.… ` / `SET @boatramp_… ` (or `RESET`/`DISCARD` them) is refused,
1590    ///   so a guest cannot spoof its injected tenant.
1591    /// - But the **real tenant-isolation boundary** is the **per-tenant database +
1592    ///   role** (`tenant = single` / `shared`), which a compromised handler cannot
1593    ///   cross regardless of what it does in-session. `rls_session` is a convenience
1594    ///   for app-authored RLS *within* a tenant's own database, layered on top of that
1595    ///   boundary — not a substitute for it.
1596    /// - For untrusted data, prefer **claim-sourced** enforcement (the GraphQL data
1597    ///   connector's row-level policy), which derives the tenant from the verified
1598    ///   request, not from anything the handler's SQL can influence.
1599    pub rls_session: bool,
1600    /// The Postgres session GUC name an app's RLS policies read for the host-resolved **tenant**
1601    /// (e.g. `app.tenant_id`), set per request/write on the `rls_session` path so RLS mirrors
1602    /// boatramp's injected predicate as a defense-in-depth backstop (v0.4.20). Only honored when
1603    /// `rls_session` is on and the backend is Postgres. `None` ⇒ not exposed (today's behavior).
1604    /// The guest can never set this GUC itself (its namespace becomes reserved).
1605    #[serde(default)]
1606    pub tenant_guc: Option<String>,
1607    /// The session GUC name for the anonymous **session** axis (e.g. `app.session_id`), the
1608    /// disjoint-column sibling of `tenant_guc` for `TenantOrSession` tables. `None` ⇒ not exposed.
1609    #[serde(default)]
1610    pub session_guc: Option<String>,
1611    /// A reserved sentinel value written to `tenant_guc` on an **`all`-scoped READ** (v0.4.21), so a
1612    /// table that opts in with `USING (… OR current_setting(tenant_guc, true) = '<marker>')` opens
1613    /// cross-tenant for the audited `all` twins. Pick a value that can **never** be a real tenant id
1614    /// (e.g. `*` or `__all__`). Only honored with `tenant_guc` set + `rls_session` on + Postgres.
1615    /// `None`/empty ⇒ `all` reads leave the GUC untouched (v0.4.20 fail-closed behavior). The guest
1616    /// can never set it — the `tenant_guc` namespace is already reserved against guest writes.
1617    #[serde(default)]
1618    pub tenant_all_marker: Option<String>,
1619    /// The on-disk file path for a single-node **`libsql`** database (`kind: "libsql"`), e.g.
1620    /// `/data/app.db`. The parent directory is created if absent. Used only by the embedded engine;
1621    /// ignored for `postgres`/`mysql` and for a remote-sqld `libsql` binding (which uses `url_env`).
1622    /// A `libsql` entry sets exactly one of `path` (single-node file) or `url_env` (remote sqld).
1623    #[serde(default)]
1624    pub path: Option<PathBuf>,
1625}
1626
1627/// How a managed compute-backed database is physically isolated per tenant (2×2 axis
1628/// 1). `Single` = a dedicated server (container) per tenant (isolation by separate
1629/// process); `Shared` = one server with a per-tenant database + login role (isolation
1630/// by grants — Postgres `REVOKE CONNECT FROM PUBLIC` + owner grant; MySQL per-schema
1631/// grant), so a tenant's role cannot connect to another tenant's database.
1632#[cfg_attr(not(feature = "handlers"), allow(dead_code))]
1633#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Deserialize)]
1634#[serde(rename_all = "lowercase")]
1635pub enum TenantIsolation {
1636    /// A dedicated database server (its own container) per tenant. The default.
1637    #[default]
1638    Single,
1639    /// One shared server hosting a per-tenant database + role (grant-isolated).
1640    Shared,
1641}
1642
1643/// The grain of a tenant for a managed compute-backed database (2×2 axis 2) —
1644/// `Project` (default) or `Site`. The two grains are parallel; the isolation
1645/// mechanism is [`TenantIsolation`].
1646#[cfg_attr(not(feature = "handlers"), allow(dead_code))]
1647#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Deserialize)]
1648#[serde(rename_all = "lowercase")]
1649pub enum TenantScope {
1650    /// A tenant is a **project** (the default).
1651    #[default]
1652    Project,
1653    /// A tenant is a **site** (finer than project).
1654    Site,
1655}
1656
1657impl ExternalDatabaseConfig {
1658    /// Validate the source is well-formed: **exactly one** of `url_env` /
1659    /// `compute`, and a `compute`-backed database has the connection details
1660    /// boatramp can't infer (`database` + `user`). `password_env` is **optional** —
1661    /// omit it to let boatramp manage the credential (Phase 2). `name` is the
1662    /// binding name, for the error message.
1663    #[cfg_attr(not(feature = "handlers"), allow(dead_code))]
1664    pub fn validate(&self, name: &str) -> Result<(), String> {
1665        let has_url = !self.url_env.is_empty();
1666        let has_compute = self.compute.as_deref().is_some_and(|c| !c.is_empty());
1667        let has_path = self
1668            .path
1669            .as_deref()
1670            .is_some_and(|p| !p.as_os_str().is_empty());
1671
1672        // A `libsql`/`sqlite` entry is the embedded engine: single-node via `path`, or remote sqld
1673        // via `url_env` — never `compute` (boatramp doesn't run a libsql server workload). Validate
1674        // it on its own axis (exactly one of `path` / `url_env`), and reject `path` on the external
1675        // engines (a Postgres/MySQL binding has no on-disk file).
1676        let is_libsql = matches!(
1677            self.kind.trim().to_ascii_lowercase().as_str(),
1678            "libsql" | "sqlite" | "sqlite3"
1679        );
1680        if is_libsql {
1681            if has_compute {
1682                return Err(format!(
1683                    "sql database {name:?}: a `libsql` database is the embedded engine — set `path` \
1684                     (single-node file) or `url_env` (remote sqld), not `compute`"
1685                ));
1686            }
1687            return match (has_path, has_url) {
1688                (true, true) => Err(format!(
1689                    "sql database {name:?}: a `libsql` database sets exactly one of `path` \
1690                     (single-node file) or `url_env` (remote sqld), not both"
1691                )),
1692                (false, false) => Err(format!(
1693                    "sql database {name:?}: a `libsql` database needs a source — set `path` \
1694                     (single-node file) or `url_env` (remote sqld)"
1695                )),
1696                _ => Ok(()),
1697            };
1698        }
1699        if has_path {
1700            return Err(format!(
1701                "sql database {name:?}: `path` is only valid for a `libsql` database (the embedded \
1702                 engine); a {} binding uses `url_env` or `compute`",
1703                self.kind
1704            ));
1705        }
1706
1707        match (has_url, has_compute) {
1708            (true, true) => Err(format!(
1709                "sql database {name:?}: set exactly one of `url_env` or `compute`, not both"
1710            )),
1711            (false, false) => Err(format!(
1712                "sql database {name:?}: needs a source — set `url_env` (bring-your-own) or \
1713                 `compute` (a database boatramp runs)"
1714            )),
1715            (false, true) => {
1716                // `database` + `user` are non-secret and can't be inferred; a missing
1717                // `password_env` is *not* an error — it selects the managed credential.
1718                for (field, val) in [("database", &self.database), ("user", &self.user)] {
1719                    if val.as_deref().is_none_or(str::is_empty) {
1720                        return Err(format!(
1721                            "sql database {name:?}: a `compute`-backed database requires `{field}`"
1722                        ));
1723                    }
1724                }
1725                Ok(())
1726            }
1727            (true, false) => Ok(()),
1728        }
1729    }
1730
1731    /// Whether this compute-backed database uses a **boatramp-managed** credential
1732    /// (Phase 2): `compute` is set and no `password_env` was supplied.
1733    #[cfg_attr(not(feature = "handlers"), allow(dead_code))]
1734    pub fn is_managed_credential(&self) -> bool {
1735        self.compute.as_deref().is_some_and(|c| !c.is_empty())
1736            && self.password_env.as_deref().is_none_or(str::is_empty)
1737    }
1738}
1739
1740/// The signing algorithm for a signer that can choose one (`Local`, `Vault`,
1741/// `Pkcs11`). ES256 is the portable default; the cloud KMS backends are ES256-only
1742/// and ignore this. Written as a RON enum: `alg: Es256` / `alg: Ed25519`.
1743#[derive(Debug, Clone, Copy, Default, Deserialize)]
1744pub enum SignerAlg {
1745    /// ECDSA P-256 (COSE ES256) — the default.
1746    #[default]
1747    Es256,
1748    /// Ed25519 (COSE EdDSA).
1749    Ed25519,
1750}
1751
1752impl SignerAlg {
1753    fn to_token_alg(self) -> boatramp_core::cose::TokenAlg {
1754        match self {
1755            Self::Es256 => boatramp_core::cose::TokenAlg::Es256,
1756            Self::Ed25519 => boatramp_core::cose::TokenAlg::Ed25519,
1757        }
1758    }
1759}
1760
1761/// External token signer selector (`serve.signer`). Maps to
1762/// [`boatramp_server::signer::SignerConfig`]; secrets (tokens/PINs) are resolved
1763/// from the named env vars at startup, never stored in config. Written as a RON
1764/// enum — `signer: Vault(...)`, `signer: AwsKms(...)`, `signer: Pkcs11(...)`, ….
1765#[derive(Debug, Clone, Deserialize)]
1766#[serde(deny_unknown_fields)]
1767pub enum AuthSignerConfig {
1768    /// In-process key (`"<alg>:<hex>"`).
1769    Local {
1770        /// The private key spec, `"<alg>:<hex>"`.
1771        private_key: String,
1772    },
1773    /// HashiCorp Vault Transit key.
1774    Vault {
1775        /// Vault base address.
1776        address: String,
1777        /// The Transit key name.
1778        key: String,
1779        /// Env var holding the Vault token.
1780        token_env: String,
1781        /// The key algorithm.
1782        #[serde(default)]
1783        alg: SignerAlg,
1784    },
1785    /// AWS KMS asymmetric key (ES256).
1786    AwsKms {
1787        /// The KMS key id or ARN.
1788        key_id: String,
1789        /// Optional region override.
1790        #[serde(default)]
1791        region: Option<String>,
1792    },
1793    /// GCP Cloud KMS key version (ES256).
1794    GcpKms {
1795        /// The key-version resource name.
1796        key_version: String,
1797        /// Env var holding a GCP OAuth2 access token.
1798        access_token_env: String,
1799    },
1800    /// Azure Key Vault key (ES256).
1801    AzureKv {
1802        /// The vault base URL.
1803        vault_url: String,
1804        /// The key name.
1805        key: String,
1806        /// The key version.
1807        key_version: String,
1808        /// Env var holding an Azure AD access token.
1809        access_token_env: String,
1810    },
1811    /// PKCS#11 HSM key.
1812    Pkcs11 {
1813        /// Path to the PKCS#11 module.
1814        module: String,
1815        /// The token label.
1816        token_label: String,
1817        /// The key's `CKA_LABEL`.
1818        key_label: String,
1819        /// Env var holding the user PIN.
1820        pin_env: String,
1821        /// The key algorithm.
1822        #[serde(default)]
1823        alg: SignerAlg,
1824    },
1825}
1826
1827impl AuthSignerConfig {
1828    /// Map the config-file form to the server's runtime [`SignerConfig`].
1829    pub fn to_signer_config(&self) -> boatramp_server::signer::SignerConfig {
1830        use boatramp_server::signer::SignerConfig;
1831        match self {
1832            Self::Local { private_key } => SignerConfig::Local {
1833                private_key: private_key.clone(),
1834            },
1835            Self::Vault {
1836                address,
1837                key,
1838                token_env,
1839                alg,
1840            } => SignerConfig::Vault {
1841                address: address.clone(),
1842                key: key.clone(),
1843                token_env: token_env.clone(),
1844                alg: alg.to_token_alg(),
1845            },
1846            Self::AwsKms { key_id, region } => SignerConfig::AwsKms {
1847                key_id: key_id.clone(),
1848                region: region.clone(),
1849            },
1850            Self::GcpKms {
1851                key_version,
1852                access_token_env,
1853            } => SignerConfig::GcpKms {
1854                key_version: key_version.clone(),
1855                access_token_env: access_token_env.clone(),
1856            },
1857            Self::AzureKv {
1858                vault_url,
1859                key,
1860                key_version,
1861                access_token_env,
1862            } => SignerConfig::AzureKv {
1863                vault_url: vault_url.clone(),
1864                key: key.clone(),
1865                key_version: key_version.clone(),
1866                access_token_env: access_token_env.clone(),
1867            },
1868            Self::Pkcs11 {
1869                module,
1870                token_label,
1871                key_label,
1872                pin_env,
1873                alg,
1874            } => SignerConfig::Pkcs11 {
1875                module: module.clone(),
1876                token_label: token_label.clone(),
1877                key_label: key_label.clone(),
1878                pin_env: pin_env.clone(),
1879                alg: alg.to_token_alg(),
1880            },
1881        }
1882    }
1883}
1884
1885/// `serve` section — server defaults, overridden by flags/env.
1886#[derive(Debug, Clone, Default, Deserialize)]
1887#[serde(default)]
1888pub struct ServeConfig {
1889    /// Bind address (e.g. `0.0.0.0:8080`).
1890    pub addr: Option<SocketAddr>,
1891    /// Data directory for filesystem backends.
1892    pub data_dir: Option<PathBuf>,
1893    /// Token root **private** key (hex) — issuing node: verifies *and* mints
1894    /// tokens / OIDC exchanges.
1895    pub auth_root_private_key: Option<String>,
1896    /// Token root **public** key (hex) — verify-only node.
1897    pub auth_root_public_key: Option<String>,
1898    /// Single-use bootstrap secret enabling `POST /api/tokens/bootstrap` (mint the
1899    /// first token without an admin bearer). Prefer the `BOATRAMP_BOOTSTRAP_SECRET`
1900    /// env / `--bootstrap-secret` flag so it isn't persisted in the config file.
1901    pub bootstrap_secret: Option<String>,
1902    /// External token signer (`[serve.signer]`): mint with a
1903    /// KMS/HSM/Vault-held root key instead of an in-process `auth_root_private_key`.
1904    /// Absent ⇒ the in-process key. When set, its public half is the trust anchor.
1905    pub signer: Option<AuthSignerConfig>,
1906    /// Reject blob uploads larger than this many bytes.
1907    pub max_upload_bytes: Option<u64>,
1908    /// Abort an upload that stalls for longer than this many seconds.
1909    pub upload_idle_timeout_secs: Option<u64>,
1910    /// Cap on simultaneous blob uploads.
1911    pub max_concurrent_uploads: Option<usize>,
1912    /// In a TLS mode, bind this plain-HTTP address on a second listener that
1913    /// redirects to HTTPS (dual-listener). Only read in `tls` builds.
1914    #[cfg_attr(not(feature = "tls"), allow(dead_code))]
1915    pub http_redirect_addr: Option<SocketAddr>,
1916    /// Site to serve for a `Host` matching no domain, instead of 404.
1917    pub default_site: Option<String>,
1918    /// The fleet's canonical public origin (e.g. `https://cp.example.com`) that a
1919    /// per-request proof-of-possession must bind to (`aud`). Required for
1920    /// holder-bound (`cnf`/PoP) tokens to be usable — a proof's origin is compared
1921    /// against this value, never against a `Host`/`X-Forwarded-*` header.
1922    pub pop_origin: Option<String>,
1923    /// Require a valid control-plane token to view deployment previews.
1924    pub protect_previews: bool,
1925    /// Rate-limit cluster-wide via the control-plane KV instead of per node.
1926    pub cluster_rate_limit: bool,
1927    /// Keep the config cache coherent across processes sharing one KV via the
1928    /// changelog.
1929    pub shared_cache_coherence: bool,
1930    /// Cloud blob-change notification provisioning tier (FA-5b2): how boatramp
1931    /// obtains the native event pipeline (S3→SQS) that backs a `blob` trigger —
1932    /// `dry-run` (print the recipe), `provision` (create + retract), `verify-only`
1933    /// (operator pre-wired), or `refuse` (fail closed). Absent ⇒ no provisioning:
1934    /// `blob` triggers then work only on a self-watching backend (fs). Only wired
1935    /// for the S3 backend (`--features s3`).
1936    pub blob_notify_tier: Option<boatramp_core::blob_notify::ProvisionTier>,
1937    /// The AWS account id used to scope the provisioned SQS queue's `SendMessage`
1938    /// policy (`aws:SourceAccount`). Required when `blob_notify_tier` provisions.
1939    pub blob_notify_account_id: Option<String>,
1940    /// `[serve.console]` — the embedded web management console. Absent (or
1941    /// `enabled: false`) ⇒ not served. This is the **baseline** for the dynamic
1942    /// `console.*` daemon-config override, which can enable/move it at runtime
1943    /// (`boatramp config set console.enabled true`) without a restart.
1944    pub console: Option<ConsoleConfig>,
1945    /// Bind address for the **dedicated local S3-ingress listener** (PLAN-blob-s3-ingress,
1946    /// Architect HIGH-4). Absent ⇒ the local S3 face is NOT served (it is opt-in — a deployment that
1947    /// only mints cloud-brokered credentials never needs it). This is a SEPARATE listener from the
1948    /// control-plane `addr`: it has its own SigV4 auth surface and never reaches `serve_by_host` or
1949    /// the `/api` router.
1950    pub s3_ingress_addr: Option<SocketAddr>,
1951    /// Path to the **dedicated S3-ingress root secret** file (raw 32 bytes) — the independently-
1952    /// rotatable HKDF root for `secret_access_key` derivation (hard domain separation from the
1953    /// `[secrets]` KEK + the COSE signing key). Like `[secrets].kek_file`, this holds a *path*, never
1954    /// key material in the config text, and (in a cluster) the **same file must be present on every
1955    /// node** so every node derives the same `secret_access_key`. Absent on a single node ⇒ an
1956    /// ephemeral per-process root is auto-generated; absent on a **multi-node** deployment ⇒ the S3
1957    /// face is refused to enable (fail-closed — credentials would otherwise be un-verifiable across
1958    /// nodes). Prefer the `BOATRAMP_S3_INGRESS_SECRET_FILE` env / flag so the path stays out of the
1959    /// committed config where that matters operationally.
1960    pub s3_ingress_secret_file: Option<PathBuf>,
1961    /// The publicly-reachable base URL an external client targets for the local S3 face — what a
1962    /// **minted** upload credential (`boatramp:handlers/blob-upload` guest mint / `boatramp blob
1963    /// mint-upload` operator) embeds as its endpoint (a presigned-put URL prefix, or the SDK endpoint
1964    /// for temp-credentials). Absent ⇒ derived from `s3_ingress_addr` as `http://<addr>` (fine for a
1965    /// same-host dev/test loop; set it explicitly to the TLS-terminated public URL in production).
1966    /// Only consulted when guest/operator upload minting is wired (`blob-upload` feature + the face
1967    /// enabled).
1968    pub s3_ingress_public_url: Option<String>,
1969    /// Operator ceiling (seconds) on a minted upload credential's TTL — a guest/operator can only
1970    /// request a SHORTER lifetime (the mint clamps to this). Absent ⇒ a conservative default
1971    /// ([`DEFAULT_S3_INGRESS_MINT_MAX_TTL_SECS`]). A `0` disables minting entirely (the binding is
1972    /// never attached).
1973    pub s3_ingress_mint_max_ttl_secs: Option<u64>,
1974    /// Operator ceiling (bytes) on a minted credential's `max_bytes` constraint — a guest can only
1975    /// request a SMALLER cap (clamped to this). Absent ⇒ no host-side max-bytes clamp (the per-container
1976    /// ceiling at the face still applies).
1977    pub s3_ingress_mint_max_bytes: Option<u64>,
1978    /// **Cloud brokering** (M4): when the node's blob backend is a cloud object store (S3/GCS/Azure)
1979    /// and this is set, minting brokers a NATIVE scoped credential (STS session policy / signed URL +
1980    /// CAB / user-delegation SAS) so the client uploads DIRECTLY to the real store (bytes never transit
1981    /// the node) — INSTEAD of the local S3 face. Absent ⇒ the local face is used (an fs/in-memory
1982    /// backend, or a cloud backend that re-transits through the local face). See [`S3IngressCloud`].
1983    pub s3_ingress_cloud: Option<S3IngressCloud>,
1984}
1985
1986/// `[serve.s3_ingress_cloud]` — the cloud-brokering knobs for the M4 blob-upload minter (which native
1987/// credential the mint brokers when the node's blob backend is a cloud object store). Only the fields
1988/// for the active blob backend are consulted; a `None` here ⇒ the local S3 face mints.
1989#[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize)]
1990pub struct S3IngressCloud {
1991    /// **AWS**: the IAM role ARN the base credential assumes to broker the scoped session-policy
1992    /// credential (`sts:AssumeRole`, the default). Absent AND `aws_use_federation_token = true` ⇒
1993    /// `sts:GetFederationToken` is used instead (for an IAM-user base credential).
1994    pub aws_role_arn: Option<String>,
1995    /// **AWS**: use `sts:GetFederationToken` instead of `AssumeRole` (IAM-user deployments). Requires
1996    /// the base credential to be a real IAM user, not itself a session.
1997    #[serde(default)]
1998    pub aws_use_federation_token: bool,
1999    /// **GCS**: the service-account client email whose V4 signed URLs / IAM-signed uploads the minter
2000    /// produces (used in the signing scope). Absent ⇒ resolved from ADC.
2001    pub gcs_client_email: Option<String>,
2002    /// **Azure**: the storage account name (for the SAS signature + the blob URL). Absent ⇒ taken from
2003    /// the `azure_account` blob-backend arg.
2004    pub azure_account: Option<String>,
2005    /// **Azure**: the blob service URL (`https://{account}.blob.core.windows.net/`). Absent ⇒ derived
2006    /// from the account name.
2007    pub azure_service_url: Option<String>,
2008    /// **Azure**: declare the storage account has a **hierarchical namespace** (HNS/ADLS-Gen2). A
2009    /// directory-scoped SAS only actually confines to a sub-prefix on an HNS account; on a flat account
2010    /// it silently degrades to container-wide (Security LOW-1). So a PREFIX mint is refused unless this
2011    /// is `true`. Default `false` (fail-closed). A single-key mint is unaffected.
2012    #[serde(default)]
2013    pub azure_hns: bool,
2014}
2015
2016/// The default operator ceiling on a minted S3 upload credential's TTL when
2017/// `[serve].s3_ingress_mint_max_ttl_secs` is unset: 1 hour — long enough for a browser UGC upload or a
2018/// bulk-agent burst, short enough to bound a leaked short-lived credential.
2019pub const DEFAULT_S3_INGRESS_MINT_MAX_TTL_SECS: u64 = 3600;
2020
2021/// `[serve.console]` — the embedded web console (a Wasm SPA baked into the
2022/// binary with the `console` build feature). Opt-in: the static shell holds no
2023/// secrets and the `/api` it drives is token-gated, so it is served
2024/// **unauthenticated** at a deliberately obscure path (a bearer token can't gate
2025/// a top-level browser navigation anyway — the path is the obscurity, the token
2026/// is the real gate).
2027#[cfg_attr(not(feature = "console"), allow(dead_code))]
2028#[derive(Debug, Clone, Default, Deserialize)]
2029#[serde(default, deny_unknown_fields)]
2030pub struct ConsoleConfig {
2031    /// Serve the embedded console (default `false`). Requires the `console` build
2032    /// feature; enabling it in a build without that feature is a logged no-op.
2033    pub enabled: bool,
2034    /// Host(s) the console answers on: `*` (any host, the default), an exact host
2035    /// (`console.example.com`), or a leading-wildcard (`*.example.com`).
2036    pub host: Option<String>,
2037    /// URL path prefix the console mounts at (default `/_console`). Kept under the
2038    /// reserved `/_` namespace so it never collides with a published site path.
2039    pub path: Option<String>,
2040}
2041
2042/// `publish` section — where and what to deploy (the `sync` target).
2043#[derive(Debug, Default, Deserialize)]
2044#[serde(default)]
2045pub struct PublishConfig {
2046    /// Base URL of the boatramp server (e.g. `https://pad.example.com`).
2047    pub server: Option<String>,
2048    /// Site name to publish to.
2049    pub site: Option<String>,
2050    /// API token for the control plane (or set `BOATRAMP_TOKEN`).
2051    pub token: Option<String>,
2052    /// Project this site belongs to (overrides with `--project` / `BOATRAMP_PROJECT`).
2053    pub project: Option<String>,
2054}
2055
2056/// `build` section.
2057#[derive(Debug, Clone, Deserialize, serde::Serialize)]
2058pub struct BuildConfig {
2059    /// Shell command to run (e.g. `npm run build`).
2060    pub command: String,
2061    /// Directory the build emits, published by `sync` (e.g. `dist`).
2062    #[serde(default, skip_serializing_if = "Option::is_none")]
2063    pub output: Option<String>,
2064}
2065
2066/// `bundle` section — the in-process Rust bundler (`bundler` feature).
2067#[derive(Debug, Clone, Default, Deserialize)]
2068#[serde(default)]
2069pub struct BundleConfig {
2070    /// Output directory for bundled assets (e.g. `dist`).
2071    #[serde(default = "default_bundle_outdir")]
2072    pub outdir: String,
2073    /// JS/TS entry points bundled by Rolldown (tree-shaken, code-split).
2074    pub js: Vec<String>,
2075    /// CSS entry points bundled by lightningcss (`@import` inlined).
2076    pub css: Vec<String>,
2077    /// Minify output (default true).
2078    #[serde(default = "default_true")]
2079    pub minify: bool,
2080}
2081
2082fn default_bundle_outdir() -> String {
2083    "dist".to_string()
2084}
2085
2086fn default_true() -> bool {
2087    true
2088}
2089
2090#[cfg(test)]
2091mod tests {
2092    use super::*;
2093
2094    fn project(text: &str) -> ProjectConfig {
2095        ron_options().from_str(text).unwrap()
2096    }
2097
2098    fn server(text: &str) -> ServerConfig {
2099        ron_options().from_str(text).unwrap()
2100    }
2101
2102    /// Build an [`EnvSource::Map`] from `(name, value)` pairs for deterministic
2103    /// override tests (no process-global `std::env` mutation).
2104    fn env(pairs: &[(&str, &str)]) -> EnvSource {
2105        EnvSource::Map(
2106            pairs
2107                .iter()
2108                .map(|(k, v)| (k.to_string(), v.to_string()))
2109                .collect(),
2110        )
2111    }
2112
2113    #[test]
2114    fn env_overrides_configure_all_three_sections_with_no_file() {
2115        // The crux of the ask: with NO `boatramp.cfg` at all (the default config),
2116        // env vars alone materialise + populate the compute, security, and handler
2117        // `sql` sections. `ServerConfig::default()` has all three absent.
2118        let mut cfg = ServerConfig::default();
2119        assert!(cfg.compute.is_none() && cfg.security.is_none() && cfg.handlers.is_none());
2120
2121        cfg.apply_env_overrides(&env(&[
2122            ("BOATRAMP_COMPUTE_VCPUS", "8"),
2123            ("BOATRAMP_COMPUTE_MEM_MIB", "4096"),
2124            ("BOATRAMP_COMPUTE_REGION", "eu-central"),
2125            ("BOATRAMP_SECURITY_PROFILE", "single-tenant"),
2126            ("BOATRAMP_SECURITY_ALLOW_SITE_PRIVATE_UPSTREAMS", "true"),
2127            ("BOATRAMP_SECURITY_MAX_UPLOAD_BYTES", "1048576"),
2128            ("BOATRAMP_HANDLERS_SQL_URL", "http://sqld:8080"),
2129            ("BOATRAMP_HANDLERS_SQL_ADMIN_URL", "http://sqld:9090"),
2130        ]))
2131        .expect("valid env overrides apply");
2132
2133        // compute: the section now exists with the env values (and defaults elsewhere).
2134        let compute = cfg.compute.expect("compute materialised from env");
2135        assert_eq!(compute.vcpus, 8);
2136        assert_eq!(compute.mem_mib, 4096);
2137        assert_eq!(compute.region.as_deref(), Some("eu-central"));
2138        assert_eq!(compute.bridge, "br-boatramp"); // untouched default
2139
2140        // security: profile + an override both took, and the posture resolves.
2141        let security = cfg.security.expect("security materialised from env");
2142        assert_eq!(security.profile.as_deref(), Some("single-tenant"));
2143        let posture = security.resolve().expect("resolves");
2144        assert!(posture.allow_site_private_upstreams);
2145        assert_eq!(posture.max_upload_bytes, 1_048_576);
2146
2147        // handler sql: the nested handlers.bindings.sql chain was created.
2148        let sql = cfg
2149            .handlers
2150            .expect("handlers materialised from env")
2151            .bindings
2152            .sql
2153            .expect("sql binding materialised from env");
2154        assert_eq!(sql.url.as_deref(), Some("http://sqld:8080"));
2155        assert_eq!(sql.admin_url.as_deref(), Some("http://sqld:9090"));
2156    }
2157
2158    #[test]
2159    fn internal_dns_defaults_on_with_the_standard_upstream_and_domain() {
2160        // The `[compute]` defaults: internal DNS on, forwarding to 1.1.1.1:53, names
2161        // under `boatramp.internal`.
2162        let compute = ComputeConfig::default();
2163        assert!(compute.internal_dns, "internal DNS is on by default");
2164        assert_eq!(compute.dns_upstream, "1.1.1.1:53");
2165        assert_eq!(compute.dns_domain, "boatramp.internal");
2166    }
2167
2168    #[test]
2169    fn internal_dns_knobs_parse_from_a_file() {
2170        // A file can turn it off and override the upstream + domain.
2171        let cfg = server(
2172            r#"(
2173                compute: ( internal_dns: false, dns_upstream: "10.0.0.53:53", dns_domain: "svc.internal" ),
2174            )"#,
2175        );
2176        let compute = cfg.compute.expect("compute section");
2177        assert!(!compute.internal_dns);
2178        assert_eq!(compute.dns_upstream, "10.0.0.53:53");
2179        assert_eq!(compute.dns_domain, "svc.internal");
2180    }
2181
2182    #[test]
2183    fn internal_dns_knobs_are_env_settable() {
2184        // Env alone materialises `[compute]` and sets each internal-DNS knob (and an
2185        // unrecognised bool spelling is a clear error, exercised by parse_bool).
2186        let mut cfg = ServerConfig::default();
2187        cfg.apply_env_overrides(&env(&[
2188            ("BOATRAMP_COMPUTE_INTERNAL_DNS", "off"),
2189            ("BOATRAMP_COMPUTE_DNS_UPSTREAM", "9.9.9.9:53"),
2190            ("BOATRAMP_COMPUTE_DNS_DOMAIN", "corp.internal"),
2191        ]))
2192        .expect("valid env overrides apply");
2193        let compute = cfg.compute.expect("compute materialised from env");
2194        assert!(!compute.internal_dns, "env `off` disables internal DNS");
2195        assert_eq!(compute.dns_upstream, "9.9.9.9:53");
2196        assert_eq!(compute.dns_domain, "corp.internal");
2197    }
2198
2199    #[test]
2200    fn env_override_wins_over_file_value_but_unset_defers() {
2201        // A file that set each section; env then overrides one field per section
2202        // and leaves the rest of the file value in place (precedence: env > file).
2203        let mut cfg = server(
2204            r#"(
2205                compute: ( vcpus: 2, mem_mib: 512, region: "us-east" ),
2206                security: ( profile: "multi-tenant" ),
2207                handlers: ( bindings: ( sql: ( url: "http://file:8080", admin_url: "http://file:9090" ) ) ),
2208            )"#,
2209        );
2210
2211        cfg.apply_env_overrides(&env(&[
2212            ("BOATRAMP_COMPUTE_VCPUS", "16"),
2213            ("BOATRAMP_SECURITY_PROFILE", "dev"),
2214            ("BOATRAMP_HANDLERS_SQL_URL", "http://env:8080"),
2215        ]))
2216        .expect("valid env overrides apply");
2217
2218        let compute = cfg.compute.unwrap();
2219        assert_eq!(compute.vcpus, 16, "env wins over the file vcpus");
2220        assert_eq!(compute.mem_mib, 512, "unset env defers to the file mem_mib");
2221        assert_eq!(
2222            compute.region.as_deref(),
2223            Some("us-east"),
2224            "unset env defers to the file region"
2225        );
2226
2227        assert_eq!(
2228            cfg.security.unwrap().profile.as_deref(),
2229            Some("dev"),
2230            "env profile wins over the file profile"
2231        );
2232
2233        let sql = cfg.handlers.unwrap().bindings.sql.unwrap();
2234        assert_eq!(
2235            sql.url.as_deref(),
2236            Some("http://env:8080"),
2237            "env wins over the file sql url"
2238        );
2239        assert_eq!(
2240            sql.admin_url.as_deref(),
2241            Some("http://file:9090"),
2242            "unset env defers to the file sql admin_url"
2243        );
2244    }
2245
2246    #[test]
2247    fn env_overrides_leave_unmentioned_sections_absent() {
2248        // With no relevant env vars set, an empty config stays empty — the sections
2249        // are materialised only on demand, so an unset environment adds nothing.
2250        let mut cfg = ServerConfig::default();
2251        cfg.apply_env_overrides(&env(&[("SOME_UNRELATED_VAR", "x")]))
2252            .expect("no-op env applies");
2253        assert!(cfg.compute.is_none());
2254        assert!(cfg.security.is_none());
2255        assert!(cfg.handlers.is_none());
2256        assert!(cfg.secrets.is_none());
2257        assert!(cfg.cluster.is_none());
2258    }
2259
2260    #[test]
2261    fn env_bool_accepts_common_spellings_and_rejects_garbage() {
2262        // Truthy/falsey spellings all parse.
2263        for (raw, want) in [
2264            ("true", true),
2265            ("1", true),
2266            ("YES", true),
2267            ("On", true),
2268            ("false", false),
2269            ("0", false),
2270            ("no", false),
2271            ("OFF", false),
2272        ] {
2273            let mut cfg = ServerConfig::default();
2274            cfg.apply_env_overrides(&env(&[("BOATRAMP_SECURITY_REQUIRE_POP", raw)]))
2275                .expect("boolean parses");
2276            assert_eq!(
2277                cfg.security.unwrap().overrides.require_pop,
2278                Some(want),
2279                "{raw:?} ⇒ {want}"
2280            );
2281        }
2282        // A non-boolean value is a clear error, not a silent default.
2283        let mut cfg = ServerConfig::default();
2284        let err = cfg
2285            .apply_env_overrides(&env(&[("BOATRAMP_SECURITY_REQUIRE_POP", "maybe")]))
2286            .expect_err("garbage boolean is rejected");
2287        match err {
2288            ConfigError::Env { var, .. } => assert_eq!(var, "BOATRAMP_SECURITY_REQUIRE_POP"),
2289            other => panic!("expected ConfigError::Env, got {other:?}"),
2290        }
2291    }
2292
2293    #[test]
2294    fn env_number_parse_error_names_the_variable() {
2295        // A non-numeric numeric var is rejected with the variable named.
2296        let mut cfg = ServerConfig::default();
2297        let err = cfg
2298            .apply_env_overrides(&env(&[("BOATRAMP_COMPUTE_VCPUS", "lots")]))
2299            .expect_err("garbage number is rejected");
2300        match err {
2301            ConfigError::Env { var, .. } => assert_eq!(var, "BOATRAMP_COMPUTE_VCPUS"),
2302            other => panic!("expected ConfigError::Env, got {other:?}"),
2303        }
2304    }
2305
2306    #[test]
2307    fn empty_env_value_is_treated_as_unset() {
2308        // `VAR=` (empty) must not clobber a file value with an empty string.
2309        let mut cfg = server(r#"( compute: ( region: "us-east" ) )"#);
2310        cfg.apply_env_overrides(&env(&[("BOATRAMP_COMPUTE_REGION", "")]))
2311            .expect("empty env applies as a no-op");
2312        assert_eq!(
2313            cfg.compute.unwrap().region.as_deref(),
2314            Some("us-east"),
2315            "an empty env value leaves the file value in place"
2316        );
2317    }
2318
2319    #[test]
2320    fn env_configures_managed_postgres_secrets_and_privilege_with_no_file() {
2321        // The construens acceptance case: with NO `boatramp.cfg` at all, the
2322        // environment alone stands up a managed co-located Postgres. It configures
2323        // the default (`"default"`-named, v0.5.0) database in
2324        // `handlers.bindings.sql.databases` (kind=postgres, compute=pg, database+user
2325        // set), the `[secrets]` envelope (local + a kek path so the managed credential
2326        // can be sealed), and `compute.managed_db_privilege = rootless`. All three
2327        // sections start absent.
2328        let mut cfg = ServerConfig::default();
2329        assert!(cfg.handlers.is_none() && cfg.secrets.is_none() && cfg.compute.is_none());
2330
2331        cfg.apply_env_overrides(&env(&[
2332            // The default database is addressed by the reserved `DEFAULT` token,
2333            // which maps to the reserved real name `"default"` (v0.5.0).
2334            ("BOATRAMP_HANDLERS_SQL_DB_DEFAULT_KIND", "postgres"),
2335            ("BOATRAMP_HANDLERS_SQL_DB_DEFAULT_COMPUTE", "pg"),
2336            ("BOATRAMP_HANDLERS_SQL_DB_DEFAULT_DATABASE", "appdb"),
2337            ("BOATRAMP_HANDLERS_SQL_DB_DEFAULT_USER", "app"),
2338            // Secrets: the local envelope + a KEK path (never key material).
2339            ("BOATRAMP_SECRETS_ENVELOPE", "local"),
2340            ("BOATRAMP_SECRETS_KEK_FILE", "/var/lib/boatramp/secrets/kek"),
2341            // The shared-kernel DB privilege strategy.
2342            ("BOATRAMP_COMPUTE_MANAGED_DB_PRIVILEGE", "rootless"),
2343        ]))
2344        .expect("valid env overrides apply");
2345
2346        // The default (`"default"`-keyed) managed database exists with the right source.
2347        let sql = cfg
2348            .handlers
2349            .expect("handlers materialised from env")
2350            .bindings
2351            .sql
2352            .expect("sql binding materialised from env");
2353        let db = sql
2354            .databases
2355            .get(boatramp_core::project::DEFAULT_DB_NAME)
2356            .expect("the default `default`-named database was created from DEFAULT");
2357        assert!(
2358            !sql.databases.contains_key(""),
2359            "the empty-string key is never produced (v0.5.0)"
2360        );
2361        assert_eq!(db.kind, "postgres");
2362        assert_eq!(db.compute.as_deref(), Some("pg"));
2363        assert_eq!(db.database.as_deref(), Some("appdb"));
2364        assert_eq!(db.user.as_deref(), Some("app"));
2365        // No `password_env` ⇒ boatramp manages the credential (Phase 2), and the
2366        // compute-backed source validates.
2367        assert!(db.password_env.is_none());
2368        assert!(db.is_managed_credential());
2369        assert!(db.validate("").is_ok());
2370
2371        // The secrets envelope + KEK path took (the path is a location, not a key).
2372        let secrets = cfg.secrets.expect("secrets materialised from env");
2373        assert_eq!(secrets.envelope, "local");
2374        assert_eq!(
2375            secrets.kek_file.as_deref(),
2376            Some(Path::new("/var/lib/boatramp/secrets/kek"))
2377        );
2378        assert!(
2379            secrets.vault.is_none(),
2380            "no vault vars ⇒ no vault sub-config"
2381        );
2382
2383        // The managed-DB privilege strategy resolved from its lowercase variant.
2384        let compute = cfg.compute.expect("compute materialised from env");
2385        assert_eq!(compute.managed_db_privilege, ManagedDbPrivilege::Rootless);
2386    }
2387
2388    #[test]
2389    fn env_declares_named_databases_and_merges_over_the_file() {
2390        // A file declares one database; the env overrides one of its fields and
2391        // ADDS a second, discovering both member names from the environment.
2392        let mut cfg = server(
2393            r#"(
2394                handlers: ( bindings: ( sql: (
2395                    databases: {
2396                        "analytics": ( kind: "postgres", url_env: "FILE_PG_URL", pool_max: 4 ),
2397                    },
2398                ) ) ),
2399            )"#,
2400        );
2401        cfg.apply_env_overrides(&env(&[
2402            // Override the file database's pool size (merge by key, per field).
2403            ("BOATRAMP_HANDLERS_SQL_DB_analytics_POOL_MAX", "32"),
2404            // Add a brand-new database whose name has an underscore, exercising the
2405            // longest-suffix name isolation (`_READ_URL_ENV`, not `_URL_ENV`).
2406            ("BOATRAMP_HANDLERS_SQL_DB_events_log_KIND", "mysql"),
2407            ("BOATRAMP_HANDLERS_SQL_DB_events_log_URL_ENV", "EVENTS_URL"),
2408            (
2409                "BOATRAMP_HANDLERS_SQL_DB_events_log_READ_URL_ENV",
2410                "EVENTS_RO_URL",
2411            ),
2412            ("BOATRAMP_HANDLERS_SQL_DB_events_log_READ_ONLY", "true"),
2413        ]))
2414        .expect("valid env overrides apply");
2415
2416        let sql = cfg.handlers.unwrap().bindings.sql.unwrap();
2417        assert_eq!(sql.databases.len(), 2);
2418
2419        let analytics = &sql.databases["analytics"];
2420        assert_eq!(
2421            analytics.pool_max,
2422            Some(32),
2423            "env pool_max wins over the file"
2424        );
2425        assert_eq!(
2426            analytics.url_env, "FILE_PG_URL",
2427            "the file's url_env survives (env didn't touch it)"
2428        );
2429
2430        let events = &sql.databases["events_log"];
2431        assert_eq!(events.kind, "mysql");
2432        assert_eq!(events.url_env, "EVENTS_URL");
2433        assert_eq!(events.read_url_env.as_deref(), Some("EVENTS_RO_URL"));
2434        assert!(events.read_only);
2435    }
2436
2437    #[test]
2438    fn default_token_maps_to_the_reserved_default_name_not_empty() {
2439        // v0.5.0 breaking change: the reserved `DEFAULT` env token maps to the real
2440        // name `"default"` (a valid URL path segment), never the empty string. This is
2441        // what makes the default binding addressable as `--db default` and keeps every
2442        // db-name ingress path-segment-safe.
2443        let mut cfg = ServerConfig::default();
2444        cfg.apply_env_overrides(&env(&[
2445            ("BOATRAMP_HANDLERS_SQL_DB_DEFAULT_KIND", "postgres"),
2446            ("BOATRAMP_HANDLERS_SQL_DB_DEFAULT_URL_ENV", "PG_URL"),
2447        ]))
2448        .expect("valid env overrides apply");
2449        let databases = cfg.handlers.unwrap().bindings.sql.unwrap().databases;
2450        assert!(
2451            databases.contains_key(boatramp_core::project::DEFAULT_DB_NAME),
2452            "DEFAULT → the reserved `default` key"
2453        );
2454        assert!(
2455            !databases.contains_key(""),
2456            "the empty-string key is never produced"
2457        );
2458    }
2459
2460    #[test]
2461    fn empty_string_db_binding_name_is_rejected_with_a_cure() {
2462        // A `boatramp.cfg` that literally writes the legacy empty-string default key
2463        // fails closed on load (it would emit a `//` control-plane path), and the
2464        // error points at the cure (`default`).
2465        let err = ServerConfig::parse(
2466            r#"(
2467                handlers: ( bindings: ( sql: (
2468                    databases: {
2469                        "": ( kind: "postgres", url_env: "PG_URL" ),
2470                    },
2471                ) ) ),
2472            )"#,
2473        )
2474        .expect_err("an empty-string db binding name is refused");
2475        match err {
2476            ConfigError::InvalidDbName { name, reason, cure } => {
2477                assert_eq!(name, "");
2478                assert!(reason.contains("empty"), "reason names the emptiness");
2479                assert!(
2480                    cure.contains("default") && cure.contains("CHANGELOG"),
2481                    "the cure points at `default` + the CHANGELOG"
2482                );
2483            }
2484            other => panic!("expected ConfigError::InvalidDbName, got {other:?}"),
2485        }
2486    }
2487
2488    #[test]
2489    fn path_separator_db_binding_name_is_rejected() {
2490        // A non-path-segment name (contains `/`) is refused with no default-cure (the
2491        // fix is to rename it, not adopt `default`).
2492        let err = ServerConfig::parse(
2493            r#"(
2494                handlers: ( bindings: ( sql: (
2495                    databases: {
2496                        "a/b": ( kind: "postgres", url_env: "PG_URL" ),
2497                    },
2498                ) ) ),
2499            )"#,
2500        )
2501        .expect_err("a `/`-bearing db binding name is refused");
2502        match err {
2503            ConfigError::InvalidDbName { name, reason, cure } => {
2504                assert_eq!(name, "a/b");
2505                assert!(reason.contains("path separator"));
2506                assert!(cure.is_empty(), "no default-cure for a non-default name");
2507            }
2508            other => panic!("expected ConfigError::InvalidDbName, got {other:?}"),
2509        }
2510    }
2511
2512    #[test]
2513    fn reserved_bramp_db_compute_prefix_is_rejected() {
2514        // #501 Stage B LOW-2: a static BYO binding may not point `compute` at a
2515        // `bramp-db-…` workload (reserved for derived managed-DB servers) — refused
2516        // fail-closed at config load.
2517        let err = ServerConfig::parse(
2518            r#"(
2519                handlers: ( bindings: ( sql: (
2520                    databases: {
2521                        "byo": ( kind: "postgres", compute: "bramp-db-acme-app", database: "d", user: "u" ),
2522                    },
2523                ) ) ),
2524            )"#,
2525        )
2526        .expect_err("a `bramp-db-` compute workload is refused");
2527        match err {
2528            ConfigError::InvalidDbName { name, reason, cure } => {
2529                assert_eq!(name, "bramp-db-acme-app");
2530                assert!(reason.contains("reserved"), "reason names the reservation");
2531                assert!(cure.contains("bramp-db-"), "the cure names the prefix");
2532            }
2533            other => panic!("expected ConfigError::InvalidDbName, got {other:?}"),
2534        }
2535        // A NON-reserved compute workload for a BYO binding still loads fine.
2536        ServerConfig::parse(
2537            r#"(
2538                handlers: ( bindings: ( sql: (
2539                    databases: {
2540                        "byo": ( kind: "postgres", compute: "my-pg", database: "d", user: "u" ),
2541                    },
2542                ) ) ),
2543            )"#,
2544        )
2545        .expect("a non-reserved compute workload loads");
2546    }
2547
2548    #[test]
2549    fn env_sets_managed_db_startup_grace() {
2550        // The per-binding startup-grace override is env-settable like the other
2551        // managed scalars, discovered by the `_STARTUP_GRACE_SECS` suffix.
2552        let mut cfg = ServerConfig::default();
2553        cfg.apply_env_overrides(&env(&[
2554            ("BOATRAMP_HANDLERS_SQL_DB_DEFAULT_KIND", "postgres"),
2555            ("BOATRAMP_HANDLERS_SQL_DB_DEFAULT_COMPUTE", "pg"),
2556            ("BOATRAMP_HANDLERS_SQL_DB_DEFAULT_DATABASE", "appdb"),
2557            ("BOATRAMP_HANDLERS_SQL_DB_DEFAULT_USER", "app"),
2558            ("BOATRAMP_HANDLERS_SQL_DB_DEFAULT_STARTUP_GRACE_SECS", "90"),
2559        ]))
2560        .expect("valid env overrides apply");
2561        let db = &cfg.handlers.unwrap().bindings.sql.unwrap().databases
2562            [boatramp_core::project::DEFAULT_DB_NAME];
2563        assert_eq!(db.startup_grace_secs, Some(90));
2564    }
2565
2566    #[test]
2567    fn env_sets_rls_gucs_and_all_marker_without_suffix_collision() {
2568        // The RLS GUC names + the v0.4.21 all-read marker are env-settable. `_TENANT_ALL_MARKER`
2569        // and `_TENANT_GUC` must NOT be shadowed by the shorter `_TENANT` suffix (longest-first
2570        // isolation) — a `_TENANT` value would otherwise swallow the DB-name split.
2571        let mut cfg = ServerConfig::default();
2572        cfg.apply_env_overrides(&env(&[
2573            ("BOATRAMP_HANDLERS_SQL_DB_DEFAULT_KIND", "postgres"),
2574            ("BOATRAMP_HANDLERS_SQL_DB_DEFAULT_DATABASE", "appdb"),
2575            (
2576                "BOATRAMP_HANDLERS_SQL_DB_DEFAULT_TENANT_GUC",
2577                "app.tenant_id",
2578            ),
2579            (
2580                "BOATRAMP_HANDLERS_SQL_DB_DEFAULT_SESSION_GUC",
2581                "app.session_id",
2582            ),
2583            ("BOATRAMP_HANDLERS_SQL_DB_DEFAULT_TENANT_ALL_MARKER", "*"),
2584        ]))
2585        .expect("valid env overrides apply");
2586        let db = &cfg.handlers.unwrap().bindings.sql.unwrap().databases
2587            [boatramp_core::project::DEFAULT_DB_NAME];
2588        assert_eq!(db.tenant_guc.as_deref(), Some("app.tenant_id"));
2589        assert_eq!(db.session_guc.as_deref(), Some("app.session_id"));
2590        assert_eq!(db.tenant_all_marker.as_deref(), Some("*"));
2591    }
2592
2593    #[test]
2594    fn env_enum_parse_error_names_the_variable_and_variants() {
2595        // An unknown enum value is a clear error that names the offending variable.
2596        let mut cfg = ServerConfig::default();
2597        let err = cfg
2598            .apply_env_overrides(&env(&[(
2599                "BOATRAMP_COMPUTE_MANAGED_DB_PRIVILEGE",
2600                "superuser",
2601            )]))
2602            .expect_err("unknown enum variant is rejected");
2603        match err {
2604            ConfigError::Env { var, reason } => {
2605                assert_eq!(var, "BOATRAMP_COMPUTE_MANAGED_DB_PRIVILEGE");
2606                assert!(reason.contains("rootless") && reason.contains("caps"));
2607            }
2608            other => panic!("expected ConfigError::Env, got {other:?}"),
2609        }
2610        // The docker enums map their lowercase serde variants too.
2611        let mut cfg = ServerConfig::default();
2612        cfg.apply_env_overrides(&env(&[
2613            ("BOATRAMP_COMPUTE_DOCKER_ENDPOINT", "bridge"),
2614            ("BOATRAMP_COMPUTE_DOCKER_VOLUME_MODE", "bind"),
2615        ]))
2616        .expect("known enum variants parse");
2617        let compute = cfg.compute.unwrap();
2618        assert_eq!(
2619            compute.docker_endpoint,
2620            boatramp_docker::DockerEndpoint::Bridge
2621        );
2622        assert_eq!(
2623            compute.docker_volume_mode,
2624            boatramp_docker::DockerVolumeMode::Bind
2625        );
2626    }
2627
2628    #[test]
2629    fn env_trust_anchors_parse_as_a_comma_separated_list() {
2630        // The kernel trust anchors are comma-separated (whitespace trimmed, empty
2631        // items dropped so a trailing comma is tolerated). A file default is
2632        // fully replaced, not appended to.
2633        let mut cfg = ServerConfig::default();
2634        cfg.apply_env_overrides(&env(&[
2635            (
2636                "BOATRAMP_COMPUTE_KERNEL_SIGNING_PUBKEYS",
2637                " es256:aa , es256:bb ,",
2638            ),
2639            ("BOATRAMP_COMPUTE_KERNEL_ALLOWED_HASHES", "deadbeef"),
2640        ]))
2641        .expect("valid list env applies");
2642        let compute = cfg.compute.unwrap();
2643        assert_eq!(
2644            compute.kernel_signing_pubkeys,
2645            vec!["es256:aa".to_string(), "es256:bb".to_string()],
2646            "trimmed, comma-split, trailing-empty dropped, defaults replaced"
2647        );
2648        assert_eq!(
2649            compute.kernel_allowed_hashes,
2650            vec!["deadbeef".to_string()],
2651            "a single value is a one-element list"
2652        );
2653    }
2654
2655    #[test]
2656    fn env_configures_secrets_vault_subconfig() {
2657        // The vault sub-config materialises only when a vault var is set, and the
2658        // token stays indirected via a variable NAME (`token_env`), never inline.
2659        let mut cfg = ServerConfig::default();
2660        cfg.apply_env_overrides(&env(&[
2661            ("BOATRAMP_SECRETS_ENVELOPE", "vault"),
2662            ("BOATRAMP_SECRETS_VAULT_ADDR", "https://vault:8200"),
2663            ("BOATRAMP_SECRETS_VAULT_KEY", "certs"),
2664        ]))
2665        .expect("valid env overrides apply");
2666        let secrets = cfg.secrets.unwrap();
2667        assert_eq!(secrets.envelope, "vault");
2668        let vault = secrets.vault.expect("vault sub-config materialised");
2669        assert_eq!(vault.addr, "https://vault:8200");
2670        assert_eq!(vault.key, "certs");
2671        // token_env defaults to VAULT_TOKEN when not overridden.
2672        assert_eq!(vault.token_env, "VAULT_TOKEN");
2673    }
2674
2675    #[test]
2676    fn env_materialises_and_overrides_the_cluster_section() {
2677        // With no file, a `BOATRAMP_CLUSTER_LISTEN` materialises the section; the
2678        // remaining fields (lists, join token, mesh) layer on. The founding/joining
2679        // action flags (`BOATRAMP_CLUSTER_INIT`/`_JOIN`) are separate `serve` args
2680        // and are not part of this section.
2681        let mut cfg = ServerConfig::default();
2682        cfg.apply_env_overrides(&env(&[
2683            ("BOATRAMP_CLUSTER_LISTEN", "10.0.0.2:7000"),
2684            ("BOATRAMP_CLUSTER_ROOT_PUBKEYS", "es256:aa,es256:bb"),
2685            ("BOATRAMP_CLUSTER_SEEDS", "https://10.0.0.1:8080"),
2686            ("BOATRAMP_CLUSTER_JOIN_TOKEN", "env:BOATRAMP_JOIN_TOKEN"),
2687            ("BOATRAMP_CLUSTER_STORE_DIR", "/var/lib/boatramp/raft"),
2688            ("BOATRAMP_CLUSTER_MESH_GATE_CLIENT_WRITES", "true"),
2689        ]))
2690        .expect("valid env overrides apply");
2691        let cluster = cfg.cluster.expect("cluster materialised from env");
2692        assert_eq!(
2693            cluster.listen,
2694            "10.0.0.2:7000".parse::<std::net::SocketAddr>().unwrap()
2695        );
2696        assert_eq!(
2697            cluster.root_pubkeys,
2698            vec!["es256:aa".to_string(), "es256:bb".to_string()]
2699        );
2700        assert_eq!(cluster.seeds, vec!["https://10.0.0.1:8080".to_string()]);
2701        assert_eq!(
2702            cluster.join_token.as_deref(),
2703            Some("env:BOATRAMP_JOIN_TOKEN")
2704        );
2705        assert_eq!(
2706            cluster.store_dir.as_deref(),
2707            Some(Path::new("/var/lib/boatramp/raft"))
2708        );
2709        assert_eq!(
2710            cluster.mesh.expect("mesh sub-config").gate_client_writes,
2711            Some(true)
2712        );
2713
2714        // Without a listen (and no file section) there is nothing to materialise:
2715        // a non-listen cluster var alone leaves the section absent.
2716        let mut cfg = ServerConfig::default();
2717        cfg.apply_env_overrides(&env(&[("BOATRAMP_CLUSTER_SEEDS", "https://10.0.0.1:8080")]))
2718            .expect("applies");
2719        assert!(
2720            cfg.cluster.is_none(),
2721            "no listen + no file section ⇒ no cluster"
2722        );
2723    }
2724
2725    #[test]
2726    fn env_cluster_listen_overrides_a_file_section() {
2727        // A file `[cluster]` section: env overrides `listen` and adds seeds.
2728        let mut cfg = server(r#"( cluster: ( listen: "0.0.0.0:7000" ) )"#);
2729        cfg.apply_env_overrides(&env(&[
2730            ("BOATRAMP_CLUSTER_LISTEN", "10.0.0.9:7000"),
2731            ("BOATRAMP_CLUSTER_SEEDS", "https://seed:8080"),
2732        ]))
2733        .expect("applies");
2734        let cluster = cfg.cluster.unwrap();
2735        assert_eq!(
2736            cluster.listen,
2737            "10.0.0.9:7000".parse::<std::net::SocketAddr>().unwrap(),
2738            "env listen wins over the file"
2739        );
2740        assert_eq!(cluster.seeds, vec!["https://seed:8080".to_string()]);
2741    }
2742
2743    #[test]
2744    fn empty_project_config_is_default() {
2745        let cfg = project("()");
2746        assert!(cfg.publish.server.is_none());
2747        assert!(cfg.publish.site.is_none());
2748        assert!(cfg.build.is_none());
2749        assert!(cfg.bundle.is_none());
2750        // Routing defaults: schema v1, the single default index candidate.
2751        assert_eq!(cfg.routing.version, 1);
2752        assert_eq!(cfg.routing.index, vec!["index.html".to_string()]);
2753    }
2754
2755    #[test]
2756    fn serve_signer_config_parses_and_maps_each_backend() {
2757        use boatramp_core::cose::TokenAlg;
2758        use boatramp_server::signer::SignerConfig;
2759
2760        // RON-native enum tagging (`Vault(...)`); `IMPLICIT_SOME` lets the optional
2761        // fields (region) take a bare value or be omitted (→ None). This is the
2762        // exact RON documented in the Authentication guide.
2763        let vault = server(
2764            r#"( serve: ( signer: Vault(
2765                address: "https://vault.example:8200",
2766                key: "boatramp-root",
2767                token_env: "VAULT_TOKEN",
2768                alg: Ed25519,
2769            ) ) )"#,
2770        );
2771        match vault.serve.unwrap().signer.unwrap().to_signer_config() {
2772            SignerConfig::Vault {
2773                address,
2774                key,
2775                token_env,
2776                alg,
2777            } => {
2778                assert_eq!(address, "https://vault.example:8200");
2779                assert_eq!(key, "boatramp-root");
2780                assert_eq!(token_env, "VAULT_TOKEN");
2781                assert_eq!(alg, TokenAlg::Ed25519);
2782            }
2783            other => panic!("expected Vault, got {other:?}"),
2784        }
2785
2786        // AWS KMS: region omitted → None; PKCS#11: alg omitted → the ES256 default.
2787        let aws =
2788            server(r#"( serve: ( signer: AwsKms(key_id: "arn:aws:kms:eu-west-1:1:key/abc") ) )"#);
2789        assert!(matches!(
2790            aws.serve.unwrap().signer.unwrap().to_signer_config(),
2791            SignerConfig::AwsKms { region: None, .. }
2792        ));
2793
2794        let hsm = server(
2795            r#"( serve: ( signer: Pkcs11(
2796                module: "/usr/lib/softhsm/libsofthsm2.so",
2797                token_label: "boatramp",
2798                key_label: "root",
2799                pin_env: "HSM_PIN",
2800            ) ) )"#,
2801        );
2802        match hsm.serve.unwrap().signer.unwrap().to_signer_config() {
2803            SignerConfig::Pkcs11 { alg, .. } => assert_eq!(alg, TokenAlg::Es256),
2804            other => panic!("expected Pkcs11, got {other:?}"),
2805        }
2806    }
2807
2808    #[test]
2809    fn project_config_parses_publish_build_and_routing() {
2810        let cfg = project(
2811            r#"(
2812                publish: ( server: "http://127.0.0.1:8080", site: "demo" ),
2813                build: ( command: "npm run build", output: "dist" ),
2814                routing: (
2815                    clean_urls: true,
2816                    redirects: [ (from: "/old/:slug", to: "/new/:slug", status: 301) ],
2817                ),
2818            )"#,
2819        );
2820        assert_eq!(cfg.publish.server.as_deref(), Some("http://127.0.0.1:8080"));
2821        assert_eq!(cfg.publish.site.as_deref(), Some("demo"));
2822        let build = cfg.build.unwrap();
2823        assert_eq!(build.command, "npm run build");
2824        assert_eq!(build.output.as_deref(), Some("dist"));
2825        assert!(cfg.routing.clean_urls);
2826        assert_eq!(cfg.routing.redirects.len(), 1);
2827        assert_eq!(cfg.routing.redirects[0].status, 301);
2828    }
2829
2830    #[test]
2831    fn project_config_rejects_bad_routing_pattern() {
2832        // The same compile-check `load` runs: a bad route pattern is an error.
2833        let cfg = project(r#"( routing: ( redirects: [ (from: "/a/**/b/**", to: "/x") ] ) )"#);
2834        assert!(cfg.routing.compile_check().is_err());
2835    }
2836
2837    #[test]
2838    fn empty_server_config_has_no_sections() {
2839        let cfg = server("()");
2840        assert!(cfg.serve.is_none());
2841        assert!(cfg.handlers.is_none());
2842        assert!(cfg.cluster.is_none());
2843        assert!(cfg.security.is_none());
2844    }
2845
2846    #[test]
2847    fn security_section_parses_and_resolves() {
2848        // A profile plus an override that wins over it.
2849        let cfg = server(
2850            r#"(
2851                security: (
2852                    profile: "dev",
2853                    overrides: (
2854                        oidc_require_audience: true,
2855                        max_upload_bytes: 0,
2856                    ),
2857                )
2858            )"#,
2859        );
2860        let posture = cfg.security.unwrap().resolve().expect("resolves");
2861        // `dev` is loose...
2862        assert!(posture.allow_unauthenticated_public_bind);
2863        // ...but the explicit override wins over the profile.
2864        assert!(posture.oidc_require_audience);
2865        assert_eq!(posture.max_upload_bytes, 0); // unlimited
2866    }
2867
2868    #[test]
2869    fn env_wires_allow_env_secret_refs_over_the_multi_tenant_default() {
2870        // With no file, the multi-tenant default leaves host-env secret refs off;
2871        // the env knob re-enables them (env > default), same as the other posture bools.
2872        let mut cfg = ServerConfig::default();
2873        cfg.apply_env_overrides(&env(&[("BOATRAMP_SECURITY_ALLOW_ENV_SECRET_REFS", "true")]))
2874            .expect("valid env override applies");
2875        let posture = cfg
2876            .security
2877            .expect("security materialised from env")
2878            .resolve()
2879            .expect("resolves");
2880        assert!(posture.allow_env_secret_refs);
2881    }
2882
2883    #[test]
2884    fn env_wires_the_multi_tenant_subknobs_over_the_default() {
2885        // Gap 4b: the four multi-tenant sub-knobs were file-only; env now sets them (env > the
2886        // multi-tenant preset default), so a 12-factor deploy can tune tenancy isolation + guest
2887        // capability minting with no `boatramp.cfg`. Verified: strict declaration stays on while
2888        // cross-tenant `all` twins + guest cap-mint are permitted (they compose — Gap 4.3).
2889        let mut cfg = ServerConfig::default();
2890        cfg.apply_env_overrides(&env(&[
2891            ("BOATRAMP_SECURITY_PROFILE", "multi-tenant"),
2892            ("BOATRAMP_SECURITY_REQUIRE_TENANCY_DECLARATION", "true"),
2893            ("BOATRAMP_SECURITY_ALLOW_CROSS_TENANT_DB", "true"),
2894            ("BOATRAMP_SECURITY_ALLOW_GUEST_MINT_CAPABILITY", "true"),
2895            ("BOATRAMP_SECURITY_MAX_GUEST_CAPABILITY_TTL_SECS", "1800"),
2896        ]))
2897        .expect("valid env overrides apply");
2898        let posture = cfg
2899            .security
2900            .expect("security materialised from env")
2901            .resolve()
2902            .expect("resolves");
2903        assert!(posture.require_tenancy_declaration);
2904        assert!(posture.allow_cross_tenant_db);
2905        assert!(posture.allow_guest_mint_capability);
2906        assert_eq!(posture.max_guest_capability_ttl_secs, 1800);
2907    }
2908
2909    #[test]
2910    fn env_wires_the_remaining_guest_feature_knobs_over_the_multi_tenant_default() {
2911        // v0.4.18 env parity: `allow_guest_email` (which regressed prod SMTP on the P48 cutover —
2912        // multi-tenant defaults it OFF and there was no env lever), its egress sibling
2913        // `allow_guest_egress_extra_ca` (shipped config-only in v0.4.17), and the four
2914        // `allow_guest_admin_*` self-config knobs were all missing from the env map. Each preset
2915        // defaults them OFF under `multi-tenant`; the env knob must now flip each back on for a
2916        // 12-factor env-only fleet, exactly like `allow_guest_mint_capability`.
2917        let mut cfg = ServerConfig::default();
2918        cfg.apply_env_overrides(&env(&[
2919            ("BOATRAMP_SECURITY_PROFILE", "multi-tenant"),
2920            ("BOATRAMP_SECURITY_ALLOW_GUEST_EMAIL", "true"),
2921            ("BOATRAMP_SECURITY_ALLOW_GUEST_EGRESS_EXTRA_CA", "true"),
2922            ("BOATRAMP_SECURITY_ALLOW_GUEST_ADMIN_DOMAINS", "true"),
2923            ("BOATRAMP_SECURITY_ALLOW_GUEST_ADMIN_EMAIL", "true"),
2924            ("BOATRAMP_SECURITY_ALLOW_GUEST_ADMIN_SITE", "true"),
2925            ("BOATRAMP_SECURITY_ALLOW_GUEST_ADMIN_SECRETS", "true"),
2926        ]))
2927        .expect("valid env overrides apply");
2928        let security = cfg.security.expect("security materialised from env");
2929        let posture = security.resolve().expect("resolves");
2930        // Every one flips on over the multi-tenant preset default (which is `false` for all six).
2931        assert!(posture.allow_guest_email, "guest email re-enabled via env");
2932        assert!(posture.allow_guest_egress_extra_ca);
2933        assert!(posture.allow_guest_admin_domains);
2934        assert!(posture.allow_guest_admin_email);
2935        assert!(posture.allow_guest_admin_site);
2936        assert!(posture.allow_guest_admin_secrets);
2937        // `security explain` attributes each to the override/env source (not the profile preset).
2938        let explained = security.explain().expect("explains");
2939        for knob in [
2940            "allow_guest_email",
2941            "allow_guest_egress_extra_ca",
2942            "allow_guest_admin_domains",
2943            "allow_guest_admin_email",
2944            "allow_guest_admin_site",
2945            "allow_guest_admin_secrets",
2946        ] {
2947            assert!(
2948                explained
2949                    .lines()
2950                    .any(|l| l.contains(knob) && l.contains("true") && l.contains("(override)")),
2951                "explain shows {knob} = true (override): \n{explained}"
2952            );
2953        }
2954    }
2955
2956    #[test]
2957    fn each_guest_feature_env_var_moves_its_own_posture_field() {
2958        // Cross-wiring guard: set each of the six guest-feature vars ALONE over the multi-tenant
2959        // default and assert THAT var's own resolved field flips — so a copy-paste arm mapping a var
2960        // to the wrong field (or an unregistered var that never materialises the section) fails here.
2961        // Complements `every_posture_override_field_has_an_env_mapping` below (which proves coverage
2962        // by field name but not that each arm targets the right field).
2963        for (var, check) in [
2964            (
2965                "BOATRAMP_SECURITY_ALLOW_GUEST_EMAIL",
2966                (|p: &boatramp_core::security::SecurityPosture| p.allow_guest_email)
2967                    as fn(&boatramp_core::security::SecurityPosture) -> bool,
2968            ),
2969            ("BOATRAMP_SECURITY_ALLOW_GUEST_EGRESS_EXTRA_CA", |p| {
2970                p.allow_guest_egress_extra_ca
2971            }),
2972            ("BOATRAMP_SECURITY_ALLOW_GUEST_ADMIN_DOMAINS", |p| {
2973                p.allow_guest_admin_domains
2974            }),
2975            ("BOATRAMP_SECURITY_ALLOW_GUEST_ADMIN_EMAIL", |p| {
2976                p.allow_guest_admin_email
2977            }),
2978            ("BOATRAMP_SECURITY_ALLOW_GUEST_ADMIN_SITE", |p| {
2979                p.allow_guest_admin_site
2980            }),
2981            ("BOATRAMP_SECURITY_ALLOW_GUEST_ADMIN_SECRETS", |p| {
2982                p.allow_guest_admin_secrets
2983            }),
2984        ] {
2985            let mut cfg = ServerConfig::default();
2986            cfg.apply_env_overrides(&env(&[
2987                ("BOATRAMP_SECURITY_PROFILE", "multi-tenant"),
2988                (var, "true"),
2989            ]))
2990            .unwrap_or_else(|e| panic!("{var} applies: {e}"));
2991            let posture = cfg
2992                .security
2993                .unwrap_or_else(|| panic!("{var} materialises the security section"))
2994                .resolve()
2995                .expect("resolves");
2996            assert!(check(&posture), "{var} did not flip the resolved posture");
2997        }
2998    }
2999
3000    #[test]
3001    fn every_posture_override_field_has_an_env_mapping() {
3002        // Exhaustive guard against the EXACT class of gap v0.4.18 closes — a `PostureOverrides`
3003        // field a 12-factor fleet can set in `[security.overrides]` but NOT via env — for EVERY
3004        // field, now and in the future. Enumerate the struct's fields structurally (serialize a
3005        // default instance; every field renders as a key) and assert each maps to a registered
3006        // `BOATRAMP_SECURITY_<UPPER(field)>` in `SECURITY_ENV_VARS`. A new override field added
3007        // without an env var (or a var left out of the registry) fails here — so the omission that
3008        // regressed `allow_guest_email` can't silently recur. The registry entry is load-bearing:
3009        // `apply_env_overrides` only materialises the section when `source.any(SECURITY_ENV_VARS)`.
3010        let all = serde_json::to_value(boatramp_core::security::PostureOverrides::default())
3011            .expect("PostureOverrides serializes");
3012        let fields = all.as_object().expect("a struct is a JSON object");
3013        assert!(!fields.is_empty(), "expected some override fields");
3014        for field in fields.keys() {
3015            let var = format!("BOATRAMP_SECURITY_{}", field.to_uppercase());
3016            assert!(
3017                SECURITY_ENV_VARS.contains(&var.as_str()),
3018                "PostureOverrides field `{field}` has no env mapping — add `{var}` to \
3019                 SECURITY_ENV_VARS + an arm in apply_env_overrides (the v0.4.18 forgot-a-knob guard)"
3020            );
3021        }
3022    }
3023
3024    #[test]
3025    fn cluster_section_parses_the_dynamic_join_shape() {
3026        let cfg = server(
3027            r#"(
3028                cluster: (
3029                    listen: "10.0.0.2:7000",
3030                    root_pubkeys: ["es256:03a1"],
3031                    seeds: ["https://10.0.0.1:8080"],
3032                    join_token: "env:BOATRAMP_JOIN_TOKEN",
3033                ),
3034            )"#,
3035        );
3036        let cluster = cfg.cluster.unwrap();
3037        assert_eq!(
3038            cluster.listen,
3039            "10.0.0.2:7000".parse::<std::net::SocketAddr>().unwrap()
3040        );
3041        assert_eq!(cluster.root_pubkeys, vec!["es256:03a1".to_string()]);
3042        assert_eq!(cluster.seeds, vec!["https://10.0.0.1:8080".to_string()]);
3043        assert_eq!(
3044            cluster.join_token.as_deref(),
3045            Some("env:BOATRAMP_JOIN_TOKEN")
3046        );
3047        // store_dir defaults to None (→ <data-dir>/raft at serve time).
3048        assert!(cluster.store_dir.is_none());
3049    }
3050
3051    #[test]
3052    fn cluster_section_founds_with_just_a_listen_addr() {
3053        // A founder needs no seeds/token — just where to bind the mesh.
3054        let cfg = server(r#"( cluster: ( listen: "0.0.0.0:7000" ) )"#);
3055        let cluster = cfg.cluster.unwrap();
3056        assert!(cluster.seeds.is_empty());
3057        assert!(cluster.root_pubkeys.is_empty());
3058        assert!(cluster.join_token.is_none());
3059    }
3060
3061    #[test]
3062    fn sql_binding_single_node_defaults() {
3063        // A bare section (or none) means single-node: no url, default dir.
3064        let cfg = server(r#"( handlers: ( bindings: ( sql: () ) ) )"#);
3065        let sql = cfg.handlers.unwrap().bindings.sql.unwrap();
3066        assert!(sql.url.is_none());
3067        assert!(sql.dir.is_none());
3068    }
3069
3070    #[test]
3071    fn sql_binding_single_node_custom_dir() {
3072        let cfg =
3073            server(r#"( handlers: ( bindings: ( sql: ( dir: "/var/lib/boatramp/sql" ) ) ) )"#);
3074        let sql = cfg.handlers.unwrap().bindings.sql.unwrap();
3075        assert_eq!(sql.dir.as_deref(), Some(Path::new("/var/lib/boatramp/sql")));
3076        assert!(sql.url.is_none());
3077    }
3078
3079    #[test]
3080    fn sql_binding_cluster() {
3081        let cfg = server(
3082            r#"(
3083                handlers: ( bindings: ( sql: (
3084                    url: "http://sqld:8080",
3085                    admin_url: "http://sqld:9090",
3086                    token_env: "BOATRAMP_SQL_TOKEN",
3087                ) ) ),
3088            )"#,
3089        );
3090        let sql = cfg.handlers.unwrap().bindings.sql.unwrap();
3091        assert_eq!(sql.url.as_deref(), Some("http://sqld:8080"));
3092        assert_eq!(sql.admin_url.as_deref(), Some("http://sqld:9090"));
3093        assert_eq!(sql.token_env.as_deref(), Some("BOATRAMP_SQL_TOKEN"));
3094        assert_eq!(sql.admin_token_env, None);
3095    }
3096
3097    #[test]
3098    fn sql_binding_preview_policy() {
3099        let cfg = server(
3100            r#"(
3101                handlers: ( bindings: ( sql: (
3102                    preview_mode: "branch",
3103                    preview_init: "/etc/boatramp/seed.sql",
3104                ) ) ),
3105            )"#,
3106        );
3107        let sql = cfg.handlers.unwrap().bindings.sql.unwrap();
3108        assert_eq!(sql.preview_mode.as_deref(), Some("branch"));
3109        assert_eq!(
3110            sql.preview_init.as_deref(),
3111            Some(Path::new("/etc/boatramp/seed.sql"))
3112        );
3113    }
3114
3115    #[test]
3116    fn sql_binding_external_databases() {
3117        let cfg = server(
3118            r#"(
3119                handlers: ( bindings: ( sql: (
3120                    databases: {
3121                        "analytics": (
3122                            kind: "postgres",
3123                            url_env: "ANALYTICS_PG_URL",
3124                            pool_max: 16,
3125                            read_only: true,
3126                        ),
3127                        "events": (
3128                            kind: "mysql",
3129                            url_env: "EVENTS_MYSQL_URL",
3130                            read_url_env: "EVENTS_MYSQL_REPLICA_URL",
3131                            allow_preview: true,
3132                        ),
3133                    },
3134                ) ) ),
3135            )"#,
3136        );
3137        let sql = cfg.handlers.unwrap().bindings.sql.unwrap();
3138        assert_eq!(sql.databases.len(), 2);
3139
3140        let analytics = &sql.databases["analytics"];
3141        assert_eq!(analytics.kind, "postgres");
3142        assert_eq!(analytics.url_env, "ANALYTICS_PG_URL");
3143        assert_eq!(analytics.pool_max, Some(16));
3144        assert!(analytics.read_only);
3145        assert!(!analytics.allow_preview);
3146        assert!(analytics.read_url_env.is_none());
3147
3148        let events = &sql.databases["events"];
3149        assert_eq!(events.kind, "mysql");
3150        assert_eq!(
3151            events.read_url_env.as_deref(),
3152            Some("EVENTS_MYSQL_REPLICA_URL")
3153        );
3154        assert!(events.allow_preview);
3155        assert!(!events.read_only);
3156    }
3157
3158    #[test]
3159    fn sql_binding_compute_backed_database() {
3160        let cfg = server(
3161            r#"(
3162                handlers: ( bindings: ( sql: (
3163                    databases: {
3164                        "analytics": (
3165                            kind: "postgres",
3166                            compute: "pg",
3167                            database: "analytics",
3168                            user: "app",
3169                            password_env: "PG_APP_PW",
3170                        ),
3171                    },
3172                ) ) ),
3173            )"#,
3174        );
3175        let db = &cfg.handlers.unwrap().bindings.sql.unwrap().databases["analytics"];
3176        assert_eq!(db.kind, "postgres");
3177        assert_eq!(db.compute.as_deref(), Some("pg"));
3178        assert_eq!(db.database.as_deref(), Some("analytics"));
3179        assert_eq!(db.user.as_deref(), Some("app"));
3180        assert_eq!(db.password_env.as_deref(), Some("PG_APP_PW"));
3181        assert!(db.url_env.is_empty(), "compute-backed has no url_env");
3182        assert!(db.validate("analytics").is_ok());
3183    }
3184
3185    #[test]
3186    fn sql_binding_source_is_exactly_one_of_url_or_compute() {
3187        // Neither source → error.
3188        assert!(ExternalDatabaseConfig::default().validate("db").is_err());
3189        // Both sources → error.
3190        let both = ExternalDatabaseConfig {
3191            kind: "postgres".into(),
3192            url_env: "PG_URL".into(),
3193            compute: Some("pg".into()),
3194            ..Default::default()
3195        };
3196        assert!(both.validate("db").is_err());
3197        // `url_env` only → ok.
3198        let url = ExternalDatabaseConfig {
3199            kind: "postgres".into(),
3200            url_env: "PG_URL".into(),
3201            ..Default::default()
3202        };
3203        assert!(url.validate("db").is_ok());
3204        // `compute` without the connection details boatramp can't infer → error.
3205        let bare = ExternalDatabaseConfig {
3206            kind: "postgres".into(),
3207            compute: Some("pg".into()),
3208            ..Default::default()
3209        };
3210        assert!(bare.validate("db").is_err());
3211        // `compute` with database/user + a bring-your-own `password_env` → ok, and
3212        // is *not* a managed credential.
3213        let byo = ExternalDatabaseConfig {
3214            kind: "postgres".into(),
3215            compute: Some("pg".into()),
3216            database: Some("analytics".into()),
3217            user: Some("app".into()),
3218            password_env: Some("PG_APP_PW".into()),
3219            ..Default::default()
3220        };
3221        assert!(byo.validate("db").is_ok());
3222        assert!(!byo.is_managed_credential());
3223        // `compute` with database/user but NO `password_env` → ok, and boatramp
3224        // manages the credential (Phase 2).
3225        let managed = ExternalDatabaseConfig {
3226            kind: "postgres".into(),
3227            compute: Some("pg".into()),
3228            database: Some("analytics".into()),
3229            user: Some("app".into()),
3230            ..Default::default()
3231        };
3232        assert!(managed.validate("db").is_ok());
3233        assert!(managed.is_managed_credential());
3234    }
3235
3236    #[test]
3237    fn libsql_source_is_exactly_one_of_path_or_url() {
3238        // A single-node `libsql` file (path only) → ok.
3239        let file = ExternalDatabaseConfig {
3240            kind: "libsql".into(),
3241            path: Some("/data/app.db".into()),
3242            ..Default::default()
3243        };
3244        assert!(file.validate("app").is_ok());
3245        // `sqlite` alias works the same.
3246        let sqlite = ExternalDatabaseConfig {
3247            kind: "sqlite".into(),
3248            path: Some("/data/app.db".into()),
3249            ..Default::default()
3250        };
3251        assert!(sqlite.validate("app").is_ok());
3252        // A remote-sqld `libsql` (url_env only) → ok.
3253        let remote = ExternalDatabaseConfig {
3254            kind: "libsql".into(),
3255            url_env: "LIBSQL_URL".into(),
3256            ..Default::default()
3257        };
3258        assert!(remote.validate("app").is_ok());
3259        // Neither `path` nor `url_env` → error.
3260        let neither = ExternalDatabaseConfig {
3261            kind: "libsql".into(),
3262            ..Default::default()
3263        };
3264        assert!(neither.validate("app").is_err());
3265        // Both `path` and `url_env` → error (exactly one).
3266        let both = ExternalDatabaseConfig {
3267            kind: "libsql".into(),
3268            path: Some("/data/app.db".into()),
3269            url_env: "LIBSQL_URL".into(),
3270            ..Default::default()
3271        };
3272        assert!(both.validate("app").is_err());
3273        // `compute` on a `libsql` binding → error (boatramp doesn't run a libsql server workload).
3274        let compute = ExternalDatabaseConfig {
3275            kind: "libsql".into(),
3276            compute: Some("x".into()),
3277            path: Some("/data/app.db".into()),
3278            ..Default::default()
3279        };
3280        assert!(compute.validate("app").is_err());
3281        // `path` on a NON-libsql (postgres) binding → error (only libsql has an on-disk file).
3282        let pg_path = ExternalDatabaseConfig {
3283            kind: "postgres".into(),
3284            url_env: "PG_URL".into(),
3285            path: Some("/data/app.db".into()),
3286            ..Default::default()
3287        };
3288        assert!(pg_path.validate("db").is_err());
3289    }
3290
3291    /// Path to a file at the repo root (two levels up from this crate).
3292    fn repo_root_file(name: &str) -> PathBuf {
3293        Path::new(env!("CARGO_MANIFEST_DIR"))
3294            .join("../..")
3295            .join(name)
3296    }
3297
3298    #[test]
3299    fn shipped_project_example_parses() {
3300        // The example we ship must always parse + compile-check, so it can't drift
3301        // from the schema.
3302        let text = std::fs::read_to_string(repo_root_file("examples/site/project.cfg.example"))
3303            .expect("example project config is present");
3304        let cfg = ProjectConfig::parse(&text).expect("example project config parses");
3305        assert_eq!(cfg.publish.server.as_deref(), Some("http://127.0.0.1:8080"));
3306        assert_eq!(cfg.build.as_ref().unwrap().command, "npm run build");
3307        assert_eq!(
3308            cfg.routing.error_documents.get(&404).map(String::as_str),
3309            Some("/404.html")
3310        );
3311    }
3312
3313    #[test]
3314    fn shipped_server_example_parses() {
3315        let text = std::fs::read_to_string(repo_root_file("boatramp.cfg.example"))
3316            .expect("example server config is present");
3317        let cfg = ServerConfig::parse(&text).expect("example server config parses");
3318        let serve = cfg.serve.expect("example sets a serve section");
3319        assert_eq!(
3320            serve.addr,
3321            Some("0.0.0.0:8080".parse::<std::net::SocketAddr>().unwrap())
3322        );
3323    }
3324
3325    #[test]
3326    fn secrets_section_parses_local_and_vault() {
3327        let local = server(r#"( secrets: ( envelope: "local", kek_file: "/k/kek" ) )"#)
3328            .secrets
3329            .expect("secrets section");
3330        assert_eq!(local.envelope, "local");
3331        assert_eq!(
3332            local.kek_file.as_deref(),
3333            Some(std::path::Path::new("/k/kek"))
3334        );
3335
3336        let vault = server(
3337            r#"( secrets: ( envelope: "vault", vault: ( addr: "https://vault:8200", key: "certs" ) ) )"#,
3338        )
3339        .secrets
3340        .expect("secrets section");
3341        let v = vault.vault.expect("vault subsection");
3342        assert_eq!(v.addr, "https://vault:8200");
3343        assert_eq!(v.key, "certs");
3344        // The token env defaults to VAULT_TOKEN and is never in the file.
3345        assert_eq!(v.token_env, "VAULT_TOKEN");
3346    }
3347
3348    #[test]
3349    fn serve_section_partial_parses() {
3350        // A partial `serve` section parses — unset fields take their defaults.
3351        let cfg = server(r#"( serve: ( addr: "0.0.0.0:8080", protect_previews: true ) )"#);
3352        let serve = cfg.serve.unwrap();
3353        assert_eq!(
3354            serve.addr,
3355            Some("0.0.0.0:8080".parse::<std::net::SocketAddr>().unwrap())
3356        );
3357        assert!(serve.protect_previews);
3358        assert!(!serve.cluster_rate_limit);
3359        assert!(serve.data_dir.is_none());
3360    }
3361
3362    #[test]
3363    fn serve_console_config_parses() {
3364        // Absent ⇒ no console.
3365        let cfg = server(r#"( serve: ( addr: "0.0.0.0:8080" ) )"#);
3366        assert!(cfg.serve.unwrap().console.is_none());
3367        // Explicit console block with host + path.
3368        let cfg = server(
3369            r#"( serve: ( console: (
3370                enabled: true,
3371                host: "console.example.com",
3372                path: "/_console",
3373            ) ) )"#,
3374        );
3375        let console = cfg.serve.unwrap().console.unwrap();
3376        assert!(console.enabled);
3377        assert_eq!(console.host.as_deref(), Some("console.example.com"));
3378        assert_eq!(console.path.as_deref(), Some("/_console"));
3379        // Bare `enabled` ⇒ host/path take their (server-side) defaults.
3380        let cfg = server(r#"( serve: ( console: ( enabled: true ) ) )"#);
3381        let console = cfg.serve.unwrap().console.unwrap();
3382        assert!(console.enabled);
3383        assert!(console.host.is_none() && console.path.is_none());
3384    }
3385}