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