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    /// **Node-level base S3 credential source** (`[serve.s3_credential]`, task #505). When set, BOTH the
1985    /// S3 blob **object backend** (`--blobs s3`) and the AWS blob-upload **cloud minter**
1986    /// (`[serve.s3_ingress_cloud]`) source their base AWS credential from boatramp's `[secrets]` sealed
1987    /// store instead of the ambient `AWS_ACCESS_KEY_ID`/`AWS_SECRET_ACCESS_KEY` env chain. ONE shared
1988    /// source (both consumers read the SAME bucket key). Absent ⇒ the ambient AWS env chain (current
1989    /// behavior, non-breaking). Requires a `[secrets]` envelope when the `secret_access_key` is a sealed
1990    /// `boatramp:`/`env:` ref — a configured ref with no envelope is a **startup error** (fail-closed, no
1991    /// silent env fallback). See [`S3CredentialConfig`].
1992    pub s3_credential: Option<S3CredentialConfig>,
1993}
1994
1995/// `[serve.s3_credential]` — a **node-level base S3 credential source** (#505) sourcing the base AWS
1996/// credential from boatramp's `[secrets]` sealed store rather than the ambient env chain. Consumed by
1997/// BOTH the S3 blob object backend and the AWS blob-upload cloud minter (one shared source, since it is
1998/// the same bucket key). Additive/non-breaking: absent ⇒ the ambient AWS env chain (unchanged).
1999///
2000/// The `access_key_id` is a public identifier (plain config). The `secret_access_key` is a **secret
2001/// reference** in the same scheme the guest `secrets` map uses: `boatramp:<name>` (the project-scoped
2002/// sealed store, resolved under the reserved default project — multi-tenant-safe, never the host env),
2003/// `env:<VAR>` / a bare `<VAR>` (the operator's own environment — honored only when the posture's
2004/// `allow_env_secret_refs` is set), unsealed at serve startup via the `[secrets]` [`KeyEnvelope`]. The
2005/// resolved plaintext is held **in memory only** (never env/argv/git/logs); see the redacted
2006/// `SealedS3Credential` the resolver produces.
2007#[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize)]
2008#[serde(deny_unknown_fields)]
2009pub struct S3CredentialConfig {
2010    /// The AWS **access key id** — a public identifier, not a secret, so it is plain config (mirrors
2011    /// how an `access_key_id` is a public value in the S3-ingress credential model). Empty is refused
2012    /// at resolution.
2013    pub access_key_id: String,
2014    /// The **secret access key**, expressed as a secret **reference** (never the raw secret in the
2015    /// config text): `boatramp:<name>` (the project-scoped sealed store), `env:<VAR>` or a bare `<VAR>`
2016    /// (the operator env, posture-gated by `allow_env_secret_refs`). Unsealed at startup via the
2017    /// `[secrets]` envelope; the resolved value is redacted from `Debug`/logs. A `boatramp:`/`env:`
2018    /// ref configured with NO `[secrets]` envelope is a fail-closed startup error.
2019    pub secret_access_key: String,
2020}
2021
2022/// `[serve.s3_ingress_cloud]` — the cloud-brokering knobs for the M4 blob-upload minter (which native
2023/// credential the mint brokers when the node's blob backend is a cloud object store). Only the fields
2024/// for the active blob backend are consulted; a `None` here ⇒ the local S3 face mints.
2025#[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize)]
2026pub struct S3IngressCloud {
2027    /// **AWS**: the IAM role ARN the base credential assumes to broker the scoped session-policy
2028    /// credential (`sts:AssumeRole`, the default). Absent AND `aws_use_federation_token = true` ⇒
2029    /// `sts:GetFederationToken` is used instead (for an IAM-user base credential).
2030    pub aws_role_arn: Option<String>,
2031    /// **AWS**: use `sts:GetFederationToken` instead of `AssumeRole` (IAM-user deployments). Requires
2032    /// the base credential to be a real IAM user, not itself a session.
2033    #[serde(default)]
2034    pub aws_use_federation_token: bool,
2035    /// **GCS**: the service-account client email whose V4 signed URLs / IAM-signed uploads the minter
2036    /// produces (used in the signing scope). Absent ⇒ resolved from ADC.
2037    pub gcs_client_email: Option<String>,
2038    /// **Azure**: the storage account name (for the SAS signature + the blob URL). Absent ⇒ taken from
2039    /// the `azure_account` blob-backend arg.
2040    pub azure_account: Option<String>,
2041    /// **Azure**: the blob service URL (`https://{account}.blob.core.windows.net/`). Absent ⇒ derived
2042    /// from the account name.
2043    pub azure_service_url: Option<String>,
2044    /// **Azure**: declare the storage account has a **hierarchical namespace** (HNS/ADLS-Gen2). A
2045    /// directory-scoped SAS only actually confines to a sub-prefix on an HNS account; on a flat account
2046    /// it silently degrades to container-wide (Security LOW-1). So a PREFIX mint is refused unless this
2047    /// is `true`. Default `false` (fail-closed). A single-key mint is unaffected.
2048    #[serde(default)]
2049    pub azure_hns: bool,
2050}
2051
2052/// The default operator ceiling on a minted S3 upload credential's TTL when
2053/// `[serve].s3_ingress_mint_max_ttl_secs` is unset: 1 hour — long enough for a browser UGC upload or a
2054/// bulk-agent burst, short enough to bound a leaked short-lived credential.
2055pub const DEFAULT_S3_INGRESS_MINT_MAX_TTL_SECS: u64 = 3600;
2056
2057/// `[serve.console]` — the embedded web console (a Wasm SPA baked into the
2058/// binary with the `console` build feature). Opt-in: the static shell holds no
2059/// secrets and the `/api` it drives is token-gated, so it is served
2060/// **unauthenticated** at a deliberately obscure path (a bearer token can't gate
2061/// a top-level browser navigation anyway — the path is the obscurity, the token
2062/// is the real gate).
2063#[cfg_attr(not(feature = "console"), allow(dead_code))]
2064#[derive(Debug, Clone, Default, Deserialize)]
2065#[serde(default, deny_unknown_fields)]
2066pub struct ConsoleConfig {
2067    /// Serve the embedded console (default `false`). Requires the `console` build
2068    /// feature; enabling it in a build without that feature is a logged no-op.
2069    pub enabled: bool,
2070    /// Host(s) the console answers on: `*` (any host, the default), an exact host
2071    /// (`console.example.com`), or a leading-wildcard (`*.example.com`).
2072    pub host: Option<String>,
2073    /// URL path prefix the console mounts at (default `/_console`). Kept under the
2074    /// reserved `/_` namespace so it never collides with a published site path.
2075    pub path: Option<String>,
2076}
2077
2078/// `publish` section — where and what to deploy (the `sync` target).
2079#[derive(Debug, Default, Deserialize)]
2080#[serde(default)]
2081pub struct PublishConfig {
2082    /// Base URL of the boatramp server (e.g. `https://pad.example.com`).
2083    pub server: Option<String>,
2084    /// Site name to publish to.
2085    pub site: Option<String>,
2086    /// API token for the control plane (or set `BOATRAMP_TOKEN`).
2087    pub token: Option<String>,
2088    /// Project this site belongs to (overrides with `--project` / `BOATRAMP_PROJECT`).
2089    pub project: Option<String>,
2090}
2091
2092/// `build` section.
2093#[derive(Debug, Clone, Deserialize, serde::Serialize)]
2094pub struct BuildConfig {
2095    /// Shell command to run (e.g. `npm run build`).
2096    pub command: String,
2097    /// Directory the build emits, published by `sync` (e.g. `dist`).
2098    #[serde(default, skip_serializing_if = "Option::is_none")]
2099    pub output: Option<String>,
2100}
2101
2102/// `bundle` section — the in-process Rust bundler (`bundler` feature).
2103#[derive(Debug, Clone, Default, Deserialize)]
2104#[serde(default)]
2105pub struct BundleConfig {
2106    /// Output directory for bundled assets (e.g. `dist`).
2107    #[serde(default = "default_bundle_outdir")]
2108    pub outdir: String,
2109    /// JS/TS entry points bundled by Rolldown (tree-shaken, code-split).
2110    pub js: Vec<String>,
2111    /// CSS entry points bundled by lightningcss (`@import` inlined).
2112    pub css: Vec<String>,
2113    /// Minify output (default true).
2114    #[serde(default = "default_true")]
2115    pub minify: bool,
2116}
2117
2118fn default_bundle_outdir() -> String {
2119    "dist".to_string()
2120}
2121
2122fn default_true() -> bool {
2123    true
2124}
2125
2126#[cfg(test)]
2127mod tests {
2128    use super::*;
2129
2130    fn project(text: &str) -> ProjectConfig {
2131        ron_options().from_str(text).unwrap()
2132    }
2133
2134    fn server(text: &str) -> ServerConfig {
2135        ron_options().from_str(text).unwrap()
2136    }
2137
2138    /// Build an [`EnvSource::Map`] from `(name, value)` pairs for deterministic
2139    /// override tests (no process-global `std::env` mutation).
2140    fn env(pairs: &[(&str, &str)]) -> EnvSource {
2141        EnvSource::Map(
2142            pairs
2143                .iter()
2144                .map(|(k, v)| (k.to_string(), v.to_string()))
2145                .collect(),
2146        )
2147    }
2148
2149    #[test]
2150    fn env_overrides_configure_all_three_sections_with_no_file() {
2151        // The crux of the ask: with NO `boatramp.cfg` at all (the default config),
2152        // env vars alone materialise + populate the compute, security, and handler
2153        // `sql` sections. `ServerConfig::default()` has all three absent.
2154        let mut cfg = ServerConfig::default();
2155        assert!(cfg.compute.is_none() && cfg.security.is_none() && cfg.handlers.is_none());
2156
2157        cfg.apply_env_overrides(&env(&[
2158            ("BOATRAMP_COMPUTE_VCPUS", "8"),
2159            ("BOATRAMP_COMPUTE_MEM_MIB", "4096"),
2160            ("BOATRAMP_COMPUTE_REGION", "eu-central"),
2161            ("BOATRAMP_SECURITY_PROFILE", "single-tenant"),
2162            ("BOATRAMP_SECURITY_ALLOW_SITE_PRIVATE_UPSTREAMS", "true"),
2163            ("BOATRAMP_SECURITY_MAX_UPLOAD_BYTES", "1048576"),
2164            ("BOATRAMP_HANDLERS_SQL_URL", "http://sqld:8080"),
2165            ("BOATRAMP_HANDLERS_SQL_ADMIN_URL", "http://sqld:9090"),
2166        ]))
2167        .expect("valid env overrides apply");
2168
2169        // compute: the section now exists with the env values (and defaults elsewhere).
2170        let compute = cfg.compute.expect("compute materialised from env");
2171        assert_eq!(compute.vcpus, 8);
2172        assert_eq!(compute.mem_mib, 4096);
2173        assert_eq!(compute.region.as_deref(), Some("eu-central"));
2174        assert_eq!(compute.bridge, "br-boatramp"); // untouched default
2175
2176        // security: profile + an override both took, and the posture resolves.
2177        let security = cfg.security.expect("security materialised from env");
2178        assert_eq!(security.profile.as_deref(), Some("single-tenant"));
2179        let posture = security.resolve().expect("resolves");
2180        assert!(posture.allow_site_private_upstreams);
2181        assert_eq!(posture.max_upload_bytes, 1_048_576);
2182
2183        // handler sql: the nested handlers.bindings.sql chain was created.
2184        let sql = cfg
2185            .handlers
2186            .expect("handlers materialised from env")
2187            .bindings
2188            .sql
2189            .expect("sql binding materialised from env");
2190        assert_eq!(sql.url.as_deref(), Some("http://sqld:8080"));
2191        assert_eq!(sql.admin_url.as_deref(), Some("http://sqld:9090"));
2192    }
2193
2194    #[test]
2195    fn internal_dns_defaults_on_with_the_standard_upstream_and_domain() {
2196        // The `[compute]` defaults: internal DNS on, forwarding to 1.1.1.1:53, names
2197        // under `boatramp.internal`.
2198        let compute = ComputeConfig::default();
2199        assert!(compute.internal_dns, "internal DNS is on by default");
2200        assert_eq!(compute.dns_upstream, "1.1.1.1:53");
2201        assert_eq!(compute.dns_domain, "boatramp.internal");
2202    }
2203
2204    #[test]
2205    fn internal_dns_knobs_parse_from_a_file() {
2206        // A file can turn it off and override the upstream + domain.
2207        let cfg = server(
2208            r#"(
2209                compute: ( internal_dns: false, dns_upstream: "10.0.0.53:53", dns_domain: "svc.internal" ),
2210            )"#,
2211        );
2212        let compute = cfg.compute.expect("compute section");
2213        assert!(!compute.internal_dns);
2214        assert_eq!(compute.dns_upstream, "10.0.0.53:53");
2215        assert_eq!(compute.dns_domain, "svc.internal");
2216    }
2217
2218    #[test]
2219    fn internal_dns_knobs_are_env_settable() {
2220        // Env alone materialises `[compute]` and sets each internal-DNS knob (and an
2221        // unrecognised bool spelling is a clear error, exercised by parse_bool).
2222        let mut cfg = ServerConfig::default();
2223        cfg.apply_env_overrides(&env(&[
2224            ("BOATRAMP_COMPUTE_INTERNAL_DNS", "off"),
2225            ("BOATRAMP_COMPUTE_DNS_UPSTREAM", "9.9.9.9:53"),
2226            ("BOATRAMP_COMPUTE_DNS_DOMAIN", "corp.internal"),
2227        ]))
2228        .expect("valid env overrides apply");
2229        let compute = cfg.compute.expect("compute materialised from env");
2230        assert!(!compute.internal_dns, "env `off` disables internal DNS");
2231        assert_eq!(compute.dns_upstream, "9.9.9.9:53");
2232        assert_eq!(compute.dns_domain, "corp.internal");
2233    }
2234
2235    #[test]
2236    fn env_override_wins_over_file_value_but_unset_defers() {
2237        // A file that set each section; env then overrides one field per section
2238        // and leaves the rest of the file value in place (precedence: env > file).
2239        let mut cfg = server(
2240            r#"(
2241                compute: ( vcpus: 2, mem_mib: 512, region: "us-east" ),
2242                security: ( profile: "multi-tenant" ),
2243                handlers: ( bindings: ( sql: ( url: "http://file:8080", admin_url: "http://file:9090" ) ) ),
2244            )"#,
2245        );
2246
2247        cfg.apply_env_overrides(&env(&[
2248            ("BOATRAMP_COMPUTE_VCPUS", "16"),
2249            ("BOATRAMP_SECURITY_PROFILE", "dev"),
2250            ("BOATRAMP_HANDLERS_SQL_URL", "http://env:8080"),
2251        ]))
2252        .expect("valid env overrides apply");
2253
2254        let compute = cfg.compute.unwrap();
2255        assert_eq!(compute.vcpus, 16, "env wins over the file vcpus");
2256        assert_eq!(compute.mem_mib, 512, "unset env defers to the file mem_mib");
2257        assert_eq!(
2258            compute.region.as_deref(),
2259            Some("us-east"),
2260            "unset env defers to the file region"
2261        );
2262
2263        assert_eq!(
2264            cfg.security.unwrap().profile.as_deref(),
2265            Some("dev"),
2266            "env profile wins over the file profile"
2267        );
2268
2269        let sql = cfg.handlers.unwrap().bindings.sql.unwrap();
2270        assert_eq!(
2271            sql.url.as_deref(),
2272            Some("http://env:8080"),
2273            "env wins over the file sql url"
2274        );
2275        assert_eq!(
2276            sql.admin_url.as_deref(),
2277            Some("http://file:9090"),
2278            "unset env defers to the file sql admin_url"
2279        );
2280    }
2281
2282    #[test]
2283    fn env_overrides_leave_unmentioned_sections_absent() {
2284        // With no relevant env vars set, an empty config stays empty — the sections
2285        // are materialised only on demand, so an unset environment adds nothing.
2286        let mut cfg = ServerConfig::default();
2287        cfg.apply_env_overrides(&env(&[("SOME_UNRELATED_VAR", "x")]))
2288            .expect("no-op env applies");
2289        assert!(cfg.compute.is_none());
2290        assert!(cfg.security.is_none());
2291        assert!(cfg.handlers.is_none());
2292        assert!(cfg.secrets.is_none());
2293        assert!(cfg.cluster.is_none());
2294    }
2295
2296    #[test]
2297    fn env_bool_accepts_common_spellings_and_rejects_garbage() {
2298        // Truthy/falsey spellings all parse.
2299        for (raw, want) in [
2300            ("true", true),
2301            ("1", true),
2302            ("YES", true),
2303            ("On", true),
2304            ("false", false),
2305            ("0", false),
2306            ("no", false),
2307            ("OFF", false),
2308        ] {
2309            let mut cfg = ServerConfig::default();
2310            cfg.apply_env_overrides(&env(&[("BOATRAMP_SECURITY_REQUIRE_POP", raw)]))
2311                .expect("boolean parses");
2312            assert_eq!(
2313                cfg.security.unwrap().overrides.require_pop,
2314                Some(want),
2315                "{raw:?} ⇒ {want}"
2316            );
2317        }
2318        // A non-boolean value is a clear error, not a silent default.
2319        let mut cfg = ServerConfig::default();
2320        let err = cfg
2321            .apply_env_overrides(&env(&[("BOATRAMP_SECURITY_REQUIRE_POP", "maybe")]))
2322            .expect_err("garbage boolean is rejected");
2323        match err {
2324            ConfigError::Env { var, .. } => assert_eq!(var, "BOATRAMP_SECURITY_REQUIRE_POP"),
2325            other => panic!("expected ConfigError::Env, got {other:?}"),
2326        }
2327    }
2328
2329    #[test]
2330    fn env_number_parse_error_names_the_variable() {
2331        // A non-numeric numeric var is rejected with the variable named.
2332        let mut cfg = ServerConfig::default();
2333        let err = cfg
2334            .apply_env_overrides(&env(&[("BOATRAMP_COMPUTE_VCPUS", "lots")]))
2335            .expect_err("garbage number is rejected");
2336        match err {
2337            ConfigError::Env { var, .. } => assert_eq!(var, "BOATRAMP_COMPUTE_VCPUS"),
2338            other => panic!("expected ConfigError::Env, got {other:?}"),
2339        }
2340    }
2341
2342    #[test]
2343    fn empty_env_value_is_treated_as_unset() {
2344        // `VAR=` (empty) must not clobber a file value with an empty string.
2345        let mut cfg = server(r#"( compute: ( region: "us-east" ) )"#);
2346        cfg.apply_env_overrides(&env(&[("BOATRAMP_COMPUTE_REGION", "")]))
2347            .expect("empty env applies as a no-op");
2348        assert_eq!(
2349            cfg.compute.unwrap().region.as_deref(),
2350            Some("us-east"),
2351            "an empty env value leaves the file value in place"
2352        );
2353    }
2354
2355    #[test]
2356    fn env_configures_managed_postgres_secrets_and_privilege_with_no_file() {
2357        // The construens acceptance case: with NO `boatramp.cfg` at all, the
2358        // environment alone stands up a managed co-located Postgres. It configures
2359        // the default (`"default"`-named, v0.5.0) database in
2360        // `handlers.bindings.sql.databases` (kind=postgres, compute=pg, database+user
2361        // set), the `[secrets]` envelope (local + a kek path so the managed credential
2362        // can be sealed), and `compute.managed_db_privilege = rootless`. All three
2363        // sections start absent.
2364        let mut cfg = ServerConfig::default();
2365        assert!(cfg.handlers.is_none() && cfg.secrets.is_none() && cfg.compute.is_none());
2366
2367        cfg.apply_env_overrides(&env(&[
2368            // The default database is addressed by the reserved `DEFAULT` token,
2369            // which maps to the reserved real name `"default"` (v0.5.0).
2370            ("BOATRAMP_HANDLERS_SQL_DB_DEFAULT_KIND", "postgres"),
2371            ("BOATRAMP_HANDLERS_SQL_DB_DEFAULT_COMPUTE", "pg"),
2372            ("BOATRAMP_HANDLERS_SQL_DB_DEFAULT_DATABASE", "appdb"),
2373            ("BOATRAMP_HANDLERS_SQL_DB_DEFAULT_USER", "app"),
2374            // Secrets: the local envelope + a KEK path (never key material).
2375            ("BOATRAMP_SECRETS_ENVELOPE", "local"),
2376            ("BOATRAMP_SECRETS_KEK_FILE", "/var/lib/boatramp/secrets/kek"),
2377            // The shared-kernel DB privilege strategy.
2378            ("BOATRAMP_COMPUTE_MANAGED_DB_PRIVILEGE", "rootless"),
2379        ]))
2380        .expect("valid env overrides apply");
2381
2382        // The default (`"default"`-keyed) managed database exists with the right source.
2383        let sql = cfg
2384            .handlers
2385            .expect("handlers materialised from env")
2386            .bindings
2387            .sql
2388            .expect("sql binding materialised from env");
2389        let db = sql
2390            .databases
2391            .get(boatramp_core::project::DEFAULT_DB_NAME)
2392            .expect("the default `default`-named database was created from DEFAULT");
2393        assert!(
2394            !sql.databases.contains_key(""),
2395            "the empty-string key is never produced (v0.5.0)"
2396        );
2397        assert_eq!(db.kind, "postgres");
2398        assert_eq!(db.compute.as_deref(), Some("pg"));
2399        assert_eq!(db.database.as_deref(), Some("appdb"));
2400        assert_eq!(db.user.as_deref(), Some("app"));
2401        // No `password_env` ⇒ boatramp manages the credential (Phase 2), and the
2402        // compute-backed source validates.
2403        assert!(db.password_env.is_none());
2404        assert!(db.is_managed_credential());
2405        assert!(db.validate("").is_ok());
2406
2407        // The secrets envelope + KEK path took (the path is a location, not a key).
2408        let secrets = cfg.secrets.expect("secrets materialised from env");
2409        assert_eq!(secrets.envelope, "local");
2410        assert_eq!(
2411            secrets.kek_file.as_deref(),
2412            Some(Path::new("/var/lib/boatramp/secrets/kek"))
2413        );
2414        assert!(
2415            secrets.vault.is_none(),
2416            "no vault vars ⇒ no vault sub-config"
2417        );
2418
2419        // The managed-DB privilege strategy resolved from its lowercase variant.
2420        let compute = cfg.compute.expect("compute materialised from env");
2421        assert_eq!(compute.managed_db_privilege, ManagedDbPrivilege::Rootless);
2422    }
2423
2424    #[test]
2425    fn env_declares_named_databases_and_merges_over_the_file() {
2426        // A file declares one database; the env overrides one of its fields and
2427        // ADDS a second, discovering both member names from the environment.
2428        let mut cfg = server(
2429            r#"(
2430                handlers: ( bindings: ( sql: (
2431                    databases: {
2432                        "analytics": ( kind: "postgres", url_env: "FILE_PG_URL", pool_max: 4 ),
2433                    },
2434                ) ) ),
2435            )"#,
2436        );
2437        cfg.apply_env_overrides(&env(&[
2438            // Override the file database's pool size (merge by key, per field).
2439            ("BOATRAMP_HANDLERS_SQL_DB_analytics_POOL_MAX", "32"),
2440            // Add a brand-new database whose name has an underscore, exercising the
2441            // longest-suffix name isolation (`_READ_URL_ENV`, not `_URL_ENV`).
2442            ("BOATRAMP_HANDLERS_SQL_DB_events_log_KIND", "mysql"),
2443            ("BOATRAMP_HANDLERS_SQL_DB_events_log_URL_ENV", "EVENTS_URL"),
2444            (
2445                "BOATRAMP_HANDLERS_SQL_DB_events_log_READ_URL_ENV",
2446                "EVENTS_RO_URL",
2447            ),
2448            ("BOATRAMP_HANDLERS_SQL_DB_events_log_READ_ONLY", "true"),
2449        ]))
2450        .expect("valid env overrides apply");
2451
2452        let sql = cfg.handlers.unwrap().bindings.sql.unwrap();
2453        assert_eq!(sql.databases.len(), 2);
2454
2455        let analytics = &sql.databases["analytics"];
2456        assert_eq!(
2457            analytics.pool_max,
2458            Some(32),
2459            "env pool_max wins over the file"
2460        );
2461        assert_eq!(
2462            analytics.url_env, "FILE_PG_URL",
2463            "the file's url_env survives (env didn't touch it)"
2464        );
2465
2466        let events = &sql.databases["events_log"];
2467        assert_eq!(events.kind, "mysql");
2468        assert_eq!(events.url_env, "EVENTS_URL");
2469        assert_eq!(events.read_url_env.as_deref(), Some("EVENTS_RO_URL"));
2470        assert!(events.read_only);
2471    }
2472
2473    #[test]
2474    fn default_token_maps_to_the_reserved_default_name_not_empty() {
2475        // v0.5.0 breaking change: the reserved `DEFAULT` env token maps to the real
2476        // name `"default"` (a valid URL path segment), never the empty string. This is
2477        // what makes the default binding addressable as `--db default` and keeps every
2478        // db-name ingress path-segment-safe.
2479        let mut cfg = ServerConfig::default();
2480        cfg.apply_env_overrides(&env(&[
2481            ("BOATRAMP_HANDLERS_SQL_DB_DEFAULT_KIND", "postgres"),
2482            ("BOATRAMP_HANDLERS_SQL_DB_DEFAULT_URL_ENV", "PG_URL"),
2483        ]))
2484        .expect("valid env overrides apply");
2485        let databases = cfg.handlers.unwrap().bindings.sql.unwrap().databases;
2486        assert!(
2487            databases.contains_key(boatramp_core::project::DEFAULT_DB_NAME),
2488            "DEFAULT → the reserved `default` key"
2489        );
2490        assert!(
2491            !databases.contains_key(""),
2492            "the empty-string key is never produced"
2493        );
2494    }
2495
2496    #[test]
2497    fn empty_string_db_binding_name_is_rejected_with_a_cure() {
2498        // A `boatramp.cfg` that literally writes the legacy empty-string default key
2499        // fails closed on load (it would emit a `//` control-plane path), and the
2500        // error points at the cure (`default`).
2501        let err = ServerConfig::parse(
2502            r#"(
2503                handlers: ( bindings: ( sql: (
2504                    databases: {
2505                        "": ( kind: "postgres", url_env: "PG_URL" ),
2506                    },
2507                ) ) ),
2508            )"#,
2509        )
2510        .expect_err("an empty-string db binding name is refused");
2511        match err {
2512            ConfigError::InvalidDbName { name, reason, cure } => {
2513                assert_eq!(name, "");
2514                assert!(reason.contains("empty"), "reason names the emptiness");
2515                assert!(
2516                    cure.contains("default") && cure.contains("CHANGELOG"),
2517                    "the cure points at `default` + the CHANGELOG"
2518                );
2519            }
2520            other => panic!("expected ConfigError::InvalidDbName, got {other:?}"),
2521        }
2522    }
2523
2524    #[test]
2525    fn path_separator_db_binding_name_is_rejected() {
2526        // A non-path-segment name (contains `/`) is refused with no default-cure (the
2527        // fix is to rename it, not adopt `default`).
2528        let err = ServerConfig::parse(
2529            r#"(
2530                handlers: ( bindings: ( sql: (
2531                    databases: {
2532                        "a/b": ( kind: "postgres", url_env: "PG_URL" ),
2533                    },
2534                ) ) ),
2535            )"#,
2536        )
2537        .expect_err("a `/`-bearing db binding name is refused");
2538        match err {
2539            ConfigError::InvalidDbName { name, reason, cure } => {
2540                assert_eq!(name, "a/b");
2541                assert!(reason.contains("path separator"));
2542                assert!(cure.is_empty(), "no default-cure for a non-default name");
2543            }
2544            other => panic!("expected ConfigError::InvalidDbName, got {other:?}"),
2545        }
2546    }
2547
2548    #[test]
2549    fn reserved_bramp_db_compute_prefix_is_rejected() {
2550        // #501 Stage B LOW-2: a static BYO binding may not point `compute` at a
2551        // `bramp-db-…` workload (reserved for derived managed-DB servers) — refused
2552        // fail-closed at config load.
2553        let err = ServerConfig::parse(
2554            r#"(
2555                handlers: ( bindings: ( sql: (
2556                    databases: {
2557                        "byo": ( kind: "postgres", compute: "bramp-db-acme-app", database: "d", user: "u" ),
2558                    },
2559                ) ) ),
2560            )"#,
2561        )
2562        .expect_err("a `bramp-db-` compute workload is refused");
2563        match err {
2564            ConfigError::InvalidDbName { name, reason, cure } => {
2565                assert_eq!(name, "bramp-db-acme-app");
2566                assert!(reason.contains("reserved"), "reason names the reservation");
2567                assert!(cure.contains("bramp-db-"), "the cure names the prefix");
2568            }
2569            other => panic!("expected ConfigError::InvalidDbName, got {other:?}"),
2570        }
2571        // A NON-reserved compute workload for a BYO binding still loads fine.
2572        ServerConfig::parse(
2573            r#"(
2574                handlers: ( bindings: ( sql: (
2575                    databases: {
2576                        "byo": ( kind: "postgres", compute: "my-pg", database: "d", user: "u" ),
2577                    },
2578                ) ) ),
2579            )"#,
2580        )
2581        .expect("a non-reserved compute workload loads");
2582    }
2583
2584    #[test]
2585    fn env_sets_managed_db_startup_grace() {
2586        // The per-binding startup-grace override is env-settable like the other
2587        // managed scalars, discovered by the `_STARTUP_GRACE_SECS` suffix.
2588        let mut cfg = ServerConfig::default();
2589        cfg.apply_env_overrides(&env(&[
2590            ("BOATRAMP_HANDLERS_SQL_DB_DEFAULT_KIND", "postgres"),
2591            ("BOATRAMP_HANDLERS_SQL_DB_DEFAULT_COMPUTE", "pg"),
2592            ("BOATRAMP_HANDLERS_SQL_DB_DEFAULT_DATABASE", "appdb"),
2593            ("BOATRAMP_HANDLERS_SQL_DB_DEFAULT_USER", "app"),
2594            ("BOATRAMP_HANDLERS_SQL_DB_DEFAULT_STARTUP_GRACE_SECS", "90"),
2595        ]))
2596        .expect("valid env overrides apply");
2597        let db = &cfg.handlers.unwrap().bindings.sql.unwrap().databases
2598            [boatramp_core::project::DEFAULT_DB_NAME];
2599        assert_eq!(db.startup_grace_secs, Some(90));
2600    }
2601
2602    #[test]
2603    fn env_sets_rls_gucs_and_all_marker_without_suffix_collision() {
2604        // The RLS GUC names + the v0.4.21 all-read marker are env-settable. `_TENANT_ALL_MARKER`
2605        // and `_TENANT_GUC` must NOT be shadowed by the shorter `_TENANT` suffix (longest-first
2606        // isolation) — a `_TENANT` value would otherwise swallow the DB-name split.
2607        let mut cfg = ServerConfig::default();
2608        cfg.apply_env_overrides(&env(&[
2609            ("BOATRAMP_HANDLERS_SQL_DB_DEFAULT_KIND", "postgres"),
2610            ("BOATRAMP_HANDLERS_SQL_DB_DEFAULT_DATABASE", "appdb"),
2611            (
2612                "BOATRAMP_HANDLERS_SQL_DB_DEFAULT_TENANT_GUC",
2613                "app.tenant_id",
2614            ),
2615            (
2616                "BOATRAMP_HANDLERS_SQL_DB_DEFAULT_SESSION_GUC",
2617                "app.session_id",
2618            ),
2619            ("BOATRAMP_HANDLERS_SQL_DB_DEFAULT_TENANT_ALL_MARKER", "*"),
2620        ]))
2621        .expect("valid env overrides apply");
2622        let db = &cfg.handlers.unwrap().bindings.sql.unwrap().databases
2623            [boatramp_core::project::DEFAULT_DB_NAME];
2624        assert_eq!(db.tenant_guc.as_deref(), Some("app.tenant_id"));
2625        assert_eq!(db.session_guc.as_deref(), Some("app.session_id"));
2626        assert_eq!(db.tenant_all_marker.as_deref(), Some("*"));
2627    }
2628
2629    #[test]
2630    fn env_enum_parse_error_names_the_variable_and_variants() {
2631        // An unknown enum value is a clear error that names the offending variable.
2632        let mut cfg = ServerConfig::default();
2633        let err = cfg
2634            .apply_env_overrides(&env(&[(
2635                "BOATRAMP_COMPUTE_MANAGED_DB_PRIVILEGE",
2636                "superuser",
2637            )]))
2638            .expect_err("unknown enum variant is rejected");
2639        match err {
2640            ConfigError::Env { var, reason } => {
2641                assert_eq!(var, "BOATRAMP_COMPUTE_MANAGED_DB_PRIVILEGE");
2642                assert!(reason.contains("rootless") && reason.contains("caps"));
2643            }
2644            other => panic!("expected ConfigError::Env, got {other:?}"),
2645        }
2646        // The docker enums map their lowercase serde variants too.
2647        let mut cfg = ServerConfig::default();
2648        cfg.apply_env_overrides(&env(&[
2649            ("BOATRAMP_COMPUTE_DOCKER_ENDPOINT", "bridge"),
2650            ("BOATRAMP_COMPUTE_DOCKER_VOLUME_MODE", "bind"),
2651        ]))
2652        .expect("known enum variants parse");
2653        let compute = cfg.compute.unwrap();
2654        assert_eq!(
2655            compute.docker_endpoint,
2656            boatramp_docker::DockerEndpoint::Bridge
2657        );
2658        assert_eq!(
2659            compute.docker_volume_mode,
2660            boatramp_docker::DockerVolumeMode::Bind
2661        );
2662    }
2663
2664    #[test]
2665    fn env_trust_anchors_parse_as_a_comma_separated_list() {
2666        // The kernel trust anchors are comma-separated (whitespace trimmed, empty
2667        // items dropped so a trailing comma is tolerated). A file default is
2668        // fully replaced, not appended to.
2669        let mut cfg = ServerConfig::default();
2670        cfg.apply_env_overrides(&env(&[
2671            (
2672                "BOATRAMP_COMPUTE_KERNEL_SIGNING_PUBKEYS",
2673                " es256:aa , es256:bb ,",
2674            ),
2675            ("BOATRAMP_COMPUTE_KERNEL_ALLOWED_HASHES", "deadbeef"),
2676        ]))
2677        .expect("valid list env applies");
2678        let compute = cfg.compute.unwrap();
2679        assert_eq!(
2680            compute.kernel_signing_pubkeys,
2681            vec!["es256:aa".to_string(), "es256:bb".to_string()],
2682            "trimmed, comma-split, trailing-empty dropped, defaults replaced"
2683        );
2684        assert_eq!(
2685            compute.kernel_allowed_hashes,
2686            vec!["deadbeef".to_string()],
2687            "a single value is a one-element list"
2688        );
2689    }
2690
2691    #[test]
2692    fn env_configures_secrets_vault_subconfig() {
2693        // The vault sub-config materialises only when a vault var is set, and the
2694        // token stays indirected via a variable NAME (`token_env`), never inline.
2695        let mut cfg = ServerConfig::default();
2696        cfg.apply_env_overrides(&env(&[
2697            ("BOATRAMP_SECRETS_ENVELOPE", "vault"),
2698            ("BOATRAMP_SECRETS_VAULT_ADDR", "https://vault:8200"),
2699            ("BOATRAMP_SECRETS_VAULT_KEY", "certs"),
2700        ]))
2701        .expect("valid env overrides apply");
2702        let secrets = cfg.secrets.unwrap();
2703        assert_eq!(secrets.envelope, "vault");
2704        let vault = secrets.vault.expect("vault sub-config materialised");
2705        assert_eq!(vault.addr, "https://vault:8200");
2706        assert_eq!(vault.key, "certs");
2707        // token_env defaults to VAULT_TOKEN when not overridden.
2708        assert_eq!(vault.token_env, "VAULT_TOKEN");
2709    }
2710
2711    #[test]
2712    fn env_materialises_and_overrides_the_cluster_section() {
2713        // With no file, a `BOATRAMP_CLUSTER_LISTEN` materialises the section; the
2714        // remaining fields (lists, join token, mesh) layer on. The founding/joining
2715        // action flags (`BOATRAMP_CLUSTER_INIT`/`_JOIN`) are separate `serve` args
2716        // and are not part of this section.
2717        let mut cfg = ServerConfig::default();
2718        cfg.apply_env_overrides(&env(&[
2719            ("BOATRAMP_CLUSTER_LISTEN", "10.0.0.2:7000"),
2720            ("BOATRAMP_CLUSTER_ROOT_PUBKEYS", "es256:aa,es256:bb"),
2721            ("BOATRAMP_CLUSTER_SEEDS", "https://10.0.0.1:8080"),
2722            ("BOATRAMP_CLUSTER_JOIN_TOKEN", "env:BOATRAMP_JOIN_TOKEN"),
2723            ("BOATRAMP_CLUSTER_STORE_DIR", "/var/lib/boatramp/raft"),
2724            ("BOATRAMP_CLUSTER_MESH_GATE_CLIENT_WRITES", "true"),
2725        ]))
2726        .expect("valid env overrides apply");
2727        let cluster = cfg.cluster.expect("cluster materialised from env");
2728        assert_eq!(
2729            cluster.listen,
2730            "10.0.0.2:7000".parse::<std::net::SocketAddr>().unwrap()
2731        );
2732        assert_eq!(
2733            cluster.root_pubkeys,
2734            vec!["es256:aa".to_string(), "es256:bb".to_string()]
2735        );
2736        assert_eq!(cluster.seeds, vec!["https://10.0.0.1:8080".to_string()]);
2737        assert_eq!(
2738            cluster.join_token.as_deref(),
2739            Some("env:BOATRAMP_JOIN_TOKEN")
2740        );
2741        assert_eq!(
2742            cluster.store_dir.as_deref(),
2743            Some(Path::new("/var/lib/boatramp/raft"))
2744        );
2745        assert_eq!(
2746            cluster.mesh.expect("mesh sub-config").gate_client_writes,
2747            Some(true)
2748        );
2749
2750        // Without a listen (and no file section) there is nothing to materialise:
2751        // a non-listen cluster var alone leaves the section absent.
2752        let mut cfg = ServerConfig::default();
2753        cfg.apply_env_overrides(&env(&[("BOATRAMP_CLUSTER_SEEDS", "https://10.0.0.1:8080")]))
2754            .expect("applies");
2755        assert!(
2756            cfg.cluster.is_none(),
2757            "no listen + no file section ⇒ no cluster"
2758        );
2759    }
2760
2761    #[test]
2762    fn env_cluster_listen_overrides_a_file_section() {
2763        // A file `[cluster]` section: env overrides `listen` and adds seeds.
2764        let mut cfg = server(r#"( cluster: ( listen: "0.0.0.0:7000" ) )"#);
2765        cfg.apply_env_overrides(&env(&[
2766            ("BOATRAMP_CLUSTER_LISTEN", "10.0.0.9:7000"),
2767            ("BOATRAMP_CLUSTER_SEEDS", "https://seed:8080"),
2768        ]))
2769        .expect("applies");
2770        let cluster = cfg.cluster.unwrap();
2771        assert_eq!(
2772            cluster.listen,
2773            "10.0.0.9:7000".parse::<std::net::SocketAddr>().unwrap(),
2774            "env listen wins over the file"
2775        );
2776        assert_eq!(cluster.seeds, vec!["https://seed:8080".to_string()]);
2777    }
2778
2779    #[test]
2780    fn empty_project_config_is_default() {
2781        let cfg = project("()");
2782        assert!(cfg.publish.server.is_none());
2783        assert!(cfg.publish.site.is_none());
2784        assert!(cfg.build.is_none());
2785        assert!(cfg.bundle.is_none());
2786        // Routing defaults: schema v1, the single default index candidate.
2787        assert_eq!(cfg.routing.version, 1);
2788        assert_eq!(cfg.routing.index, vec!["index.html".to_string()]);
2789    }
2790
2791    #[test]
2792    fn serve_signer_config_parses_and_maps_each_backend() {
2793        use boatramp_core::cose::TokenAlg;
2794        use boatramp_server::signer::SignerConfig;
2795
2796        // RON-native enum tagging (`Vault(...)`); `IMPLICIT_SOME` lets the optional
2797        // fields (region) take a bare value or be omitted (→ None). This is the
2798        // exact RON documented in the Authentication guide.
2799        let vault = server(
2800            r#"( serve: ( signer: Vault(
2801                address: "https://vault.example:8200",
2802                key: "boatramp-root",
2803                token_env: "VAULT_TOKEN",
2804                alg: Ed25519,
2805            ) ) )"#,
2806        );
2807        match vault.serve.unwrap().signer.unwrap().to_signer_config() {
2808            SignerConfig::Vault {
2809                address,
2810                key,
2811                token_env,
2812                alg,
2813            } => {
2814                assert_eq!(address, "https://vault.example:8200");
2815                assert_eq!(key, "boatramp-root");
2816                assert_eq!(token_env, "VAULT_TOKEN");
2817                assert_eq!(alg, TokenAlg::Ed25519);
2818            }
2819            other => panic!("expected Vault, got {other:?}"),
2820        }
2821
2822        // AWS KMS: region omitted → None; PKCS#11: alg omitted → the ES256 default.
2823        let aws =
2824            server(r#"( serve: ( signer: AwsKms(key_id: "arn:aws:kms:eu-west-1:1:key/abc") ) )"#);
2825        assert!(matches!(
2826            aws.serve.unwrap().signer.unwrap().to_signer_config(),
2827            SignerConfig::AwsKms { region: None, .. }
2828        ));
2829
2830        let hsm = server(
2831            r#"( serve: ( signer: Pkcs11(
2832                module: "/usr/lib/softhsm/libsofthsm2.so",
2833                token_label: "boatramp",
2834                key_label: "root",
2835                pin_env: "HSM_PIN",
2836            ) ) )"#,
2837        );
2838        match hsm.serve.unwrap().signer.unwrap().to_signer_config() {
2839            SignerConfig::Pkcs11 { alg, .. } => assert_eq!(alg, TokenAlg::Es256),
2840            other => panic!("expected Pkcs11, got {other:?}"),
2841        }
2842    }
2843
2844    #[test]
2845    fn project_config_parses_publish_build_and_routing() {
2846        let cfg = project(
2847            r#"(
2848                publish: ( server: "http://127.0.0.1:8080", site: "demo" ),
2849                build: ( command: "npm run build", output: "dist" ),
2850                routing: (
2851                    clean_urls: true,
2852                    redirects: [ (from: "/old/:slug", to: "/new/:slug", status: 301) ],
2853                ),
2854            )"#,
2855        );
2856        assert_eq!(cfg.publish.server.as_deref(), Some("http://127.0.0.1:8080"));
2857        assert_eq!(cfg.publish.site.as_deref(), Some("demo"));
2858        let build = cfg.build.unwrap();
2859        assert_eq!(build.command, "npm run build");
2860        assert_eq!(build.output.as_deref(), Some("dist"));
2861        assert!(cfg.routing.clean_urls);
2862        assert_eq!(cfg.routing.redirects.len(), 1);
2863        assert_eq!(cfg.routing.redirects[0].status, 301);
2864    }
2865
2866    #[test]
2867    fn project_config_rejects_bad_routing_pattern() {
2868        // The same compile-check `load` runs: a bad route pattern is an error.
2869        let cfg = project(r#"( routing: ( redirects: [ (from: "/a/**/b/**", to: "/x") ] ) )"#);
2870        assert!(cfg.routing.compile_check().is_err());
2871    }
2872
2873    #[test]
2874    fn empty_server_config_has_no_sections() {
2875        let cfg = server("()");
2876        assert!(cfg.serve.is_none());
2877        assert!(cfg.handlers.is_none());
2878        assert!(cfg.cluster.is_none());
2879        assert!(cfg.security.is_none());
2880    }
2881
2882    #[test]
2883    fn security_section_parses_and_resolves() {
2884        // A profile plus an override that wins over it.
2885        let cfg = server(
2886            r#"(
2887                security: (
2888                    profile: "dev",
2889                    overrides: (
2890                        oidc_require_audience: true,
2891                        max_upload_bytes: 0,
2892                    ),
2893                )
2894            )"#,
2895        );
2896        let posture = cfg.security.unwrap().resolve().expect("resolves");
2897        // `dev` is loose...
2898        assert!(posture.allow_unauthenticated_public_bind);
2899        // ...but the explicit override wins over the profile.
2900        assert!(posture.oidc_require_audience);
2901        assert_eq!(posture.max_upload_bytes, 0); // unlimited
2902    }
2903
2904    #[test]
2905    fn env_wires_allow_env_secret_refs_over_the_multi_tenant_default() {
2906        // With no file, the multi-tenant default leaves host-env secret refs off;
2907        // the env knob re-enables them (env > default), same as the other posture bools.
2908        let mut cfg = ServerConfig::default();
2909        cfg.apply_env_overrides(&env(&[("BOATRAMP_SECURITY_ALLOW_ENV_SECRET_REFS", "true")]))
2910            .expect("valid env override applies");
2911        let posture = cfg
2912            .security
2913            .expect("security materialised from env")
2914            .resolve()
2915            .expect("resolves");
2916        assert!(posture.allow_env_secret_refs);
2917    }
2918
2919    #[test]
2920    fn env_wires_the_multi_tenant_subknobs_over_the_default() {
2921        // Gap 4b: the four multi-tenant sub-knobs were file-only; env now sets them (env > the
2922        // multi-tenant preset default), so a 12-factor deploy can tune tenancy isolation + guest
2923        // capability minting with no `boatramp.cfg`. Verified: strict declaration stays on while
2924        // cross-tenant `all` twins + guest cap-mint are permitted (they compose — Gap 4.3).
2925        let mut cfg = ServerConfig::default();
2926        cfg.apply_env_overrides(&env(&[
2927            ("BOATRAMP_SECURITY_PROFILE", "multi-tenant"),
2928            ("BOATRAMP_SECURITY_REQUIRE_TENANCY_DECLARATION", "true"),
2929            ("BOATRAMP_SECURITY_ALLOW_CROSS_TENANT_DB", "true"),
2930            ("BOATRAMP_SECURITY_ALLOW_GUEST_MINT_CAPABILITY", "true"),
2931            ("BOATRAMP_SECURITY_MAX_GUEST_CAPABILITY_TTL_SECS", "1800"),
2932        ]))
2933        .expect("valid env overrides apply");
2934        let posture = cfg
2935            .security
2936            .expect("security materialised from env")
2937            .resolve()
2938            .expect("resolves");
2939        assert!(posture.require_tenancy_declaration);
2940        assert!(posture.allow_cross_tenant_db);
2941        assert!(posture.allow_guest_mint_capability);
2942        assert_eq!(posture.max_guest_capability_ttl_secs, 1800);
2943    }
2944
2945    #[test]
2946    fn env_wires_the_remaining_guest_feature_knobs_over_the_multi_tenant_default() {
2947        // v0.4.18 env parity: `allow_guest_email` (which regressed prod SMTP on the P48 cutover —
2948        // multi-tenant defaults it OFF and there was no env lever), its egress sibling
2949        // `allow_guest_egress_extra_ca` (shipped config-only in v0.4.17), and the four
2950        // `allow_guest_admin_*` self-config knobs were all missing from the env map. Each preset
2951        // defaults them OFF under `multi-tenant`; the env knob must now flip each back on for a
2952        // 12-factor env-only fleet, exactly like `allow_guest_mint_capability`.
2953        let mut cfg = ServerConfig::default();
2954        cfg.apply_env_overrides(&env(&[
2955            ("BOATRAMP_SECURITY_PROFILE", "multi-tenant"),
2956            ("BOATRAMP_SECURITY_ALLOW_GUEST_EMAIL", "true"),
2957            ("BOATRAMP_SECURITY_ALLOW_GUEST_EGRESS_EXTRA_CA", "true"),
2958            ("BOATRAMP_SECURITY_ALLOW_GUEST_ADMIN_DOMAINS", "true"),
2959            ("BOATRAMP_SECURITY_ALLOW_GUEST_ADMIN_EMAIL", "true"),
2960            ("BOATRAMP_SECURITY_ALLOW_GUEST_ADMIN_SITE", "true"),
2961            ("BOATRAMP_SECURITY_ALLOW_GUEST_ADMIN_SECRETS", "true"),
2962        ]))
2963        .expect("valid env overrides apply");
2964        let security = cfg.security.expect("security materialised from env");
2965        let posture = security.resolve().expect("resolves");
2966        // Every one flips on over the multi-tenant preset default (which is `false` for all six).
2967        assert!(posture.allow_guest_email, "guest email re-enabled via env");
2968        assert!(posture.allow_guest_egress_extra_ca);
2969        assert!(posture.allow_guest_admin_domains);
2970        assert!(posture.allow_guest_admin_email);
2971        assert!(posture.allow_guest_admin_site);
2972        assert!(posture.allow_guest_admin_secrets);
2973        // `security explain` attributes each to the override/env source (not the profile preset).
2974        let explained = security.explain().expect("explains");
2975        for knob in [
2976            "allow_guest_email",
2977            "allow_guest_egress_extra_ca",
2978            "allow_guest_admin_domains",
2979            "allow_guest_admin_email",
2980            "allow_guest_admin_site",
2981            "allow_guest_admin_secrets",
2982        ] {
2983            assert!(
2984                explained
2985                    .lines()
2986                    .any(|l| l.contains(knob) && l.contains("true") && l.contains("(override)")),
2987                "explain shows {knob} = true (override): \n{explained}"
2988            );
2989        }
2990    }
2991
2992    #[test]
2993    fn each_guest_feature_env_var_moves_its_own_posture_field() {
2994        // Cross-wiring guard: set each of the six guest-feature vars ALONE over the multi-tenant
2995        // default and assert THAT var's own resolved field flips — so a copy-paste arm mapping a var
2996        // to the wrong field (or an unregistered var that never materialises the section) fails here.
2997        // Complements `every_posture_override_field_has_an_env_mapping` below (which proves coverage
2998        // by field name but not that each arm targets the right field).
2999        for (var, check) in [
3000            (
3001                "BOATRAMP_SECURITY_ALLOW_GUEST_EMAIL",
3002                (|p: &boatramp_core::security::SecurityPosture| p.allow_guest_email)
3003                    as fn(&boatramp_core::security::SecurityPosture) -> bool,
3004            ),
3005            ("BOATRAMP_SECURITY_ALLOW_GUEST_EGRESS_EXTRA_CA", |p| {
3006                p.allow_guest_egress_extra_ca
3007            }),
3008            ("BOATRAMP_SECURITY_ALLOW_GUEST_ADMIN_DOMAINS", |p| {
3009                p.allow_guest_admin_domains
3010            }),
3011            ("BOATRAMP_SECURITY_ALLOW_GUEST_ADMIN_EMAIL", |p| {
3012                p.allow_guest_admin_email
3013            }),
3014            ("BOATRAMP_SECURITY_ALLOW_GUEST_ADMIN_SITE", |p| {
3015                p.allow_guest_admin_site
3016            }),
3017            ("BOATRAMP_SECURITY_ALLOW_GUEST_ADMIN_SECRETS", |p| {
3018                p.allow_guest_admin_secrets
3019            }),
3020        ] {
3021            let mut cfg = ServerConfig::default();
3022            cfg.apply_env_overrides(&env(&[
3023                ("BOATRAMP_SECURITY_PROFILE", "multi-tenant"),
3024                (var, "true"),
3025            ]))
3026            .unwrap_or_else(|e| panic!("{var} applies: {e}"));
3027            let posture = cfg
3028                .security
3029                .unwrap_or_else(|| panic!("{var} materialises the security section"))
3030                .resolve()
3031                .expect("resolves");
3032            assert!(check(&posture), "{var} did not flip the resolved posture");
3033        }
3034    }
3035
3036    #[test]
3037    fn every_posture_override_field_has_an_env_mapping() {
3038        // Exhaustive guard against the EXACT class of gap v0.4.18 closes — a `PostureOverrides`
3039        // field a 12-factor fleet can set in `[security.overrides]` but NOT via env — for EVERY
3040        // field, now and in the future. Enumerate the struct's fields structurally (serialize a
3041        // default instance; every field renders as a key) and assert each maps to a registered
3042        // `BOATRAMP_SECURITY_<UPPER(field)>` in `SECURITY_ENV_VARS`. A new override field added
3043        // without an env var (or a var left out of the registry) fails here — so the omission that
3044        // regressed `allow_guest_email` can't silently recur. The registry entry is load-bearing:
3045        // `apply_env_overrides` only materialises the section when `source.any(SECURITY_ENV_VARS)`.
3046        let all = serde_json::to_value(boatramp_core::security::PostureOverrides::default())
3047            .expect("PostureOverrides serializes");
3048        let fields = all.as_object().expect("a struct is a JSON object");
3049        assert!(!fields.is_empty(), "expected some override fields");
3050        for field in fields.keys() {
3051            let var = format!("BOATRAMP_SECURITY_{}", field.to_uppercase());
3052            assert!(
3053                SECURITY_ENV_VARS.contains(&var.as_str()),
3054                "PostureOverrides field `{field}` has no env mapping — add `{var}` to \
3055                 SECURITY_ENV_VARS + an arm in apply_env_overrides (the v0.4.18 forgot-a-knob guard)"
3056            );
3057        }
3058    }
3059
3060    #[test]
3061    fn cluster_section_parses_the_dynamic_join_shape() {
3062        let cfg = server(
3063            r#"(
3064                cluster: (
3065                    listen: "10.0.0.2:7000",
3066                    root_pubkeys: ["es256:03a1"],
3067                    seeds: ["https://10.0.0.1:8080"],
3068                    join_token: "env:BOATRAMP_JOIN_TOKEN",
3069                ),
3070            )"#,
3071        );
3072        let cluster = cfg.cluster.unwrap();
3073        assert_eq!(
3074            cluster.listen,
3075            "10.0.0.2:7000".parse::<std::net::SocketAddr>().unwrap()
3076        );
3077        assert_eq!(cluster.root_pubkeys, vec!["es256:03a1".to_string()]);
3078        assert_eq!(cluster.seeds, vec!["https://10.0.0.1:8080".to_string()]);
3079        assert_eq!(
3080            cluster.join_token.as_deref(),
3081            Some("env:BOATRAMP_JOIN_TOKEN")
3082        );
3083        // store_dir defaults to None (→ <data-dir>/raft at serve time).
3084        assert!(cluster.store_dir.is_none());
3085    }
3086
3087    #[test]
3088    fn cluster_section_founds_with_just_a_listen_addr() {
3089        // A founder needs no seeds/token — just where to bind the mesh.
3090        let cfg = server(r#"( cluster: ( listen: "0.0.0.0:7000" ) )"#);
3091        let cluster = cfg.cluster.unwrap();
3092        assert!(cluster.seeds.is_empty());
3093        assert!(cluster.root_pubkeys.is_empty());
3094        assert!(cluster.join_token.is_none());
3095    }
3096
3097    #[test]
3098    fn sql_binding_single_node_defaults() {
3099        // A bare section (or none) means single-node: no url, default dir.
3100        let cfg = server(r#"( handlers: ( bindings: ( sql: () ) ) )"#);
3101        let sql = cfg.handlers.unwrap().bindings.sql.unwrap();
3102        assert!(sql.url.is_none());
3103        assert!(sql.dir.is_none());
3104    }
3105
3106    #[test]
3107    fn sql_binding_single_node_custom_dir() {
3108        let cfg =
3109            server(r#"( handlers: ( bindings: ( sql: ( dir: "/var/lib/boatramp/sql" ) ) ) )"#);
3110        let sql = cfg.handlers.unwrap().bindings.sql.unwrap();
3111        assert_eq!(sql.dir.as_deref(), Some(Path::new("/var/lib/boatramp/sql")));
3112        assert!(sql.url.is_none());
3113    }
3114
3115    #[test]
3116    fn sql_binding_cluster() {
3117        let cfg = server(
3118            r#"(
3119                handlers: ( bindings: ( sql: (
3120                    url: "http://sqld:8080",
3121                    admin_url: "http://sqld:9090",
3122                    token_env: "BOATRAMP_SQL_TOKEN",
3123                ) ) ),
3124            )"#,
3125        );
3126        let sql = cfg.handlers.unwrap().bindings.sql.unwrap();
3127        assert_eq!(sql.url.as_deref(), Some("http://sqld:8080"));
3128        assert_eq!(sql.admin_url.as_deref(), Some("http://sqld:9090"));
3129        assert_eq!(sql.token_env.as_deref(), Some("BOATRAMP_SQL_TOKEN"));
3130        assert_eq!(sql.admin_token_env, None);
3131    }
3132
3133    #[test]
3134    fn sql_binding_preview_policy() {
3135        let cfg = server(
3136            r#"(
3137                handlers: ( bindings: ( sql: (
3138                    preview_mode: "branch",
3139                    preview_init: "/etc/boatramp/seed.sql",
3140                ) ) ),
3141            )"#,
3142        );
3143        let sql = cfg.handlers.unwrap().bindings.sql.unwrap();
3144        assert_eq!(sql.preview_mode.as_deref(), Some("branch"));
3145        assert_eq!(
3146            sql.preview_init.as_deref(),
3147            Some(Path::new("/etc/boatramp/seed.sql"))
3148        );
3149    }
3150
3151    #[test]
3152    fn sql_binding_external_databases() {
3153        let cfg = server(
3154            r#"(
3155                handlers: ( bindings: ( sql: (
3156                    databases: {
3157                        "analytics": (
3158                            kind: "postgres",
3159                            url_env: "ANALYTICS_PG_URL",
3160                            pool_max: 16,
3161                            read_only: true,
3162                        ),
3163                        "events": (
3164                            kind: "mysql",
3165                            url_env: "EVENTS_MYSQL_URL",
3166                            read_url_env: "EVENTS_MYSQL_REPLICA_URL",
3167                            allow_preview: true,
3168                        ),
3169                    },
3170                ) ) ),
3171            )"#,
3172        );
3173        let sql = cfg.handlers.unwrap().bindings.sql.unwrap();
3174        assert_eq!(sql.databases.len(), 2);
3175
3176        let analytics = &sql.databases["analytics"];
3177        assert_eq!(analytics.kind, "postgres");
3178        assert_eq!(analytics.url_env, "ANALYTICS_PG_URL");
3179        assert_eq!(analytics.pool_max, Some(16));
3180        assert!(analytics.read_only);
3181        assert!(!analytics.allow_preview);
3182        assert!(analytics.read_url_env.is_none());
3183
3184        let events = &sql.databases["events"];
3185        assert_eq!(events.kind, "mysql");
3186        assert_eq!(
3187            events.read_url_env.as_deref(),
3188            Some("EVENTS_MYSQL_REPLICA_URL")
3189        );
3190        assert!(events.allow_preview);
3191        assert!(!events.read_only);
3192    }
3193
3194    #[test]
3195    fn sql_binding_compute_backed_database() {
3196        let cfg = server(
3197            r#"(
3198                handlers: ( bindings: ( sql: (
3199                    databases: {
3200                        "analytics": (
3201                            kind: "postgres",
3202                            compute: "pg",
3203                            database: "analytics",
3204                            user: "app",
3205                            password_env: "PG_APP_PW",
3206                        ),
3207                    },
3208                ) ) ),
3209            )"#,
3210        );
3211        let db = &cfg.handlers.unwrap().bindings.sql.unwrap().databases["analytics"];
3212        assert_eq!(db.kind, "postgres");
3213        assert_eq!(db.compute.as_deref(), Some("pg"));
3214        assert_eq!(db.database.as_deref(), Some("analytics"));
3215        assert_eq!(db.user.as_deref(), Some("app"));
3216        assert_eq!(db.password_env.as_deref(), Some("PG_APP_PW"));
3217        assert!(db.url_env.is_empty(), "compute-backed has no url_env");
3218        assert!(db.validate("analytics").is_ok());
3219    }
3220
3221    #[test]
3222    fn sql_binding_source_is_exactly_one_of_url_or_compute() {
3223        // Neither source → error.
3224        assert!(ExternalDatabaseConfig::default().validate("db").is_err());
3225        // Both sources → error.
3226        let both = ExternalDatabaseConfig {
3227            kind: "postgres".into(),
3228            url_env: "PG_URL".into(),
3229            compute: Some("pg".into()),
3230            ..Default::default()
3231        };
3232        assert!(both.validate("db").is_err());
3233        // `url_env` only → ok.
3234        let url = ExternalDatabaseConfig {
3235            kind: "postgres".into(),
3236            url_env: "PG_URL".into(),
3237            ..Default::default()
3238        };
3239        assert!(url.validate("db").is_ok());
3240        // `compute` without the connection details boatramp can't infer → error.
3241        let bare = ExternalDatabaseConfig {
3242            kind: "postgres".into(),
3243            compute: Some("pg".into()),
3244            ..Default::default()
3245        };
3246        assert!(bare.validate("db").is_err());
3247        // `compute` with database/user + a bring-your-own `password_env` → ok, and
3248        // is *not* a managed credential.
3249        let byo = ExternalDatabaseConfig {
3250            kind: "postgres".into(),
3251            compute: Some("pg".into()),
3252            database: Some("analytics".into()),
3253            user: Some("app".into()),
3254            password_env: Some("PG_APP_PW".into()),
3255            ..Default::default()
3256        };
3257        assert!(byo.validate("db").is_ok());
3258        assert!(!byo.is_managed_credential());
3259        // `compute` with database/user but NO `password_env` → ok, and boatramp
3260        // manages the credential (Phase 2).
3261        let managed = ExternalDatabaseConfig {
3262            kind: "postgres".into(),
3263            compute: Some("pg".into()),
3264            database: Some("analytics".into()),
3265            user: Some("app".into()),
3266            ..Default::default()
3267        };
3268        assert!(managed.validate("db").is_ok());
3269        assert!(managed.is_managed_credential());
3270    }
3271
3272    #[test]
3273    fn libsql_source_is_exactly_one_of_path_or_url() {
3274        // A single-node `libsql` file (path only) → ok.
3275        let file = ExternalDatabaseConfig {
3276            kind: "libsql".into(),
3277            path: Some("/data/app.db".into()),
3278            ..Default::default()
3279        };
3280        assert!(file.validate("app").is_ok());
3281        // `sqlite` alias works the same.
3282        let sqlite = ExternalDatabaseConfig {
3283            kind: "sqlite".into(),
3284            path: Some("/data/app.db".into()),
3285            ..Default::default()
3286        };
3287        assert!(sqlite.validate("app").is_ok());
3288        // A remote-sqld `libsql` (url_env only) → ok.
3289        let remote = ExternalDatabaseConfig {
3290            kind: "libsql".into(),
3291            url_env: "LIBSQL_URL".into(),
3292            ..Default::default()
3293        };
3294        assert!(remote.validate("app").is_ok());
3295        // Neither `path` nor `url_env` → error.
3296        let neither = ExternalDatabaseConfig {
3297            kind: "libsql".into(),
3298            ..Default::default()
3299        };
3300        assert!(neither.validate("app").is_err());
3301        // Both `path` and `url_env` → error (exactly one).
3302        let both = ExternalDatabaseConfig {
3303            kind: "libsql".into(),
3304            path: Some("/data/app.db".into()),
3305            url_env: "LIBSQL_URL".into(),
3306            ..Default::default()
3307        };
3308        assert!(both.validate("app").is_err());
3309        // `compute` on a `libsql` binding → error (boatramp doesn't run a libsql server workload).
3310        let compute = ExternalDatabaseConfig {
3311            kind: "libsql".into(),
3312            compute: Some("x".into()),
3313            path: Some("/data/app.db".into()),
3314            ..Default::default()
3315        };
3316        assert!(compute.validate("app").is_err());
3317        // `path` on a NON-libsql (postgres) binding → error (only libsql has an on-disk file).
3318        let pg_path = ExternalDatabaseConfig {
3319            kind: "postgres".into(),
3320            url_env: "PG_URL".into(),
3321            path: Some("/data/app.db".into()),
3322            ..Default::default()
3323        };
3324        assert!(pg_path.validate("db").is_err());
3325    }
3326
3327    /// Path to a file at the repo root (two levels up from this crate).
3328    fn repo_root_file(name: &str) -> PathBuf {
3329        Path::new(env!("CARGO_MANIFEST_DIR"))
3330            .join("../..")
3331            .join(name)
3332    }
3333
3334    #[test]
3335    fn shipped_project_example_parses() {
3336        // The example we ship must always parse + compile-check, so it can't drift
3337        // from the schema.
3338        let text = std::fs::read_to_string(repo_root_file("examples/site/project.cfg.example"))
3339            .expect("example project config is present");
3340        let cfg = ProjectConfig::parse(&text).expect("example project config parses");
3341        assert_eq!(cfg.publish.server.as_deref(), Some("http://127.0.0.1:8080"));
3342        assert_eq!(cfg.build.as_ref().unwrap().command, "npm run build");
3343        assert_eq!(
3344            cfg.routing.error_documents.get(&404).map(String::as_str),
3345            Some("/404.html")
3346        );
3347    }
3348
3349    #[test]
3350    fn shipped_server_example_parses() {
3351        let text = std::fs::read_to_string(repo_root_file("boatramp.cfg.example"))
3352            .expect("example server config is present");
3353        let cfg = ServerConfig::parse(&text).expect("example server config parses");
3354        let serve = cfg.serve.expect("example sets a serve section");
3355        assert_eq!(
3356            serve.addr,
3357            Some("0.0.0.0:8080".parse::<std::net::SocketAddr>().unwrap())
3358        );
3359    }
3360
3361    #[test]
3362    fn secrets_section_parses_local_and_vault() {
3363        let local = server(r#"( secrets: ( envelope: "local", kek_file: "/k/kek" ) )"#)
3364            .secrets
3365            .expect("secrets section");
3366        assert_eq!(local.envelope, "local");
3367        assert_eq!(
3368            local.kek_file.as_deref(),
3369            Some(std::path::Path::new("/k/kek"))
3370        );
3371
3372        let vault = server(
3373            r#"( secrets: ( envelope: "vault", vault: ( addr: "https://vault:8200", key: "certs" ) ) )"#,
3374        )
3375        .secrets
3376        .expect("secrets section");
3377        let v = vault.vault.expect("vault subsection");
3378        assert_eq!(v.addr, "https://vault:8200");
3379        assert_eq!(v.key, "certs");
3380        // The token env defaults to VAULT_TOKEN and is never in the file.
3381        assert_eq!(v.token_env, "VAULT_TOKEN");
3382    }
3383
3384    #[test]
3385    fn serve_section_partial_parses() {
3386        // A partial `serve` section parses — unset fields take their defaults.
3387        let cfg = server(r#"( serve: ( addr: "0.0.0.0:8080", protect_previews: true ) )"#);
3388        let serve = cfg.serve.unwrap();
3389        assert_eq!(
3390            serve.addr,
3391            Some("0.0.0.0:8080".parse::<std::net::SocketAddr>().unwrap())
3392        );
3393        assert!(serve.protect_previews);
3394        assert!(!serve.cluster_rate_limit);
3395        assert!(serve.data_dir.is_none());
3396    }
3397
3398    #[test]
3399    fn serve_console_config_parses() {
3400        // Absent ⇒ no console.
3401        let cfg = server(r#"( serve: ( addr: "0.0.0.0:8080" ) )"#);
3402        assert!(cfg.serve.unwrap().console.is_none());
3403        // Explicit console block with host + path.
3404        let cfg = server(
3405            r#"( serve: ( console: (
3406                enabled: true,
3407                host: "console.example.com",
3408                path: "/_console",
3409            ) ) )"#,
3410        );
3411        let console = cfg.serve.unwrap().console.unwrap();
3412        assert!(console.enabled);
3413        assert_eq!(console.host.as_deref(), Some("console.example.com"));
3414        assert_eq!(console.path.as_deref(), Some("/_console"));
3415        // Bare `enabled` ⇒ host/path take their (server-side) defaults.
3416        let cfg = server(r#"( serve: ( console: ( enabled: true ) ) )"#);
3417        let console = cfg.serve.unwrap().console.unwrap();
3418        assert!(console.enabled);
3419        assert!(console.host.is_none() && console.path.is_none());
3420    }
3421
3422    #[test]
3423    fn serve_s3_credential_config_parses() {
3424        // #505: absent ⇒ no sealed source (the ambient AWS env chain).
3425        let cfg = server(r#"( serve: ( addr: "0.0.0.0:8080" ) )"#);
3426        assert!(cfg.serve.unwrap().s3_credential.is_none());
3427        // An explicit `[serve.s3_credential]`: a plain `access_key_id` + a `boatramp:` sealed
3428        // `secret_access_key` ref (the config text carries only the REFERENCE, never the secret).
3429        let cfg = server(
3430            r#"( serve: ( s3_credential: (
3431                access_key_id: "tid_public_akid",
3432                secret_access_key: "boatramp:tigris-secret",
3433            ) ) )"#,
3434        );
3435        let cred = cfg.serve.unwrap().s3_credential.unwrap();
3436        assert_eq!(cred.access_key_id, "tid_public_akid");
3437        assert_eq!(cred.secret_access_key, "boatramp:tigris-secret");
3438        // An unknown field is rejected (`deny_unknown_fields`) — a fat-fingered key fails fast.
3439        let err: Result<ServerConfig, _> = ron_options().from_str(
3440            r#"( serve: ( s3_credential: ( access_key_id: "x", secret_access_key: "boatramp:y", bogus: 1 ) ) )"#,
3441        );
3442        assert!(
3443            err.is_err(),
3444            "unknown [serve.s3_credential] field must be rejected"
3445        );
3446    }
3447}