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    /// A `[serve.blob_backends.<project>]` key is not a valid project name, or is the reserved
117    /// `default` project (which always resolves the global `[serve]` backend). Refused at config load
118    /// (fail-closed) rather than silently binding a project's blobs to the wrong backend.
119    #[error("per-project blob backend {name:?}: {reason}{cure}")]
120    InvalidBlobBackendProject {
121        /// The offending project key (the `blob_backends` map key).
122        name: String,
123        /// Why it was rejected.
124        reason: &'static str,
125        /// A trailing remediation hint.
126        cure: &'static str,
127    },
128}
129
130/// Project configuration, loaded from `project.cfg` (RON) in the project folder.
131///
132/// Read by the client commands (`sync`, `build`, `bundle`, `validate`).
133/// Everything is optional; a missing file is the default.
134#[derive(Debug, Default, Deserialize)]
135#[serde(default)]
136pub struct ProjectConfig {
137    /// Where and how to publish this project.
138    pub publish: PublishConfig,
139    /// Optional build step run before `sync`.
140    pub build: Option<BuildConfig>,
141    /// Optional embedded-bundler step (`bundler` feature).
142    pub bundle: Option<BundleConfig>,
143    /// Deploy-scoped routing/handlers config. Folded into the deployment
144    /// manifest at `sync` (so it is atomic with the content and rolls back with
145    /// it). The bulk of a project's config — redirects, rewrites, headers,
146    /// handlers, consumers, crons, streams.
147    pub routing: DeployConfig,
148}
149
150impl ProjectConfig {
151    /// Parse a `project.cfg` document as **RON** (the default). Kept for the existing
152    /// callers/tests; [`Self::parse_with_format`] is the format-aware entry point.
153    pub fn parse(text: &str) -> Result<Self, ConfigError> {
154        Self::parse_with_format(text, ConfigFormat::Ron)
155    }
156
157    /// Parse a `project.cfg` document in `fmt` (RON or JSON). The deserializer is
158    /// selected by format (RON ⇒ [`ron_options`], JSON ⇒ `serde_json`) into the SAME
159    /// typed struct; the `routing` section is then compile-checked (route patterns,
160    /// cron schedules, imports) regardless of format so a bad config fails fast.
161    pub fn parse_with_format(text: &str, fmt: ConfigFormat) -> Result<Self, ConfigError> {
162        let config: Self = match fmt {
163            ConfigFormat::Ron => ron_options().from_str(text)?,
164            ConfigFormat::Json => serde_json::from_str(text)?,
165        };
166        config.routing.compile_check()?;
167        Ok(config)
168    }
169
170    /// Load from `path`, decoding as RON or JSON per [`resolve_format`] (`override_`
171    /// wins; else `.json` ⇒ JSON, everything else ⇒ RON). A missing file yields the
172    /// default config (unlike an apply manifest).
173    pub fn load(path: &Path, override_: Option<ConfigFormat>) -> Result<Self, ConfigError> {
174        let fmt = resolve_format(path, override_);
175        match std::fs::read_to_string(path) {
176            Ok(contents) => {
177                Self::parse_with_format(&contents, fmt).map_err(|err| ConfigError::File {
178                    path: path.display().to_string(),
179                    source: Box::new(err),
180                })
181            }
182            Err(err) if err.kind() == std::io::ErrorKind::NotFound => Ok(Self::default()),
183            Err(err) => Err(err.into()),
184        }
185    }
186}
187
188/// Server daemon configuration, loaded from `boatramp.cfg` (RON). Read by
189/// `boatramp serve`; flags/env override the `serve` values.
190#[derive(Debug, Default, Deserialize)]
191#[serde(default)]
192pub struct ServerConfig {
193    /// Server defaults for `serve` (flag/env override these).
194    pub serve: Option<ServeConfig>,
195    /// Server-side handler runtime config (which backend serves each binding),
196    /// consumed only with the `handlers` feature.
197    pub handlers: Option<HandlersConfig>,
198    /// Self-hosted cluster mode (consumed only with the `cluster` feature).
199    pub cluster: Option<ClusterConfig>,
200    /// Opt-in **compute** backends. Present ⇒ this node
201    /// runs compute workloads via the backends it can offer; absent ⇒ no compute
202    /// (the reconcile loop stays a no-op).
203    pub compute: Option<ComputeConfig>,
204    /// Operator security posture (the hardening knobs): a profile
205    /// preset + overrides, resolved at startup. Absent ⇒ the strict
206    /// `multi-tenant` default. Operator-only — never part of site config.
207    pub security: Option<boatramp_core::security::SecurityConfig>,
208    /// Secrets-at-rest envelope. Absent ⇒ private
209    /// keys stored cleartext in the (replicated) control plane.
210    pub secrets: Option<SecretsConfig>,
211}
212
213/// `secrets` section — envelope encryption for private keys at rest.
214#[cfg_attr(not(feature = "cluster"), allow(dead_code))]
215#[derive(Debug, Clone, Default, Deserialize)]
216#[serde(default, deny_unknown_fields)]
217pub struct SecretsConfig {
218    /// Backend: `"local"` (machine-local AES-256-GCM KEK) or `"vault"` (Vault
219    /// Transit). Empty/other ⇒ no wrapping. In a cluster a local KEK must be the
220    /// **same file on every node** (wrapped certs replicate); Vault avoids that.
221    pub envelope: String,
222    /// Local-KEK key file (`envelope = "local"`). Default
223    /// `<data-dir>/secrets/kek`. Auto-generated `0600` if absent.
224    pub kek_file: Option<PathBuf>,
225    /// Vault Transit config (`envelope = "vault"`).
226    pub vault: Option<VaultSecretsConfig>,
227}
228
229/// Vault Transit settings for `envelope = "vault"`. The token is read from the
230/// environment (`token_env`), never stored in the config file.
231#[cfg_attr(not(all(feature = "cluster", feature = "acme-dns")), allow(dead_code))]
232#[derive(Debug, Clone, Deserialize)]
233#[serde(deny_unknown_fields)]
234pub struct VaultSecretsConfig {
235    /// Vault address, e.g. `https://vault:8200`.
236    pub addr: String,
237    /// Transit key name to wrap under.
238    pub key: String,
239    /// Environment variable holding the Vault token (default `VAULT_TOKEN`).
240    #[serde(default = "default_vault_token_env")]
241    pub token_env: String,
242}
243
244fn default_vault_token_env() -> String {
245    "VAULT_TOKEN".to_string()
246}
247
248impl Default for VaultSecretsConfig {
249    fn default() -> Self {
250        Self {
251            addr: String::new(),
252            key: String::new(),
253            token_env: default_vault_token_env(),
254        }
255    }
256}
257
258/// The RESERVED compute-workload name prefix (#501 Stage B LOW-2). boatramp DERIVES the
259/// per-project managed-database server workloads with this prefix
260/// (`boatramp_storage::tenant_provision::DERIVED_MANAGED_DB_PREFIX`), so an operator must
261/// NOT name a static `[handlers].bindings.sql.databases.*.compute` workload with it — a
262/// collision could shadow / alias a derived managed server. Screened fail-closed at
263/// config load ([`ServerConfig::validate_sql_db_names`]). Kept as a literal here (not the
264/// `boatramp-storage` const) so the screen holds on a build without the sql engine
265/// features; the two must stay in sync (a single source of truth would couple config
266/// loading to the optional storage dep).
267const RESERVED_MANAGED_DB_COMPUTE_PREFIX: &str = "bramp-db-";
268
269impl ServerConfig {
270    /// Parse a `boatramp.cfg` document as **RON** (the default). Kept for the existing
271    /// callers/tests; [`Self::parse_with_format`] is the format-aware entry point.
272    pub fn parse(text: &str) -> Result<Self, ConfigError> {
273        Self::parse_with_format(text, ConfigFormat::Ron)
274    }
275
276    /// Parse a `boatramp.cfg` document in `fmt` (RON or JSON). The deserializer is
277    /// selected by format (RON ⇒ [`ron_options`], JSON ⇒ `serde_json`) into the SAME
278    /// typed struct. Db-binding names declared in the file are validated here (the same
279    /// fail-closed check `load` re-runs after the env merge) **regardless of format**, so
280    /// a file-only config path — e.g. `boatramp cloudflare` rendering, or the
281    /// operator-resources loader — is guarded even without going through `load`.
282    pub fn parse_with_format(text: &str, fmt: ConfigFormat) -> Result<Self, ConfigError> {
283        let config: Self = match fmt {
284            ConfigFormat::Ron => ron_options().from_str(text)?,
285            ConfigFormat::Json => serde_json::from_str(text)?,
286        };
287        config.validate_sql_db_names()?;
288        config.validate_blob_backend_projects()?;
289        Ok(config)
290    }
291
292    /// Load from `path`, decoding as RON or JSON per [`resolve_format`] (`override_`
293    /// wins; else `.json` ⇒ JSON, everything else ⇒ RON), then layer `BOATRAMP_*`
294    /// environment overrides on top. A missing file yields the default config, so
295    /// `serve` can be configured entirely from the environment (12-factor deployments
296    /// where dropping a `boatramp.cfg` is awkward — fly.io / Cloudflare / containers).
297    ///
298    /// The env-override merge runs AFTER the parse for either format — JSON is only an
299    /// alternative decoder into the same typed struct; it does not change the
300    /// file < env precedence.
301    pub fn load(path: &Path, override_: Option<ConfigFormat>) -> Result<Self, ConfigError> {
302        let fmt = resolve_format(path, override_);
303        let mut config = match std::fs::read_to_string(path) {
304            Ok(contents) => {
305                Self::parse_with_format(&contents, fmt).map_err(|err| ConfigError::File {
306                    path: path.display().to_string(),
307                    source: Box::new(err),
308                })?
309            }
310            Err(err) if err.kind() == std::io::ErrorKind::NotFound => Self::default(),
311            Err(err) => return Err(err.into()),
312        };
313        config.apply_env_overrides(&EnvSource::Process)?;
314        Ok(config)
315    }
316
317    /// Layer `BOATRAMP_*` environment overrides onto the loaded config for the
318    /// `compute`, `security`, and handler-`sql` sections — the operational knobs
319    /// that were previously reachable only through the `boatramp.cfg` file.
320    ///
321    /// **Precedence: env overrides file.** This matches the existing `serve`
322    /// section (its `#[arg(long, env = …)]` flags already let an env var win over
323    /// the file value), keeping the resolution rule uniform. A set variable
324    /// updates the field even when the file also set it; an unset variable leaves
325    /// the file (or built-in default) untouched. When a section is absent from the
326    /// file but any of its variables are set, the section is materialised from its
327    /// defaults first — so no config file is required to configure it.
328    ///
329    /// `source` supplies the variables (the process environment in production; an
330    /// explicit map in tests), so this stays a pure function of its inputs.
331    fn apply_env_overrides(&mut self, source: &EnvSource) -> Result<(), ConfigError> {
332        // --- compute ---------------------------------------------------------
333        // Materialise `[compute]` only if at least one of its variables is set, so
334        // an unset environment leaves an absent section absent (⇒ no compute).
335        if source.any(COMPUTE_ENV_VARS) {
336            let compute = self.compute.get_or_insert_with(ComputeConfig::default);
337            if let Some(v) = source.get("BOATRAMP_COMPUTE_BRIDGE") {
338                compute.bridge = v;
339            }
340            if let Some(v) = source.get("BOATRAMP_COMPUTE_SUBNET") {
341                compute.subnet = v;
342            }
343            if let Some(v) = source.parse("BOATRAMP_COMPUTE_VCPUS")? {
344                compute.vcpus = v;
345            }
346            if let Some(v) = source.parse("BOATRAMP_COMPUTE_MEM_MIB")? {
347                compute.mem_mib = v;
348            }
349            if let Some(v) = source.get("BOATRAMP_COMPUTE_REGION") {
350                compute.region = Some(v);
351            }
352            if let Some(v) = source.get("BOATRAMP_COMPUTE_SQL_SHIM_URL") {
353                compute.sql_shim_url = Some(v);
354            }
355            // The two shared-kernel enums have no `FromStr`, only a serde
356            // `rename_all = "lowercase"`; map their variants by that same spelling.
357            if let Some(v) = source.parse_enum(
358                "BOATRAMP_COMPUTE_MANAGED_DB_PRIVILEGE",
359                &[
360                    ("rootless", ManagedDbPrivilege::Rootless),
361                    ("caps", ManagedDbPrivilege::Caps),
362                ],
363            )? {
364                compute.managed_db_privilege = v;
365            }
366            if let Some(v) = source.parse_enum(
367                "BOATRAMP_COMPUTE_DOCKER_ENDPOINT",
368                &[
369                    ("published", boatramp_docker::DockerEndpoint::Published),
370                    ("bridge", boatramp_docker::DockerEndpoint::Bridge),
371                ],
372            )? {
373                compute.docker_endpoint = v;
374            }
375            if let Some(v) = source.parse_enum(
376                "BOATRAMP_COMPUTE_DOCKER_VOLUME_MODE",
377                &[
378                    ("named", boatramp_docker::DockerVolumeMode::Named),
379                    ("bind", boatramp_docker::DockerVolumeMode::Bind),
380                ],
381            )? {
382                compute.docker_volume_mode = v;
383            }
384            // Kernel trust anchors — comma-separated lists. These are
385            // security-critical: they are the trust anchor for the posture-scaled
386            // kernel bar, so a value here decides which kernels a `multi-tenant`
387            // node will boot. In a 12-factor deployment the environment IS the
388            // operator's trusted config source (a fly.toml `[env]` is committed the
389            // same as a file), so they are exposed here — but an operator should
390            // know the environment is *more* visible than a file (it leaks through
391            // `/proc/<pid>/environ` and is inherited by every subprocess), so a
392            // file remains the better home for them when one is available.
393            if let Some(v) = source.parse_list("BOATRAMP_COMPUTE_KERNEL_SIGNING_PUBKEYS") {
394                compute.kernel_signing_pubkeys = v;
395            }
396            if let Some(v) = source.parse_list("BOATRAMP_COMPUTE_KERNEL_ALLOWED_HASHES") {
397                compute.kernel_allowed_hashes = v;
398            }
399            // Internal DNS (per-project service discovery on the bridge gateway).
400            if let Some(v) = source.parse_bool("BOATRAMP_COMPUTE_INTERNAL_DNS")? {
401                compute.internal_dns = v;
402            }
403            if let Some(v) = source.get("BOATRAMP_COMPUTE_DNS_UPSTREAM") {
404                compute.dns_upstream = v;
405            }
406            if let Some(v) = source.get("BOATRAMP_COMPUTE_DNS_DOMAIN") {
407                compute.dns_domain = v;
408            }
409        }
410
411        // --- security --------------------------------------------------------
412        // Always materialise `[security]` when any knob is set: an absent section
413        // resolves to the strict `multi-tenant` default, and an env override then
414        // layers over that exactly as a file `overrides` block would.
415        if source.any(SECURITY_ENV_VARS) {
416            let security = self
417                .security
418                .get_or_insert_with(boatramp_core::security::SecurityConfig::default);
419            if let Some(v) = source.get("BOATRAMP_SECURITY_PROFILE") {
420                security.profile = Some(v);
421            }
422            let o = &mut security.overrides;
423            if let Some(v) =
424                source.parse_bool("BOATRAMP_SECURITY_ALLOW_UNAUTHENTICATED_PUBLIC_BIND")?
425            {
426                o.allow_unauthenticated_public_bind = Some(v);
427            }
428            if let Some(v) = source.parse("BOATRAMP_SECURITY_MAX_UPLOAD_BYTES")? {
429                o.max_upload_bytes = Some(v);
430            }
431            if let Some(v) = source.parse_bool("BOATRAMP_SECURITY_ALLOW_SITE_UNIX_UPSTREAMS")? {
432                o.allow_site_unix_upstreams = Some(v);
433            }
434            if let Some(v) = source.parse_bool("BOATRAMP_SECURITY_ALLOW_SITE_PRIVATE_UPSTREAMS")? {
435                o.allow_site_private_upstreams = Some(v);
436            }
437            if let Some(v) = source.parse_bool("BOATRAMP_SECURITY_ALLOW_GUEST_PRIVATE_EGRESS")? {
438                o.allow_guest_private_egress = Some(v);
439            }
440            if let Some(v) = source.parse_bool("BOATRAMP_SECURITY_ALLOW_GUEST_SELF_EGRESS")? {
441                o.allow_guest_self_egress = Some(v);
442            }
443            if let Some(v) = source.parse_bool("BOATRAMP_SECURITY_ALLOW_GUEST_EGRESS_EXTRA_CA")? {
444                o.allow_guest_egress_extra_ca = Some(v);
445            }
446            if let Some(v) = source.parse_bool("BOATRAMP_SECURITY_ALLOW_GUEST_TCP_EGRESS")? {
447                o.allow_guest_tcp_egress = Some(v);
448            }
449            if let Some(v) = source.parse("BOATRAMP_SECURITY_MAX_HANDLER_BLOB_BYTES")? {
450                o.max_handler_blob_bytes = Some(v);
451            }
452            if let Some(v) = source.parse("BOATRAMP_SECURITY_MAX_COMPONENT_BYTES")? {
453                o.max_component_bytes = Some(v);
454            }
455            if let Some(v) = source.parse_bool("BOATRAMP_SECURITY_OIDC_REQUIRE_AUDIENCE")? {
456                o.oidc_require_audience = Some(v);
457            }
458            if let Some(v) = source.parse_bool("BOATRAMP_SECURITY_DOMAIN_VERIFY_ALLOW_PRIVATE")? {
459                o.domain_verify_allow_private = Some(v);
460            }
461            if let Some(v) = source.parse_bool("BOATRAMP_SECURITY_DOMAIN_VERIFY_SELF_SERVE")? {
462                o.domain_verify_self_serve = Some(v);
463            }
464            if let Some(v) = source.parse_bool("BOATRAMP_SECURITY_ALLOW_SHARED_KERNEL_COMPUTE")? {
465                o.allow_shared_kernel_compute = Some(v);
466            }
467            if let Some(v) = source.parse_bool("BOATRAMP_SECURITY_ALLOW_COMPUTE_EXEC")? {
468                o.allow_compute_exec = Some(v);
469            }
470            if let Some(v) = source.parse_bool("BOATRAMP_SECURITY_RATELIMIT_FAIL_OPEN")? {
471                o.ratelimit_fail_open = Some(v);
472            }
473            if let Some(v) = source.parse_bool("BOATRAMP_SECURITY_ALLOW_IMPLICIT_ROUTING")? {
474                o.allow_implicit_routing = Some(v);
475            }
476            if let Some(v) = source.parse_bool("BOATRAMP_SECURITY_REQUIRE_POP")? {
477                o.require_pop = Some(v);
478            }
479            if let Some(v) = source.parse_bool("BOATRAMP_SECURITY_REQUIRE_DOMAIN_VERIFICATION")? {
480                o.require_domain_verification = Some(v);
481            }
482            if let Some(v) = source.parse_bool("BOATRAMP_SECURITY_ALLOW_ENV_SECRET_REFS")? {
483                o.allow_env_secret_refs = Some(v);
484            }
485            // The multi-tenant sub-knobs (Gap 4b): previously file-only, now env-settable so a
486            // 12-factor deployment can tune tenancy isolation + guest capability minting without a
487            // `boatramp.cfg`. Fleet-scoped (a per-project override still lives in the config file).
488            if let Some(v) = source.parse_bool("BOATRAMP_SECURITY_REQUIRE_TENANCY_DECLARATION")? {
489                o.require_tenancy_declaration = Some(v);
490            }
491            if let Some(v) = source.parse_bool("BOATRAMP_SECURITY_ALLOW_CROSS_TENANT_DB")? {
492                o.allow_cross_tenant_db = Some(v);
493            }
494            if let Some(v) = source.parse_bool("BOATRAMP_SECURITY_ALLOW_GUEST_MINT_CAPABILITY")? {
495                o.allow_guest_mint_capability = Some(v);
496            }
497            if let Some(v) = source.parse("BOATRAMP_SECURITY_MAX_GUEST_CAPABILITY_TTL_SECS")? {
498                o.max_guest_capability_ttl_secs = Some(v);
499            }
500            // Remaining guest-feature knobs — env parity for a 12-factor fleet that runs env-only
501            // (no `boatramp.cfg`). Each preset defaults these OFF under `multi-tenant`, so an
502            // env-only multi-tenant deployment had no lever to opt a guest feature back on. The
503            // override field + `apply()` + `explain()` already exist for every one; only the env
504            // mapping was missing (`allow_guest_email` regressed prod SMTP on the P48 cutover).
505            if let Some(v) = source.parse_bool("BOATRAMP_SECURITY_ALLOW_GUEST_EMAIL")? {
506                o.allow_guest_email = Some(v);
507            }
508            if let Some(v) = source.parse_bool("BOATRAMP_SECURITY_ALLOW_GUEST_ADMIN_DOMAINS")? {
509                o.allow_guest_admin_domains = Some(v);
510            }
511            if let Some(v) = source.parse_bool("BOATRAMP_SECURITY_ALLOW_GUEST_ADMIN_EMAIL")? {
512                o.allow_guest_admin_email = Some(v);
513            }
514            if let Some(v) = source.parse_bool("BOATRAMP_SECURITY_ALLOW_GUEST_ADMIN_SITE")? {
515                o.allow_guest_admin_site = Some(v);
516            }
517            if let Some(v) = source.parse_bool("BOATRAMP_SECURITY_ALLOW_GUEST_ADMIN_SECRETS")? {
518                o.allow_guest_admin_secrets = Some(v);
519            }
520        }
521
522        // --- handler sql (`handlers.bindings.sql`) ---------------------------
523        // Materialise the nested `handlers.bindings.sql` chain only when a `sql`
524        // variable is set, so an unset environment doesn't conjure an empty
525        // handlers section. The variables mirror the config path
526        // (`BOATRAMP_HANDLERS_SQL_*`) and cover the cluster-vs-single-node knobs;
527        // secrets stay indirected via `*_TOKEN_ENV` names, never the token itself.
528        if source.any(SQL_ENV_VARS) {
529            let handlers = self.handlers.get_or_insert_with(HandlersConfig::default);
530            let sql = handlers
531                .bindings
532                .sql
533                .get_or_insert_with(SqlBindingConfig::default);
534            if let Some(v) = source.get("BOATRAMP_HANDLERS_SQL_DIR") {
535                sql.dir = Some(PathBuf::from(v));
536            }
537            if let Some(v) = source.get("BOATRAMP_HANDLERS_SQL_URL") {
538                sql.url = Some(v);
539            }
540            if let Some(v) = source.get("BOATRAMP_HANDLERS_SQL_ADMIN_URL") {
541                sql.admin_url = Some(v);
542            }
543            if let Some(v) = source.get("BOATRAMP_HANDLERS_SQL_REPLICA_URL") {
544                sql.replica_url = Some(v);
545            }
546            if let Some(v) = source.get("BOATRAMP_HANDLERS_SQL_TOKEN_ENV") {
547                sql.token_env = Some(v);
548            }
549            if let Some(v) = source.get("BOATRAMP_HANDLERS_SQL_ADMIN_TOKEN_ENV") {
550                sql.admin_token_env = Some(v);
551            }
552            if let Some(v) = source.get("BOATRAMP_HANDLERS_SQL_PREVIEW_MODE") {
553                sql.preview_mode = Some(v);
554            }
555            if let Some(v) = source.get("BOATRAMP_HANDLERS_SQL_PREVIEW_INIT") {
556                sql.preview_init = Some(PathBuf::from(v));
557            }
558            if let Some(v) = source.parse("BOATRAMP_HANDLERS_SQL_DEPROVISION_GRACE_SECS")? {
559                sql.deprovision_grace_secs = Some(v);
560            }
561            // The owner-gated migration trusted-extension allowlist — a comma-separated list
562            // (e.g. `pg_trgm,pgcrypto`). Env-over-file, like the scalars above; unset ⇒ keep the
563            // file value (which stays `None`/empty = the safe deny-all default). This is only an
564            // input path to the field; the migrator's `Extension`-step gate / fail-closed refusal /
565            // `sql`-step `CREATE EXTENSION` ban are unchanged.
566            if let Some(v) = source.parse_list("BOATRAMP_HANDLERS_SQL_MIGRATE_TRUSTED_EXTENSIONS") {
567                sql.migrate_trusted_extensions = Some(v);
568            }
569            if let Some(v) = source.parse("BOATRAMP_HANDLERS_SQL_MAX_DECLARED_DATABASES")? {
570                sql.max_declared_databases = Some(v);
571            }
572            if let Some(v) = source.parse("BOATRAMP_HANDLERS_SQL_MAX_DECLARED_VOLUME_MIB")? {
573                sql.max_declared_volume_mib = Some(v);
574            }
575        }
576
577        // --- handler JWKS freshness (`[handlers]` two-tier own/foreign refresh + hard-ttl + prewarm) ---
578        // Env parity for the token-verification JWKS cache knobs, so a file-less (`[env]`-only) fleet
579        // can tune the gateway's auth-freshness posture without a `boatramp.cfg` + roll. Materialises
580        // `[handlers]` only when a JWKS var is set (an unset environment conjures no section).
581        if source.any(JWKS_ENV_VARS) {
582            let handlers = self.handlers.get_or_insert_with(HandlersConfig::default);
583            if let Some(v) = source.parse("BOATRAMP_HANDLERS_JWKS_REFRESH_SECS")? {
584                handlers.jwks_refresh_secs = Some(v);
585            }
586            if let Some(v) = source.parse("BOATRAMP_HANDLERS_JWKS_HARD_TTL_SECS")? {
587                handlers.jwks_hard_ttl_secs = Some(v);
588            }
589            if let Some(v) = source.parse("BOATRAMP_HANDLERS_JWKS_FOREIGN_REFRESH_SECS")? {
590                handlers.jwks_foreign_refresh_secs = Some(v);
591            }
592            if let Some(v) = source.parse("BOATRAMP_HANDLERS_JWKS_FOREIGN_HARD_TTL_SECS")? {
593                handlers.jwks_foreign_hard_ttl_secs = Some(v);
594            }
595            if let Some(v) = source.parse_bool("BOATRAMP_HANDLERS_JWKS_PREWARM")? {
596                handlers.jwks_prewarm = Some(v);
597            }
598        }
599
600        // --- handler concurrency lanes (`[handlers]` serve/sync/async caps) ------
601        // Env parity for the per-component serve-admission gate and the two lane ceilings, so a
602        // file-less (`[env]`-only) fleet can tune them without a `boatramp.cfg` + roll (these were
603        // previously the last `[handlers]` scalars with no env lever, which pinned a knob like
604        // `serve_concurrency` into the config file). Materialises `[handlers]` only when one is set.
605        // Each is an `Option<usize>` set as-is; `serve_concurrency = 0` is the MEANINGFUL "disable the
606        // gate" value, and a `sync_max_concurrency = 0` is rejected downstream (the global sync lane is
607        // a required safety ceiling) — the env lever changes neither semantic, only the input path.
608        if source.any(HANDLER_CONCURRENCY_ENV_VARS) {
609            let handlers = self.handlers.get_or_insert_with(HandlersConfig::default);
610            if let Some(v) = source.parse("BOATRAMP_HANDLERS_SERVE_CONCURRENCY")? {
611                handlers.serve_concurrency = Some(v);
612            }
613            if let Some(v) = source.parse("BOATRAMP_HANDLERS_SYNC_MAX_CONCURRENCY")? {
614                handlers.sync_max_concurrency = Some(v);
615            }
616            if let Some(v) = source.parse("BOATRAMP_HANDLERS_ASYNC_MAX_CONCURRENCY")? {
617                handlers.async_max_concurrency = Some(v);
618            }
619        }
620
621        // --- handler blob-serve hedge (`[handlers]` blob_hedge_*) ----------------
622        // Env parity for the hedged-read tail knobs, so an env-only fleet can turn hedging on (and tune
623        // its delay / concurrent-hedge cap) without a `boatramp.cfg`. Materialises `[handlers]` only when
624        // one is set; `delay_ms` unset/0 keeps hedging off (one GET per read).
625        if source.any(HANDLER_BLOB_HEDGE_ENV_VARS) {
626            let handlers = self.handlers.get_or_insert_with(HandlersConfig::default);
627            if let Some(v) = source.parse("BOATRAMP_HANDLERS_BLOB_HEDGE_DELAY_MS")? {
628                handlers.blob_hedge_delay_ms = Some(v);
629            }
630            if let Some(v) = source.parse("BOATRAMP_HANDLERS_BLOB_HEDGE_MAX_INFLIGHT")? {
631                handlers.blob_hedge_max_inflight = Some(v);
632            }
633        }
634
635        // --- handler sql external databases (`handlers.bindings.sql.databases`) ---
636        // The bring-your-own / managed-compute DB map, keyed by name. There is no
637        // config file to enumerate the members, so the member names are discovered
638        // from the environment: any `BOATRAMP_HANDLERS_SQL_DB_<NAME>_<FIELD>`
639        // variable declares database `<NAME>`. Each env-declared DB is merged into
640        // (overriding, per field, by key) whatever the file already declared under
641        // that name — the same env-over-file precedence as the scalars.
642        //
643        // The default database (the binding a handler opens as `sql.open("")`) is
644        // addressed by the reserved `DEFAULT` token, which can't appear as a literal
645        // in a variable name: `BOATRAMP_HANDLERS_SQL_DB_DEFAULT_KIND` populates the
646        // reserved [`DEFAULT_DB_NAME`](boatramp_core::project::DEFAULT_DB_NAME) key
647        // (`"default"`). As of v0.5.0 this is a real, path-segment-safe name (never the
648        // empty string), so the binding is addressable as `--db default` and every
649        // db-name ingress carries a valid URL path segment. The guest-facing
650        // `sql.open("")` contract is preserved by aliasing `"" ⇄ "default"` at the
651        // backend-resolution boundary — external bindings are a pure label over their
652        // connection params, so the renamed binding points at the SAME physical DB.
653        if source.any_with_prefix(SQL_DB_ENV_PREFIX) {
654            let handlers = self.handlers.get_or_insert_with(HandlersConfig::default);
655            let sql = handlers
656                .bindings
657                .sql
658                .get_or_insert_with(SqlBindingConfig::default);
659            for name in source.sql_database_names() {
660                // `DEFAULT` is the reserved token for the default database; it maps to
661                // the reserved real name `"default"` (v0.5.0; was the empty string).
662                let key = if name == "DEFAULT" {
663                    boatramp_core::project::DEFAULT_DB_NAME.to_string()
664                } else {
665                    name.clone()
666                };
667                let db = sql.databases.entry(key).or_default();
668                let prefix = format!("{SQL_DB_ENV_PREFIX}{name}_");
669                if let Some(v) = source.get(&format!("{prefix}KIND")) {
670                    db.kind = v;
671                }
672                if let Some(v) = source.get(&format!("{prefix}URL_ENV")) {
673                    db.url_env = v;
674                }
675                if let Some(v) = source.get(&format!("{prefix}READ_URL_ENV")) {
676                    db.read_url_env = Some(v);
677                }
678                if let Some(v) = source.get(&format!("{prefix}COMPUTE")) {
679                    db.compute = Some(v);
680                }
681                if let Some(v) = source.get(&format!("{prefix}DATABASE")) {
682                    db.database = Some(v);
683                }
684                if let Some(v) = source.get(&format!("{prefix}USER")) {
685                    db.user = Some(v);
686                }
687                if let Some(v) = source.get(&format!("{prefix}PASSWORD_ENV")) {
688                    db.password_env = Some(v);
689                }
690                if let Some(v) = source.parse(&format!("{prefix}POOL_MAX"))? {
691                    db.pool_max = Some(v);
692                }
693                if let Some(v) = source.parse_bool(&format!("{prefix}READ_ONLY"))? {
694                    db.read_only = v;
695                }
696                if let Some(v) = source.parse_bool(&format!("{prefix}ALLOW_PREVIEW"))? {
697                    db.allow_preview = v;
698                }
699                if let Some(v) = source.parse(&format!("{prefix}CONNECT_TIMEOUT_SECS"))? {
700                    db.connect_timeout_secs = Some(v);
701                }
702                if let Some(v) = source.get(&format!("{prefix}IMAGE")) {
703                    db.image = Some(v);
704                }
705                if let Some(v) = source.parse(&format!("{prefix}VOLUME_SIZE_MIB"))? {
706                    db.volume_size_mib = Some(v);
707                }
708                if let Some(v) = source.parse(&format!("{prefix}STARTUP_GRACE_SECS"))? {
709                    db.startup_grace_secs = Some(v);
710                }
711                if let Some(v) = source.parse_enum(
712                    &format!("{prefix}TENANT"),
713                    &[
714                        ("single", TenantIsolation::Single),
715                        ("shared", TenantIsolation::Shared),
716                    ],
717                )? {
718                    db.tenant = v;
719                }
720                if let Some(v) = source.parse_enum(
721                    &format!("{prefix}TENANT_SCOPE"),
722                    &[
723                        ("project", TenantScope::Project),
724                        ("site", TenantScope::Site),
725                    ],
726                )? {
727                    db.tenant_scope = v;
728                }
729                if let Some(v) = source.parse_bool(&format!("{prefix}RLS_SESSION"))? {
730                    db.rls_session = v;
731                }
732                if let Some(v) = source.get(&format!("{prefix}TENANT_GUC")) {
733                    db.tenant_guc = Some(v);
734                }
735                if let Some(v) = source.get(&format!("{prefix}SESSION_GUC")) {
736                    db.session_guc = Some(v);
737                }
738                if let Some(v) = source.get(&format!("{prefix}TENANT_ALL_MARKER")) {
739                    db.tenant_all_marker = Some(v);
740                }
741            }
742        }
743
744        // --- serve per-project blob backends (`[serve.blob_backends.<project>]`) ---
745        // PLAN-per-project-blob-backend. A keyed map (like the SQL `databases` map) with no config
746        // file to enumerate its members, so member PROJECT names are discovered from the environment:
747        // any `BOATRAMP_SERVE_BLOB_BACKEND_<PROJECT>_<FIELD>` declares project `<PROJECT>`. Each is
748        // merged per-field (env-over-file) into whatever the file declared under that name. The sealed
749        // credential's two public refs are flattened as `_S3_ACCESS_KEY_ID` / `_S3_SECRET_ACCESS_KEY`
750        // (the secret is always a `boatramp:`/`env:` REFERENCE, never the raw secret — invariant 3).
751        if source.any_with_prefix(BLOB_BACKEND_ENV_PREFIX) {
752            let serve = self.serve.get_or_insert_with(ServeConfig::default);
753            for name in source.blob_backend_projects() {
754                let be = serve.blob_backends.entry(name.clone()).or_default();
755                let prefix = format!("{BLOB_BACKEND_ENV_PREFIX}{name}_");
756                if let Some(v) = source.parse_enum(
757                    &format!("{prefix}KIND"),
758                    &[
759                        ("fs", crate::backends::BlobBackend::Fs),
760                        ("s3", crate::backends::BlobBackend::S3),
761                        ("gcs", crate::backends::BlobBackend::Gcs),
762                        ("azure", crate::backends::BlobBackend::Azure),
763                    ],
764                )? {
765                    be.blobs = Some(v);
766                }
767                if let Some(v) = source.get(&format!("{prefix}S3_BUCKET")) {
768                    be.s3_bucket = Some(v);
769                }
770                if let Some(v) = source.get(&format!("{prefix}S3_ENDPOINT")) {
771                    be.s3_endpoint = Some(v);
772                }
773                if let Some(v) = source.get(&format!("{prefix}S3_REGION")) {
774                    be.s3_region = Some(v);
775                }
776                if let Some(v) = source.parse_bool(&format!("{prefix}S3_PATH_STYLE"))? {
777                    be.s3_path_style = v;
778                }
779                // The sealed base S3 credential — materialised only when one of its refs is set. The
780                // `access_key_id` is public; the `secret_access_key` is a `boatramp:`/`env:` ref.
781                let access_key_id = source.get(&format!("{prefix}S3_ACCESS_KEY_ID"));
782                let secret_ref = source.get(&format!("{prefix}S3_SECRET_ACCESS_KEY"));
783                if access_key_id.is_some() || secret_ref.is_some() {
784                    let cred = be
785                        .s3_credential
786                        .get_or_insert_with(S3CredentialConfig::default);
787                    if let Some(v) = access_key_id {
788                        cred.access_key_id = v;
789                    }
790                    if let Some(v) = secret_ref {
791                        cred.secret_access_key = v;
792                    }
793                }
794            }
795        }
796
797        // --- serve S3-ingress cloud brokering (`[serve.s3_ingress_cloud]`) ---
798        // Env parity for the blob-upload minter's cloud-brokering policy, so a file-less fleet (e.g. the
799        // Tigris presigned-only deployment, whose `boatramp.cfg` existed ONLY to carry
800        // `aws_presigned_only`) needs no config file. Materialises the nested struct only when one is
801        // set. These are POLICY toggles, not key material: the AWS base credential the mint signs from
802        // stays the sealed `[secrets]` one (`BOATRAMP_SECRETS_*`), unchanged. `aws_role_arn` /
803        // `aws_use_federation_token` / `aws_presigned_only` remain mutually validated at wiring — the env
804        // lever is only the input path, not a relaxation of that fail-loud check.
805        if source.any(S3_INGRESS_CLOUD_ENV_VARS) {
806            let serve = self.serve.get_or_insert_with(ServeConfig::default);
807            let ic = serve
808                .s3_ingress_cloud
809                .get_or_insert_with(S3IngressCloud::default);
810            if let Some(v) = source.get("BOATRAMP_S3_INGRESS_CLOUD_AWS_ROLE_ARN") {
811                ic.aws_role_arn = Some(v);
812            }
813            if let Some(v) =
814                source.parse_bool("BOATRAMP_S3_INGRESS_CLOUD_AWS_USE_FEDERATION_TOKEN")?
815            {
816                ic.aws_use_federation_token = v;
817            }
818            if let Some(v) = source.parse_bool("BOATRAMP_S3_INGRESS_CLOUD_AWS_PRESIGNED_ONLY")? {
819                ic.aws_presigned_only = v;
820            }
821            if let Some(v) = source.get("BOATRAMP_S3_INGRESS_CLOUD_GCS_CLIENT_EMAIL") {
822                ic.gcs_client_email = Some(v);
823            }
824            if let Some(v) = source.get("BOATRAMP_S3_INGRESS_CLOUD_AZURE_ACCOUNT") {
825                ic.azure_account = Some(v);
826            }
827            if let Some(v) = source.get("BOATRAMP_S3_INGRESS_CLOUD_AZURE_SERVICE_URL") {
828                ic.azure_service_url = Some(v);
829            }
830            if let Some(v) = source.parse_bool("BOATRAMP_S3_INGRESS_CLOUD_AZURE_HNS")? {
831                ic.azure_hns = v;
832            }
833        }
834
835        // --- secrets (`[secrets]`) -------------------------------------------
836        // Envelope encryption for private keys at rest. `kek_file` holds a *path*
837        // (never key material) and the Vault token stays indirected via
838        // `token_env` (a variable name, not the token). Materialise the nested
839        // `vault` sub-config only when a vault variable is set.
840        if source.any(SECRETS_ENV_VARS) {
841            let secrets = self.secrets.get_or_insert_with(SecretsConfig::default);
842            if let Some(v) = source.get("BOATRAMP_SECRETS_ENVELOPE") {
843                secrets.envelope = v;
844            }
845            if let Some(v) = source.get("BOATRAMP_SECRETS_KEK_FILE") {
846                secrets.kek_file = Some(PathBuf::from(v));
847            }
848            if source.any(SECRETS_VAULT_ENV_VARS) {
849                let vault = secrets
850                    .vault
851                    .get_or_insert_with(VaultSecretsConfig::default);
852                if let Some(v) = source.get("BOATRAMP_SECRETS_VAULT_ADDR") {
853                    vault.addr = v;
854                }
855                if let Some(v) = source.get("BOATRAMP_SECRETS_VAULT_KEY") {
856                    vault.key = v;
857                }
858                if let Some(v) = source.get("BOATRAMP_SECRETS_VAULT_TOKEN_ENV") {
859                    vault.token_env = v;
860                }
861            }
862        }
863
864        // --- cluster (`[cluster]`) -------------------------------------------
865        // The self-hosted cluster section's own fields. The founding/joining
866        // *actions* already have their own `serve` flags with env
867        // (`BOATRAMP_CLUSTER_INIT` / `_JOIN` / `_ADVERTISE_ADDR`); those are
868        // distinct from — and not duplicated by — the `[cluster]` section fields
869        // exposed here. `join_token` keeps a secret out of plain sight via the
870        // usual `env:VAR` / `path:/file` prefix, so the env holds the *reference*,
871        // not the token. `ClusterConfig` has no `Default` (a founder needs at least
872        // a `listen`), so a `BOATRAMP_CLUSTER_LISTEN` is required to materialise an
873        // absent section from the environment.
874        if source.any(CLUSTER_ENV_VARS) {
875            // Materialise an absent section only if a bind address is supplied;
876            // otherwise there is no valid `ClusterConfig` to build (it has no
877            // `Default` — a node must know where to bind its mesh). When the file
878            // already declared `[cluster]`, its `listen` stands and the other env
879            // fields layer over it even without `BOATRAMP_CLUSTER_LISTEN`.
880            let listen = source.parse::<SocketAddr>("BOATRAMP_CLUSTER_LISTEN")?;
881            if self.cluster.is_none()
882                && let Some(listen) = listen
883            {
884                self.cluster = Some(ClusterConfig {
885                    listen,
886                    root_pubkeys: Vec::new(),
887                    seeds: Vec::new(),
888                    join_token: None,
889                    store_dir: None,
890                    mesh: None,
891                });
892            }
893            if let Some(cluster) = self.cluster.as_mut() {
894                // A `listen` override applies to an already-present section too (a
895                // freshly materialised one already carries it).
896                if let Some(v) = listen {
897                    cluster.listen = v;
898                }
899                if let Some(v) = source.parse_list("BOATRAMP_CLUSTER_ROOT_PUBKEYS") {
900                    cluster.root_pubkeys = v;
901                }
902                if let Some(v) = source.parse_list("BOATRAMP_CLUSTER_SEEDS") {
903                    cluster.seeds = v;
904                }
905                if let Some(v) = source.get("BOATRAMP_CLUSTER_JOIN_TOKEN") {
906                    cluster.join_token = Some(v);
907                }
908                if let Some(v) = source.get("BOATRAMP_CLUSTER_STORE_DIR") {
909                    cluster.store_dir = Some(PathBuf::from(v));
910                }
911                if source.any(CLUSTER_MESH_ENV_VARS) {
912                    let mesh = cluster.mesh.get_or_insert_with(MeshConfig::default);
913                    if let Some(v) = source.get("BOATRAMP_CLUSTER_MESH_KEY_FILE") {
914                        mesh.key_file = Some(PathBuf::from(v));
915                    }
916                    if let Some(v) = source.get("BOATRAMP_CLUSTER_MESH_KEY_ROTATION") {
917                        mesh.key_rotation = Some(v);
918                    }
919                    if let Some(v) = source.get("BOATRAMP_CLUSTER_MESH_JOIN_TOKEN_TTL") {
920                        mesh.join_token_ttl = Some(v);
921                    }
922                    if let Some(v) =
923                        source.parse_bool("BOATRAMP_CLUSTER_MESH_GATE_CLIENT_WRITES")?
924                    {
925                        mesh.gate_client_writes = Some(v);
926                    }
927                }
928            }
929        }
930
931        // Fail closed on any db-binding name that is not a safe URL path segment.
932        // Runs on the fully merged (file + env) `databases` map, so it catches a name
933        // from either source — and (crucially) the legacy empty-string default key,
934        // which is no longer produced by the `DEFAULT` token but could still be
935        // written literally in a `boatramp.cfg` file.
936        self.validate_sql_db_names()?;
937        // Fail closed on a `[serve.blob_backends]` key that is not a valid project name, or is the
938        // reserved `default` project (which always resolves the global `[serve]` backend). Runs on the
939        // fully merged (file + env) map (PLAN-per-project-blob-backend).
940        self.validate_blob_backend_projects()?;
941        Ok(())
942    }
943
944    /// Validate every configured `handlers.bindings.sql.databases` binding name
945    /// through the one canonical [`validate_resource_name`](boatramp_core::project::validate_resource_name)
946    /// (`kind = "database"`). A db-binding name is threaded verbatim into the
947    /// control-plane URL (`/api/sql/{db}/…`, `/api/migrate/{db}/…`) and the CLI
948    /// `--db`, so it must be a non-empty, path-segment-safe identifier — the same rule
949    /// project/site/function names already pass. The empty-string legacy default key
950    /// gets a targeted cure pointing at the reserved `default` name.
951    ///
952    /// Also screens each binding's `compute` field against the
953    /// [`RESERVED_MANAGED_DB_COMPUTE_PREFIX`] (#501 Stage B LOW-2): the `bramp-db-`
954    /// prefix is reserved for the derived per-project managed-DB server workloads, so an
955    /// operator may not point a static BYO binding at a `bramp-db-…` workload.
956    fn validate_sql_db_names(&self) -> Result<(), ConfigError> {
957        let Some(databases) = self
958            .handlers
959            .as_ref()
960            .and_then(|h| h.bindings.sql.as_ref())
961            .map(|s| &s.databases)
962        else {
963            return Ok(());
964        };
965        for (name, db) in databases {
966            if let Err(err) = boatramp_core::project::validate_resource_name("database", name) {
967                // The empty-string case is the pre-v0.5.0 default binding key: point
968                // at the cure (name it `default`, or set nothing and let the reserved
969                // `DEFAULT` token map to `default` automatically). Any other
970                // non-conforming name gets the v0.7.0 slug cure pointing at
971                // `project doctor`. This is a boot-LOUD refusal — an operator learns of
972                // a bad name at `serve` boot, not at the first request.
973                let cure = if name.is_empty() {
974                    " — name your default binding `default` (or set \
975                     BOATRAMP_HANDLERS_SQL_DB_DEFAULT_*, which now maps to `default` \
976                     automatically); see the v0.5.0 CHANGELOG"
977                } else {
978                    boatramp_core::project::INVALID_NAME_CURE
979                };
980                return Err(ConfigError::InvalidDbName {
981                    name: err.value,
982                    reason: err.reason,
983                    cure,
984                });
985            }
986            // #501 Stage B LOW-2: the `bramp-db-` compute-workload prefix is RESERVED for
987            // the derived per-project managed-DB server workloads
988            // (`boatramp_storage::tenant_provision::DERIVED_MANAGED_DB_PREFIX`). An operator
989            // must not point a static BYO binding at a `compute` workload with that prefix —
990            // it could shadow / alias a derived managed server. Screen it fail-closed at
991            // config load (cheap: a `starts_with` on an already-parsed field).
992            if let Some(compute) = db.compute.as_deref()
993                && compute.starts_with(RESERVED_MANAGED_DB_COMPUTE_PREFIX)
994            {
995                return Err(ConfigError::InvalidDbName {
996                    name: compute.to_string(),
997                    reason: "the `bramp-db-` compute-workload prefix is reserved for \
998                             boatramp-derived managed-database servers",
999                    cure: " — rename the `compute` workload to not start with `bramp-db-`",
1000                });
1001            }
1002        }
1003        Ok(())
1004    }
1005
1006    /// Validate every configured `[serve.blob_backends.<project>]` key
1007    /// (PLAN-per-project-blob-backend). A key must be a valid project name (the canonical
1008    /// [`validate_resource_name`](boatramp_core::project::validate_resource_name), `kind = "project"`),
1009    /// and must NOT be the reserved `default` project: the `default` project ALWAYS resolves the global
1010    /// `[serve]` backend (invariant 5), so a `[serve.blob_backends.default]` entry would be ambiguous
1011    /// (the node-wide backend is configured under `[serve]`, not here). Both are boot-LOUD refusals
1012    /// (fail-closed — an operator learns of a bad name at `serve` boot, not at the first request). The
1013    /// project the entry binds to is host-routed at serve time, never guest input (invariant 1).
1014    fn validate_blob_backend_projects(&self) -> Result<(), ConfigError> {
1015        let Some(serve) = self.serve.as_ref() else {
1016            return Ok(());
1017        };
1018        for name in serve.blob_backends.keys() {
1019            if name == boatramp_core::project::DEFAULT_PROJECT {
1020                return Err(ConfigError::InvalidBlobBackendProject {
1021                    name: name.clone(),
1022                    reason: "the reserved `default` project always resolves the global [serve] blob \
1023                             backend",
1024                    cure: " — configure the node-wide backend under [serve] (blobs/s3_*), not \
1025                           [serve.blob_backends.default]",
1026                });
1027            }
1028            if let Err(err) = boatramp_core::project::validate_resource_name("project", name) {
1029                return Err(ConfigError::InvalidBlobBackendProject {
1030                    name: err.value,
1031                    reason: err.reason,
1032                    cure: boatramp_core::project::INVALID_NAME_CURE,
1033                });
1034            }
1035        }
1036        Ok(())
1037    }
1038}
1039
1040/// The `BOATRAMP_*` variables that populate the `[compute]` section. Kept as one
1041/// list so [`ServerConfig::apply_env_overrides`] can decide whether to materialise
1042/// an absent section without repeating the names.
1043const COMPUTE_ENV_VARS: &[&str] = &[
1044    "BOATRAMP_COMPUTE_BRIDGE",
1045    "BOATRAMP_COMPUTE_SUBNET",
1046    "BOATRAMP_COMPUTE_VCPUS",
1047    "BOATRAMP_COMPUTE_MEM_MIB",
1048    "BOATRAMP_COMPUTE_REGION",
1049    "BOATRAMP_COMPUTE_SQL_SHIM_URL",
1050    "BOATRAMP_COMPUTE_MANAGED_DB_PRIVILEGE",
1051    "BOATRAMP_COMPUTE_DOCKER_ENDPOINT",
1052    "BOATRAMP_COMPUTE_DOCKER_VOLUME_MODE",
1053    "BOATRAMP_COMPUTE_KERNEL_SIGNING_PUBKEYS",
1054    "BOATRAMP_COMPUTE_KERNEL_ALLOWED_HASHES",
1055    "BOATRAMP_COMPUTE_INTERNAL_DNS",
1056    "BOATRAMP_COMPUTE_DNS_UPSTREAM",
1057    "BOATRAMP_COMPUTE_DNS_DOMAIN",
1058];
1059
1060/// The `BOATRAMP_*` variables that populate the `[security]` section.
1061const SECURITY_ENV_VARS: &[&str] = &[
1062    "BOATRAMP_SECURITY_PROFILE",
1063    "BOATRAMP_SECURITY_ALLOW_UNAUTHENTICATED_PUBLIC_BIND",
1064    "BOATRAMP_SECURITY_MAX_UPLOAD_BYTES",
1065    "BOATRAMP_SECURITY_ALLOW_SITE_UNIX_UPSTREAMS",
1066    "BOATRAMP_SECURITY_ALLOW_SITE_PRIVATE_UPSTREAMS",
1067    "BOATRAMP_SECURITY_ALLOW_GUEST_PRIVATE_EGRESS",
1068    "BOATRAMP_SECURITY_ALLOW_GUEST_SELF_EGRESS",
1069    "BOATRAMP_SECURITY_ALLOW_GUEST_EGRESS_EXTRA_CA",
1070    "BOATRAMP_SECURITY_ALLOW_GUEST_TCP_EGRESS",
1071    "BOATRAMP_SECURITY_MAX_HANDLER_BLOB_BYTES",
1072    "BOATRAMP_SECURITY_MAX_COMPONENT_BYTES",
1073    "BOATRAMP_SECURITY_OIDC_REQUIRE_AUDIENCE",
1074    "BOATRAMP_SECURITY_DOMAIN_VERIFY_ALLOW_PRIVATE",
1075    "BOATRAMP_SECURITY_DOMAIN_VERIFY_SELF_SERVE",
1076    "BOATRAMP_SECURITY_ALLOW_SHARED_KERNEL_COMPUTE",
1077    "BOATRAMP_SECURITY_ALLOW_COMPUTE_EXEC",
1078    "BOATRAMP_SECURITY_RATELIMIT_FAIL_OPEN",
1079    "BOATRAMP_SECURITY_ALLOW_IMPLICIT_ROUTING",
1080    "BOATRAMP_SECURITY_REQUIRE_POP",
1081    "BOATRAMP_SECURITY_REQUIRE_DOMAIN_VERIFICATION",
1082    "BOATRAMP_SECURITY_ALLOW_ENV_SECRET_REFS",
1083    "BOATRAMP_SECURITY_REQUIRE_TENANCY_DECLARATION",
1084    "BOATRAMP_SECURITY_ALLOW_CROSS_TENANT_DB",
1085    "BOATRAMP_SECURITY_ALLOW_GUEST_MINT_CAPABILITY",
1086    "BOATRAMP_SECURITY_MAX_GUEST_CAPABILITY_TTL_SECS",
1087    "BOATRAMP_SECURITY_ALLOW_GUEST_EMAIL",
1088    "BOATRAMP_SECURITY_ALLOW_GUEST_ADMIN_DOMAINS",
1089    "BOATRAMP_SECURITY_ALLOW_GUEST_ADMIN_EMAIL",
1090    "BOATRAMP_SECURITY_ALLOW_GUEST_ADMIN_SITE",
1091    "BOATRAMP_SECURITY_ALLOW_GUEST_ADMIN_SECRETS",
1092];
1093
1094/// The `BOATRAMP_*` variables that populate `handlers.bindings.sql`.
1095const SQL_ENV_VARS: &[&str] = &[
1096    "BOATRAMP_HANDLERS_SQL_DIR",
1097    "BOATRAMP_HANDLERS_SQL_URL",
1098    "BOATRAMP_HANDLERS_SQL_ADMIN_URL",
1099    "BOATRAMP_HANDLERS_SQL_REPLICA_URL",
1100    "BOATRAMP_HANDLERS_SQL_TOKEN_ENV",
1101    "BOATRAMP_HANDLERS_SQL_ADMIN_TOKEN_ENV",
1102    "BOATRAMP_HANDLERS_SQL_PREVIEW_MODE",
1103    "BOATRAMP_HANDLERS_SQL_PREVIEW_INIT",
1104    "BOATRAMP_HANDLERS_SQL_DEPROVISION_GRACE_SECS",
1105    "BOATRAMP_HANDLERS_SQL_MIGRATE_TRUSTED_EXTENSIONS",
1106    "BOATRAMP_HANDLERS_SQL_MAX_DECLARED_DATABASES",
1107    "BOATRAMP_HANDLERS_SQL_MAX_DECLARED_VOLUME_MIB",
1108];
1109
1110/// The `[handlers]` JWKS-freshness env levers (two-tier own/foreign refresh + hard-ttl + prewarm),
1111/// mirroring the `jwks_*` fields on [`HandlersConfig`]. Kept in sync by the forgot-a-knob guard test.
1112const JWKS_ENV_VARS: &[&str] = &[
1113    "BOATRAMP_HANDLERS_JWKS_REFRESH_SECS",
1114    "BOATRAMP_HANDLERS_JWKS_HARD_TTL_SECS",
1115    "BOATRAMP_HANDLERS_JWKS_FOREIGN_REFRESH_SECS",
1116    "BOATRAMP_HANDLERS_JWKS_FOREIGN_HARD_TTL_SECS",
1117    "BOATRAMP_HANDLERS_JWKS_PREWARM",
1118];
1119
1120/// The `[handlers]` concurrency-lane env levers (per-component serve-admission gate + the global
1121/// sync/async lane ceilings), mirroring the `serve_concurrency` / `sync_max_concurrency` /
1122/// `async_max_concurrency` fields on [`HandlersConfig`]. Kept in sync by the forgot-a-knob guard test.
1123const HANDLER_CONCURRENCY_ENV_VARS: &[&str] = &[
1124    "BOATRAMP_HANDLERS_SERVE_CONCURRENCY",
1125    "BOATRAMP_HANDLERS_SYNC_MAX_CONCURRENCY",
1126    "BOATRAMP_HANDLERS_ASYNC_MAX_CONCURRENCY",
1127];
1128
1129/// The `[handlers]` hedged-blob-read env levers (serve-path fetch-tail cut), mirroring the
1130/// `blob_hedge_delay_ms` / `blob_hedge_max_inflight` fields on [`HandlersConfig`]. Kept in sync by the
1131/// forgot-a-knob guard test.
1132const HANDLER_BLOB_HEDGE_ENV_VARS: &[&str] = &[
1133    "BOATRAMP_HANDLERS_BLOB_HEDGE_DELAY_MS",
1134    "BOATRAMP_HANDLERS_BLOB_HEDGE_MAX_INFLIGHT",
1135];
1136
1137/// The `[serve.s3_ingress_cloud]` env levers (the blob-upload minter's cloud-brokering policy),
1138/// mirroring the fields on [`S3IngressCloud`]. Kept in sync by the forgot-a-knob guard test. These are
1139/// policy toggles only; the signing credential stays the sealed `[secrets]` one.
1140const S3_INGRESS_CLOUD_ENV_VARS: &[&str] = &[
1141    "BOATRAMP_S3_INGRESS_CLOUD_AWS_ROLE_ARN",
1142    "BOATRAMP_S3_INGRESS_CLOUD_AWS_USE_FEDERATION_TOKEN",
1143    "BOATRAMP_S3_INGRESS_CLOUD_AWS_PRESIGNED_ONLY",
1144    "BOATRAMP_S3_INGRESS_CLOUD_GCS_CLIENT_EMAIL",
1145    "BOATRAMP_S3_INGRESS_CLOUD_AZURE_ACCOUNT",
1146    "BOATRAMP_S3_INGRESS_CLOUD_AZURE_SERVICE_URL",
1147    "BOATRAMP_S3_INGRESS_CLOUD_AZURE_HNS",
1148];
1149
1150/// The fixed prefix of a keyed `handlers.bindings.sql.databases` variable —
1151/// `BOATRAMP_HANDLERS_SQL_DB_<NAME>_<FIELD>`. Member names aren't known ahead of
1152/// time (there is no config file to enumerate them), so they are discovered by
1153/// scanning the environment for this prefix.
1154const SQL_DB_ENV_PREFIX: &str = "BOATRAMP_HANDLERS_SQL_DB_";
1155
1156/// The recognised `_<FIELD>` suffixes of a `databases` variable, ordered so a
1157/// name-isolating strip matches the **longest** suffix first (`_READ_URL_ENV`
1158/// before `_URL_ENV`). Each mirrors a field of [`ExternalDatabaseConfig`].
1159const SQL_DB_FIELD_SUFFIXES: &[&str] = &[
1160    "_STARTUP_GRACE_SECS",
1161    "_CONNECT_TIMEOUT_SECS",
1162    // `_SESSION_GUC` / `_TENANT_GUC` / `_TENANT_ALL_MARKER` before `_TENANT`/`_TENANT_SCOPE`
1163    // (longest-first name isolation).
1164    "_SESSION_GUC",
1165    "_TENANT_ALL_MARKER",
1166    "_TENANT_GUC",
1167    "_VOLUME_SIZE_MIB",
1168    "_READ_URL_ENV",
1169    "_PASSWORD_ENV",
1170    "_ALLOW_PREVIEW",
1171    "_URL_ENV",
1172    "_DATABASE",
1173    "_READ_ONLY",
1174    "_POOL_MAX",
1175    "_RLS_SESSION",
1176    "_TENANT_SCOPE",
1177    "_COMPUTE",
1178    "_TENANT",
1179    "_IMAGE",
1180    "_KIND",
1181    "_USER",
1182];
1183
1184/// The fixed prefix of a keyed `[serve.blob_backends.<project>]` variable —
1185/// `BOATRAMP_SERVE_BLOB_BACKEND_<PROJECT>_<FIELD>` (PLAN-per-project-blob-backend). Member project
1186/// names aren't known ahead of time (there is no config file to enumerate them), so they are discovered
1187/// by scanning the environment for this prefix — mirroring [`SQL_DB_ENV_PREFIX`].
1188const BLOB_BACKEND_ENV_PREFIX: &str = "BOATRAMP_SERVE_BLOB_BACKEND_";
1189
1190/// The recognised `_<FIELD>` suffixes of a `[serve.blob_backends]` variable, ordered so a
1191/// name-isolating strip matches the **longest** suffix first (so `_S3_SECRET_ACCESS_KEY` wins over any
1192/// shorter overlap). Each mirrors a field of [`BlobBackendConfig`] (the sealed credential's two public
1193/// refs are flattened as `_S3_ACCESS_KEY_ID` / `_S3_SECRET_ACCESS_KEY`). Kept in sync by the
1194/// `blob_backend_env_covers_every_field` forgot-a-knob guard test.
1195const BLOB_BACKEND_FIELD_SUFFIXES: &[&str] = &[
1196    "_S3_SECRET_ACCESS_KEY",
1197    "_S3_ACCESS_KEY_ID",
1198    "_S3_PATH_STYLE",
1199    "_S3_ENDPOINT",
1200    "_S3_BUCKET",
1201    "_S3_REGION",
1202    "_KIND",
1203];
1204
1205/// The `BOATRAMP_*` variables that populate the `[secrets]` section (excluding the
1206/// nested `vault` sub-config, gated separately by [`SECRETS_VAULT_ENV_VARS`]).
1207const SECRETS_ENV_VARS: &[&str] = &[
1208    "BOATRAMP_SECRETS_ENVELOPE",
1209    "BOATRAMP_SECRETS_KEK_FILE",
1210    "BOATRAMP_SECRETS_VAULT_ADDR",
1211    "BOATRAMP_SECRETS_VAULT_KEY",
1212    "BOATRAMP_SECRETS_VAULT_TOKEN_ENV",
1213];
1214
1215/// The `BOATRAMP_*` variables that populate the nested `[secrets.vault]` sub-config.
1216const SECRETS_VAULT_ENV_VARS: &[&str] = &[
1217    "BOATRAMP_SECRETS_VAULT_ADDR",
1218    "BOATRAMP_SECRETS_VAULT_KEY",
1219    "BOATRAMP_SECRETS_VAULT_TOKEN_ENV",
1220];
1221
1222/// The `BOATRAMP_*` variables that populate the `[cluster]` section fields (the
1223/// section's own config, distinct from the founding/joining *action* flags
1224/// `BOATRAMP_CLUSTER_INIT` / `_JOIN` / `_ADVERTISE_ADDR`, which are `serve` clap
1225/// args and are deliberately not listed here).
1226const CLUSTER_ENV_VARS: &[&str] = &[
1227    "BOATRAMP_CLUSTER_LISTEN",
1228    "BOATRAMP_CLUSTER_ROOT_PUBKEYS",
1229    "BOATRAMP_CLUSTER_SEEDS",
1230    "BOATRAMP_CLUSTER_JOIN_TOKEN",
1231    "BOATRAMP_CLUSTER_STORE_DIR",
1232    "BOATRAMP_CLUSTER_MESH_KEY_FILE",
1233    "BOATRAMP_CLUSTER_MESH_KEY_ROTATION",
1234    "BOATRAMP_CLUSTER_MESH_JOIN_TOKEN_TTL",
1235    "BOATRAMP_CLUSTER_MESH_GATE_CLIENT_WRITES",
1236];
1237
1238/// The `BOATRAMP_*` variables that populate the nested `[cluster.mesh]` sub-config.
1239const CLUSTER_MESH_ENV_VARS: &[&str] = &[
1240    "BOATRAMP_CLUSTER_MESH_KEY_FILE",
1241    "BOATRAMP_CLUSTER_MESH_KEY_ROTATION",
1242    "BOATRAMP_CLUSTER_MESH_JOIN_TOKEN_TTL",
1243    "BOATRAMP_CLUSTER_MESH_GATE_CLIENT_WRITES",
1244];
1245
1246/// Where env-override values come from: the real process environment, or an
1247/// explicit map for a deterministic unit test. Keeping the lookup behind this enum
1248/// lets [`ServerConfig::apply_env_overrides`] be tested without touching (racy,
1249/// process-global) `std::env`.
1250enum EnvSource {
1251    /// The live process environment (`std::env::var`).
1252    Process,
1253    /// A fixed name→value map (tests only).
1254    #[cfg(test)]
1255    Map(BTreeMap<String, String>),
1256}
1257
1258impl EnvSource {
1259    /// The value of `var`, if set to a non-empty string. An empty value is treated
1260    /// as unset so an accidental `VAR=` doesn't clobber a file value with `""`.
1261    fn get(&self, var: &str) -> Option<String> {
1262        let raw = match self {
1263            Self::Process => std::env::var(var).ok(),
1264            #[cfg(test)]
1265            Self::Map(m) => m.get(var).cloned(),
1266        };
1267        raw.filter(|v| !v.is_empty())
1268    }
1269
1270    /// Whether any of `vars` is set (to a non-empty value).
1271    fn any(&self, vars: &[&str]) -> bool {
1272        vars.iter().any(|v| self.get(v).is_some())
1273    }
1274
1275    /// Whether any variable whose name starts with `prefix` is set (to a
1276    /// non-empty value). Used to decide whether to materialise a keyed map (the
1277    /// `databases` env scheme) whose member names aren't known ahead of time.
1278    fn any_with_prefix(&self, prefix: &str) -> bool {
1279        self.names()
1280            .any(|name| name.starts_with(prefix) && self.get(&name).is_some())
1281    }
1282
1283    /// The full set of variable names visible to this source. Used to discover the
1284    /// keyed-map member names from the environment (there is no config file to
1285    /// enumerate them). Returned owned so it doesn't borrow the process env.
1286    fn names(&self) -> Box<dyn Iterator<Item = String> + '_> {
1287        match self {
1288            Self::Process => Box::new(std::env::vars().map(|(k, _)| k)),
1289            #[cfg(test)]
1290            Self::Map(m) => Box::new(m.keys().cloned()),
1291        }
1292    }
1293
1294    /// Parse `var` as one of a fixed set of string-mapped variants, mapping an
1295    /// unknown value to a clear [`ConfigError::Env`] that names the variable and
1296    /// the accepted values. Used for the config enums that have no `FromStr`
1297    /// (their only string mapping is a serde `rename_all`). `Ok(None)` when unset.
1298    fn parse_enum<T: Copy>(
1299        &self,
1300        var: &str,
1301        variants: &[(&str, T)],
1302    ) -> Result<Option<T>, ConfigError> {
1303        match self.get(var) {
1304            Some(raw) => {
1305                let lower = raw.trim().to_ascii_lowercase();
1306                variants
1307                    .iter()
1308                    .find(|(name, _)| *name == lower)
1309                    .map(|(_, v)| Some(*v))
1310                    .ok_or_else(|| ConfigError::Env {
1311                        var: var.to_string(),
1312                        reason: format!(
1313                            "expected one of {}, got {raw:?}",
1314                            variants
1315                                .iter()
1316                                .map(|(n, _)| *n)
1317                                .collect::<Vec<_>>()
1318                                .join("/")
1319                        ),
1320                    })
1321            }
1322            None => Ok(None),
1323        }
1324    }
1325
1326    /// The distinct `<NAME>` tokens of every `BOATRAMP_HANDLERS_SQL_DB_<NAME>_<FIELD>`
1327    /// variable that is set. The name is everything between the fixed prefix and the
1328    /// *last* `_<FIELD>` segment, so a database name may itself contain underscores
1329    /// (the field suffix is one of a known set). Returned sorted + de-duplicated so
1330    /// the map is built deterministically.
1331    fn sql_database_names(&self) -> Vec<String> {
1332        let mut names: Vec<String> = self
1333            .names()
1334            .filter(|n| n.starts_with(SQL_DB_ENV_PREFIX) && self.get(n).is_some())
1335            .filter_map(|n| {
1336                let rest = n.strip_prefix(SQL_DB_ENV_PREFIX)?;
1337                // Strip the recognised field suffix to isolate `<NAME>`. The suffixes
1338                // are matched longest-first so `READ_URL_ENV` wins over `URL_ENV`.
1339                SQL_DB_FIELD_SUFFIXES
1340                    .iter()
1341                    .find_map(|suffix| rest.strip_suffix(suffix))
1342                    .filter(|name| !name.is_empty())
1343                    .map(str::to_string)
1344            })
1345            .collect();
1346        names.sort();
1347        names.dedup();
1348        names
1349    }
1350
1351    /// The distinct `<PROJECT>` tokens of every `BOATRAMP_SERVE_BLOB_BACKEND_<PROJECT>_<FIELD>`
1352    /// variable that is set (PLAN-per-project-blob-backend). The name is everything between the fixed
1353    /// prefix and the *last* `_<FIELD>` segment, so a project name may itself contain underscores (the
1354    /// field suffix is one of a known set, matched longest-first). Returned sorted + de-duplicated so
1355    /// the map is built deterministically. Mirrors [`Self::sql_database_names`].
1356    fn blob_backend_projects(&self) -> Vec<String> {
1357        let mut names: Vec<String> = self
1358            .names()
1359            .filter(|n| n.starts_with(BLOB_BACKEND_ENV_PREFIX) && self.get(n).is_some())
1360            .filter_map(|n| {
1361                let rest = n.strip_prefix(BLOB_BACKEND_ENV_PREFIX)?;
1362                BLOB_BACKEND_FIELD_SUFFIXES
1363                    .iter()
1364                    .find_map(|suffix| rest.strip_suffix(suffix))
1365                    .filter(|name| !name.is_empty())
1366                    .map(str::to_string)
1367            })
1368            .collect();
1369        names.sort();
1370        names.dedup();
1371        names
1372    }
1373
1374    /// Parse `var` as a **comma-separated** list of non-empty trimmed items, e.g.
1375    /// the kernel trust anchors. A single value (no comma) yields a one-element
1376    /// list. Empty items are dropped so a trailing comma or doubled separator is
1377    /// tolerated. `Ok(None)` when unset; `Some(Vec::new())` never happens (an
1378    /// all-empty value is treated as unset by [`Self::get`]).
1379    fn parse_list(&self, var: &str) -> Option<Vec<String>> {
1380        self.get(var).map(|raw| {
1381            raw.split(',')
1382                .map(str::trim)
1383                .filter(|s| !s.is_empty())
1384                .map(str::to_string)
1385                .collect()
1386        })
1387    }
1388
1389    /// Parse `var` as any [`FromStr`](std::str::FromStr) type (numbers), mapping a
1390    /// parse failure to a clear [`ConfigError::Env`]. `Ok(None)` when the variable
1391    /// is unset.
1392    fn parse<T>(&self, var: &str) -> Result<Option<T>, ConfigError>
1393    where
1394        T: std::str::FromStr,
1395        T::Err: std::fmt::Display,
1396    {
1397        match self.get(var) {
1398            Some(raw) => raw.parse::<T>().map(Some).map_err(|e| ConfigError::Env {
1399                var: var.to_string(),
1400                reason: e.to_string(),
1401            }),
1402            None => Ok(None),
1403        }
1404    }
1405
1406    /// Parse `var` as a boolean, accepting the common truthy/falsey spellings
1407    /// (`true`/`false`, `1`/`0`, `yes`/`no`, `on`/`off`) case-insensitively so an
1408    /// operator isn't surprised by a strict `true`-only parse. `Ok(None)` when
1409    /// unset.
1410    fn parse_bool(&self, var: &str) -> Result<Option<bool>, ConfigError> {
1411        match self.get(var) {
1412            Some(raw) => match raw.trim().to_ascii_lowercase().as_str() {
1413                "true" | "1" | "yes" | "on" => Ok(Some(true)),
1414                "false" | "0" | "no" | "off" => Ok(Some(false)),
1415                other => Err(ConfigError::Env {
1416                    var: var.to_string(),
1417                    reason: format!("expected a boolean (true/false), got {other:?}"),
1418                }),
1419            },
1420            None => Ok(None),
1421        }
1422    }
1423}
1424
1425/// How a **managed database** (PLAN-managed-compute-sql) runs its stock image on a
1426/// shared-kernel backend, whose entrypoint would otherwise fail under the dropped-`ALL`
1427/// hardening. `rootless` (the default) needs no capabilities and works under any
1428/// posture; `caps` is the fallback for an image that won't run rootless.
1429#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Deserialize)]
1430#[serde(rename_all = "lowercase")]
1431pub enum ManagedDbPrivilege {
1432    /// Run the DB as its image's user (`999:999` for the official postgres/mysql
1433    /// images) against a pre-owned volume — no added capabilities, any posture.
1434    #[default]
1435    Rootless,
1436    /// Add the minimal capability set the entrypoint needs (`CHOWN`, `DAC_OVERRIDE`,
1437    /// `FOWNER`, `SETUID`, `SETGID`). Honored only under the single-tenant posture.
1438    Caps,
1439}
1440
1441/// `compute` section — opt-in compute backends. Present
1442/// ⇒ `serve` registers the backends this node can offer and advertises them to
1443/// the scheduler; backends are capability-detected (container on Linux, remote
1444/// docker when a daemon is reachable, VMM when `/dev/kvm` exists).
1445#[derive(Debug, Clone, Deserialize)]
1446#[serde(default, deny_unknown_fields)]
1447pub struct ComputeConfig {
1448    /// Bridge the container veths / VM taps attach to (default `br-boatramp`).
1449    pub bridge: String,
1450    /// Guest IP subnet (default `10.0.0.0/24`).
1451    pub subnet: String,
1452    /// vCPUs this node advertises as schedulable (`0` ⇒ detect from the host).
1453    pub vcpus: u32,
1454    /// Memory (MiB) this node advertises as schedulable (`0` ⇒ a 1 GiB default).
1455    pub mem_mib: u32,
1456    /// **Static** kernel-signing public keys (`"<alg>:<hex>"`) — the trust anchor
1457    /// for the posture-scaled kernel bar. Under `multi-tenant`, a dynamically-
1458    /// selected default kernel must carry a signature verifying against one of
1459    /// these. Host-access-gated (never in the KV tier); changing it needs a
1460    /// restart. Empty ⇒ no kernel may be signed-verified (strict posture then
1461    /// accepts none).
1462    pub kernel_signing_pubkeys: Vec<String>,
1463    /// **Static** allow-list of kernel content hashes (sha256 hex) a dynamic
1464    /// default may select under `multi-tenant`. Host-access-gated. Empty ⇒ no
1465    /// kernel is allow-listed.
1466    pub kernel_allowed_hashes: Vec<String>,
1467    /// This node's **region** tag (FA-8). Advertised on the compute `Node` so a
1468    /// gateway routing to a `compute:`-backed workload with `--lb nearest` sends
1469    /// each request to the nearest replica by its node's region — no manual
1470    /// `--region` map. `None` ⇒ region-agnostic.
1471    pub region: Option<String>,
1472    /// How the remote-Docker backend reports a workload's reachable endpoint.
1473    /// `published` (default) publishes the container port on `127.0.0.1:<ephemeral>`
1474    /// so a host-native `serve` reaches it on any daemon (incl. Docker Desktop /
1475    /// macOS, where the bridge IP is not host-routable); `bridge` routes to the
1476    /// container bridge IP directly (only when `serve` shares the daemon's network).
1477    pub docker_endpoint: boatramp_docker::DockerEndpoint,
1478    /// How the remote-Docker backend backs a workload's persistent volumes.
1479    /// `named` (default) attaches a daemon-managed `docker volume` by name (portable
1480    /// across daemons + Docker Desktop / macOS); `bind` bind-mounts a host directory
1481    /// under `<data_dir>/compute/volumes/<name>` (local daemon only).
1482    pub docker_volume_mode: boatramp_docker::DockerVolumeMode,
1483    /// Guest-reachable base URL of the compute **sql-shim** (PLAN-compute-bindings) —
1484    /// e.g. `http://10.0.0.1:8081` (the compute bridge gateway) or the docker bridge
1485    /// gateway. Set ⇒ a workload's `--bind sql` reaches the managed database through a
1486    /// listener bound on `0.0.0.0:<port>`. `None` (default) ⇒ compute sql bindings off.
1487    #[serde(default, skip_serializing_if = "Option::is_none")]
1488    #[cfg_attr(not(feature = "handlers"), allow(dead_code))]
1489    pub sql_shim_url: Option<String>,
1490    /// Privilege strategy for a managed database's stock image on a shared-kernel
1491    /// backend (see [`ManagedDbPrivilege`]). `rootless` by default.
1492    #[serde(default)]
1493    #[cfg_attr(not(feature = "handlers"), allow(dead_code))]
1494    pub managed_db_privilege: ManagedDbPrivilege,
1495    /// Per-project **internal DNS** (service discovery): run a lightweight resolver
1496    /// on the bridge gateway so a guest can reach peers by name (`<workload>` /
1497    /// `<workload>.<project>.<dns_domain>`) instead of a numeric IP, scoped to its
1498    /// own project. Default **on** — it activates only when the container backend +
1499    /// bridge come up, so a node without them is unaffected. `false` disables it and
1500    /// leaves each image's own `/etc/resolv.conf`.
1501    #[serde(default = "default_internal_dns")]
1502    pub internal_dns: bool,
1503    /// The upstream resolver the internal DNS forwards non-internal queries to
1504    /// (external names + non-`A`/`AAAA` types), so the resolver is the guest's single
1505    /// nameserver. `"host:port"`; default `1.1.1.1:53`.
1506    #[serde(default = "default_dns_upstream")]
1507    pub dns_upstream: String,
1508    /// The internal DNS suffix names live under (`<workload>.<project>.<dns_domain>`);
1509    /// also the `search` domain written into each container's resolv.conf. Default
1510    /// `boatramp.internal`.
1511    #[serde(default = "default_dns_domain")]
1512    pub dns_domain: String,
1513}
1514
1515/// Default for [`ComputeConfig::internal_dns`] — on (activates only with the
1516/// container backend + bridge).
1517fn default_internal_dns() -> bool {
1518    true
1519}
1520
1521/// Default upstream resolver for [`ComputeConfig::dns_upstream`].
1522fn default_dns_upstream() -> String {
1523    "1.1.1.1:53".to_string()
1524}
1525
1526/// Default internal DNS suffix for [`ComputeConfig::dns_domain`].
1527fn default_dns_domain() -> String {
1528    boatramp_container::dns::DEFAULT_INTERNAL_DOMAIN.to_string()
1529}
1530
1531/// The built-in **boatramp kernel-signing public key** (`es256:…`), whose private
1532/// half lives as the `KERNEL_SIGNING_KEY` Actions secret in
1533/// [`BoatRamp/boatramp-vmlinux`](https://github.com/BoatRamp/boatramp-vmlinux).
1534/// Shipped as a default trust anchor so the first-party signed `boatramp-vmlinux`
1535/// verifies out of the box under the strict posture. An operator can replace
1536/// `kernel_signing_pubkeys` to trust only their own keys.
1537pub const BOATRAMP_KERNEL_SIGNING_PUBKEY: &str =
1538    "es256:02c4e4af2e9cba6ba6745c513f193622e6674a8b2d0187ebea5612f5b46a7eade4";
1539
1540/// The first-party signed-kernel content hashes trusted under the **strict**
1541/// posture, for this build's **guest arch**. The guest arch mirrors the host: an
1542/// x86_64 host boots x86_64 KVM guests (the embedded VMM); an Apple-silicon host
1543/// boots aarch64 guests (the Virtualization.framework `vmm-vz` backend). An x86_64
1544/// kernel can't boot an aarch64 VM (and vice versa), so each arch trusts only its
1545/// own signed `boatramp-vmlinux-<arch>` releases. Bump on each new signed release.
1546///
1547/// The **relaxed** (single-tenant) posture ignores this list — it verifies only the
1548/// content-hash pin — so an operator-supplied kernel boots there regardless of arch.
1549fn default_allowed_kernel_hashes() -> Vec<String> {
1550    #[cfg(target_arch = "x86_64")]
1551    {
1552        vec![
1553            // v0.2.0 minimal Firecracker 6.1-config kernel: boots under the
1554            // firecracker-*binary* backend (ACPI device discovery) but NOT the
1555            // in-process embedded VMM. Kept trusted so operators on the currently
1556            // published release don't fail strict verification.
1557            "cf1e590a9e642be3667131ca35fbf390378a457d8908169d2a169608e299d974".to_string(),
1558            // Same kernel + CONFIG_VIRTIO_MMIO_CMDLINE_DEVICES=y (flake `#vmlinux`),
1559            // so the embedded VMM binds its virtio-block root over the cmdline
1560            // transport. Reproducible build output (deterministic nix build,
1561            // verified on KVM); the next signed boatramp-vmlinux release — which
1562            // reuses this flake — publishes + signs it, gated by
1563            // `vmlinux-release-boot.yml`.
1564            "d0dc2098ab2a2a3c1bc72ab61dc85d9e464d798d7e55b6b80525db5ca2f00c5a".to_string(),
1565        ]
1566    }
1567    #[cfg(target_arch = "aarch64")]
1568    {
1569        vec![
1570            // `boatramp-vmlinux-aarch64` v0.2.3 (the Virtualization.framework guest
1571            // kernel, flake `#vmlinux` on aarch64-linux — a raw arm64 `Image`). This
1572            // release enables the generic PCIe host + virtio-pci so the guest actually
1573            // discovers VZ's virtio disk/net/console (the earlier v0.2.2 `be95fb0d…`
1574            // built with `CONFIG_PCI` off never booted under VZ and is dropped). This
1575            // is the hash of the **published, ES256-signed** release asset (signed by
1576            // BOATRAMP_KERNEL_SIGNING_PUBKEY), so a selected `compute.default_kernel`
1577            // clears the strict bar out of the box; the boot + scale-to-zero round-trip
1578            // was validated against this exact published kernel. NOTE: unlike x86_64,
1579            // the aarch64 build is not currently bit-reproducible across build hosts
1580            // (same config + size, different build metadata), so pin/verify against the
1581            // published `.sha256`/`.sig`, not a local rebuild. Bump on each new release.
1582            "d785a48d754e65a4630443301f1fb84cb69cf882336d3cf37055e437b3d8e21f".to_string(),
1583        ]
1584    }
1585    #[cfg(not(any(target_arch = "x86_64", target_arch = "aarch64")))]
1586    {
1587        Vec::new()
1588    }
1589}
1590
1591impl Default for ComputeConfig {
1592    fn default() -> Self {
1593        Self {
1594            bridge: "br-boatramp".to_string(),
1595            subnet: "10.0.0.0/24".to_string(),
1596            vcpus: 0,
1597            mem_mib: 0,
1598            kernel_signing_pubkeys: vec![BOATRAMP_KERNEL_SIGNING_PUBKEY.to_string()],
1599            kernel_allowed_hashes: default_allowed_kernel_hashes(),
1600            region: None,
1601            docker_endpoint: boatramp_docker::DockerEndpoint::default(),
1602            docker_volume_mode: boatramp_docker::DockerVolumeMode::default(),
1603            sql_shim_url: None,
1604            managed_db_privilege: ManagedDbPrivilege::default(),
1605            internal_dns: default_internal_dns(),
1606            dns_upstream: default_dns_upstream(),
1607            dns_domain: default_dns_domain(),
1608        }
1609    }
1610}
1611
1612/// `cluster` section — self-hosted **cluster mode**. Parsed in
1613/// every build so config files stay portable; only *consumed* when the `cluster`
1614/// feature is compiled in (`boatramp serve --mode cluster`).
1615#[cfg_attr(not(feature = "cluster"), allow(dead_code))]
1616#[derive(Debug, Clone, Deserialize)]
1617pub struct ClusterConfig {
1618    /// Address to bind this node's Raft **peer mesh** on (the `/raft/*` +
1619    /// `/stream/*` endpoints) — distinct from the public `serve.addr`.
1620    pub listen: SocketAddr,
1621    /// The cluster **root anchor set** — the `es256:`/`ed25519:`-tagged public
1622    /// keys that define this cluster's identity (a cluster *is* its root key).
1623    /// Every join/trust decision verifies against this set. Empty ⇒ falls back to
1624    /// `serve.auth_root_public_key` (the single-anchor default). A *set* enables
1625    /// make-before-break root rotation.
1626    #[serde(default)]
1627    pub root_pubkeys: Vec<String>,
1628    /// **Seeds** — control-plane addresses of existing cluster members
1629    /// (`host:port`), any of which can admit this node. Present ⇒ this node
1630    /// **joins** (redeems its `join_token`); absent + no durable state + explicit
1631    /// `--cluster-init` ⇒ it **founds**. There is no peer map: members are learned
1632    /// from the root-signed join response.
1633    #[serde(default)]
1634    pub seeds: Vec<String>,
1635    /// The single-use bearer **join token** used when `seeds` are set. Keeps the
1636    /// secret out of the file via a prefix: `env:VAR`, `path:/file`, or an inline
1637    /// literal. Usually supplied via `serve --cluster-join <ticket>` instead.
1638    #[serde(default)]
1639    pub join_token: Option<String>,
1640    /// Directory for this node's **durable** Raft log/state store (node-local;
1641    /// distinct from the replicated control plane). Default
1642    /// `<data-dir>/raft`.
1643    #[serde(default)]
1644    pub store_dir: Option<PathBuf>,
1645    /// Mesh identity + TLS settings. Absent ⇒ defaults (identity key
1646    /// auto-generated under `<data-dir>/mesh/identity.key`).
1647    #[serde(default)]
1648    pub mesh: Option<MeshConfig>,
1649}
1650
1651/// `[cluster.mesh]` — mesh identity + TLS knobs.
1652#[cfg_attr(not(feature = "cluster"), allow(dead_code))]
1653#[derive(Debug, Clone, Default, Deserialize)]
1654#[serde(default, deny_unknown_fields)]
1655pub struct MeshConfig {
1656    /// Path to this node's Ed25519 identity key (PKCS#8 DER, `0600`,
1657    /// auto-generated). Default `<data-dir>/mesh/identity.key`.
1658    pub key_file: Option<PathBuf>,
1659    /// Automatic key-rotation cadence (e.g. `"30d"`); `None` = manual only.
1660    /// Consumed by the rotation loop.
1661    pub key_rotation: Option<String>,
1662    /// TTL for a single-use join token (e.g. `"1h"`).
1663    pub join_token_ttl: Option<String>,
1664    /// Gate mesh `client-write`s behind a control-plane **cluster-write
1665    /// capability**, so a trusted peer can't inject arbitrary
1666    /// control-plane writes on mesh trust alone. Requires the token root
1667    /// **private** key on every node (each mints + presents its own capability);
1668    /// default `false`.
1669    pub gate_client_writes: Option<bool>,
1670}
1671
1672/// `handlers` section — server-side handler runtime config (read by `serve`).
1673/// Parsed in every build (so config files stay portable), but only *consumed*
1674/// when the `handlers` feature is compiled in.
1675#[cfg_attr(not(feature = "handlers"), allow(dead_code))]
1676#[derive(Debug, Clone, Default, Deserialize)]
1677#[serde(default)]
1678pub struct HandlersConfig {
1679    /// `handlers.bindings` — which backend serves each handler binding.
1680    pub bindings: BindingsConfig,
1681    /// Use the wasmtime **pooling** instance allocator: faster
1682    /// instantiation at the cost of a large up-front virtual-memory reservation.
1683    /// Off by default — opt in and benchmark for your workload.
1684    pub pooling: bool,
1685    /// Capacity of the per-lane **warm compile cache** — how many distinct compiled+linked components
1686    /// (keyed by content hash) stay resident per lane (request / consumer / session). A component
1687    /// evicted here (LRU, once the node serves more than this many distinct components on a lane) pays
1688    /// a cold cranelift recompile on its next request. Absent ⇒ 64 (the historical default). Raise it
1689    /// on a node that serves more than ~64 components so none is evicted; the `/api/instance-stats`
1690    /// surface reports `warm_capacity` + `evictions` so the right value is measured, not guessed.
1691    #[serde(default, skip_serializing_if = "Option::is_none")]
1692    pub instance_cache_size: Option<usize>,
1693    /// **Blob container-marker cache size** (entries). Every blob container open re-`HEAD`s the
1694    /// `.boatramp-container` ownership marker — a second serial object-store round-trip per serve. A
1695    /// process-wide, positive-only cache of VERIFIED markers (keyed by the fully-resolved, tenant-confined
1696    /// container prefix; invalidated on container delete) skips that HEAD for an already-verified
1697    /// container WITHOUT touching confinement (`container_access` still runs on every op). Absent ⇒ 4096;
1698    /// `0` disables the cache (every open re-HEADs). A node rarely has more than a handful of live
1699    /// containers, so the default is generous headroom.
1700    #[serde(default, skip_serializing_if = "Option::is_none")]
1701    pub blob_marker_cache_entries: Option<usize>,
1702    /// **Hedged blob-read delay** (milliseconds). When a serve's object GET has not returned within this
1703    /// many ms, the host races a SECOND GET and takes whichever lands first — cutting the serve-path
1704    /// fetch tail on an external store (measured: `blob_range` p50 ≈ 16ms but p99 ≈ 727ms, with CPU
1705    /// idle). Blob reads are idempotent, so the hedge is always safe; the loser is cancelled. Absent/`0`
1706    /// ⇒ disabled (one GET per read). Set it a little above the warm p90 (e.g. 60–100ms) so only the
1707    /// genuinely-slow tail hedges. Pairs with [`blob_hedge_max_inflight`](Self::blob_hedge_max_inflight).
1708    #[serde(default, skip_serializing_if = "Option::is_none")]
1709    pub blob_hedge_delay_ms: Option<u64>,
1710    /// **Concurrent-hedge cap** — the max number of in-flight hedge (second) reads at once. Guards against
1711    /// a hedge storm when the whole store is slow (every read would otherwise double): over the cap a slow
1712    /// read simply waits on its single request. Absent ⇒ a small internal default (16). Only meaningful
1713    /// when [`blob_hedge_delay_ms`](Self::blob_hedge_delay_ms) is set.
1714    #[serde(default, skip_serializing_if = "Option::is_none")]
1715    pub blob_hedge_max_inflight: Option<usize>,
1716    /// **Per-component serve-admission concurrency** (image-serve-latency Ask B). Caps how many
1717    /// requests to the SAME component (keyed by content hash) are concurrently inside the expensive
1718    /// `build_bindings` + instantiate + serve-to-head region; a burst beyond it (e.g. a gallery firing
1719    /// dozens of `/img` thumbnails) queues cheaply on a semaphore instead of oversubscribing the tokio
1720    /// workers, which on a small-core node makes each request's await-resumptions pile up into a
1721    /// multi-second scheduling stall (the measured `bindgap`). Absent ⇒ a host-parallelism default
1722    /// (`available_parallelism * 4`, floored at 8) so a small node is bounded out of the box; `0`
1723    /// disables the gate (legacy unbounded serve). Raise it on a big node, or lower it if one hot
1724    /// component should be tighter; `/api/instance-stats` + the `bindgap` Server-Timing phase make the
1725    /// right value measurable.
1726    #[serde(default, skip_serializing_if = "Option::is_none")]
1727    pub serve_concurrency: Option<usize>,
1728    /// Engine-wide **safety max** on a *connection-bearing* invocation (a site
1729    /// handler or a synchronous function/webhook invoke), milliseconds. A route
1730    /// or function may declare a *lower* timeout, never a higher one. Kept tight
1731    /// on purpose: a client, proxy, and the shared request pool are all blocked
1732    /// while a sync handler runs. Absent ⇒ 10s (the historical default). This is
1733    /// a node safety ceiling, not a per-invocation budget, and is distinct from
1734    /// a per-site `max_timeout_ms`.
1735    pub sync_max_timeout_ms: Option<u64>,
1736    /// Max concurrent in-flight *sync-lane* invocations node-wide — the GLOBAL ceiling every
1737    /// connection-bearing serve (site handler, synchronous invoke, and the `/graphql` gateway's
1738    /// subgraph fan-out) passes through, distinct from the PER-COMPONENT `serve_concurrency` gate.
1739    /// Absent ⇒ a host-parallelism default (`available_parallelism * 4`, floored at **64** — so it is
1740    /// unchanged on nodes up to ~16 vCPU and only scales ABOVE that). Without this, the lane was pinned
1741    /// at 64 regardless of host size, so adding vCPUs past ~16 bought no extra concurrent live
1742    /// throughput and there was no knob to lift it. Raise it on a big node to let the sync lane use more
1743    /// cores; lower it to cap aggregate live concurrency. Read once at startup. NOTE: with `[handlers]
1744    /// pooling` on, the shared instance pool is sized off the summed lane concurrencies, so a larger
1745    /// value enlarges the up-front virtual reservation (the non-pooling default sizes memory
1746    /// per-invocation and is unaffected). Unlike `serve_concurrency`, `0` is NOT "disable" — the
1747    /// global sync lane is a required safety ceiling, so a configured `0` is rejected (falls back to
1748    /// the host default, with a loud WARN at startup).
1749    pub sync_max_concurrency: Option<usize>,
1750    /// Emit the per-phase `Server-Timing` RESPONSE HEADER to clients. Default **off** (absent ⇒
1751    /// `false`): the per-phase breakdown always goes to the structured phase-timing LOG (operator
1752    /// observability), but putting it on the wire exposes internal phase structure + a timing
1753    /// side-channel to every caller. Turn it on for a debugging window (e.g. correlating a client's
1754    /// slow request to a host phase), off in production. Read once at startup.
1755    #[serde(default, skip_serializing_if = "Option::is_none")]
1756    pub server_timing: Option<bool>,
1757    /// Engine-wide safety max on a *durable async* invocation — the drain that
1758    /// runs `?mode=async` calls, workflow steps, cron/queue/blob triggers, and
1759    /// `wasi:messaging` consumers, milliseconds. No client is connected and the
1760    /// work is retried + dead-lettered, so this can be far larger than the sync
1761    /// ceiling: it is what lets a legitimately long background job (e.g. an LLM
1762    /// generation) declare and actually get minutes of runtime. Absent ⇒ 15
1763    /// minutes. Runs on its own concurrency budget (`async_max_concurrency`), so
1764    /// a long job never starves live traffic.
1765    pub async_max_timeout_ms: Option<u64>,
1766    /// Max concurrent in-flight *async-lane* invocations, kept separate from the
1767    /// (larger) request pool so a burst of long background jobs can't exhaust the
1768    /// slots live site traffic needs. Absent ⇒ 8.
1769    pub async_max_concurrency: Option<usize>,
1770    /// Optional CPU **fuel** ceiling for an async-lane invocation. A large async
1771    /// timeout bounds only wall-clock; without a fuel bound a CPU-bound guest can
1772    /// spin for the whole window. Absent ⇒ unmetered (same as the sync default).
1773    pub async_max_fuel: Option<u64>,
1774    /// Per-component WASM linear-memory **ceiling** for the *async* lane, in MiB —
1775    /// the durable `wasi:messaging` / workflow-step lane where heavy, retryable jobs
1776    /// (image decode+resize, PDF, document processing) belong. This RAISES the lane
1777    /// ceiling above the 64 MiB default; a component's own `limits.memory_mb` (or the
1778    /// site `max_memory_mb`) then clamps it back **down** from here — so an operator
1779    /// sets the lane high enough for the heaviest consumer and each component
1780    /// right-sizes itself. Absent ⇒ 64 MiB (unchanged for every existing component;
1781    /// no component can raise its own memory above this operator-set ceiling). With
1782    /// `[handlers] pooling` on, the shared pool is sized off the largest lane ceiling;
1783    /// see the virtual-reservation note on `pooling`.
1784    pub async_max_memory_mb: Option<usize>,
1785    /// Per-component WASM linear-memory ceiling for the *sync* (request) lane, MiB.
1786    /// Absent ⇒ 64 MiB. Same semantics as [`async_max_memory_mb`](Self::async_max_memory_mb)
1787    /// (raises the lane ceiling; a component clamps down). Raising the sync lane means
1788    /// many concurrent request instances can each reach this ceiling, so weigh it
1789    /// against the request pool's size.
1790    pub sync_max_memory_mb: Option<usize>,
1791    /// Per-component WASM linear-memory ceiling for the *streaming* lane, MiB.
1792    /// Absent ⇒ 64 MiB. Same semantics as [`async_max_memory_mb`](Self::async_max_memory_mb).
1793    pub streaming_max_memory_mb: Option<usize>,
1794    /// **Relaxed messaging-publish durability** — the max number of published
1795    /// messages that may be acknowledged from the in-memory buffer BEFORE a durable
1796    /// checkpoint is forced. **Absent / `0` ⇒ strong durability (the default):**
1797    /// every `publish()` returns only after the message is crash-durable — a
1798    /// *stronger* guarantee than NATS JetStream's default sync publish. Set `N > 0`
1799    /// to opt a node into fast-ack (publish returns on the buffer insert, ~10µs
1800    /// instead of ~one flush interval), at the cost of a **bounded loss window: up
1801    /// to `N` acknowledged-but-unflushed messages are lost on a process crash / OOM
1802    /// / SIGKILL / power loss** before the next flush. Affects ONLY the messaging
1803    /// bus publish path — control-plane, auth, and consumer ack/redelivery
1804    /// durability are unaffected. Single-node only (cluster durability is
1805    /// replication). A node with `N > 0` logs a warning at startup.
1806    pub messaging_max_unflushed_msgs: Option<usize>,
1807    /// **Event-driven delivery — safety-net reconcile cadence** (ms). The coarse timer the delivery
1808    /// drainer falls back to when no fast-path wake fires: it drains the durable ready-set and fires
1809    /// lease-expiry redelivery via the per-message due-heap, so a dropped wake or a time-based
1810    /// visibility never stalls delivery beyond this interval. It never scans idle topics (an idle
1811    /// fleet costs ~0). Absent ⇒ ~2 s. Lower for tighter redelivery latency at more wakeups; raise to
1812    /// quiet a large idle fleet further.
1813    pub messaging_safetynet_interval_ms: Option<u64>,
1814    /// **Event-driven delivery — ready-set rebuild cadence** (ms). The long-cadence self-heal that
1815    /// re-derives the ready-set from the authoritative message index — recovering a marker lost to a
1816    /// crash between the index write and the ready write, pruning a stale marker, and self-populating
1817    /// a fresh/upgraded node's ready-set. This is the one full-ish scan, so it runs rarely. Absent ⇒
1818    /// ~30 s. The correctness backstop for the ready-set (a lost marker costs at most one rebuild
1819    /// interval of latency, never a lost message).
1820    pub messaging_readyset_rebuild_interval_ms: Option<u64>,
1821    /// Max wall-clock for a *streaming-lane* response (a `#[handler(stream)]`
1822    /// route — SSE, chunked, agent token streaming), milliseconds. A client is
1823    /// connected but the body is written incrementally over seconds-to-minutes,
1824    /// so this is far larger than the sync ceiling. Runs on its own concurrency
1825    /// budget (`streaming_max_concurrency`), isolated from both the fast request
1826    /// pool and the async drain. Absent ⇒ 15 minutes.
1827    pub streaming_max_timeout_ms: Option<u64>,
1828    /// Max concurrent in-flight *streaming-lane* responses, kept separate from the
1829    /// request pool and the async drain so a burst of long-lived streams starves
1830    /// neither. Absent ⇒ 64.
1831    pub streaming_max_concurrency: Option<usize>,
1832    /// Optional CPU **fuel** ceiling for a streaming-lane response. Absent ⇒
1833    /// unmetered (a stream is I/O-bound on the client, not CPU-bound).
1834    pub streaming_max_fuel: Option<u64>,
1835    /// Optional ceiling on a guest's **outbound** `wasi:http` call — the connect
1836    /// and time-to-first-byte wait — milliseconds, independent of the invocation
1837    /// timeout, so a hung upstream is bounded on its own terms. The streaming
1838    /// (between-bytes) timeout is left at wasmtime's default so a slow token
1839    /// stream is not cut mid-flight. Absent ⇒ wasmtime's default.
1840    pub outbound_timeout_ms: Option<u64>,
1841    /// **JWKS freshness — `own` (first-party) tier: background-refresh age** (seconds). The soft age at
1842    /// which a node-fixed `token_claims.jwks_url`/`jwks_env` verifier is refreshed in the BACKGROUND
1843    /// (the current keys keep serving — no request blocks on the fetch). Absent ⇒ 120 s. Floored at 60 s.
1844    #[serde(default, skip_serializing_if = "Option::is_none")]
1845    pub jwks_refresh_secs: Option<u64>,
1846    /// **JWKS freshness — `own` tier: hard TTL / revocation bound** (seconds). The age past which the
1847    /// first-party keys are no longer served and a request BLOCKS on a fresh fetch (fail-closed on
1848    /// failure) — caps how long a key revoked at the IdP can keep verifying. Absent ⇒ 600 s. Must be
1849    /// `> jwks_refresh_secs` (else clamped up, with a warning). Floored at 60 s.
1850    #[serde(default, skip_serializing_if = "Option::is_none")]
1851    pub jwks_hard_ttl_secs: Option<u64>,
1852    /// **JWKS freshness — `foreign` (user-declared multi-issuer) tier: background-refresh age**
1853    /// (seconds). As [`jwks_refresh_secs`](Self::jwks_refresh_secs) but for the multi-issuer
1854    /// (`issuer_trust`+`jwks` discovery) path, which is less trusted. Absent ⇒ 60 s. Floored at 60 s.
1855    #[serde(default, skip_serializing_if = "Option::is_none")]
1856    pub jwks_foreign_refresh_secs: Option<u64>,
1857    /// **JWKS freshness — `foreign` tier: hard TTL / revocation bound** (seconds). As
1858    /// [`jwks_hard_ttl_secs`](Self::jwks_hard_ttl_secs) but for user-declared issuers — typically set
1859    /// TIGHTER (faster revocation of a potentially-compromised foreign key). Absent ⇒ 300 s. Must be
1860    /// `> jwks_foreign_refresh_secs`. Floored at 60 s.
1861    #[serde(default, skip_serializing_if = "Option::is_none")]
1862    pub jwks_foreign_hard_ttl_secs: Option<u64>,
1863    /// **JWKS pre-warm at startup.** When on (the default), the node fetches each configured
1864    /// first-party (`own`-tier) `jwks_url` at startup so even the FIRST request is instant; foreign
1865    /// (user-declared) issuers can't be pre-warmed (they aren't known until a token arrives). Set
1866    /// `false` to skip startup JWKS fetches (the first request per issuer then pays the fetch). Absent ⇒ on.
1867    #[serde(default, skip_serializing_if = "Option::is_none")]
1868    pub jwks_prewarm: Option<bool>,
1869}
1870
1871/// `handlers.bindings` — per-binding backend configuration. kv/blob reuse the
1872/// server's own KV/Storage backends (per-site prefixed); `sql` is the single
1873/// libsql backend, whose single-node-vs-cluster split is the only choice.
1874#[cfg_attr(not(feature = "handlers"), allow(dead_code))]
1875#[derive(Debug, Clone, Default, Deserialize)]
1876#[serde(default)]
1877pub struct BindingsConfig {
1878    /// `handlers.bindings.sql` — libsql settings. Absent ⇒ single-node,
1879    /// per-site embedded files under `<data-dir>/handlers-sql`.
1880    pub sql: Option<SqlBindingConfig>,
1881}
1882
1883/// libsql settings for the handler `sql` binding — the single SQL backend. Each
1884/// site gets a real database boundary (an embedded file per site, or a sqld
1885/// namespace per site), never schema separation (which arbitrary guest SQL
1886/// escapes). Setting `url` switches from single-node to a shared sqld cluster;
1887/// everything else stays identical.
1888#[cfg_attr(not(feature = "handlers"), allow(dead_code))]
1889#[derive(Debug, Clone, Default, Deserialize)]
1890#[serde(default)]
1891pub struct SqlBindingConfig {
1892    /// Single-node: root directory for the per-site embedded database files
1893    /// (default `<data-dir>/handlers-sql`). Ignored when `url` is set.
1894    pub dir: Option<PathBuf>,
1895    /// Cluster: base sqld data URL (e.g. `http://sqld:8080`). When set, each
1896    /// site is a sqld namespace addressed as a subdomain of this URL; `admin_url`
1897    /// is then required.
1898    pub url: Option<String>,
1899    /// Cluster: sqld admin API base URL (e.g. `http://sqld:9090`) for creating
1900    /// per-site namespaces. Required when `url` is set.
1901    pub admin_url: Option<String>,
1902    /// Cluster: optional sqld **read-replica** data URL. When set, handlers'
1903    /// read-only `sql` transactions (`open-read-only`) route to this endpoint
1904    /// while writes stay on `url` (reads → replicas, writes → primary).
1905    /// Reads may lag (eventually consistent). Ignored in
1906    /// single-node mode (no `url`).
1907    pub replica_url: Option<String>,
1908    /// Name of the env var holding the sqld data auth token (optional; never
1909    /// the token itself in-file).
1910    pub token_env: Option<String>,
1911    /// Name of the env var holding the sqld admin API auth key (optional).
1912    pub admin_token_env: Option<String>,
1913    /// How preview deployments get their SQL database: `empty` (default — a
1914    /// fresh isolated db), `branch` (a consistent copy of the site's live db;
1915    /// single-node only), or `shared` (the site's live db). See
1916    /// `boatramp_core::sql::PreviewSqlMode`.
1917    pub preview_mode: Option<String>,
1918    /// Path to an idempotent SQL script run when an `empty` preview database is
1919    /// first opened (e.g. schema/seed). Ignored in `branch`/`shared` modes.
1920    pub preview_init: Option<PathBuf>,
1921    /// `handlers.bindings.sql.databases` — external **bring-your-own** databases,
1922    /// each opened by name via `sql.open("<name>")`. An operator-configured
1923    /// Postgres/MySQL whose *isolation is the operator's* (it's their database),
1924    /// so these bypass the per-site libsql boundary and are reachable by any
1925    /// handler/function granted the `sql` binding. Needs the `sql-postgres` /
1926    /// `sql-mysql` build feature for the engine. A name here shadows the same
1927    /// name on the managed libsql default.
1928    pub databases: BTreeMap<String, ExternalDatabaseConfig>,
1929    /// **Soft-delete grace window** for a per-tenant managed database, in seconds
1930    /// (env `BOATRAMP_HANDLERS_SQL_DEPROVISION_GRACE_SECS`). When a project/site is
1931    /// deleted, a **Shared + Postgres** tenant is *soft*-deleted (its database is
1932    /// renamed aside and its role disabled) and stays recoverable for this long
1933    /// before a reaper hard-drops it — see
1934    /// [`tenant_sql`](crate::tenant_sql). `None` ⇒ the 7-day default
1935    /// (`DEFAULT_DEPROVISION_GRACE_SECS`); `0` ⇒ disable the soft path (immediate,
1936    /// irreversible hard drop everywhere). MySQL and all `Single` tenants always
1937    /// hard-drop immediately (the engine/cell can't be renamed aside safely), so this
1938    /// knob only affects the Shared-Postgres cell.
1939    pub deprovision_grace_secs: Option<u64>,
1940    /// **Trusted-extension allowlist** for the owner-gated schema-migration surface — the ONLY
1941    /// Postgres extensions a migration `Extension` step may enable (a name not here is refused
1942    /// fail-closed). A raw `sql` migration step may not `CREATE EXTENSION` at all, so this list is
1943    /// the single, operator-controlled gate on which extensions a project can install via
1944    /// migrations. Empty / `None` ⇒ no extension may be enabled through a migration (the safest
1945    /// default). Keep it tight (e.g. `["pgcrypto", "uuid-ossp", "citext"]`); an entry like
1946    /// `dblink`/`postgres_fdw` deliberately widens cross-database reach, so add those only knowingly.
1947    ///
1948    /// Env-settable (12-factor parity) via **`BOATRAMP_HANDLERS_SQL_MIGRATE_TRUSTED_EXTENSIONS`** —
1949    /// a comma-separated list (`pg_trgm,pgcrypto`), env-over-file, unset ⇒ the file value. Only an
1950    /// input path; the allowlist semantics (the `Extension`-step gate, the fail-closed refusal of an
1951    /// unlisted name, the `sql`-step `CREATE EXTENSION` ban) are unchanged.
1952    pub migrate_trusted_extensions: Option<Vec<String>>,
1953    /// **Per-project declared-database COUNT ceiling** (#501 Stage B MEDIUM-1 — the
1954    /// disk-exhaustion / errno-28 guard). The maximum number of `databases:` entries a
1955    /// single project may declare; a declare that would exceed it is refused fail-closed
1956    /// (a 422-class error). Each declared DB eagerly provisions a 10–200 GiB volume, so
1957    /// without this a `Project·Admin` could declare an unbounded number and exhaust the
1958    /// node's disk. `None` ⇒ the built-in default
1959    /// (`apply_db_caps::DEFAULT_MAX_DECLARED_DATABASES_PER_PROJECT`, 16); `0` ⇒ declaring
1960    /// any managed database is disabled on this node. Env-settable via
1961    /// **`BOATRAMP_HANDLERS_SQL_MAX_DECLARED_DATABASES`** (env-over-file).
1962    pub max_declared_databases: Option<usize>,
1963    /// **Per-project aggregate declared-VOLUME ceiling**, in MiB (#501 Stage B
1964    /// MEDIUM-1). The maximum SUM of `volume_size_mib` across all of a project's declared
1965    /// databases; a declare whose incoming volume would push the project's total past
1966    /// this is refused fail-closed. `None` ⇒ the built-in default
1967    /// (`apply_db_caps::DEFAULT_MAX_DECLARED_VOLUME_MIB`, 512 GiB); `0` ⇒ disable managed
1968    /// declarations on this node (the aggregate can never fit a non-zero volume). Env-settable via
1969    /// **`BOATRAMP_HANDLERS_SQL_MAX_DECLARED_VOLUME_MIB`** (env-over-file).
1970    pub max_declared_volume_mib: Option<u64>,
1971}
1972
1973/// One external SQL database for the handler `sql` binding. Its **source** is one
1974/// of two mutually-exclusive forms:
1975///  - `url_env` — a **bring-your-own** database: the connection URL is a secret,
1976///    named indirectly by an env var (never written in the config file).
1977///  - `compute` — a database **boatramp runs** as a compute workload: boatramp
1978///    derives the connection from the workload's live endpoint (host\:port) plus
1979///    the `database`/`user`/`password_env` here, so there is no URL to hand-map and
1980///    it follows the workload across restarts (PLAN-managed-compute-sql).
1981#[cfg_attr(not(feature = "handlers"), allow(dead_code))]
1982#[derive(Debug, Clone, Default, Deserialize)]
1983#[serde(default)]
1984pub struct ExternalDatabaseConfig {
1985    /// Engine: `postgres` (aliases `postgresql`/`pg`), `mysql` (alias
1986    /// `mariadb`), or `libsql` (aliases `sqlite`/`sqlite3`) — the embedded
1987    /// SQLite-compatible engine (single-node file, or a remote sqld primary via
1988    /// `url_env`). A `libsql` entry needs neither `compute` nor an external URL for
1989    /// the single-node case: it names an on-disk file via [`path`](Self::path).
1990    pub kind: String,
1991    /// Name of the env var holding the connection URL (e.g.
1992    /// `postgres://user:pw@host/db`). Required unless `compute` is set — or, for a
1993    /// single-node `libsql` database, unless `path` is set (an embedded file needs
1994    /// no URL/secret).
1995    pub url_env: String,
1996    /// Optional env var holding a **read-replica** connection URL. When set,
1997    /// `open-read-only` transactions route there; writes stay on `url_env`.
1998    pub read_url_env: Option<String>,
1999    /// Optional env var holding a **DDL/migration** connection URL for the
2000    /// **owner-role analog** of the schema-migration surface — a login that is
2001    /// DDL-capable *and distinct from the runtime binding user* (`user` /
2002    /// `url_env`). Its whole purpose is to keep migration DDL off the runtime
2003    /// tenant identity, mirroring the Postgres owner-role split (Postgres mints a
2004    /// per-tenant non-superuser owner role automatically; MySQL has no such role
2005    /// model, so the DDL identity must be supplied explicitly).
2006    ///
2007    /// **MySQL:** required to run schema migrations. Point it at an admin/DDL
2008    /// login (e.g. `mysql://root:…@host/db` or a purpose-made `_migrate` grant
2009    /// with `CREATE, ALTER, DROP, INDEX, REFERENCES` on the schema) that is **not**
2010    /// the runtime `user`. If it is unset (or resolves to the same identity as the
2011    /// runtime binding), migrate **refuses** fail-closed rather than run owner-DDL
2012    /// as the runtime tenant user — there is no owner/runtime split to fall back
2013    /// on. Ignored by the normal handler `sql` path; read only by the migration
2014    /// runner.
2015    ///
2016    /// **Postgres:** ignored — the per-project non-superuser owner role +
2017    /// its sealed credential are minted automatically at provision, so no
2018    /// operator-supplied DDL URL is needed (a set value is harmless and unused).
2019    pub migration_url_env: Option<String>,
2020    /// The name of a **compute workload** (a Postgres/MySQL server boatramp runs)
2021    /// to source this database from, instead of `url_env`. boatramp resolves the
2022    /// workload's live endpoint and builds the connection. Mutually exclusive with
2023    /// `url_env`.
2024    ///
2025    /// **Reserved prefix (#501 Stage B LOW-2):** do NOT name a static workload with the
2026    /// `bramp-db-` prefix — it is reserved for the per-project managed-database servers
2027    /// boatramp derives for declarative `databases:` entries
2028    /// (`boatramp_storage::tenant_provision::DERIVED_MANAGED_DB_PREFIX`). A `bramp-db-…`
2029    /// value here is refused fail-closed at config load
2030    /// ([`ConfigError::InvalidDbName`](crate::config::ConfigError::InvalidDbName)).
2031    pub compute: Option<String>,
2032    /// The database name inside the compute-backed server (non-secret).
2033    pub database: Option<String>,
2034    /// The connecting user for the compute-backed server (non-secret).
2035    pub user: Option<String>,
2036    /// Env var holding the password for `user` on the compute-backed server.
2037    /// **Omit to let boatramp fully manage the credential** (PLAN-managed-compute-sql
2038    /// Phase 2): it generates a strong password once, seals it with the `[secrets]`
2039    /// envelope, injects it into the DB workload's server-init env at launch, and
2040    /// connects the handler with it — the operator sets no DB secret at all. Set it
2041    /// only to bring your own password for the compute-backed server.
2042    pub password_env: Option<String>,
2043    /// Maximum pooled connections (default 8).
2044    pub pool_max: Option<u32>,
2045    /// Open every transaction `READ ONLY` (the engine rejects writes) — for a
2046    /// database functions should only read.
2047    pub read_only: bool,
2048    /// Permit **preview** deployments to reach this database. Default `false`: a
2049    /// preview is refused, so it can never touch the operator's live external DB.
2050    pub allow_preview: bool,
2051    /// Connection/acquire timeout in seconds (default 10).
2052    pub connect_timeout_secs: Option<u64>,
2053    /// The stock OCI image for a **managed co-located** database (`compute` set, no
2054    /// `password_env`). When omitted, boatramp auto-registers the workload from the
2055    /// engine's default image (`pgvector/pgvector:pg16` for postgres, `mysql:8.0`
2056    /// for mysql). Ignored for a bring-your-own (`url_env`) database.
2057    pub image: Option<String>,
2058    /// The persistent data-volume size in MiB for a **managed co-located** database
2059    /// (default 10240 = 10 GiB). Ignored for a bring-your-own database.
2060    pub volume_size_mib: Option<u32>,
2061    /// Startup grace (seconds) for a **managed co-located** database: how long a
2062    /// freshly launched server has to finish its first `initdb` before the reconcile
2063    /// loop treats a still-unhealthy replica as a broken launch to stop + relaunch.
2064    /// When set it overrides the engine default the synthesizer picks (Postgres 60,
2065    /// MySQL 120). Omit to use that default. Ignored for a bring-your-own database.
2066    pub startup_grace_secs: Option<u32>,
2067    /// **Isolation mechanism** for a compute-backed managed database (2×2 axis 1).
2068    /// `single` (default) — a *dedicated* database server (its own container) per
2069    /// tenant; `shared` — *one* server hosting a permission-separated database + role
2070    /// per tenant. Ignored for a bring-your-own (`url_env`) database.
2071    pub tenant: TenantIsolation,
2072    /// **Tenant grain** for a compute-backed managed database (2×2 axis 2). `project`
2073    /// (default) — a tenant is a project; `site` — a tenant is a site. A tenant may
2074    /// hold several databases (one per binding that names it); it gets one login role
2075    /// and sealed credential per (tenant, server), granted on all its own databases
2076    /// and none of another tenant's. The reserved `default` project uses the plain
2077    /// configured name, so a single-tenant install is just one ordinary database.
2078    pub tenant_scope: TenantScope,
2079    /// **Opt-in** (default `false`): inject the request's `boatramp.project` /
2080    /// `boatramp.site` into the SQL session at each transaction start (Postgres
2081    /// `set_config` GUC, MySQL session var), so hand-written **native RLS** policies
2082    /// can key on them per-request. The GraphQL data connector's row-level policy is
2083    /// claim-sourced and needs nothing here; this is for hand-rolled RLS on the plain
2084    /// `sql.open` path (Postgres — the engine with native row-level security).
2085    ///
2086    /// # Trust model — read before relying on this for isolation
2087    ///
2088    /// `rls_session` **provides** the request's tenant to the SQL session for an app's
2089    /// RLS to key on. It is **not** a general hostile-guest boundary:
2090    ///
2091    /// - The reserved keys (`boatramp.*` / `@boatramp_*`) are **protected** from guest
2092    ///   override — a handler statement that tries to `set_config('boatramp.…', …)` /
2093    ///   `SET boatramp.… ` / `SET @boatramp_… ` (or `RESET`/`DISCARD` them) is refused,
2094    ///   so a guest cannot spoof its injected tenant.
2095    /// - But the **real tenant-isolation boundary** is the **per-tenant database +
2096    ///   role** (`tenant = single` / `shared`), which a compromised handler cannot
2097    ///   cross regardless of what it does in-session. `rls_session` is a convenience
2098    ///   for app-authored RLS *within* a tenant's own database, layered on top of that
2099    ///   boundary — not a substitute for it.
2100    /// - For untrusted data, prefer **claim-sourced** enforcement (the GraphQL data
2101    ///   connector's row-level policy), which derives the tenant from the verified
2102    ///   request, not from anything the handler's SQL can influence.
2103    pub rls_session: bool,
2104    /// The Postgres session GUC name an app's RLS policies read for the host-resolved **tenant**
2105    /// (e.g. `app.tenant_id`), set per request/write on the `rls_session` path so RLS mirrors
2106    /// boatramp's injected predicate as a defense-in-depth backstop (v0.4.20). Only honored when
2107    /// `rls_session` is on and the backend is Postgres. `None` ⇒ not exposed (today's behavior).
2108    /// The guest can never set this GUC itself (its namespace becomes reserved).
2109    #[serde(default)]
2110    pub tenant_guc: Option<String>,
2111    /// The session GUC name for the anonymous **session** axis (e.g. `app.session_id`), the
2112    /// disjoint-column sibling of `tenant_guc` for `TenantOrSession` tables. `None` ⇒ not exposed.
2113    #[serde(default)]
2114    pub session_guc: Option<String>,
2115    /// A reserved sentinel value written to `tenant_guc` on an **`all`-scoped READ** (v0.4.21), so a
2116    /// table that opts in with `USING (… OR current_setting(tenant_guc, true) = '<marker>')` opens
2117    /// cross-tenant for the audited `all` twins. Pick a value that can **never** be a real tenant id
2118    /// (e.g. `*` or `__all__`). Only honored with `tenant_guc` set + `rls_session` on + Postgres.
2119    /// `None`/empty ⇒ `all` reads leave the GUC untouched (v0.4.20 fail-closed behavior). The guest
2120    /// can never set it — the `tenant_guc` namespace is already reserved against guest writes.
2121    #[serde(default)]
2122    pub tenant_all_marker: Option<String>,
2123    /// The on-disk file path for a single-node **`libsql`** database (`kind: "libsql"`), e.g.
2124    /// `/data/app.db`. The parent directory is created if absent. Used only by the embedded engine;
2125    /// ignored for `postgres`/`mysql` and for a remote-sqld `libsql` binding (which uses `url_env`).
2126    /// A `libsql` entry sets exactly one of `path` (single-node file) or `url_env` (remote sqld).
2127    #[serde(default)]
2128    pub path: Option<PathBuf>,
2129}
2130
2131/// How a managed compute-backed database is physically isolated per tenant (2×2 axis
2132/// 1). `Single` = a dedicated server (container) per tenant (isolation by separate
2133/// process); `Shared` = one server with a per-tenant database + login role (isolation
2134/// by grants — Postgres `REVOKE CONNECT FROM PUBLIC` + owner grant; MySQL per-schema
2135/// grant), so a tenant's role cannot connect to another tenant's database.
2136#[cfg_attr(not(feature = "handlers"), allow(dead_code))]
2137#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Deserialize)]
2138#[serde(rename_all = "lowercase")]
2139pub enum TenantIsolation {
2140    /// A dedicated database server (its own container) per tenant. The default.
2141    #[default]
2142    Single,
2143    /// One shared server hosting a per-tenant database + role (grant-isolated).
2144    Shared,
2145}
2146
2147/// The grain of a tenant for a managed compute-backed database (2×2 axis 2) —
2148/// `Project` (default) or `Site`. The two grains are parallel; the isolation
2149/// mechanism is [`TenantIsolation`].
2150#[cfg_attr(not(feature = "handlers"), allow(dead_code))]
2151#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Deserialize)]
2152#[serde(rename_all = "lowercase")]
2153pub enum TenantScope {
2154    /// A tenant is a **project** (the default).
2155    #[default]
2156    Project,
2157    /// A tenant is a **site** (finer than project).
2158    Site,
2159}
2160
2161impl ExternalDatabaseConfig {
2162    /// Validate the source is well-formed: **exactly one** of `url_env` /
2163    /// `compute`, and a `compute`-backed database has the connection details
2164    /// boatramp can't infer (`database` + `user`). `password_env` is **optional** —
2165    /// omit it to let boatramp manage the credential (Phase 2). `name` is the
2166    /// binding name, for the error message.
2167    #[cfg_attr(not(feature = "handlers"), allow(dead_code))]
2168    pub fn validate(&self, name: &str) -> Result<(), String> {
2169        let has_url = !self.url_env.is_empty();
2170        let has_compute = self.compute.as_deref().is_some_and(|c| !c.is_empty());
2171        let has_path = self
2172            .path
2173            .as_deref()
2174            .is_some_and(|p| !p.as_os_str().is_empty());
2175
2176        // A `libsql`/`sqlite` entry is the embedded engine: single-node via `path`, or remote sqld
2177        // via `url_env` — never `compute` (boatramp doesn't run a libsql server workload). Validate
2178        // it on its own axis (exactly one of `path` / `url_env`), and reject `path` on the external
2179        // engines (a Postgres/MySQL binding has no on-disk file).
2180        let is_libsql = matches!(
2181            self.kind.trim().to_ascii_lowercase().as_str(),
2182            "libsql" | "sqlite" | "sqlite3"
2183        );
2184        if is_libsql {
2185            if has_compute {
2186                return Err(format!(
2187                    "sql database {name:?}: a `libsql` database is the embedded engine — set `path` \
2188                     (single-node file) or `url_env` (remote sqld), not `compute`"
2189                ));
2190            }
2191            return match (has_path, has_url) {
2192                (true, true) => Err(format!(
2193                    "sql database {name:?}: a `libsql` database sets exactly one of `path` \
2194                     (single-node file) or `url_env` (remote sqld), not both"
2195                )),
2196                (false, false) => Err(format!(
2197                    "sql database {name:?}: a `libsql` database needs a source — set `path` \
2198                     (single-node file) or `url_env` (remote sqld)"
2199                )),
2200                _ => Ok(()),
2201            };
2202        }
2203        if has_path {
2204            return Err(format!(
2205                "sql database {name:?}: `path` is only valid for a `libsql` database (the embedded \
2206                 engine); a {} binding uses `url_env` or `compute`",
2207                self.kind
2208            ));
2209        }
2210
2211        match (has_url, has_compute) {
2212            (true, true) => Err(format!(
2213                "sql database {name:?}: set exactly one of `url_env` or `compute`, not both"
2214            )),
2215            (false, false) => Err(format!(
2216                "sql database {name:?}: needs a source — set `url_env` (bring-your-own) or \
2217                 `compute` (a database boatramp runs)"
2218            )),
2219            (false, true) => {
2220                // `database` + `user` are non-secret and can't be inferred; a missing
2221                // `password_env` is *not* an error — it selects the managed credential.
2222                for (field, val) in [("database", &self.database), ("user", &self.user)] {
2223                    if val.as_deref().is_none_or(str::is_empty) {
2224                        return Err(format!(
2225                            "sql database {name:?}: a `compute`-backed database requires `{field}`"
2226                        ));
2227                    }
2228                }
2229                Ok(())
2230            }
2231            (true, false) => Ok(()),
2232        }
2233    }
2234
2235    /// Whether this compute-backed database uses a **boatramp-managed** credential
2236    /// (Phase 2): `compute` is set and no `password_env` was supplied.
2237    #[cfg_attr(not(feature = "handlers"), allow(dead_code))]
2238    pub fn is_managed_credential(&self) -> bool {
2239        self.compute.as_deref().is_some_and(|c| !c.is_empty())
2240            && self.password_env.as_deref().is_none_or(str::is_empty)
2241    }
2242}
2243
2244/// The signing algorithm for a signer that can choose one (`Local`, `Vault`,
2245/// `Pkcs11`). ES256 is the portable default; the cloud KMS backends are ES256-only
2246/// and ignore this. Written as a RON enum: `alg: Es256` / `alg: Ed25519`.
2247#[derive(Debug, Clone, Copy, Default, Deserialize)]
2248pub enum SignerAlg {
2249    /// ECDSA P-256 (COSE ES256) — the default.
2250    #[default]
2251    Es256,
2252    /// Ed25519 (COSE EdDSA).
2253    Ed25519,
2254}
2255
2256impl SignerAlg {
2257    fn to_token_alg(self) -> boatramp_core::cose::TokenAlg {
2258        match self {
2259            Self::Es256 => boatramp_core::cose::TokenAlg::Es256,
2260            Self::Ed25519 => boatramp_core::cose::TokenAlg::Ed25519,
2261        }
2262    }
2263}
2264
2265/// External token signer selector (`serve.signer`). Maps to
2266/// [`boatramp_server::signer::SignerConfig`]; secrets (tokens/PINs) are resolved
2267/// from the named env vars at startup, never stored in config. Written as a RON
2268/// enum — `signer: Vault(...)`, `signer: AwsKms(...)`, `signer: Pkcs11(...)`, ….
2269#[derive(Debug, Clone, Deserialize)]
2270#[serde(deny_unknown_fields)]
2271pub enum AuthSignerConfig {
2272    /// In-process key (`"<alg>:<hex>"`).
2273    Local {
2274        /// The private key spec, `"<alg>:<hex>"`.
2275        private_key: String,
2276    },
2277    /// HashiCorp Vault Transit key.
2278    Vault {
2279        /// Vault base address.
2280        address: String,
2281        /// The Transit key name.
2282        key: String,
2283        /// Env var holding the Vault token.
2284        token_env: String,
2285        /// The key algorithm.
2286        #[serde(default)]
2287        alg: SignerAlg,
2288    },
2289    /// AWS KMS asymmetric key (ES256).
2290    AwsKms {
2291        /// The KMS key id or ARN.
2292        key_id: String,
2293        /// Optional region override.
2294        #[serde(default)]
2295        region: Option<String>,
2296    },
2297    /// GCP Cloud KMS key version (ES256).
2298    GcpKms {
2299        /// The key-version resource name.
2300        key_version: String,
2301        /// Env var holding a GCP OAuth2 access token.
2302        access_token_env: String,
2303    },
2304    /// Azure Key Vault key (ES256).
2305    AzureKv {
2306        /// The vault base URL.
2307        vault_url: String,
2308        /// The key name.
2309        key: String,
2310        /// The key version.
2311        key_version: String,
2312        /// Env var holding an Azure AD access token.
2313        access_token_env: String,
2314    },
2315    /// PKCS#11 HSM key.
2316    Pkcs11 {
2317        /// Path to the PKCS#11 module.
2318        module: String,
2319        /// The token label.
2320        token_label: String,
2321        /// The key's `CKA_LABEL`.
2322        key_label: String,
2323        /// Env var holding the user PIN.
2324        pin_env: String,
2325        /// The key algorithm.
2326        #[serde(default)]
2327        alg: SignerAlg,
2328    },
2329}
2330
2331impl AuthSignerConfig {
2332    /// Map the config-file form to the server's runtime [`SignerConfig`].
2333    pub fn to_signer_config(&self) -> boatramp_server::signer::SignerConfig {
2334        use boatramp_server::signer::SignerConfig;
2335        match self {
2336            Self::Local { private_key } => SignerConfig::Local {
2337                private_key: private_key.clone(),
2338            },
2339            Self::Vault {
2340                address,
2341                key,
2342                token_env,
2343                alg,
2344            } => SignerConfig::Vault {
2345                address: address.clone(),
2346                key: key.clone(),
2347                token_env: token_env.clone(),
2348                alg: alg.to_token_alg(),
2349            },
2350            Self::AwsKms { key_id, region } => SignerConfig::AwsKms {
2351                key_id: key_id.clone(),
2352                region: region.clone(),
2353            },
2354            Self::GcpKms {
2355                key_version,
2356                access_token_env,
2357            } => SignerConfig::GcpKms {
2358                key_version: key_version.clone(),
2359                access_token_env: access_token_env.clone(),
2360            },
2361            Self::AzureKv {
2362                vault_url,
2363                key,
2364                key_version,
2365                access_token_env,
2366            } => SignerConfig::AzureKv {
2367                vault_url: vault_url.clone(),
2368                key: key.clone(),
2369                key_version: key_version.clone(),
2370                access_token_env: access_token_env.clone(),
2371            },
2372            Self::Pkcs11 {
2373                module,
2374                token_label,
2375                key_label,
2376                pin_env,
2377                alg,
2378            } => SignerConfig::Pkcs11 {
2379                module: module.clone(),
2380                token_label: token_label.clone(),
2381                key_label: key_label.clone(),
2382                pin_env: pin_env.clone(),
2383                alg: alg.to_token_alg(),
2384            },
2385        }
2386    }
2387}
2388
2389/// `serve` section — server defaults, overridden by flags/env.
2390#[derive(Debug, Clone, Default, Deserialize)]
2391#[serde(default)]
2392pub struct ServeConfig {
2393    /// Bind address (e.g. `0.0.0.0:8080`).
2394    pub addr: Option<SocketAddr>,
2395    /// Data directory for filesystem backends.
2396    pub data_dir: Option<PathBuf>,
2397    /// Blob object-store backend (`fs`/`s3`/`gcs`/`azure`) — the config-level analog of the
2398    /// `--blobs` flag. Absent ⇒ the flag/env decides (`--blobs`/`BOATRAMP_BLOBS`, default `fs`).
2399    /// The flag/env still wins over this (uniform `serve` precedence). Read primarily by `boatramp
2400    /// blob migrate`, which builds a source/destination backend from a config file alone; `serve`
2401    /// also honours it as the config-level fallback under the flag.
2402    pub blobs: Option<crate::backends::BlobBackend>,
2403    /// S3 bucket (`--blobs s3`). Config-level fallback for `--s3-bucket`/`BOATRAMP_S3_BUCKET`.
2404    pub s3_bucket: Option<String>,
2405    /// S3 endpoint URL (e.g. a MinIO/R2/Tigris endpoint). Fallback for `--s3-endpoint`.
2406    pub s3_endpoint: Option<String>,
2407    /// S3 region. Fallback for `--s3-region`.
2408    pub s3_region: Option<String>,
2409    /// Use S3 path-style addressing (required by MinIO). Fallback for `--s3-path-style`.
2410    pub s3_path_style: bool,
2411    /// GCS bucket (`--blobs gcs`). Fallback for `--gcs-bucket`.
2412    pub gcs_bucket: Option<String>,
2413    /// GCS storage endpoint URL (e.g. a `fake-gcs-server` emulator). Fallback for `--gcs-endpoint`.
2414    pub gcs_endpoint: Option<String>,
2415    /// Skip GCS credential resolution (anonymous — the emulator). Fallback for `--gcs-anonymous`.
2416    pub gcs_anonymous: bool,
2417    /// Azure storage account name (`--blobs azure`). Fallback for `--azure-account`.
2418    pub azure_account: Option<String>,
2419    /// Azure container name (`--blobs azure`). Fallback for `--azure-container`.
2420    pub azure_container: Option<String>,
2421    /// Azure storage account access key (shared-key auth). Fallback for `--azure-access-key`.
2422    /// Prefer the env/flag over persisting a key in the config file.
2423    pub azure_access_key: Option<String>,
2424    /// Use the Azurite emulator (well-known dev credentials + local endpoint). Fallback for
2425    /// `--azure-emulator`.
2426    pub azure_emulator: bool,
2427    /// `[serve.blob_fallback]` — a **read-only SECONDARY blob backend** for a zero-downtime
2428    /// backend switch (blob-backend migration Part 2). When set, serving reads the PRIMARY (the
2429    /// `blobs`/`s3_*`/`gcs_*`/`azure_*` fields above) first and, on a definitive miss for a
2430    /// boatramp-owned key, falls through to this secondary — so a `--blobs` switch (fs→cloud,
2431    /// provider→provider, region→region) has no serving gap while `boatramp blob migrate` drains
2432    /// the secondary into the primary. **Writes are primary-only**; the secondary is never written
2433    /// or deleted. This is a **bounded transition aid**: drain, verify, then remove this block and
2434    /// restart (the node logs a prominent startup WARNING while it is active, and GC prune is
2435    /// refused). Absent ⇒ no fallback (unchanged). See [`BlobFallbackConfig`].
2436    pub blob_fallback: Option<BlobFallbackConfig>,
2437    /// `[serve.blob_backends.<project>]` — **per-project** blob object-store overrides
2438    /// (PLAN-per-project-blob-backend). A project named here serves its `wasi:blobstore` data from its
2439    /// OWN bucket/endpoint/credential instead of the one node-wide `[serve]` backend; a project with NO
2440    /// entry — and the reserved `default` project — resolves the global default (invariant 5: an
2441    /// all-global deployment is byte-for-byte unchanged). Operator-configured (node config + sealed
2442    /// `[secrets]`), mirroring `[handlers.bindings.sql.databases]`; a project OWNER declaring its own
2443    /// backend is out of scope for this cut. Each entry's sealed S3 credential is a secret **reference**
2444    /// (`boatramp:`/`env:`), never inlined (invariant 3). Empty ⇒ no overrides (the common case). See
2445    /// [`BlobBackendConfig`]. Env parity: `BOATRAMP_SERVE_BLOB_BACKEND_<PROJECT>_*`.
2446    pub blob_backends: BTreeMap<String, BlobBackendConfig>,
2447    /// Token root **private** key (hex) — issuing node: verifies *and* mints
2448    /// tokens / OIDC exchanges.
2449    pub auth_root_private_key: Option<String>,
2450    /// Token root **public** key (hex) — verify-only node.
2451    pub auth_root_public_key: Option<String>,
2452    /// Single-use bootstrap secret enabling `POST /api/tokens/bootstrap` (mint the
2453    /// first token without an admin bearer). Prefer the `BOATRAMP_BOOTSTRAP_SECRET`
2454    /// env / `--bootstrap-secret` flag so it isn't persisted in the config file.
2455    pub bootstrap_secret: Option<String>,
2456    /// External token signer (`[serve.signer]`): mint with a
2457    /// KMS/HSM/Vault-held root key instead of an in-process `auth_root_private_key`.
2458    /// Absent ⇒ the in-process key. When set, its public half is the trust anchor.
2459    pub signer: Option<AuthSignerConfig>,
2460    /// Reject blob uploads larger than this many bytes.
2461    pub max_upload_bytes: Option<u64>,
2462    /// Abort an upload that stalls for longer than this many seconds.
2463    pub upload_idle_timeout_secs: Option<u64>,
2464    /// Cap on simultaneous blob uploads.
2465    pub max_concurrent_uploads: Option<usize>,
2466    /// In a TLS mode, bind this plain-HTTP address on a second listener that
2467    /// redirects to HTTPS (dual-listener). Only read in `tls` builds.
2468    #[cfg_attr(not(feature = "tls"), allow(dead_code))]
2469    pub http_redirect_addr: Option<SocketAddr>,
2470    /// Site to serve for a `Host` matching no domain, instead of 404.
2471    pub default_site: Option<String>,
2472    /// The fleet's canonical public origin (e.g. `https://cp.example.com`) that a
2473    /// per-request proof-of-possession must bind to (`aud`). Required for
2474    /// holder-bound (`cnf`/PoP) tokens to be usable — a proof's origin is compared
2475    /// against this value, never against a `Host`/`X-Forwarded-*` header.
2476    pub pop_origin: Option<String>,
2477    /// Require a valid control-plane token to view deployment previews.
2478    pub protect_previews: bool,
2479    /// Rate-limit cluster-wide via the control-plane KV instead of per node.
2480    pub cluster_rate_limit: bool,
2481    /// Keep the config cache coherent across processes sharing one KV via the
2482    /// changelog.
2483    pub shared_cache_coherence: bool,
2484    /// Cloud blob-change notification provisioning tier (FA-5b2): how boatramp
2485    /// obtains the native event pipeline (S3→SQS) that backs a `blob` trigger —
2486    /// `dry-run` (print the recipe), `provision` (create + retract), `verify-only`
2487    /// (operator pre-wired), or `refuse` (fail closed). Absent ⇒ no provisioning:
2488    /// `blob` triggers then work only on a self-watching backend (fs). Only wired
2489    /// for the S3 backend (`--features s3`).
2490    pub blob_notify_tier: Option<boatramp_core::blob_notify::ProvisionTier>,
2491    /// The AWS account id used to scope the provisioned SQS queue's `SendMessage`
2492    /// policy (`aws:SourceAccount`). Required when `blob_notify_tier` provisions.
2493    pub blob_notify_account_id: Option<String>,
2494    /// `[serve.console]` — the embedded web management console. Absent (or
2495    /// `enabled: false`) ⇒ not served. This is the **baseline** for the dynamic
2496    /// `console.*` daemon-config override, which can enable/move it at runtime
2497    /// (`boatramp config set console.enabled true`) without a restart.
2498    pub console: Option<ConsoleConfig>,
2499    /// Bind address for the **dedicated local S3-ingress listener** (PLAN-blob-s3-ingress,
2500    /// Architect HIGH-4). Absent ⇒ the local S3 face is NOT served (it is opt-in — a deployment that
2501    /// only mints cloud-brokered credentials never needs it). This is a SEPARATE listener from the
2502    /// control-plane `addr`: it has its own SigV4 auth surface and never reaches `serve_by_host` or
2503    /// the `/api` router.
2504    pub s3_ingress_addr: Option<SocketAddr>,
2505    /// Path to the **dedicated S3-ingress root secret** file (raw 32 bytes) — the independently-
2506    /// rotatable HKDF root for `secret_access_key` derivation (hard domain separation from the
2507    /// `[secrets]` KEK + the COSE signing key). Like `[secrets].kek_file`, this holds a *path*, never
2508    /// key material in the config text, and (in a cluster) the **same file must be present on every
2509    /// node** so every node derives the same `secret_access_key`. Absent on a single node ⇒ an
2510    /// ephemeral per-process root is auto-generated; absent on a **multi-node** deployment ⇒ the S3
2511    /// face is refused to enable (fail-closed — credentials would otherwise be un-verifiable across
2512    /// nodes). Prefer the `BOATRAMP_S3_INGRESS_SECRET_FILE` env / flag so the path stays out of the
2513    /// committed config where that matters operationally.
2514    pub s3_ingress_secret_file: Option<PathBuf>,
2515    /// The publicly-reachable base URL an external client targets for the local S3 face — what a
2516    /// **minted** upload credential (`boatramp:handlers/blob-upload` guest mint / `boatramp blob
2517    /// mint-upload` operator) embeds as its endpoint (a presigned-put URL prefix, or the SDK endpoint
2518    /// for temp-credentials). Absent ⇒ derived from `s3_ingress_addr` as `http://<addr>` (fine for a
2519    /// same-host dev/test loop; set it explicitly to the TLS-terminated public URL in production).
2520    /// Only consulted when guest/operator upload minting is wired (`blob-upload` feature + the face
2521    /// enabled).
2522    pub s3_ingress_public_url: Option<String>,
2523    /// Operator ceiling (seconds) on a minted upload credential's TTL — a guest/operator can only
2524    /// request a SHORTER lifetime (the mint clamps to this). Absent ⇒ a conservative default
2525    /// ([`DEFAULT_S3_INGRESS_MINT_MAX_TTL_SECS`]). A `0` disables minting entirely (the binding is
2526    /// never attached).
2527    pub s3_ingress_mint_max_ttl_secs: Option<u64>,
2528    /// Operator ceiling (bytes) on a minted credential's `max_bytes` constraint — a guest can only
2529    /// request a SMALLER cap (clamped to this). Absent ⇒ no host-side max-bytes clamp (the per-container
2530    /// ceiling at the face still applies).
2531    pub s3_ingress_mint_max_bytes: Option<u64>,
2532    /// **Cloud brokering** (M4): when the node's blob backend is a cloud object store (S3/GCS/Azure)
2533    /// and this is set, minting brokers a NATIVE scoped credential (STS session policy / signed URL +
2534    /// CAB / user-delegation SAS) so the client uploads DIRECTLY to the real store (bytes never transit
2535    /// the node) — INSTEAD of the local S3 face. Absent ⇒ the local face is used (an fs/in-memory
2536    /// backend, or a cloud backend that re-transits through the local face). See [`S3IngressCloud`].
2537    pub s3_ingress_cloud: Option<S3IngressCloud>,
2538    /// **Node-level base S3 credential source** (`[serve.s3_credential]`, task #505). When set, BOTH the
2539    /// S3 blob **object backend** (`--blobs s3`) and the AWS blob-upload **cloud minter**
2540    /// (`[serve.s3_ingress_cloud]`) source their base AWS credential from boatramp's `[secrets]` sealed
2541    /// store instead of the ambient `AWS_ACCESS_KEY_ID`/`AWS_SECRET_ACCESS_KEY` env chain. ONE shared
2542    /// source (both consumers read the SAME bucket key). Absent ⇒ the ambient AWS env chain (current
2543    /// behavior, non-breaking). Requires a `[secrets]` envelope when the `secret_access_key` is a sealed
2544    /// `boatramp:`/`env:` ref — a configured ref with no envelope is a **startup error** (fail-closed, no
2545    /// silent env fallback). See [`S3CredentialConfig`].
2546    pub s3_credential: Option<S3CredentialConfig>,
2547    /// `[serve.kv]` — control-plane SlateDB KV durability cadence + shutdown budget (v0.9.0
2548    /// KV-recovery). Absent ⇒ the defaults (periodic checkpoint ON at
2549    /// [`DEFAULT_KV_CHECKPOINT_INTERVAL_SECS`], close budget [`DEFAULT_KV_CLOSE_DEADLINE_SECS`]).
2550    /// See [`KvConfig`].
2551    pub kv: Option<KvConfig>,
2552}
2553
2554/// `[serve.s3_credential]` — a **node-level base S3 credential source** (#505) sourcing the base AWS
2555/// credential from boatramp's `[secrets]` sealed store rather than the ambient env chain. Consumed by
2556/// BOTH the S3 blob object backend and the AWS blob-upload cloud minter (one shared source, since it is
2557/// the same bucket key). Additive/non-breaking: absent ⇒ the ambient AWS env chain (unchanged).
2558///
2559/// The `access_key_id` is a public identifier (plain config). The `secret_access_key` is a **secret
2560/// reference** in the same scheme the guest `secrets` map uses: `boatramp:<name>` (the project-scoped
2561/// sealed store, resolved under the reserved default project — multi-tenant-safe, never the host env),
2562/// `env:<VAR>` / a bare `<VAR>` (the operator's own environment — honored only when the posture's
2563/// `allow_env_secret_refs` is set), unsealed at serve startup via the `[secrets]` [`KeyEnvelope`]. The
2564/// resolved plaintext is held **in memory only** (never env/argv/git/logs); see the redacted
2565/// `SealedS3Credential` the resolver produces.
2566#[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize)]
2567#[serde(deny_unknown_fields)]
2568pub struct S3CredentialConfig {
2569    /// The AWS **access key id** — a public identifier, not a secret, so it is plain config (mirrors
2570    /// how an `access_key_id` is a public value in the S3-ingress credential model). Empty is refused
2571    /// at resolution.
2572    pub access_key_id: String,
2573    /// The **secret access key**, expressed as a secret **reference** (never the raw secret in the
2574    /// config text): `boatramp:<name>` (the project-scoped sealed store), `env:<VAR>` or a bare `<VAR>`
2575    /// (the operator env, posture-gated by `allow_env_secret_refs`). Unsealed at startup via the
2576    /// `[secrets]` envelope; the resolved value is redacted from `Debug`/logs. A `boatramp:`/`env:`
2577    /// ref configured with NO `[secrets]` envelope is a fail-closed startup error.
2578    pub secret_access_key: String,
2579}
2580
2581/// `[serve.blob_backends.<project>]` — a **per-project** blob object-store backend
2582/// (PLAN-per-project-blob-backend). Same backend-descriptor shape as the `[serve]` primary's S3 fields
2583/// plus its OWN sealed base S3 credential (`#505` path), so project ACME can point its `wasi:blobstore`
2584/// at its own bucket/endpoint/account. Key-prefix confinement (`container_access`) still runs on top —
2585/// a separate bucket adds PHYSICAL isolation, it does not replace the confinement (invariant 2).
2586///
2587/// Operator-configured; the backend is bound to the serve's **host-resolved** project at serve wiring,
2588/// never to guest input (invariant 1). The sealed credential is resolved under THIS project's sealed
2589/// `[secrets]` store at wiring; a declared backend whose credential/bucket cannot be built REFUSES the
2590/// serve (fail-closed — never a silent fallback to the global or another project's backend, invariant
2591/// 4). First cut is S3 (and `fs`, which is degenerate — it shares the node blob dir, so only a cloud
2592/// bucket gives physical isolation); a per-project `gcs`/`azure` needs its own descriptor fields and is
2593/// a follow-up (declaring one fails closed at build — the required bucket/account is absent).
2594#[derive(Debug, Clone, Default, Deserialize)]
2595#[serde(deny_unknown_fields)]
2596pub struct BlobBackendConfig {
2597    /// The backend kind (`fs`/`s3`/`gcs`/`azure`). **Required** (mirrors the SQL binding's required
2598    /// `kind`): a per-project backend with no explicit kind is a startup error, so a forgotten
2599    /// `blobs = "s3"` can't silently build an `fs` backend at the shared node dir that would NOT
2600    /// isolate the project's blobs. Resolved at serve wiring (fail-closed when absent).
2601    pub blobs: Option<crate::backends::BlobBackend>,
2602    /// S3 bucket (`blobs = s3`) — the project's OWN bucket.
2603    pub s3_bucket: Option<String>,
2604    /// S3 endpoint URL (a MinIO/R2/Tigris endpoint) for this project's backend.
2605    pub s3_endpoint: Option<String>,
2606    /// S3 region for this project's backend.
2607    pub s3_region: Option<String>,
2608    /// Use S3 path-style addressing (MinIO) for this project's backend.
2609    #[serde(default)]
2610    pub s3_path_style: bool,
2611    /// This project's OWN sealed base S3 credential (`#505`) — resolved through the SAME
2612    /// `resolve_s3_credential` path as the node primary, but keyed under THIS project's sealed store
2613    /// (`boatramp:<name>` resolves against `project`'s secrets, not the node default). The
2614    /// `access_key_id` is a public identifier; `secret_access_key` is a `boatramp:`/`env:` **reference**
2615    /// (never the raw secret in config, invariant 3). Absent ⇒ the ambient AWS env chain.
2616    pub s3_credential: Option<S3CredentialConfig>,
2617}
2618
2619/// `[serve.blob_fallback]` — a **read-only SECONDARY blob backend** for a zero-downtime backend switch
2620/// (blob-backend migration Part 2). Same backend-descriptor shape as the PRIMARY (`[serve]`'s
2621/// `blobs`/`s3_*`/`gcs_*`/`azure_*` fields) so a source/dest is fully described by config, plus its OWN
2622/// optional `s3_credential` (the secondary can source its base S3 credential from the sealed `[secrets]`
2623/// store via its own `boatramp:`/`env:` ref, #505). Constructed exactly like the primary but with NO
2624/// watcher provisioning (a read-only drain source never watches). Serving wraps
2625/// `FallbackStorage::new(primary, secondary, …)` so a primary miss on a boatramp-owned key falls through
2626/// to this secondary; writes/deletes are primary-only.
2627///
2628/// The secondary is **never** handed to the blob-upload/STS minter — external ingress mints against the
2629/// PRIMARY only (the new backend the client should upload to), so this credential never reaches the
2630/// minter path.
2631#[derive(Debug, Clone, Default, Deserialize)]
2632#[serde(deny_unknown_fields)]
2633pub struct BlobFallbackConfig {
2634    /// The secondary blob backend (`fs`/`s3`/`gcs`/`azure`) — the OLD backend to fall back to on a
2635    /// primary miss. Absent ⇒ `fs` (the default, matching the primary's `blobs` default).
2636    pub blobs: Option<crate::backends::BlobBackend>,
2637    /// S3 bucket (secondary `blobs = s3`).
2638    pub s3_bucket: Option<String>,
2639    /// S3 endpoint URL (a MinIO/R2/Tigris endpoint) for the secondary.
2640    pub s3_endpoint: Option<String>,
2641    /// S3 region for the secondary.
2642    pub s3_region: Option<String>,
2643    /// Use S3 path-style addressing (MinIO) for the secondary.
2644    #[serde(default)]
2645    pub s3_path_style: bool,
2646    /// The secondary's OWN node-level sealed base S3 credential source (#505) — resolved through the
2647    /// SAME `resolve_s3_credential` path as the primary (same fail-closed posture, no second parser).
2648    /// Absent ⇒ the ambient AWS env chain (unchanged).
2649    pub s3_credential: Option<S3CredentialConfig>,
2650    /// GCS bucket (secondary `blobs = gcs`).
2651    pub gcs_bucket: Option<String>,
2652    /// GCS storage endpoint URL (a `fake-gcs-server` emulator) for the secondary.
2653    pub gcs_endpoint: Option<String>,
2654    /// Skip GCS credential resolution (anonymous — the emulator) for the secondary.
2655    #[serde(default)]
2656    pub gcs_anonymous: bool,
2657    /// Azure storage account name (secondary `blobs = azure`).
2658    pub azure_account: Option<String>,
2659    /// Azure container name for the secondary.
2660    pub azure_container: Option<String>,
2661    /// Azure storage account access key (shared-key auth) for the secondary.
2662    pub azure_access_key: Option<String>,
2663    /// Use the Azurite emulator for the secondary.
2664    #[serde(default)]
2665    pub azure_emulator: bool,
2666    /// Bound (seconds) on each secondary read so a wedged secondary degrades a primary miss to
2667    /// `NotFound` instead of hanging the serve path. Absent ⇒ [`DEFAULT_BLOB_FALLBACK_TIMEOUT_SECS`].
2668    pub secondary_timeout_secs: Option<u64>,
2669}
2670
2671/// Default bound (seconds) on a `[serve.blob_fallback]` secondary read when
2672/// `secondary_timeout_secs` is unset: 5s — long enough for a cloud round-trip, short enough that a
2673/// wedged secondary degrades a primary miss to `NotFound` promptly rather than hanging serving.
2674pub const DEFAULT_BLOB_FALLBACK_TIMEOUT_SECS: u64 = 5;
2675
2676/// Default control-plane KV **periodic checkpoint** cadence (seconds) when `[serve.kv]
2677/// checkpoint_interval` is unset (v0.9.0 KV-recovery, C1). The cadence advances the durable frontier
2678/// (WAL→L0 MemTable freeze) so the self-heal-on-open trailing-tail loss window is bounded to at most
2679/// this interval for anything NOT already frontier-synced by a crown-jewel write. 10s balances a tiny
2680/// loss window against manifest-PUT churn; an idle store's checkpoint is a dirty-gated no-op regardless.
2681pub const DEFAULT_KV_CHECKPOINT_INTERVAL_SECS: u64 = 10;
2682
2683/// Default **graceful-close budget** (seconds) when `[serve.kv] close_deadline` is unset (v0.9.0
2684/// KV-recovery, C12). The shutdown drain+close is abandoned only after this budget — GENEROUS (not the
2685/// old hardcoded 3s, which self-exited BEFORE fly's SIGKILL grace and left the frontier un-advanced =
2686/// the exact torn tail we prevent). With continuous checkpointing (C1/C2) the close is cheap, so this
2687/// budget rarely bites; operators should still raise fly `kill_timeout` to ≥ their measured drain+close.
2688pub const DEFAULT_KV_CLOSE_DEADLINE_SECS: u64 = 20;
2689
2690/// `[serve.kv]` — control-plane KV configuration. The backend itself is selected by `--kv` /
2691/// `BOATRAMP_KV` (`slatedb` default, `sql`, `memory`, `cloudflare`); this block holds the
2692/// backend-specific settings, nested so a knob can never silently mislead under the wrong backend
2693/// (UX-C3): the SlateDB durability knobs live under [`slatedb`](Self::slatedb), and the SQL
2694/// connection under [`sql`](Self::sql). Absent block ⇒ the SlateDB defaults apply.
2695#[derive(Debug, Clone, Default, Deserialize)]
2696#[serde(default, deny_unknown_fields)]
2697pub struct KvConfig {
2698    /// `[serve.kv.slatedb]` — SlateDB-specific durability knobs (checkpoint cadence + close budget).
2699    /// Nested under `slatedb` (UX-C3) so they don't appear to apply under `--kv sql` / `--kv memory`.
2700    /// Absent ⇒ both defaults (checkpoint cadence ON, generous close budget).
2701    pub slatedb: Option<SlatedbKvConfig>,
2702    /// `[serve.kv.sql]` — the SQL KV backend's connection (`--kv sql`). Absent under `--kv sql` ⇒ the
2703    /// backend is configured entirely by the `BOATRAMP_KV_SQL_*` env (resolved at serve wiring).
2704    pub sql: Option<SqlKvConfig>,
2705}
2706
2707impl KvConfig {
2708    /// The resolved periodic-checkpoint interval (SlateDB): `None` ⇒ cadence DISABLED (explicit `0`);
2709    /// else the configured seconds, or [`DEFAULT_KV_CHECKPOINT_INTERVAL_SECS`] when unset/absent.
2710    pub fn checkpoint_interval(&self) -> Option<std::time::Duration> {
2711        match self.slatedb.as_ref().and_then(|s| s.checkpoint_interval) {
2712            Some(0) => None,
2713            Some(secs) => Some(std::time::Duration::from_secs(secs)),
2714            None => Some(std::time::Duration::from_secs(
2715                DEFAULT_KV_CHECKPOINT_INTERVAL_SECS,
2716            )),
2717        }
2718    }
2719
2720    /// The resolved graceful-close budget (SlateDB). A configured `0` (or unset/absent) falls back to
2721    /// [`DEFAULT_KV_CLOSE_DEADLINE_SECS`] — the budget must be positive so a genuinely-wedged close
2722    /// still cannot hang shutdown forever, while never being the too-tight 3s that caused the incident.
2723    pub fn close_deadline(&self) -> std::time::Duration {
2724        match self.slatedb.as_ref().and_then(|s| s.close_deadline) {
2725            Some(secs) if secs > 0 => std::time::Duration::from_secs(secs),
2726            _ => std::time::Duration::from_secs(DEFAULT_KV_CLOSE_DEADLINE_SECS),
2727        }
2728    }
2729}
2730
2731/// `[serve.kv.slatedb]` — control-plane SlateDB KV durability knobs (v0.9.0 KV-recovery). Both are
2732/// backstops/tuning: the crown-jewel per-write frontier-sync (C2) is unconditional and independent of
2733/// these. Absent ⇒ both defaults apply (checkpoint cadence ON, generous close budget). (v0.12.0 UX-C3:
2734/// MOVED here from the `[serve.kv]` top level so they do not appear to apply under a non-SlateDB
2735/// backend; with `deny_unknown_fields` a pre-v0.12.0 top-level knob now fails loud rather than
2736/// silently misleading.)
2737#[derive(Debug, Clone, Default, Deserialize)]
2738#[serde(default, deny_unknown_fields)]
2739pub struct SlatedbKvConfig {
2740    /// Periodic checkpoint cadence, seconds. Unset ⇒ [`DEFAULT_KV_CHECKPOINT_INTERVAL_SECS`] (ON).
2741    /// `0` DISABLES the cadence (the crown-jewel per-write frontier-sync still runs; only the
2742    /// backstop that bounds the loss window for derived/relaxed writes is off).
2743    pub checkpoint_interval: Option<u64>,
2744    /// Graceful drain+close budget, seconds. Unset ⇒ [`DEFAULT_KV_CLOSE_DEADLINE_SECS`]. `0` is
2745    /// rejected up to the default (a zero budget would abandon every close, guaranteeing a torn tail).
2746    pub close_deadline: Option<u64>,
2747}
2748
2749/// `[serve.kv.sql]` — the **SQL control-plane KV** backend connection (`--kv sql`). The connection
2750/// URL is NEVER written in the config (UX-C2): a bring-your-own / remote engine names the env var
2751/// holding it via [`url_env`](Self::url_env) (mirroring `ExternalDatabaseConfig`), while an embedded
2752/// single-node SQLite database names an on-disk file via [`path`](Self::path). Every field is also
2753/// settable by `BOATRAMP_KV_SQL_*` env (resolved at serve wiring). **This workstream (build-order
2754/// step 1) wires `sqlite` (libsql-local) only**; `postgres`/`mysql` are later workstreams.
2755#[derive(Debug, Clone, Default, Deserialize)]
2756#[serde(default, deny_unknown_fields)]
2757pub struct SqlKvConfig {
2758    /// Engine: `sqlite` (aliases `sqlite3`/`libsql`) — the embedded single-node file; `postgres`
2759    /// (aliases `postgresql`/`pg`) or `mysql` (alias `mariadb`) — the multi-writer engines (later
2760    /// workstreams), the same alias set as the `databases:` block. Empty ⇒ `sqlite`.
2761    pub kind: String,
2762    /// Name of the env var holding the connection URL (e.g. `postgres://…`, or a remote sqld URL) —
2763    /// NEVER a raw URL in the config. Unused for an embedded single-node `sqlite` database (which
2764    /// uses [`path`](Self::path)).
2765    pub url_env: Option<String>,
2766    /// On-disk file path for an embedded single-node `sqlite` KV (e.g. `/data/kv.db`). The parent
2767    /// directory is created if absent. Ignored for `postgres`/`mysql` and for a remote-sqld URL.
2768    pub path: Option<String>,
2769    /// Maximum pooled connections for a `postgres`/`mysql` KV (later workstreams). Ignored for the
2770    /// embedded `sqlite` path (one `Database` handle, connections opened per op).
2771    pub pool_max: Option<u32>,
2772}
2773
2774/// `[serve.s3_ingress_cloud]` — the cloud-brokering knobs for the M4 blob-upload minter (which native
2775/// credential the mint brokers when the node's blob backend is a cloud object store). Only the fields
2776/// for the active blob backend are consulted; a `None` here ⇒ the local S3 face mints.
2777#[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize)]
2778pub struct S3IngressCloud {
2779    /// **AWS**: the IAM role ARN the base credential assumes to broker the scoped session-policy
2780    /// credential (`sts:AssumeRole`, the default). Absent AND `aws_use_federation_token = true` ⇒
2781    /// `sts:GetFederationToken` is used instead (for an IAM-user base credential).
2782    pub aws_role_arn: Option<String>,
2783    /// **AWS**: use `sts:GetFederationToken` instead of `AssumeRole` (IAM-user deployments). Requires
2784    /// the base credential to be a real IAM user, not itself a session.
2785    #[serde(default)]
2786    pub aws_use_federation_token: bool,
2787    /// **AWS**: the S3-compatible backend has NO STS (Tigris/R2/MinIO): mint single-object presigned PUTs
2788    /// only. Prefix/multipart mints are refused (they require STS). Mutually exclusive with
2789    /// `aws_role_arn`/`aws_use_federation_token` (a misconfiguration that set both fails loud at wiring,
2790    /// never silently picks one). The presigned PUT is signed from the node's base S3 credential — the
2791    /// SAME source the S3 blob backend uses — so no new credential is needed. Default `false`.
2792    #[serde(default)]
2793    pub aws_presigned_only: bool,
2794    /// **GCS**: the service-account client email whose V4 signed URLs / IAM-signed uploads the minter
2795    /// produces (used in the signing scope). Absent ⇒ resolved from ADC.
2796    pub gcs_client_email: Option<String>,
2797    /// **Azure**: the storage account name (for the SAS signature + the blob URL). Absent ⇒ taken from
2798    /// the `azure_account` blob-backend arg.
2799    pub azure_account: Option<String>,
2800    /// **Azure**: the blob service URL (`https://{account}.blob.core.windows.net/`). Absent ⇒ derived
2801    /// from the account name.
2802    pub azure_service_url: Option<String>,
2803    /// **Azure**: declare the storage account has a **hierarchical namespace** (HNS/ADLS-Gen2). A
2804    /// directory-scoped SAS only actually confines to a sub-prefix on an HNS account; on a flat account
2805    /// it silently degrades to container-wide (Security LOW-1). So a PREFIX mint is refused unless this
2806    /// is `true`. Default `false` (fail-closed). A single-key mint is unaffected.
2807    #[serde(default)]
2808    pub azure_hns: bool,
2809}
2810
2811/// The default operator ceiling on a minted S3 upload credential's TTL when
2812/// `[serve].s3_ingress_mint_max_ttl_secs` is unset: 1 hour — long enough for a browser UGC upload or a
2813/// bulk-agent burst, short enough to bound a leaked short-lived credential.
2814pub const DEFAULT_S3_INGRESS_MINT_MAX_TTL_SECS: u64 = 3600;
2815
2816/// `[serve.console]` — the embedded web console (a Wasm SPA baked into the
2817/// binary with the `console` build feature). Opt-in: the static shell holds no
2818/// secrets and the `/api` it drives is token-gated, so it is served
2819/// **unauthenticated** at a deliberately obscure path (a bearer token can't gate
2820/// a top-level browser navigation anyway — the path is the obscurity, the token
2821/// is the real gate).
2822#[cfg_attr(not(feature = "console"), allow(dead_code))]
2823#[derive(Debug, Clone, Default, Deserialize)]
2824#[serde(default, deny_unknown_fields)]
2825pub struct ConsoleConfig {
2826    /// Serve the embedded console (default `false`). Requires the `console` build
2827    /// feature; enabling it in a build without that feature is a logged no-op.
2828    pub enabled: bool,
2829    /// Host(s) the console answers on: `*` (any host, the default), an exact host
2830    /// (`console.example.com`), or a leading-wildcard (`*.example.com`).
2831    pub host: Option<String>,
2832    /// URL path prefix the console mounts at (default `/_console`). Kept under the
2833    /// reserved `/_` namespace so it never collides with a published site path.
2834    pub path: Option<String>,
2835}
2836
2837/// `publish` section — where and what to deploy (the `sync` target).
2838#[derive(Debug, Default, Deserialize)]
2839#[serde(default)]
2840pub struct PublishConfig {
2841    /// Base URL of the boatramp server (e.g. `https://pad.example.com`).
2842    pub server: Option<String>,
2843    /// Site name to publish to.
2844    pub site: Option<String>,
2845    /// API token for the control plane (or set `BOATRAMP_TOKEN`).
2846    pub token: Option<String>,
2847    /// Project this site belongs to (overrides with `--project` / `BOATRAMP_PROJECT`).
2848    pub project: Option<String>,
2849}
2850
2851/// `build` section.
2852#[derive(Debug, Clone, Deserialize, serde::Serialize)]
2853pub struct BuildConfig {
2854    /// Shell command to run (e.g. `npm run build`).
2855    pub command: String,
2856    /// Directory the build emits, published by `sync` (e.g. `dist`).
2857    #[serde(default, skip_serializing_if = "Option::is_none")]
2858    pub output: Option<String>,
2859}
2860
2861/// `bundle` section — the in-process Rust bundler (`bundler` feature).
2862#[derive(Debug, Clone, Default, Deserialize)]
2863#[serde(default)]
2864pub struct BundleConfig {
2865    /// Output directory for bundled assets (e.g. `dist`).
2866    #[serde(default = "default_bundle_outdir")]
2867    pub outdir: String,
2868    /// JS/TS entry points bundled by Rolldown (tree-shaken, code-split).
2869    pub js: Vec<String>,
2870    /// CSS entry points bundled by lightningcss (`@import` inlined).
2871    pub css: Vec<String>,
2872    /// Minify output (default true).
2873    #[serde(default = "default_true")]
2874    pub minify: bool,
2875}
2876
2877fn default_bundle_outdir() -> String {
2878    "dist".to_string()
2879}
2880
2881fn default_true() -> bool {
2882    true
2883}
2884
2885#[cfg(test)]
2886mod tests {
2887    use super::*;
2888
2889    fn project(text: &str) -> ProjectConfig {
2890        ron_options().from_str(text).unwrap()
2891    }
2892
2893    fn server(text: &str) -> ServerConfig {
2894        ron_options().from_str(text).unwrap()
2895    }
2896
2897    /// Build an [`EnvSource::Map`] from `(name, value)` pairs for deterministic
2898    /// override tests (no process-global `std::env` mutation).
2899    fn env(pairs: &[(&str, &str)]) -> EnvSource {
2900        EnvSource::Map(
2901            pairs
2902                .iter()
2903                .map(|(k, v)| (k.to_string(), v.to_string()))
2904                .collect(),
2905        )
2906    }
2907
2908    #[test]
2909    fn env_overrides_configure_all_three_sections_with_no_file() {
2910        // The crux of the ask: with NO `boatramp.cfg` at all (the default config),
2911        // env vars alone materialise + populate the compute, security, and handler
2912        // `sql` sections. `ServerConfig::default()` has all three absent.
2913        let mut cfg = ServerConfig::default();
2914        assert!(cfg.compute.is_none() && cfg.security.is_none() && cfg.handlers.is_none());
2915
2916        cfg.apply_env_overrides(&env(&[
2917            ("BOATRAMP_COMPUTE_VCPUS", "8"),
2918            ("BOATRAMP_COMPUTE_MEM_MIB", "4096"),
2919            ("BOATRAMP_COMPUTE_REGION", "eu-central"),
2920            ("BOATRAMP_SECURITY_PROFILE", "single-tenant"),
2921            ("BOATRAMP_SECURITY_ALLOW_SITE_PRIVATE_UPSTREAMS", "true"),
2922            ("BOATRAMP_SECURITY_MAX_UPLOAD_BYTES", "1048576"),
2923            ("BOATRAMP_HANDLERS_SQL_URL", "http://sqld:8080"),
2924            ("BOATRAMP_HANDLERS_SQL_ADMIN_URL", "http://sqld:9090"),
2925        ]))
2926        .expect("valid env overrides apply");
2927
2928        // compute: the section now exists with the env values (and defaults elsewhere).
2929        let compute = cfg.compute.expect("compute materialised from env");
2930        assert_eq!(compute.vcpus, 8);
2931        assert_eq!(compute.mem_mib, 4096);
2932        assert_eq!(compute.region.as_deref(), Some("eu-central"));
2933        assert_eq!(compute.bridge, "br-boatramp"); // untouched default
2934
2935        // security: profile + an override both took, and the posture resolves.
2936        let security = cfg.security.expect("security materialised from env");
2937        assert_eq!(security.profile.as_deref(), Some("single-tenant"));
2938        let posture = security.resolve().expect("resolves");
2939        assert!(posture.allow_site_private_upstreams);
2940        assert_eq!(posture.max_upload_bytes, 1_048_576);
2941
2942        // handler sql: the nested handlers.bindings.sql chain was created.
2943        let sql = cfg
2944            .handlers
2945            .expect("handlers materialised from env")
2946            .bindings
2947            .sql
2948            .expect("sql binding materialised from env");
2949        assert_eq!(sql.url.as_deref(), Some("http://sqld:8080"));
2950        assert_eq!(sql.admin_url.as_deref(), Some("http://sqld:9090"));
2951    }
2952
2953    #[test]
2954    fn internal_dns_defaults_on_with_the_standard_upstream_and_domain() {
2955        // The `[compute]` defaults: internal DNS on, forwarding to 1.1.1.1:53, names
2956        // under `boatramp.internal`.
2957        let compute = ComputeConfig::default();
2958        assert!(compute.internal_dns, "internal DNS is on by default");
2959        assert_eq!(compute.dns_upstream, "1.1.1.1:53");
2960        assert_eq!(compute.dns_domain, "boatramp.internal");
2961    }
2962
2963    #[test]
2964    fn internal_dns_knobs_parse_from_a_file() {
2965        // A file can turn it off and override the upstream + domain.
2966        let cfg = server(
2967            r#"(
2968                compute: ( internal_dns: false, dns_upstream: "10.0.0.53:53", dns_domain: "svc.internal" ),
2969            )"#,
2970        );
2971        let compute = cfg.compute.expect("compute section");
2972        assert!(!compute.internal_dns);
2973        assert_eq!(compute.dns_upstream, "10.0.0.53:53");
2974        assert_eq!(compute.dns_domain, "svc.internal");
2975    }
2976
2977    #[test]
2978    fn internal_dns_knobs_are_env_settable() {
2979        // Env alone materialises `[compute]` and sets each internal-DNS knob (and an
2980        // unrecognised bool spelling is a clear error, exercised by parse_bool).
2981        let mut cfg = ServerConfig::default();
2982        cfg.apply_env_overrides(&env(&[
2983            ("BOATRAMP_COMPUTE_INTERNAL_DNS", "off"),
2984            ("BOATRAMP_COMPUTE_DNS_UPSTREAM", "9.9.9.9:53"),
2985            ("BOATRAMP_COMPUTE_DNS_DOMAIN", "corp.internal"),
2986        ]))
2987        .expect("valid env overrides apply");
2988        let compute = cfg.compute.expect("compute materialised from env");
2989        assert!(!compute.internal_dns, "env `off` disables internal DNS");
2990        assert_eq!(compute.dns_upstream, "9.9.9.9:53");
2991        assert_eq!(compute.dns_domain, "corp.internal");
2992    }
2993
2994    #[test]
2995    fn env_override_wins_over_file_value_but_unset_defers() {
2996        // A file that set each section; env then overrides one field per section
2997        // and leaves the rest of the file value in place (precedence: env > file).
2998        let mut cfg = server(
2999            r#"(
3000                compute: ( vcpus: 2, mem_mib: 512, region: "us-east" ),
3001                security: ( profile: "multi-tenant" ),
3002                handlers: ( bindings: ( sql: ( url: "http://file:8080", admin_url: "http://file:9090" ) ) ),
3003            )"#,
3004        );
3005
3006        cfg.apply_env_overrides(&env(&[
3007            ("BOATRAMP_COMPUTE_VCPUS", "16"),
3008            ("BOATRAMP_SECURITY_PROFILE", "dev"),
3009            ("BOATRAMP_HANDLERS_SQL_URL", "http://env:8080"),
3010        ]))
3011        .expect("valid env overrides apply");
3012
3013        let compute = cfg.compute.unwrap();
3014        assert_eq!(compute.vcpus, 16, "env wins over the file vcpus");
3015        assert_eq!(compute.mem_mib, 512, "unset env defers to the file mem_mib");
3016        assert_eq!(
3017            compute.region.as_deref(),
3018            Some("us-east"),
3019            "unset env defers to the file region"
3020        );
3021
3022        assert_eq!(
3023            cfg.security.unwrap().profile.as_deref(),
3024            Some("dev"),
3025            "env profile wins over the file profile"
3026        );
3027
3028        let sql = cfg.handlers.unwrap().bindings.sql.unwrap();
3029        assert_eq!(
3030            sql.url.as_deref(),
3031            Some("http://env:8080"),
3032            "env wins over the file sql url"
3033        );
3034        assert_eq!(
3035            sql.admin_url.as_deref(),
3036            Some("http://file:9090"),
3037            "unset env defers to the file sql admin_url"
3038        );
3039    }
3040
3041    #[test]
3042    fn env_overrides_leave_unmentioned_sections_absent() {
3043        // With no relevant env vars set, an empty config stays empty — the sections
3044        // are materialised only on demand, so an unset environment adds nothing.
3045        let mut cfg = ServerConfig::default();
3046        cfg.apply_env_overrides(&env(&[("SOME_UNRELATED_VAR", "x")]))
3047            .expect("no-op env applies");
3048        assert!(cfg.compute.is_none());
3049        assert!(cfg.security.is_none());
3050        assert!(cfg.handlers.is_none());
3051        assert!(cfg.secrets.is_none());
3052        assert!(cfg.cluster.is_none());
3053    }
3054
3055    #[test]
3056    fn env_bool_accepts_common_spellings_and_rejects_garbage() {
3057        // Truthy/falsey spellings all parse.
3058        for (raw, want) in [
3059            ("true", true),
3060            ("1", true),
3061            ("YES", true),
3062            ("On", true),
3063            ("false", false),
3064            ("0", false),
3065            ("no", false),
3066            ("OFF", false),
3067        ] {
3068            let mut cfg = ServerConfig::default();
3069            cfg.apply_env_overrides(&env(&[("BOATRAMP_SECURITY_REQUIRE_POP", raw)]))
3070                .expect("boolean parses");
3071            assert_eq!(
3072                cfg.security.unwrap().overrides.require_pop,
3073                Some(want),
3074                "{raw:?} ⇒ {want}"
3075            );
3076        }
3077        // A non-boolean value is a clear error, not a silent default.
3078        let mut cfg = ServerConfig::default();
3079        let err = cfg
3080            .apply_env_overrides(&env(&[("BOATRAMP_SECURITY_REQUIRE_POP", "maybe")]))
3081            .expect_err("garbage boolean is rejected");
3082        match err {
3083            ConfigError::Env { var, .. } => assert_eq!(var, "BOATRAMP_SECURITY_REQUIRE_POP"),
3084            other => panic!("expected ConfigError::Env, got {other:?}"),
3085        }
3086    }
3087
3088    #[test]
3089    fn env_number_parse_error_names_the_variable() {
3090        // A non-numeric numeric var is rejected with the variable named.
3091        let mut cfg = ServerConfig::default();
3092        let err = cfg
3093            .apply_env_overrides(&env(&[("BOATRAMP_COMPUTE_VCPUS", "lots")]))
3094            .expect_err("garbage number is rejected");
3095        match err {
3096            ConfigError::Env { var, .. } => assert_eq!(var, "BOATRAMP_COMPUTE_VCPUS"),
3097            other => panic!("expected ConfigError::Env, got {other:?}"),
3098        }
3099    }
3100
3101    #[test]
3102    fn empty_env_value_is_treated_as_unset() {
3103        // `VAR=` (empty) must not clobber a file value with an empty string.
3104        let mut cfg = server(r#"( compute: ( region: "us-east" ) )"#);
3105        cfg.apply_env_overrides(&env(&[("BOATRAMP_COMPUTE_REGION", "")]))
3106            .expect("empty env applies as a no-op");
3107        assert_eq!(
3108            cfg.compute.unwrap().region.as_deref(),
3109            Some("us-east"),
3110            "an empty env value leaves the file value in place"
3111        );
3112    }
3113
3114    #[test]
3115    fn env_configures_managed_postgres_secrets_and_privilege_with_no_file() {
3116        // The construens acceptance case: with NO `boatramp.cfg` at all, the
3117        // environment alone stands up a managed co-located Postgres. It configures
3118        // the default (`"default"`-named, v0.5.0) database in
3119        // `handlers.bindings.sql.databases` (kind=postgres, compute=pg, database+user
3120        // set), the `[secrets]` envelope (local + a kek path so the managed credential
3121        // can be sealed), and `compute.managed_db_privilege = rootless`. All three
3122        // sections start absent.
3123        let mut cfg = ServerConfig::default();
3124        assert!(cfg.handlers.is_none() && cfg.secrets.is_none() && cfg.compute.is_none());
3125
3126        cfg.apply_env_overrides(&env(&[
3127            // The default database is addressed by the reserved `DEFAULT` token,
3128            // which maps to the reserved real name `"default"` (v0.5.0).
3129            ("BOATRAMP_HANDLERS_SQL_DB_DEFAULT_KIND", "postgres"),
3130            ("BOATRAMP_HANDLERS_SQL_DB_DEFAULT_COMPUTE", "pg"),
3131            ("BOATRAMP_HANDLERS_SQL_DB_DEFAULT_DATABASE", "appdb"),
3132            ("BOATRAMP_HANDLERS_SQL_DB_DEFAULT_USER", "app"),
3133            // Secrets: the local envelope + a KEK path (never key material).
3134            ("BOATRAMP_SECRETS_ENVELOPE", "local"),
3135            ("BOATRAMP_SECRETS_KEK_FILE", "/var/lib/boatramp/secrets/kek"),
3136            // The shared-kernel DB privilege strategy.
3137            ("BOATRAMP_COMPUTE_MANAGED_DB_PRIVILEGE", "rootless"),
3138        ]))
3139        .expect("valid env overrides apply");
3140
3141        // The default (`"default"`-keyed) managed database exists with the right source.
3142        let sql = cfg
3143            .handlers
3144            .expect("handlers materialised from env")
3145            .bindings
3146            .sql
3147            .expect("sql binding materialised from env");
3148        let db = sql
3149            .databases
3150            .get(boatramp_core::project::DEFAULT_DB_NAME)
3151            .expect("the default `default`-named database was created from DEFAULT");
3152        assert!(
3153            !sql.databases.contains_key(""),
3154            "the empty-string key is never produced (v0.5.0)"
3155        );
3156        assert_eq!(db.kind, "postgres");
3157        assert_eq!(db.compute.as_deref(), Some("pg"));
3158        assert_eq!(db.database.as_deref(), Some("appdb"));
3159        assert_eq!(db.user.as_deref(), Some("app"));
3160        // No `password_env` ⇒ boatramp manages the credential (Phase 2), and the
3161        // compute-backed source validates.
3162        assert!(db.password_env.is_none());
3163        assert!(db.is_managed_credential());
3164        assert!(db.validate("").is_ok());
3165
3166        // The secrets envelope + KEK path took (the path is a location, not a key).
3167        let secrets = cfg.secrets.expect("secrets materialised from env");
3168        assert_eq!(secrets.envelope, "local");
3169        assert_eq!(
3170            secrets.kek_file.as_deref(),
3171            Some(Path::new("/var/lib/boatramp/secrets/kek"))
3172        );
3173        assert!(
3174            secrets.vault.is_none(),
3175            "no vault vars ⇒ no vault sub-config"
3176        );
3177
3178        // The managed-DB privilege strategy resolved from its lowercase variant.
3179        let compute = cfg.compute.expect("compute materialised from env");
3180        assert_eq!(compute.managed_db_privilege, ManagedDbPrivilege::Rootless);
3181    }
3182
3183    #[test]
3184    fn env_declares_named_databases_and_merges_over_the_file() {
3185        // A file declares one database; the env overrides one of its fields and
3186        // ADDS a second, discovering both member names from the environment.
3187        let mut cfg = server(
3188            r#"(
3189                handlers: ( bindings: ( sql: (
3190                    databases: {
3191                        "analytics": ( kind: "postgres", url_env: "FILE_PG_URL", pool_max: 4 ),
3192                    },
3193                ) ) ),
3194            )"#,
3195        );
3196        cfg.apply_env_overrides(&env(&[
3197            // Override the file database's pool size (merge by key, per field).
3198            ("BOATRAMP_HANDLERS_SQL_DB_analytics_POOL_MAX", "32"),
3199            // Add a brand-new database whose name has an underscore, exercising the
3200            // longest-suffix name isolation (`_READ_URL_ENV`, not `_URL_ENV`).
3201            ("BOATRAMP_HANDLERS_SQL_DB_events_log_KIND", "mysql"),
3202            ("BOATRAMP_HANDLERS_SQL_DB_events_log_URL_ENV", "EVENTS_URL"),
3203            (
3204                "BOATRAMP_HANDLERS_SQL_DB_events_log_READ_URL_ENV",
3205                "EVENTS_RO_URL",
3206            ),
3207            ("BOATRAMP_HANDLERS_SQL_DB_events_log_READ_ONLY", "true"),
3208        ]))
3209        .expect("valid env overrides apply");
3210
3211        let sql = cfg.handlers.unwrap().bindings.sql.unwrap();
3212        assert_eq!(sql.databases.len(), 2);
3213
3214        let analytics = &sql.databases["analytics"];
3215        assert_eq!(
3216            analytics.pool_max,
3217            Some(32),
3218            "env pool_max wins over the file"
3219        );
3220        assert_eq!(
3221            analytics.url_env, "FILE_PG_URL",
3222            "the file's url_env survives (env didn't touch it)"
3223        );
3224
3225        let events = &sql.databases["events_log"];
3226        assert_eq!(events.kind, "mysql");
3227        assert_eq!(events.url_env, "EVENTS_URL");
3228        assert_eq!(events.read_url_env.as_deref(), Some("EVENTS_RO_URL"));
3229        assert!(events.read_only);
3230    }
3231
3232    #[test]
3233    fn default_token_maps_to_the_reserved_default_name_not_empty() {
3234        // v0.5.0 breaking change: the reserved `DEFAULT` env token maps to the real
3235        // name `"default"` (a valid URL path segment), never the empty string. This is
3236        // what makes the default binding addressable as `--db default` and keeps every
3237        // db-name ingress path-segment-safe.
3238        let mut cfg = ServerConfig::default();
3239        cfg.apply_env_overrides(&env(&[
3240            ("BOATRAMP_HANDLERS_SQL_DB_DEFAULT_KIND", "postgres"),
3241            ("BOATRAMP_HANDLERS_SQL_DB_DEFAULT_URL_ENV", "PG_URL"),
3242        ]))
3243        .expect("valid env overrides apply");
3244        let databases = cfg.handlers.unwrap().bindings.sql.unwrap().databases;
3245        assert!(
3246            databases.contains_key(boatramp_core::project::DEFAULT_DB_NAME),
3247            "DEFAULT → the reserved `default` key"
3248        );
3249        assert!(
3250            !databases.contains_key(""),
3251            "the empty-string key is never produced"
3252        );
3253    }
3254
3255    #[test]
3256    fn empty_string_db_binding_name_is_rejected_with_a_cure() {
3257        // A `boatramp.cfg` that literally writes the legacy empty-string default key
3258        // fails closed on load (it would emit a `//` control-plane path), and the
3259        // error points at the cure (`default`).
3260        let err = ServerConfig::parse(
3261            r#"(
3262                handlers: ( bindings: ( sql: (
3263                    databases: {
3264                        "": ( kind: "postgres", url_env: "PG_URL" ),
3265                    },
3266                ) ) ),
3267            )"#,
3268        )
3269        .expect_err("an empty-string db binding name is refused");
3270        match err {
3271            ConfigError::InvalidDbName { name, reason, cure } => {
3272                assert_eq!(name, "");
3273                assert!(reason.contains("empty"), "reason names the emptiness");
3274                assert!(
3275                    cure.contains("default") && cure.contains("CHANGELOG"),
3276                    "the cure points at `default` + the CHANGELOG"
3277                );
3278            }
3279            other => panic!("expected ConfigError::InvalidDbName, got {other:?}"),
3280        }
3281    }
3282
3283    #[test]
3284    fn path_separator_db_binding_name_is_rejected() {
3285        // A non-slug name (contains `/`) is refused with the v0.7.0 slug reason and the
3286        // slug cure (pointing at `project doctor`) — NOT the empty-default cure (the fix
3287        // is to rename it to a valid slug, not adopt `default`). Boot-LOUD.
3288        let err = ServerConfig::parse(
3289            r#"(
3290                handlers: ( bindings: ( sql: (
3291                    databases: {
3292                        "a/b": ( kind: "postgres", url_env: "PG_URL" ),
3293                    },
3294                ) ) ),
3295            )"#,
3296        )
3297        .expect_err("a `/`-bearing db binding name is refused");
3298        match err {
3299            ConfigError::InvalidDbName { name, reason, cure } => {
3300                assert_eq!(name, "a/b");
3301                // The v0.7.0 slug reason (a positive statement of the allowlist).
3302                assert!(
3303                    reason.contains("valid slug"),
3304                    "reason states the slug rule, got {reason:?}"
3305                );
3306                // The slug cure points at `project doctor`, not the empty-default cure.
3307                assert_eq!(cure, boatramp_core::project::INVALID_NAME_CURE);
3308                assert!(!cure.contains("CHANGELOG"), "not the empty-default cure");
3309            }
3310            other => panic!("expected ConfigError::InvalidDbName, got {other:?}"),
3311        }
3312    }
3313
3314    #[test]
3315    fn reserved_bramp_db_compute_prefix_is_rejected() {
3316        // #501 Stage B LOW-2: a static BYO binding may not point `compute` at a
3317        // `bramp-db-…` workload (reserved for derived managed-DB servers) — refused
3318        // fail-closed at config load.
3319        let err = ServerConfig::parse(
3320            r#"(
3321                handlers: ( bindings: ( sql: (
3322                    databases: {
3323                        "byo": ( kind: "postgres", compute: "bramp-db-acme-app", database: "d", user: "u" ),
3324                    },
3325                ) ) ),
3326            )"#,
3327        )
3328        .expect_err("a `bramp-db-` compute workload is refused");
3329        match err {
3330            ConfigError::InvalidDbName { name, reason, cure } => {
3331                assert_eq!(name, "bramp-db-acme-app");
3332                assert!(reason.contains("reserved"), "reason names the reservation");
3333                assert!(cure.contains("bramp-db-"), "the cure names the prefix");
3334            }
3335            other => panic!("expected ConfigError::InvalidDbName, got {other:?}"),
3336        }
3337        // A NON-reserved compute workload for a BYO binding still loads fine.
3338        ServerConfig::parse(
3339            r#"(
3340                handlers: ( bindings: ( sql: (
3341                    databases: {
3342                        "byo": ( kind: "postgres", compute: "my-pg", database: "d", user: "u" ),
3343                    },
3344                ) ) ),
3345            )"#,
3346        )
3347        .expect("a non-reserved compute workload loads");
3348    }
3349
3350    #[test]
3351    fn env_sets_managed_db_startup_grace() {
3352        // The per-binding startup-grace override is env-settable like the other
3353        // managed scalars, discovered by the `_STARTUP_GRACE_SECS` suffix.
3354        let mut cfg = ServerConfig::default();
3355        cfg.apply_env_overrides(&env(&[
3356            ("BOATRAMP_HANDLERS_SQL_DB_DEFAULT_KIND", "postgres"),
3357            ("BOATRAMP_HANDLERS_SQL_DB_DEFAULT_COMPUTE", "pg"),
3358            ("BOATRAMP_HANDLERS_SQL_DB_DEFAULT_DATABASE", "appdb"),
3359            ("BOATRAMP_HANDLERS_SQL_DB_DEFAULT_USER", "app"),
3360            ("BOATRAMP_HANDLERS_SQL_DB_DEFAULT_STARTUP_GRACE_SECS", "90"),
3361        ]))
3362        .expect("valid env overrides apply");
3363        let db = &cfg.handlers.unwrap().bindings.sql.unwrap().databases
3364            [boatramp_core::project::DEFAULT_DB_NAME];
3365        assert_eq!(db.startup_grace_secs, Some(90));
3366    }
3367
3368    #[test]
3369    fn env_sets_rls_gucs_and_all_marker_without_suffix_collision() {
3370        // The RLS GUC names + the v0.4.21 all-read marker are env-settable. `_TENANT_ALL_MARKER`
3371        // and `_TENANT_GUC` must NOT be shadowed by the shorter `_TENANT` suffix (longest-first
3372        // isolation) — a `_TENANT` value would otherwise swallow the DB-name split.
3373        let mut cfg = ServerConfig::default();
3374        cfg.apply_env_overrides(&env(&[
3375            ("BOATRAMP_HANDLERS_SQL_DB_DEFAULT_KIND", "postgres"),
3376            ("BOATRAMP_HANDLERS_SQL_DB_DEFAULT_DATABASE", "appdb"),
3377            (
3378                "BOATRAMP_HANDLERS_SQL_DB_DEFAULT_TENANT_GUC",
3379                "app.tenant_id",
3380            ),
3381            (
3382                "BOATRAMP_HANDLERS_SQL_DB_DEFAULT_SESSION_GUC",
3383                "app.session_id",
3384            ),
3385            ("BOATRAMP_HANDLERS_SQL_DB_DEFAULT_TENANT_ALL_MARKER", "*"),
3386        ]))
3387        .expect("valid env overrides apply");
3388        let db = &cfg.handlers.unwrap().bindings.sql.unwrap().databases
3389            [boatramp_core::project::DEFAULT_DB_NAME];
3390        assert_eq!(db.tenant_guc.as_deref(), Some("app.tenant_id"));
3391        assert_eq!(db.session_guc.as_deref(), Some("app.session_id"));
3392        assert_eq!(db.tenant_all_marker.as_deref(), Some("*"));
3393    }
3394
3395    #[test]
3396    fn env_enum_parse_error_names_the_variable_and_variants() {
3397        // An unknown enum value is a clear error that names the offending variable.
3398        let mut cfg = ServerConfig::default();
3399        let err = cfg
3400            .apply_env_overrides(&env(&[(
3401                "BOATRAMP_COMPUTE_MANAGED_DB_PRIVILEGE",
3402                "superuser",
3403            )]))
3404            .expect_err("unknown enum variant is rejected");
3405        match err {
3406            ConfigError::Env { var, reason } => {
3407                assert_eq!(var, "BOATRAMP_COMPUTE_MANAGED_DB_PRIVILEGE");
3408                assert!(reason.contains("rootless") && reason.contains("caps"));
3409            }
3410            other => panic!("expected ConfigError::Env, got {other:?}"),
3411        }
3412        // The docker enums map their lowercase serde variants too.
3413        let mut cfg = ServerConfig::default();
3414        cfg.apply_env_overrides(&env(&[
3415            ("BOATRAMP_COMPUTE_DOCKER_ENDPOINT", "bridge"),
3416            ("BOATRAMP_COMPUTE_DOCKER_VOLUME_MODE", "bind"),
3417        ]))
3418        .expect("known enum variants parse");
3419        let compute = cfg.compute.unwrap();
3420        assert_eq!(
3421            compute.docker_endpoint,
3422            boatramp_docker::DockerEndpoint::Bridge
3423        );
3424        assert_eq!(
3425            compute.docker_volume_mode,
3426            boatramp_docker::DockerVolumeMode::Bind
3427        );
3428    }
3429
3430    #[test]
3431    fn env_trust_anchors_parse_as_a_comma_separated_list() {
3432        // The kernel trust anchors are comma-separated (whitespace trimmed, empty
3433        // items dropped so a trailing comma is tolerated). A file default is
3434        // fully replaced, not appended to.
3435        let mut cfg = ServerConfig::default();
3436        cfg.apply_env_overrides(&env(&[
3437            (
3438                "BOATRAMP_COMPUTE_KERNEL_SIGNING_PUBKEYS",
3439                " es256:aa , es256:bb ,",
3440            ),
3441            ("BOATRAMP_COMPUTE_KERNEL_ALLOWED_HASHES", "deadbeef"),
3442        ]))
3443        .expect("valid list env applies");
3444        let compute = cfg.compute.unwrap();
3445        assert_eq!(
3446            compute.kernel_signing_pubkeys,
3447            vec!["es256:aa".to_string(), "es256:bb".to_string()],
3448            "trimmed, comma-split, trailing-empty dropped, defaults replaced"
3449        );
3450        assert_eq!(
3451            compute.kernel_allowed_hashes,
3452            vec!["deadbeef".to_string()],
3453            "a single value is a one-element list"
3454        );
3455    }
3456
3457    #[test]
3458    fn env_configures_secrets_vault_subconfig() {
3459        // The vault sub-config materialises only when a vault var is set, and the
3460        // token stays indirected via a variable NAME (`token_env`), never inline.
3461        let mut cfg = ServerConfig::default();
3462        cfg.apply_env_overrides(&env(&[
3463            ("BOATRAMP_SECRETS_ENVELOPE", "vault"),
3464            ("BOATRAMP_SECRETS_VAULT_ADDR", "https://vault:8200"),
3465            ("BOATRAMP_SECRETS_VAULT_KEY", "certs"),
3466        ]))
3467        .expect("valid env overrides apply");
3468        let secrets = cfg.secrets.unwrap();
3469        assert_eq!(secrets.envelope, "vault");
3470        let vault = secrets.vault.expect("vault sub-config materialised");
3471        assert_eq!(vault.addr, "https://vault:8200");
3472        assert_eq!(vault.key, "certs");
3473        // token_env defaults to VAULT_TOKEN when not overridden.
3474        assert_eq!(vault.token_env, "VAULT_TOKEN");
3475    }
3476
3477    #[test]
3478    fn env_materialises_and_overrides_the_cluster_section() {
3479        // With no file, a `BOATRAMP_CLUSTER_LISTEN` materialises the section; the
3480        // remaining fields (lists, join token, mesh) layer on. The founding/joining
3481        // action flags (`BOATRAMP_CLUSTER_INIT`/`_JOIN`) are separate `serve` args
3482        // and are not part of this section.
3483        let mut cfg = ServerConfig::default();
3484        cfg.apply_env_overrides(&env(&[
3485            ("BOATRAMP_CLUSTER_LISTEN", "10.0.0.2:7000"),
3486            ("BOATRAMP_CLUSTER_ROOT_PUBKEYS", "es256:aa,es256:bb"),
3487            ("BOATRAMP_CLUSTER_SEEDS", "https://10.0.0.1:8080"),
3488            ("BOATRAMP_CLUSTER_JOIN_TOKEN", "env:BOATRAMP_JOIN_TOKEN"),
3489            ("BOATRAMP_CLUSTER_STORE_DIR", "/var/lib/boatramp/raft"),
3490            ("BOATRAMP_CLUSTER_MESH_GATE_CLIENT_WRITES", "true"),
3491        ]))
3492        .expect("valid env overrides apply");
3493        let cluster = cfg.cluster.expect("cluster materialised from env");
3494        assert_eq!(
3495            cluster.listen,
3496            "10.0.0.2:7000".parse::<std::net::SocketAddr>().unwrap()
3497        );
3498        assert_eq!(
3499            cluster.root_pubkeys,
3500            vec!["es256:aa".to_string(), "es256:bb".to_string()]
3501        );
3502        assert_eq!(cluster.seeds, vec!["https://10.0.0.1:8080".to_string()]);
3503        assert_eq!(
3504            cluster.join_token.as_deref(),
3505            Some("env:BOATRAMP_JOIN_TOKEN")
3506        );
3507        assert_eq!(
3508            cluster.store_dir.as_deref(),
3509            Some(Path::new("/var/lib/boatramp/raft"))
3510        );
3511        assert_eq!(
3512            cluster.mesh.expect("mesh sub-config").gate_client_writes,
3513            Some(true)
3514        );
3515
3516        // Without a listen (and no file section) there is nothing to materialise:
3517        // a non-listen cluster var alone leaves the section absent.
3518        let mut cfg = ServerConfig::default();
3519        cfg.apply_env_overrides(&env(&[("BOATRAMP_CLUSTER_SEEDS", "https://10.0.0.1:8080")]))
3520            .expect("applies");
3521        assert!(
3522            cfg.cluster.is_none(),
3523            "no listen + no file section ⇒ no cluster"
3524        );
3525    }
3526
3527    #[test]
3528    fn env_cluster_listen_overrides_a_file_section() {
3529        // A file `[cluster]` section: env overrides `listen` and adds seeds.
3530        let mut cfg = server(r#"( cluster: ( listen: "0.0.0.0:7000" ) )"#);
3531        cfg.apply_env_overrides(&env(&[
3532            ("BOATRAMP_CLUSTER_LISTEN", "10.0.0.9:7000"),
3533            ("BOATRAMP_CLUSTER_SEEDS", "https://seed:8080"),
3534        ]))
3535        .expect("applies");
3536        let cluster = cfg.cluster.unwrap();
3537        assert_eq!(
3538            cluster.listen,
3539            "10.0.0.9:7000".parse::<std::net::SocketAddr>().unwrap(),
3540            "env listen wins over the file"
3541        );
3542        assert_eq!(cluster.seeds, vec!["https://seed:8080".to_string()]);
3543    }
3544
3545    #[test]
3546    fn empty_project_config_is_default() {
3547        let cfg = project("()");
3548        assert!(cfg.publish.server.is_none());
3549        assert!(cfg.publish.site.is_none());
3550        assert!(cfg.build.is_none());
3551        assert!(cfg.bundle.is_none());
3552        // Routing defaults: schema v1, the single default index candidate.
3553        assert_eq!(cfg.routing.version, 1);
3554        assert_eq!(cfg.routing.index, vec!["index.html".to_string()]);
3555    }
3556
3557    #[test]
3558    fn serve_signer_config_parses_and_maps_each_backend() {
3559        use boatramp_core::cose::TokenAlg;
3560        use boatramp_server::signer::SignerConfig;
3561
3562        // RON-native enum tagging (`Vault(...)`); `IMPLICIT_SOME` lets the optional
3563        // fields (region) take a bare value or be omitted (→ None). This is the
3564        // exact RON documented in the Authentication guide.
3565        let vault = server(
3566            r#"( serve: ( signer: Vault(
3567                address: "https://vault.example:8200",
3568                key: "boatramp-root",
3569                token_env: "VAULT_TOKEN",
3570                alg: Ed25519,
3571            ) ) )"#,
3572        );
3573        match vault.serve.unwrap().signer.unwrap().to_signer_config() {
3574            SignerConfig::Vault {
3575                address,
3576                key,
3577                token_env,
3578                alg,
3579            } => {
3580                assert_eq!(address, "https://vault.example:8200");
3581                assert_eq!(key, "boatramp-root");
3582                assert_eq!(token_env, "VAULT_TOKEN");
3583                assert_eq!(alg, TokenAlg::Ed25519);
3584            }
3585            other => panic!("expected Vault, got {other:?}"),
3586        }
3587
3588        // AWS KMS: region omitted → None; PKCS#11: alg omitted → the ES256 default.
3589        let aws =
3590            server(r#"( serve: ( signer: AwsKms(key_id: "arn:aws:kms:eu-west-1:1:key/abc") ) )"#);
3591        assert!(matches!(
3592            aws.serve.unwrap().signer.unwrap().to_signer_config(),
3593            SignerConfig::AwsKms { region: None, .. }
3594        ));
3595
3596        let hsm = server(
3597            r#"( serve: ( signer: Pkcs11(
3598                module: "/usr/lib/softhsm/libsofthsm2.so",
3599                token_label: "boatramp",
3600                key_label: "root",
3601                pin_env: "HSM_PIN",
3602            ) ) )"#,
3603        );
3604        match hsm.serve.unwrap().signer.unwrap().to_signer_config() {
3605            SignerConfig::Pkcs11 { alg, .. } => assert_eq!(alg, TokenAlg::Es256),
3606            other => panic!("expected Pkcs11, got {other:?}"),
3607        }
3608    }
3609
3610    #[test]
3611    fn project_config_parses_publish_build_and_routing() {
3612        let cfg = project(
3613            r#"(
3614                publish: ( server: "http://127.0.0.1:8080", site: "demo" ),
3615                build: ( command: "npm run build", output: "dist" ),
3616                routing: (
3617                    clean_urls: true,
3618                    redirects: [ (from: "/old/:slug", to: "/new/:slug", status: 301) ],
3619                ),
3620            )"#,
3621        );
3622        assert_eq!(cfg.publish.server.as_deref(), Some("http://127.0.0.1:8080"));
3623        assert_eq!(cfg.publish.site.as_deref(), Some("demo"));
3624        let build = cfg.build.unwrap();
3625        assert_eq!(build.command, "npm run build");
3626        assert_eq!(build.output.as_deref(), Some("dist"));
3627        assert!(cfg.routing.clean_urls);
3628        assert_eq!(cfg.routing.redirects.len(), 1);
3629        assert_eq!(cfg.routing.redirects[0].status, 301);
3630    }
3631
3632    #[test]
3633    fn project_config_rejects_bad_routing_pattern() {
3634        // The same compile-check `load` runs: a bad route pattern is an error.
3635        let cfg = project(r#"( routing: ( redirects: [ (from: "/a/**/b/**", to: "/x") ] ) )"#);
3636        assert!(cfg.routing.compile_check().is_err());
3637    }
3638
3639    #[test]
3640    fn empty_server_config_has_no_sections() {
3641        let cfg = server("()");
3642        assert!(cfg.serve.is_none());
3643        assert!(cfg.handlers.is_none());
3644        assert!(cfg.cluster.is_none());
3645        assert!(cfg.security.is_none());
3646    }
3647
3648    #[test]
3649    fn security_section_parses_and_resolves() {
3650        // A profile plus an override that wins over it.
3651        let cfg = server(
3652            r#"(
3653                security: (
3654                    profile: "dev",
3655                    overrides: (
3656                        oidc_require_audience: true,
3657                        max_upload_bytes: 0,
3658                    ),
3659                )
3660            )"#,
3661        );
3662        let posture = cfg.security.unwrap().resolve().expect("resolves");
3663        // `dev` is loose...
3664        assert!(posture.allow_unauthenticated_public_bind);
3665        // ...but the explicit override wins over the profile.
3666        assert!(posture.oidc_require_audience);
3667        assert_eq!(posture.max_upload_bytes, 0); // unlimited
3668    }
3669
3670    #[test]
3671    fn env_wires_allow_env_secret_refs_over_the_multi_tenant_default() {
3672        // With no file, the multi-tenant default leaves host-env secret refs off;
3673        // the env knob re-enables them (env > default), same as the other posture bools.
3674        let mut cfg = ServerConfig::default();
3675        cfg.apply_env_overrides(&env(&[("BOATRAMP_SECURITY_ALLOW_ENV_SECRET_REFS", "true")]))
3676            .expect("valid env override applies");
3677        let posture = cfg
3678            .security
3679            .expect("security materialised from env")
3680            .resolve()
3681            .expect("resolves");
3682        assert!(posture.allow_env_secret_refs);
3683    }
3684
3685    #[test]
3686    fn env_wires_the_multi_tenant_subknobs_over_the_default() {
3687        // Gap 4b: the four multi-tenant sub-knobs were file-only; env now sets them (env > the
3688        // multi-tenant preset default), so a 12-factor deploy can tune tenancy isolation + guest
3689        // capability minting with no `boatramp.cfg`. Verified: strict declaration stays on while
3690        // cross-tenant `all` twins + guest cap-mint are permitted (they compose — Gap 4.3).
3691        let mut cfg = ServerConfig::default();
3692        cfg.apply_env_overrides(&env(&[
3693            ("BOATRAMP_SECURITY_PROFILE", "multi-tenant"),
3694            ("BOATRAMP_SECURITY_REQUIRE_TENANCY_DECLARATION", "true"),
3695            ("BOATRAMP_SECURITY_ALLOW_CROSS_TENANT_DB", "true"),
3696            ("BOATRAMP_SECURITY_ALLOW_GUEST_MINT_CAPABILITY", "true"),
3697            ("BOATRAMP_SECURITY_MAX_GUEST_CAPABILITY_TTL_SECS", "1800"),
3698        ]))
3699        .expect("valid env overrides apply");
3700        let posture = cfg
3701            .security
3702            .expect("security materialised from env")
3703            .resolve()
3704            .expect("resolves");
3705        assert!(posture.require_tenancy_declaration);
3706        assert!(posture.allow_cross_tenant_db);
3707        assert!(posture.allow_guest_mint_capability);
3708        assert_eq!(posture.max_guest_capability_ttl_secs, 1800);
3709    }
3710
3711    #[test]
3712    fn env_wires_the_remaining_guest_feature_knobs_over_the_multi_tenant_default() {
3713        // v0.4.18 env parity: `allow_guest_email` (which regressed prod SMTP on the P48 cutover —
3714        // multi-tenant defaults it OFF and there was no env lever), its egress sibling
3715        // `allow_guest_egress_extra_ca` (shipped config-only in v0.4.17), and the four
3716        // `allow_guest_admin_*` self-config knobs were all missing from the env map. Each preset
3717        // defaults them OFF under `multi-tenant`; the env knob must now flip each back on for a
3718        // 12-factor env-only fleet, exactly like `allow_guest_mint_capability`.
3719        let mut cfg = ServerConfig::default();
3720        cfg.apply_env_overrides(&env(&[
3721            ("BOATRAMP_SECURITY_PROFILE", "multi-tenant"),
3722            ("BOATRAMP_SECURITY_ALLOW_GUEST_EMAIL", "true"),
3723            ("BOATRAMP_SECURITY_ALLOW_GUEST_EGRESS_EXTRA_CA", "true"),
3724            ("BOATRAMP_SECURITY_ALLOW_GUEST_ADMIN_DOMAINS", "true"),
3725            ("BOATRAMP_SECURITY_ALLOW_GUEST_ADMIN_EMAIL", "true"),
3726            ("BOATRAMP_SECURITY_ALLOW_GUEST_ADMIN_SITE", "true"),
3727            ("BOATRAMP_SECURITY_ALLOW_GUEST_ADMIN_SECRETS", "true"),
3728        ]))
3729        .expect("valid env overrides apply");
3730        let security = cfg.security.expect("security materialised from env");
3731        let posture = security.resolve().expect("resolves");
3732        // Every one flips on over the multi-tenant preset default (which is `false` for all six).
3733        assert!(posture.allow_guest_email, "guest email re-enabled via env");
3734        assert!(posture.allow_guest_egress_extra_ca);
3735        assert!(posture.allow_guest_admin_domains);
3736        assert!(posture.allow_guest_admin_email);
3737        assert!(posture.allow_guest_admin_site);
3738        assert!(posture.allow_guest_admin_secrets);
3739        // `security explain` attributes each to the override/env source (not the profile preset).
3740        let explained = security.explain().expect("explains");
3741        for knob in [
3742            "allow_guest_email",
3743            "allow_guest_egress_extra_ca",
3744            "allow_guest_admin_domains",
3745            "allow_guest_admin_email",
3746            "allow_guest_admin_site",
3747            "allow_guest_admin_secrets",
3748        ] {
3749            assert!(
3750                explained
3751                    .lines()
3752                    .any(|l| l.contains(knob) && l.contains("true") && l.contains("(override)")),
3753                "explain shows {knob} = true (override): \n{explained}"
3754            );
3755        }
3756    }
3757
3758    #[test]
3759    fn each_guest_feature_env_var_moves_its_own_posture_field() {
3760        // Cross-wiring guard: set each of the guest-feature vars ALONE over the multi-tenant
3761        // default and assert THAT var's own resolved field flips — so a copy-paste arm mapping a var
3762        // to the wrong field (or an unregistered var that never materialises the section) fails here.
3763        // Complements `every_posture_override_field_has_an_env_mapping` below (which proves coverage
3764        // by field name but not that each arm targets the right field).
3765        for (var, check) in [
3766            (
3767                "BOATRAMP_SECURITY_ALLOW_GUEST_EMAIL",
3768                (|p: &boatramp_core::security::SecurityPosture| p.allow_guest_email)
3769                    as fn(&boatramp_core::security::SecurityPosture) -> bool,
3770            ),
3771            ("BOATRAMP_SECURITY_ALLOW_GUEST_EGRESS_EXTRA_CA", |p| {
3772                p.allow_guest_egress_extra_ca
3773            }),
3774            ("BOATRAMP_SECURITY_ALLOW_GUEST_TCP_EGRESS", |p| {
3775                p.allow_guest_tcp_egress
3776            }),
3777            ("BOATRAMP_SECURITY_ALLOW_GUEST_ADMIN_DOMAINS", |p| {
3778                p.allow_guest_admin_domains
3779            }),
3780            ("BOATRAMP_SECURITY_ALLOW_GUEST_ADMIN_EMAIL", |p| {
3781                p.allow_guest_admin_email
3782            }),
3783            ("BOATRAMP_SECURITY_ALLOW_GUEST_ADMIN_SITE", |p| {
3784                p.allow_guest_admin_site
3785            }),
3786            ("BOATRAMP_SECURITY_ALLOW_GUEST_ADMIN_SECRETS", |p| {
3787                p.allow_guest_admin_secrets
3788            }),
3789        ] {
3790            let mut cfg = ServerConfig::default();
3791            cfg.apply_env_overrides(&env(&[
3792                ("BOATRAMP_SECURITY_PROFILE", "multi-tenant"),
3793                (var, "true"),
3794            ]))
3795            .unwrap_or_else(|e| panic!("{var} applies: {e}"));
3796            let posture = cfg
3797                .security
3798                .unwrap_or_else(|| panic!("{var} materialises the security section"))
3799                .resolve()
3800                .expect("resolves");
3801            assert!(check(&posture), "{var} did not flip the resolved posture");
3802        }
3803    }
3804
3805    #[test]
3806    fn every_posture_override_field_has_an_env_mapping() {
3807        // Exhaustive guard against the EXACT class of gap v0.4.18 closes — a `PostureOverrides`
3808        // field a 12-factor fleet can set in `[security.overrides]` but NOT via env — for EVERY
3809        // field, now and in the future. Enumerate the struct's fields structurally (serialize a
3810        // default instance; every field renders as a key) and assert each maps to a registered
3811        // `BOATRAMP_SECURITY_<UPPER(field)>` in `SECURITY_ENV_VARS`. A new override field added
3812        // without an env var (or a var left out of the registry) fails here — so the omission that
3813        // regressed `allow_guest_email` can't silently recur. The registry entry is load-bearing:
3814        // `apply_env_overrides` only materialises the section when `source.any(SECURITY_ENV_VARS)`.
3815        let all = serde_json::to_value(boatramp_core::security::PostureOverrides::default())
3816            .expect("PostureOverrides serializes");
3817        let fields = all.as_object().expect("a struct is a JSON object");
3818        assert!(!fields.is_empty(), "expected some override fields");
3819        for field in fields.keys() {
3820            let var = format!("BOATRAMP_SECURITY_{}", field.to_uppercase());
3821            assert!(
3822                SECURITY_ENV_VARS.contains(&var.as_str()),
3823                "PostureOverrides field `{field}` has no env mapping — add `{var}` to \
3824                 SECURITY_ENV_VARS + an arm in apply_env_overrides (the v0.4.18 forgot-a-knob guard)"
3825            );
3826        }
3827    }
3828
3829    #[test]
3830    fn cluster_section_parses_the_dynamic_join_shape() {
3831        let cfg = server(
3832            r#"(
3833                cluster: (
3834                    listen: "10.0.0.2:7000",
3835                    root_pubkeys: ["es256:03a1"],
3836                    seeds: ["https://10.0.0.1:8080"],
3837                    join_token: "env:BOATRAMP_JOIN_TOKEN",
3838                ),
3839            )"#,
3840        );
3841        let cluster = cfg.cluster.unwrap();
3842        assert_eq!(
3843            cluster.listen,
3844            "10.0.0.2:7000".parse::<std::net::SocketAddr>().unwrap()
3845        );
3846        assert_eq!(cluster.root_pubkeys, vec!["es256:03a1".to_string()]);
3847        assert_eq!(cluster.seeds, vec!["https://10.0.0.1:8080".to_string()]);
3848        assert_eq!(
3849            cluster.join_token.as_deref(),
3850            Some("env:BOATRAMP_JOIN_TOKEN")
3851        );
3852        // store_dir defaults to None (→ <data-dir>/raft at serve time).
3853        assert!(cluster.store_dir.is_none());
3854    }
3855
3856    #[test]
3857    fn cluster_section_founds_with_just_a_listen_addr() {
3858        // A founder needs no seeds/token — just where to bind the mesh.
3859        let cfg = server(r#"( cluster: ( listen: "0.0.0.0:7000" ) )"#);
3860        let cluster = cfg.cluster.unwrap();
3861        assert!(cluster.seeds.is_empty());
3862        assert!(cluster.root_pubkeys.is_empty());
3863        assert!(cluster.join_token.is_none());
3864    }
3865
3866    #[test]
3867    fn sql_binding_single_node_defaults() {
3868        // A bare section (or none) means single-node: no url, default dir.
3869        let cfg = server(r#"( handlers: ( bindings: ( sql: () ) ) )"#);
3870        let sql = cfg.handlers.unwrap().bindings.sql.unwrap();
3871        assert!(sql.url.is_none());
3872        assert!(sql.dir.is_none());
3873    }
3874
3875    #[test]
3876    fn sql_binding_single_node_custom_dir() {
3877        let cfg =
3878            server(r#"( handlers: ( bindings: ( sql: ( dir: "/var/lib/boatramp/sql" ) ) ) )"#);
3879        let sql = cfg.handlers.unwrap().bindings.sql.unwrap();
3880        assert_eq!(sql.dir.as_deref(), Some(Path::new("/var/lib/boatramp/sql")));
3881        assert!(sql.url.is_none());
3882    }
3883
3884    #[test]
3885    fn sql_binding_cluster() {
3886        let cfg = server(
3887            r#"(
3888                handlers: ( bindings: ( sql: (
3889                    url: "http://sqld:8080",
3890                    admin_url: "http://sqld:9090",
3891                    token_env: "BOATRAMP_SQL_TOKEN",
3892                ) ) ),
3893            )"#,
3894        );
3895        let sql = cfg.handlers.unwrap().bindings.sql.unwrap();
3896        assert_eq!(sql.url.as_deref(), Some("http://sqld:8080"));
3897        assert_eq!(sql.admin_url.as_deref(), Some("http://sqld:9090"));
3898        assert_eq!(sql.token_env.as_deref(), Some("BOATRAMP_SQL_TOKEN"));
3899        assert_eq!(sql.admin_token_env, None);
3900    }
3901
3902    #[test]
3903    fn sql_binding_env_only_sets_trusted_extensions_and_declared_caps() {
3904        // The crux of the ask: with NO `boatramp.cfg`, env vars alone materialise + populate the
3905        // sql binding's migration trusted-extension allowlist (a parse_list, comma-separated +
3906        // trimmed) and the declared-DB ceilings — so a fly `[env]`-only fleet can allowlist
3907        // `pg_trgm` without a `[[files]] boatramp.cfg` edit + a server roll.
3908        let mut cfg = ServerConfig::default();
3909        assert!(cfg.handlers.is_none());
3910        cfg.apply_env_overrides(&env(&[
3911            (
3912                "BOATRAMP_HANDLERS_SQL_MIGRATE_TRUSTED_EXTENSIONS",
3913                "pg_trgm, pgcrypto",
3914            ),
3915            ("BOATRAMP_HANDLERS_SQL_MAX_DECLARED_DATABASES", "32"),
3916            ("BOATRAMP_HANDLERS_SQL_MAX_DECLARED_VOLUME_MIB", "1048576"),
3917        ]))
3918        .expect("valid env overrides apply");
3919        let sql = cfg
3920            .handlers
3921            .expect("handlers materialised from env")
3922            .bindings
3923            .sql
3924            .expect("sql binding materialised from the trusted-extensions var alone");
3925        assert_eq!(
3926            sql.migrate_trusted_extensions.as_deref(),
3927            Some(&["pg_trgm".to_string(), "pgcrypto".to_string()][..]),
3928            "the allowlist is the comma-split, trimmed env list (source = env)"
3929        );
3930        assert_eq!(sql.max_declared_databases, Some(32));
3931        assert_eq!(sql.max_declared_volume_mib, Some(1_048_576));
3932    }
3933
3934    #[test]
3935    fn sql_binding_env_over_file_for_trusted_extensions() {
3936        // Field-level env-over-file precedence: a file allowlist is overridden ONLY for the var that
3937        // is set; an unset var keeps the file value (never clobbered to empty).
3938        let mut cfg = server(
3939            r#"(
3940                handlers: ( bindings: ( sql: (
3941                    migrate_trusted_extensions: ["citext"],
3942                    max_declared_databases: 8,
3943                ) ) ),
3944            )"#,
3945        );
3946        cfg.apply_env_overrides(&env(&[(
3947            "BOATRAMP_HANDLERS_SQL_MIGRATE_TRUSTED_EXTENSIONS",
3948            "pg_trgm",
3949        )]))
3950        .expect("env overrides apply");
3951        let sql = cfg.handlers.unwrap().bindings.sql.unwrap();
3952        assert_eq!(
3953            sql.migrate_trusted_extensions.as_deref(),
3954            Some(&["pg_trgm".to_string()][..]),
3955            "env wins over the file allowlist for the var that is set"
3956        );
3957        assert_eq!(
3958            sql.max_declared_databases,
3959            Some(8),
3960            "a var left unset keeps the file value (not clobbered)"
3961        );
3962    }
3963
3964    #[test]
3965    fn every_sql_binding_scalar_has_an_env_mapping() {
3966        // Forgot-a-knob guard (the v0.4.18 shape, for `handlers.bindings.sql`): every env-mappable
3967        // SCALAR field on SqlBindingConfig must have a `BOATRAMP_HANDLERS_SQL_*` entry in
3968        // SQL_ENV_VARS, so a file-less (fly `[env]`-only) fleet can set it without a `boatramp.cfg`
3969        // + server roll — the EXACT gap that left `migrate_trusted_extensions` env-unsettable. The
3970        // destructure is the compile-time half: a NEW field added to SqlBindingConfig breaks this
3971        // test until it is classified below (a scalar → add a var here + a registry entry + an
3972        // overlay arm; or the `databases` map, which is discovered by the
3973        // `BOATRAMP_HANDLERS_SQL_DB_<NAME>_*` prefix scan, not a scalar var). The loop is the runtime
3974        // half: each classified scalar is actually registered.
3975        let SqlBindingConfig {
3976            dir: _,
3977            url: _,
3978            admin_url: _,
3979            replica_url: _,
3980            token_env: _,
3981            admin_token_env: _,
3982            preview_mode: _,
3983            preview_init: _,
3984            // NOT a scalar env var: the keyed external-database map, discovered by prefix scan.
3985            databases: _,
3986            deprovision_grace_secs: _,
3987            migrate_trusted_extensions: _,
3988            max_declared_databases: _,
3989            max_declared_volume_mib: _,
3990        } = SqlBindingConfig::default();
3991        for var in [
3992            "BOATRAMP_HANDLERS_SQL_DIR",
3993            "BOATRAMP_HANDLERS_SQL_URL",
3994            "BOATRAMP_HANDLERS_SQL_ADMIN_URL",
3995            "BOATRAMP_HANDLERS_SQL_REPLICA_URL",
3996            "BOATRAMP_HANDLERS_SQL_TOKEN_ENV",
3997            "BOATRAMP_HANDLERS_SQL_ADMIN_TOKEN_ENV",
3998            "BOATRAMP_HANDLERS_SQL_PREVIEW_MODE",
3999            "BOATRAMP_HANDLERS_SQL_PREVIEW_INIT",
4000            "BOATRAMP_HANDLERS_SQL_DEPROVISION_GRACE_SECS",
4001            "BOATRAMP_HANDLERS_SQL_MIGRATE_TRUSTED_EXTENSIONS",
4002            "BOATRAMP_HANDLERS_SQL_MAX_DECLARED_DATABASES",
4003            "BOATRAMP_HANDLERS_SQL_MAX_DECLARED_VOLUME_MIB",
4004        ] {
4005            assert!(
4006                SQL_ENV_VARS.contains(&var),
4007                "{var} missing from SQL_ENV_VARS — a sql-binding scalar lost its env lever \
4008                 (the forgot-a-knob gap); add it to the registry + an overlay arm"
4009            );
4010        }
4011    }
4012
4013    #[test]
4014    fn env_wires_the_jwks_freshness_knobs_over_the_default() {
4015        // The two-tier JWKS freshness knobs are env-settable (12-factor parity), and every lever is
4016        // registered in JWKS_ENV_VARS — a forgot-a-knob guard so a new `jwks_*` field can't silently
4017        // lose its env override.
4018        let mut cfg = ServerConfig::default();
4019        assert!(cfg.handlers.is_none());
4020        cfg.apply_env_overrides(&env(&[
4021            ("BOATRAMP_HANDLERS_JWKS_REFRESH_SECS", "90"),
4022            ("BOATRAMP_HANDLERS_JWKS_HARD_TTL_SECS", "450"),
4023            ("BOATRAMP_HANDLERS_JWKS_FOREIGN_REFRESH_SECS", "30"),
4024            ("BOATRAMP_HANDLERS_JWKS_FOREIGN_HARD_TTL_SECS", "150"),
4025            ("BOATRAMP_HANDLERS_JWKS_PREWARM", "false"),
4026        ]))
4027        .expect("valid env overrides apply");
4028        let h = cfg.handlers.expect("handlers materialised from env");
4029        assert_eq!(h.jwks_refresh_secs, Some(90));
4030        assert_eq!(h.jwks_hard_ttl_secs, Some(450));
4031        assert_eq!(h.jwks_foreign_refresh_secs, Some(30));
4032        assert_eq!(h.jwks_foreign_hard_ttl_secs, Some(150));
4033        assert_eq!(h.jwks_prewarm, Some(false));
4034        for var in [
4035            "BOATRAMP_HANDLERS_JWKS_REFRESH_SECS",
4036            "BOATRAMP_HANDLERS_JWKS_HARD_TTL_SECS",
4037            "BOATRAMP_HANDLERS_JWKS_FOREIGN_REFRESH_SECS",
4038            "BOATRAMP_HANDLERS_JWKS_FOREIGN_HARD_TTL_SECS",
4039            "BOATRAMP_HANDLERS_JWKS_PREWARM",
4040        ] {
4041            assert!(
4042                JWKS_ENV_VARS.contains(&var),
4043                "{var} missing from JWKS_ENV_VARS — a JWKS freshness knob lost its env lever"
4044            );
4045        }
4046    }
4047
4048    #[test]
4049    fn env_wires_the_handler_concurrency_knobs_over_the_default() {
4050        // The per-component serve-admission gate + the two lane ceilings are env-settable (12-factor
4051        // parity), and every lever is registered in HANDLER_CONCURRENCY_ENV_VARS — a forgot-a-knob guard
4052        // so a new concurrency field can't silently lose its env override and get pinned back into a
4053        // `boatramp.cfg`. `serve_concurrency = 0` is the MEANINGFUL "disable the gate" value and must
4054        // round-trip as `Some(0)`, not be dropped.
4055        let mut cfg = ServerConfig::default();
4056        assert!(cfg.handlers.is_none());
4057        cfg.apply_env_overrides(&env(&[
4058            ("BOATRAMP_HANDLERS_SERVE_CONCURRENCY", "0"),
4059            ("BOATRAMP_HANDLERS_SYNC_MAX_CONCURRENCY", "128"),
4060            ("BOATRAMP_HANDLERS_ASYNC_MAX_CONCURRENCY", "16"),
4061        ]))
4062        .expect("valid env overrides apply");
4063        let h = cfg.handlers.expect("handlers materialised from env");
4064        assert_eq!(h.serve_concurrency, Some(0), "0 = disable must round-trip");
4065        assert_eq!(h.sync_max_concurrency, Some(128));
4066        assert_eq!(h.async_max_concurrency, Some(16));
4067        for var in [
4068            "BOATRAMP_HANDLERS_SERVE_CONCURRENCY",
4069            "BOATRAMP_HANDLERS_SYNC_MAX_CONCURRENCY",
4070            "BOATRAMP_HANDLERS_ASYNC_MAX_CONCURRENCY",
4071        ] {
4072            assert!(
4073                HANDLER_CONCURRENCY_ENV_VARS.contains(&var),
4074                "{var} missing from HANDLER_CONCURRENCY_ENV_VARS — a concurrency knob lost its env lever"
4075            );
4076        }
4077    }
4078
4079    #[test]
4080    fn env_wires_the_blob_hedge_knobs_over_the_default() {
4081        // The hedged-read tail knobs are env-settable so a file-less fleet can turn hedging on and tune
4082        // it; every lever is registered in HANDLER_BLOB_HEDGE_ENV_VARS (forgot-a-knob guard).
4083        let mut cfg = ServerConfig::default();
4084        assert!(cfg.handlers.is_none());
4085        cfg.apply_env_overrides(&env(&[
4086            ("BOATRAMP_HANDLERS_BLOB_HEDGE_DELAY_MS", "80"),
4087            ("BOATRAMP_HANDLERS_BLOB_HEDGE_MAX_INFLIGHT", "24"),
4088        ]))
4089        .expect("valid env overrides apply");
4090        let h = cfg.handlers.expect("handlers materialised from env");
4091        assert_eq!(h.blob_hedge_delay_ms, Some(80));
4092        assert_eq!(h.blob_hedge_max_inflight, Some(24));
4093        for var in [
4094            "BOATRAMP_HANDLERS_BLOB_HEDGE_DELAY_MS",
4095            "BOATRAMP_HANDLERS_BLOB_HEDGE_MAX_INFLIGHT",
4096        ] {
4097            assert!(
4098                HANDLER_BLOB_HEDGE_ENV_VARS.contains(&var),
4099                "{var} missing from HANDLER_BLOB_HEDGE_ENV_VARS — a hedge knob lost its env lever"
4100            );
4101        }
4102    }
4103
4104    #[test]
4105    fn env_wires_the_s3_ingress_cloud_knobs_over_the_default() {
4106        // The blob-upload minter's cloud-brokering policy is env-settable, so the Tigris presigned-only
4107        // deployment needs no `boatramp.cfg` for it. Every lever is registered in
4108        // S3_INGRESS_CLOUD_ENV_VARS (forgot-a-knob guard). The signing credential is NOT here — it stays
4109        // the sealed `[secrets]` one; these are policy toggles only.
4110        let mut cfg = ServerConfig::default();
4111        assert!(cfg.serve.is_none());
4112        cfg.apply_env_overrides(&env(&[(
4113            "BOATRAMP_S3_INGRESS_CLOUD_AWS_PRESIGNED_ONLY",
4114            "true",
4115        )]))
4116        .expect("valid env overrides apply");
4117        let ic = cfg
4118            .serve
4119            .expect("serve materialised from env")
4120            .s3_ingress_cloud
4121            .expect("s3_ingress_cloud materialised from env");
4122        assert!(ic.aws_presigned_only, "presigned-only toggled on via env");
4123        assert!(
4124            !ic.aws_use_federation_token,
4125            "untouched toggle stays default"
4126        );
4127        assert!(ic.aws_role_arn.is_none(), "untouched field stays None");
4128        for var in S3_INGRESS_CLOUD_ENV_VARS {
4129            assert!(
4130                var.starts_with("BOATRAMP_S3_INGRESS_CLOUD_"),
4131                "{var} is not an s3_ingress_cloud lever"
4132            );
4133        }
4134    }
4135
4136    #[test]
4137    fn env_wires_the_per_project_blob_backend_over_the_default() {
4138        // PLAN-per-project-blob-backend: a keyed `[serve.blob_backends.<project>]` map discovered from
4139        // the env with NO config file, mirroring the SQL `databases` map. The project name may contain
4140        // underscores (name isolation strips the LONGEST field suffix). The sealed credential is a
4141        // REFERENCE (`boatramp:`/`env:`), never the raw secret (invariant 3).
4142        let mut cfg = ServerConfig::default();
4143        assert!(cfg.serve.is_none());
4144        cfg.apply_env_overrides(&env(&[
4145            ("BOATRAMP_SERVE_BLOB_BACKEND_acme_eu_KIND", "s3"),
4146            (
4147                "BOATRAMP_SERVE_BLOB_BACKEND_acme_eu_S3_BUCKET",
4148                "acme-eu-blobs",
4149            ),
4150            (
4151                "BOATRAMP_SERVE_BLOB_BACKEND_acme_eu_S3_ENDPOINT",
4152                "https://s3.eu.example.com",
4153            ),
4154            ("BOATRAMP_SERVE_BLOB_BACKEND_acme_eu_S3_REGION", "eu-west-1"),
4155            ("BOATRAMP_SERVE_BLOB_BACKEND_acme_eu_S3_PATH_STYLE", "true"),
4156            (
4157                "BOATRAMP_SERVE_BLOB_BACKEND_acme_eu_S3_ACCESS_KEY_ID",
4158                "AKIAACME",
4159            ),
4160            (
4161                "BOATRAMP_SERVE_BLOB_BACKEND_acme_eu_S3_SECRET_ACCESS_KEY",
4162                "boatramp:acme-eu-s3",
4163            ),
4164        ]))
4165        .expect("valid per-project blob-backend env overrides apply");
4166        let serve = cfg.serve.expect("serve materialised from env");
4167        let be = serve.blob_backends.get("acme_eu").expect(
4168            "the acme_eu per-project backend was discovered from env (underscore survives name \
4169             isolation)",
4170        );
4171        assert_eq!(be.blobs, Some(crate::backends::BlobBackend::S3));
4172        assert_eq!(be.s3_bucket.as_deref(), Some("acme-eu-blobs"));
4173        assert_eq!(be.s3_endpoint.as_deref(), Some("https://s3.eu.example.com"));
4174        assert_eq!(be.s3_region.as_deref(), Some("eu-west-1"));
4175        assert!(be.s3_path_style);
4176        let cred = be
4177            .s3_credential
4178            .as_ref()
4179            .expect("sealed credential materialised from its two refs");
4180        assert_eq!(cred.access_key_id, "AKIAACME");
4181        // The secret is the REFERENCE as written — never an inlined secret value (invariant 3).
4182        assert_eq!(cred.secret_access_key, "boatramp:acme-eu-s3");
4183    }
4184
4185    #[test]
4186    fn blob_backend_env_covers_every_field() {
4187        // Forgot-a-knob guard (mirrors the SQL-DB + hedge guards): every field of `BlobBackendConfig`
4188        // reachable from config MUST have an env suffix in `BLOB_BACKEND_FIELD_SUFFIXES`, so a newly
4189        // added field can't silently lose its env lever. Set every suffix for one project and assert
4190        // each field landed; assert the suffix set is exactly the expected one (no stale/missing lever).
4191        let expected: &[&str] = &[
4192            "_KIND",
4193            "_S3_BUCKET",
4194            "_S3_ENDPOINT",
4195            "_S3_REGION",
4196            "_S3_PATH_STYLE",
4197            "_S3_ACCESS_KEY_ID",
4198            "_S3_SECRET_ACCESS_KEY",
4199        ];
4200        for suffix in expected {
4201            assert!(
4202                BLOB_BACKEND_FIELD_SUFFIXES.contains(suffix),
4203                "{suffix} missing from BLOB_BACKEND_FIELD_SUFFIXES — a blob-backend field lost its \
4204                 env lever"
4205            );
4206        }
4207        assert_eq!(
4208            BLOB_BACKEND_FIELD_SUFFIXES.len(),
4209            expected.len(),
4210            "BLOB_BACKEND_FIELD_SUFFIXES has a suffix with no matching expected field (stale lever)"
4211        );
4212    }
4213
4214    #[test]
4215    fn blob_backend_rejects_the_reserved_default_project() {
4216        // Invariant 5: the reserved `default` project ALWAYS resolves the global `[serve]` backend, so
4217        // a `[serve.blob_backends.default]` entry is refused at load (fail-closed, boot-loud) — the
4218        // node-wide backend is configured under `[serve]`, not here.
4219        let err = ServerConfig::parse(
4220            r#"( serve: ( blob_backends: { "default": ( blobs: s3, s3_bucket: "x" ) } ) )"#,
4221        )
4222        .expect_err("a `default`-keyed per-project blob backend must be refused");
4223        assert!(
4224            matches!(err, ConfigError::InvalidBlobBackendProject { .. }),
4225            "reserved-default blob backend is InvalidBlobBackendProject, got {err:?}"
4226        );
4227    }
4228
4229    #[test]
4230    fn blob_backend_rejects_an_unsafe_project_name() {
4231        // A `blob_backends` key is a project name threaded into the per-project data-plane scope, so it
4232        // runs the canonical slug validator (fail-closed on a path-traversal / injection shape).
4233        let err = ServerConfig::parse(
4234            r#"( serve: ( blob_backends: { "../evil": ( blobs: s3, s3_bucket: "x" ) } ) )"#,
4235        )
4236        .expect_err("a path-traversal project key must be refused");
4237        assert!(
4238            matches!(err, ConfigError::InvalidBlobBackendProject { .. }),
4239            "unsafe blob-backend project name is InvalidBlobBackendProject, got {err:?}"
4240        );
4241    }
4242
4243    #[test]
4244    fn blob_backend_config_rejects_unknown_fields_and_inlined_secret_stays_a_ref() {
4245        // `deny_unknown_fields` on `BlobBackendConfig` + its `S3CredentialConfig` catches a typo'd key
4246        // at load; and the sealed credential's `secret_access_key` is stored verbatim as the REFERENCE
4247        // the operator wrote (a `boatramp:` name), never re-interpreted into a raw secret.
4248        let cfg = ServerConfig::parse(
4249            r#"( serve: ( blob_backends: { "acme": (
4250                blobs: s3,
4251                s3_bucket: "acme-blobs",
4252                s3_credential: ( access_key_id: "AKIA", secret_access_key: "boatramp:acme" ),
4253            ) } ) )"#,
4254        )
4255        .expect("a well-formed per-project blob backend parses");
4256        let be = cfg
4257            .serve
4258            .unwrap()
4259            .blob_backends
4260            .remove("acme")
4261            .expect("acme backend parsed");
4262        assert_eq!(be.blobs, Some(crate::backends::BlobBackend::S3));
4263        assert_eq!(
4264            be.s3_credential.unwrap().secret_access_key,
4265            "boatramp:acme",
4266            "the secret stays the indirect reference, never an inlined secret"
4267        );
4268        let bad = ServerConfig::parse(
4269            r#"( serve: ( blob_backends: { "acme": ( blobs: s3, bogus: 1 ) } ) )"#,
4270        );
4271        assert!(
4272            bad.is_err(),
4273            "an unknown [serve.blob_backends.<p>] field must be rejected (deny_unknown_fields)"
4274        );
4275    }
4276
4277    #[test]
4278    fn sql_binding_preview_policy() {
4279        let cfg = server(
4280            r#"(
4281                handlers: ( bindings: ( sql: (
4282                    preview_mode: "branch",
4283                    preview_init: "/etc/boatramp/seed.sql",
4284                ) ) ),
4285            )"#,
4286        );
4287        let sql = cfg.handlers.unwrap().bindings.sql.unwrap();
4288        assert_eq!(sql.preview_mode.as_deref(), Some("branch"));
4289        assert_eq!(
4290            sql.preview_init.as_deref(),
4291            Some(Path::new("/etc/boatramp/seed.sql"))
4292        );
4293    }
4294
4295    #[test]
4296    fn sql_binding_external_databases() {
4297        let cfg = server(
4298            r#"(
4299                handlers: ( bindings: ( sql: (
4300                    databases: {
4301                        "analytics": (
4302                            kind: "postgres",
4303                            url_env: "ANALYTICS_PG_URL",
4304                            pool_max: 16,
4305                            read_only: true,
4306                        ),
4307                        "events": (
4308                            kind: "mysql",
4309                            url_env: "EVENTS_MYSQL_URL",
4310                            read_url_env: "EVENTS_MYSQL_REPLICA_URL",
4311                            allow_preview: true,
4312                        ),
4313                    },
4314                ) ) ),
4315            )"#,
4316        );
4317        let sql = cfg.handlers.unwrap().bindings.sql.unwrap();
4318        assert_eq!(sql.databases.len(), 2);
4319
4320        let analytics = &sql.databases["analytics"];
4321        assert_eq!(analytics.kind, "postgres");
4322        assert_eq!(analytics.url_env, "ANALYTICS_PG_URL");
4323        assert_eq!(analytics.pool_max, Some(16));
4324        assert!(analytics.read_only);
4325        assert!(!analytics.allow_preview);
4326        assert!(analytics.read_url_env.is_none());
4327
4328        let events = &sql.databases["events"];
4329        assert_eq!(events.kind, "mysql");
4330        assert_eq!(
4331            events.read_url_env.as_deref(),
4332            Some("EVENTS_MYSQL_REPLICA_URL")
4333        );
4334        assert!(events.allow_preview);
4335        assert!(!events.read_only);
4336    }
4337
4338    #[test]
4339    fn sql_binding_compute_backed_database() {
4340        let cfg = server(
4341            r#"(
4342                handlers: ( bindings: ( sql: (
4343                    databases: {
4344                        "analytics": (
4345                            kind: "postgres",
4346                            compute: "pg",
4347                            database: "analytics",
4348                            user: "app",
4349                            password_env: "PG_APP_PW",
4350                        ),
4351                    },
4352                ) ) ),
4353            )"#,
4354        );
4355        let db = &cfg.handlers.unwrap().bindings.sql.unwrap().databases["analytics"];
4356        assert_eq!(db.kind, "postgres");
4357        assert_eq!(db.compute.as_deref(), Some("pg"));
4358        assert_eq!(db.database.as_deref(), Some("analytics"));
4359        assert_eq!(db.user.as_deref(), Some("app"));
4360        assert_eq!(db.password_env.as_deref(), Some("PG_APP_PW"));
4361        assert!(db.url_env.is_empty(), "compute-backed has no url_env");
4362        assert!(db.validate("analytics").is_ok());
4363    }
4364
4365    #[test]
4366    fn sql_binding_source_is_exactly_one_of_url_or_compute() {
4367        // Neither source → error.
4368        assert!(ExternalDatabaseConfig::default().validate("db").is_err());
4369        // Both sources → error.
4370        let both = ExternalDatabaseConfig {
4371            kind: "postgres".into(),
4372            url_env: "PG_URL".into(),
4373            compute: Some("pg".into()),
4374            ..Default::default()
4375        };
4376        assert!(both.validate("db").is_err());
4377        // `url_env` only → ok.
4378        let url = ExternalDatabaseConfig {
4379            kind: "postgres".into(),
4380            url_env: "PG_URL".into(),
4381            ..Default::default()
4382        };
4383        assert!(url.validate("db").is_ok());
4384        // `compute` without the connection details boatramp can't infer → error.
4385        let bare = ExternalDatabaseConfig {
4386            kind: "postgres".into(),
4387            compute: Some("pg".into()),
4388            ..Default::default()
4389        };
4390        assert!(bare.validate("db").is_err());
4391        // `compute` with database/user + a bring-your-own `password_env` → ok, and
4392        // is *not* a managed credential.
4393        let byo = ExternalDatabaseConfig {
4394            kind: "postgres".into(),
4395            compute: Some("pg".into()),
4396            database: Some("analytics".into()),
4397            user: Some("app".into()),
4398            password_env: Some("PG_APP_PW".into()),
4399            ..Default::default()
4400        };
4401        assert!(byo.validate("db").is_ok());
4402        assert!(!byo.is_managed_credential());
4403        // `compute` with database/user but NO `password_env` → ok, and boatramp
4404        // manages the credential (Phase 2).
4405        let managed = ExternalDatabaseConfig {
4406            kind: "postgres".into(),
4407            compute: Some("pg".into()),
4408            database: Some("analytics".into()),
4409            user: Some("app".into()),
4410            ..Default::default()
4411        };
4412        assert!(managed.validate("db").is_ok());
4413        assert!(managed.is_managed_credential());
4414    }
4415
4416    #[test]
4417    fn libsql_source_is_exactly_one_of_path_or_url() {
4418        // A single-node `libsql` file (path only) → ok.
4419        let file = ExternalDatabaseConfig {
4420            kind: "libsql".into(),
4421            path: Some("/data/app.db".into()),
4422            ..Default::default()
4423        };
4424        assert!(file.validate("app").is_ok());
4425        // `sqlite` alias works the same.
4426        let sqlite = ExternalDatabaseConfig {
4427            kind: "sqlite".into(),
4428            path: Some("/data/app.db".into()),
4429            ..Default::default()
4430        };
4431        assert!(sqlite.validate("app").is_ok());
4432        // A remote-sqld `libsql` (url_env only) → ok.
4433        let remote = ExternalDatabaseConfig {
4434            kind: "libsql".into(),
4435            url_env: "LIBSQL_URL".into(),
4436            ..Default::default()
4437        };
4438        assert!(remote.validate("app").is_ok());
4439        // Neither `path` nor `url_env` → error.
4440        let neither = ExternalDatabaseConfig {
4441            kind: "libsql".into(),
4442            ..Default::default()
4443        };
4444        assert!(neither.validate("app").is_err());
4445        // Both `path` and `url_env` → error (exactly one).
4446        let both = ExternalDatabaseConfig {
4447            kind: "libsql".into(),
4448            path: Some("/data/app.db".into()),
4449            url_env: "LIBSQL_URL".into(),
4450            ..Default::default()
4451        };
4452        assert!(both.validate("app").is_err());
4453        // `compute` on a `libsql` binding → error (boatramp doesn't run a libsql server workload).
4454        let compute = ExternalDatabaseConfig {
4455            kind: "libsql".into(),
4456            compute: Some("x".into()),
4457            path: Some("/data/app.db".into()),
4458            ..Default::default()
4459        };
4460        assert!(compute.validate("app").is_err());
4461        // `path` on a NON-libsql (postgres) binding → error (only libsql has an on-disk file).
4462        let pg_path = ExternalDatabaseConfig {
4463            kind: "postgres".into(),
4464            url_env: "PG_URL".into(),
4465            path: Some("/data/app.db".into()),
4466            ..Default::default()
4467        };
4468        assert!(pg_path.validate("db").is_err());
4469    }
4470
4471    /// Path to a file at the repo root (two levels up from this crate).
4472    fn repo_root_file(name: &str) -> PathBuf {
4473        Path::new(env!("CARGO_MANIFEST_DIR"))
4474            .join("../..")
4475            .join(name)
4476    }
4477
4478    #[test]
4479    fn shipped_project_example_parses() {
4480        // The example we ship must always parse + compile-check, so it can't drift
4481        // from the schema.
4482        let text = std::fs::read_to_string(repo_root_file("examples/site/project.cfg.example"))
4483            .expect("example project config is present");
4484        let cfg = ProjectConfig::parse(&text).expect("example project config parses");
4485        assert_eq!(cfg.publish.server.as_deref(), Some("http://127.0.0.1:8080"));
4486        assert_eq!(cfg.build.as_ref().unwrap().command, "npm run build");
4487        assert_eq!(
4488            cfg.routing.error_documents.get(&404).map(String::as_str),
4489            Some("/404.html")
4490        );
4491    }
4492
4493    #[test]
4494    fn shipped_server_example_parses() {
4495        let text = std::fs::read_to_string(repo_root_file("boatramp.cfg.example"))
4496            .expect("example server config is present");
4497        let cfg = ServerConfig::parse(&text).expect("example server config parses");
4498        let serve = cfg.serve.expect("example sets a serve section");
4499        assert_eq!(
4500            serve.addr,
4501            Some("0.0.0.0:8080".parse::<std::net::SocketAddr>().unwrap())
4502        );
4503    }
4504
4505    #[test]
4506    fn secrets_section_parses_local_and_vault() {
4507        let local = server(r#"( secrets: ( envelope: "local", kek_file: "/k/kek" ) )"#)
4508            .secrets
4509            .expect("secrets section");
4510        assert_eq!(local.envelope, "local");
4511        assert_eq!(
4512            local.kek_file.as_deref(),
4513            Some(std::path::Path::new("/k/kek"))
4514        );
4515
4516        let vault = server(
4517            r#"( secrets: ( envelope: "vault", vault: ( addr: "https://vault:8200", key: "certs" ) ) )"#,
4518        )
4519        .secrets
4520        .expect("secrets section");
4521        let v = vault.vault.expect("vault subsection");
4522        assert_eq!(v.addr, "https://vault:8200");
4523        assert_eq!(v.key, "certs");
4524        // The token env defaults to VAULT_TOKEN and is never in the file.
4525        assert_eq!(v.token_env, "VAULT_TOKEN");
4526    }
4527
4528    #[test]
4529    fn serve_section_partial_parses() {
4530        // A partial `serve` section parses — unset fields take their defaults.
4531        let cfg = server(r#"( serve: ( addr: "0.0.0.0:8080", protect_previews: true ) )"#);
4532        let serve = cfg.serve.unwrap();
4533        assert_eq!(
4534            serve.addr,
4535            Some("0.0.0.0:8080".parse::<std::net::SocketAddr>().unwrap())
4536        );
4537        assert!(serve.protect_previews);
4538        assert!(!serve.cluster_rate_limit);
4539        assert!(serve.data_dir.is_none());
4540    }
4541
4542    #[test]
4543    fn serve_console_config_parses() {
4544        // Absent ⇒ no console.
4545        let cfg = server(r#"( serve: ( addr: "0.0.0.0:8080" ) )"#);
4546        assert!(cfg.serve.unwrap().console.is_none());
4547        // Explicit console block with host + path.
4548        let cfg = server(
4549            r#"( serve: ( console: (
4550                enabled: true,
4551                host: "console.example.com",
4552                path: "/_console",
4553            ) ) )"#,
4554        );
4555        let console = cfg.serve.unwrap().console.unwrap();
4556        assert!(console.enabled);
4557        assert_eq!(console.host.as_deref(), Some("console.example.com"));
4558        assert_eq!(console.path.as_deref(), Some("/_console"));
4559        // Bare `enabled` ⇒ host/path take their (server-side) defaults.
4560        let cfg = server(r#"( serve: ( console: ( enabled: true ) ) )"#);
4561        let console = cfg.serve.unwrap().console.unwrap();
4562        assert!(console.enabled);
4563        assert!(console.host.is_none() && console.path.is_none());
4564    }
4565
4566    #[test]
4567    fn serve_s3_credential_config_parses() {
4568        // #505: absent ⇒ no sealed source (the ambient AWS env chain).
4569        let cfg = server(r#"( serve: ( addr: "0.0.0.0:8080" ) )"#);
4570        assert!(cfg.serve.unwrap().s3_credential.is_none());
4571        // An explicit `[serve.s3_credential]`: a plain `access_key_id` + a `boatramp:` sealed
4572        // `secret_access_key` ref (the config text carries only the REFERENCE, never the secret).
4573        let cfg = server(
4574            r#"( serve: ( s3_credential: (
4575                access_key_id: "tid_public_akid",
4576                secret_access_key: "boatramp:tigris-secret",
4577            ) ) )"#,
4578        );
4579        let cred = cfg.serve.unwrap().s3_credential.unwrap();
4580        assert_eq!(cred.access_key_id, "tid_public_akid");
4581        assert_eq!(cred.secret_access_key, "boatramp:tigris-secret");
4582        // An unknown field is rejected (`deny_unknown_fields`) — a fat-fingered key fails fast.
4583        let err: Result<ServerConfig, _> = ron_options().from_str(
4584            r#"( serve: ( s3_credential: ( access_key_id: "x", secret_access_key: "boatramp:y", bogus: 1 ) ) )"#,
4585        );
4586        assert!(
4587            err.is_err(),
4588            "unknown [serve.s3_credential] field must be rejected"
4589        );
4590    }
4591
4592    #[test]
4593    fn serve_blob_fallback_config_parses() {
4594        // Blob-backend migration Part 2: absent ⇒ no fallback (the read-through composite is not wired).
4595        let cfg = server(r#"( serve: ( addr: "0.0.0.0:8080" ) )"#);
4596        assert!(cfg.serve.unwrap().blob_fallback.is_none());
4597        // A `[serve.blob_fallback]` secondary: the OLD fs backend to drain while the primary is s3,
4598        // with its own sealed S3 credential ref and a custom secondary timeout.
4599        let cfg = server(
4600            r#"( serve: (
4601                blobs: s3,
4602                s3_bucket: "new-bucket",
4603                blob_fallback: (
4604                    blobs: fs,
4605                    secondary_timeout_secs: 3,
4606                    s3_credential: (
4607                        access_key_id: "old_akid",
4608                        secret_access_key: "boatramp:old-secret",
4609                    ),
4610                ),
4611            ) )"#,
4612        );
4613        let serve = cfg.serve.unwrap();
4614        let fb = serve.blob_fallback.unwrap();
4615        assert_eq!(fb.blobs, Some(crate::backends::BlobBackend::Fs));
4616        assert_eq!(fb.secondary_timeout_secs, Some(3));
4617        let cred = fb.s3_credential.unwrap();
4618        assert_eq!(cred.access_key_id, "old_akid");
4619        assert_eq!(cred.secret_access_key, "boatramp:old-secret");
4620        // An unknown field is rejected (`deny_unknown_fields`).
4621        let err: Result<ServerConfig, _> =
4622            ron_options().from_str(r#"( serve: ( blob_fallback: ( blobs: fs, bogus: 1 ) ) )"#);
4623        assert!(
4624            err.is_err(),
4625            "unknown [serve.blob_fallback] field must be rejected"
4626        );
4627    }
4628
4629    #[test]
4630    fn serve_kv_config_parses_and_defaults() {
4631        // Absent `[serve.kv]` ⇒ the defaults: periodic checkpoint ON at the default cadence, and the
4632        // generous default close budget (NOT the old 3s).
4633        let cfg = server(r#"( serve: ( addr: "0.0.0.0:8080" ) )"#);
4634        assert!(cfg.serve.unwrap().kv.is_none());
4635        let default_kv = super::KvConfig::default();
4636        assert_eq!(
4637            default_kv.checkpoint_interval(),
4638            Some(std::time::Duration::from_secs(
4639                super::DEFAULT_KV_CHECKPOINT_INTERVAL_SECS
4640            )),
4641            "an absent/unset checkpoint_interval defaults to the ON cadence"
4642        );
4643        assert_eq!(
4644            default_kv.close_deadline(),
4645            std::time::Duration::from_secs(super::DEFAULT_KV_CLOSE_DEADLINE_SECS),
4646            "an absent/unset close_deadline defaults to the generous budget"
4647        );
4648
4649        // An explicit block: a tuned cadence + a tuned close budget, now nested under `slatedb`
4650        // (UX-C3) so they never appear to apply under a non-SlateDB backend.
4651        let cfg = server(
4652            r#"( serve: ( kv: ( slatedb: ( checkpoint_interval: 5, close_deadline: 30 ) ) ) )"#,
4653        );
4654        let kv = cfg.serve.unwrap().kv.unwrap();
4655        assert_eq!(
4656            kv.checkpoint_interval(),
4657            Some(std::time::Duration::from_secs(5))
4658        );
4659        assert_eq!(kv.close_deadline(), std::time::Duration::from_secs(30));
4660
4661        // checkpoint_interval = 0 DISABLES the cadence; a 0 close_deadline falls back to the default
4662        // (a zero close budget would abandon every close, guaranteeing a torn tail — never allowed).
4663        let cfg = server(
4664            r#"( serve: ( kv: ( slatedb: ( checkpoint_interval: 0, close_deadline: 0 ) ) ) )"#,
4665        );
4666        let kv = cfg.serve.unwrap().kv.unwrap();
4667        assert_eq!(kv.checkpoint_interval(), None, "0 disables the cadence");
4668        assert_eq!(
4669            kv.close_deadline(),
4670            std::time::Duration::from_secs(super::DEFAULT_KV_CLOSE_DEADLINE_SECS),
4671            "a 0 close_deadline is clamped up to the default, never zero"
4672        );
4673
4674        // The SQL KV backend connection parses under `sql` (UX-C2: `url_env`, never a raw URL).
4675        let cfg = server(r#"( serve: ( kv: ( sql: ( kind: "sqlite", path: "/data/kv.db" ) ) ) )"#);
4676        let sql = cfg.serve.unwrap().kv.unwrap().sql.unwrap();
4677        assert_eq!(sql.kind, "sqlite");
4678        assert_eq!(sql.path.as_deref(), Some("/data/kv.db"));
4679
4680        // UX-C3: a pre-v0.12.0 TOP-LEVEL durability knob now fails loud (it moved under `slatedb`),
4681        // never silently mislead — `deny_unknown_fields` rejects it at the `[serve.kv]` level.
4682        let err: Result<ServerConfig, _> =
4683            ron_options().from_str(r#"( serve: ( kv: ( checkpoint_interval: 5 ) ) )"#);
4684        assert!(
4685            err.is_err(),
4686            "a top-level checkpoint_interval must be rejected (moved under [serve.kv.slatedb])"
4687        );
4688
4689        // An unknown field inside the `slatedb` sub-block is rejected (`deny_unknown_fields`).
4690        let err: Result<ServerConfig, _> = ron_options()
4691            .from_str(r#"( serve: ( kv: ( slatedb: ( checkpoint_interval: 5, bogus: 1 ) ) ) )"#);
4692        assert!(
4693            err.is_err(),
4694            "unknown [serve.kv.slatedb] field must be rejected"
4695        );
4696    }
4697
4698    // =======================================================================
4699    // JSON config input gate (v0.6.5) — serve/project config + detection half.
4700    //
4701    // ROBUST-successor gate (continuing the v0.6.4 blob-purge style): a `#[test]`
4702    // battery whose sole CI contract is the ordinary `cargo test` exit code — NO
4703    // grepped uppercase marker, NO bash env-var mutation loop. Every test is prefixed
4704    // `config_json_gate_` so the CI lane filters with `cargo test … config_json`. The
4705    // apply-manifest half (version current-schema-only, bad-route compile-check) lives
4706    // in `boatramp::apply`'s test module under the same prefix.
4707    // =======================================================================
4708
4709    /// Detection: `resolve_format` follows the explicit-override-wins, else
4710    /// `.json`⇒Json / everything-else⇒Ron rule (no content-sniffing).
4711    #[test]
4712    fn config_json_gate_resolve_format_table() {
4713        use std::path::Path;
4714        // Auto by extension.
4715        assert_eq!(
4716            resolve_format(Path::new("boatramp.json"), None),
4717            ConfigFormat::Json
4718        );
4719        assert_eq!(
4720            resolve_format(Path::new("apply.cfg"), None),
4721            ConfigFormat::Ron
4722        );
4723        assert_eq!(
4724            resolve_format(Path::new("apply.ron"), None),
4725            ConfigFormat::Ron
4726        );
4727        // No extension ⇒ Ron.
4728        assert_eq!(resolve_format(Path::new("apply"), None), ConfigFormat::Ron);
4729        // Case-insensitive `.json`.
4730        assert_eq!(
4731            resolve_format(Path::new("x.JSON"), None),
4732            ConfigFormat::Json
4733        );
4734        // Explicit override wins BOTH ways.
4735        assert_eq!(
4736            resolve_format(Path::new("x.json"), Some(ConfigFormat::Ron)),
4737            ConfigFormat::Ron
4738        );
4739        assert_eq!(
4740            resolve_format(Path::new("x.cfg"), Some(ConfigFormat::Json)),
4741            ConfigFormat::Json
4742        );
4743    }
4744
4745    /// Equivalence: a representative serve config authored in RON and in equivalent
4746    /// JSON parses to the SAME field values — including the externally-tagged
4747    /// enum-variant field `[serve].blobs` (`BlobBackend::S3`; RON `s3` ≡ JSON `"s3"`),
4748    /// proving variant-name fidelity through the JSON decoder.
4749    #[test]
4750    fn config_json_gate_serve_ron_and_json_are_equivalent() {
4751        let ron = r#"( serve: ( addr: "0.0.0.0:8080", blobs: s3, s3_bucket: "b" ) )"#;
4752        let json = r#"{ "serve": { "addr": "0.0.0.0:8080", "blobs": "s3", "s3_bucket": "b" } }"#;
4753        let from_ron = ServerConfig::parse_with_format(ron, ConfigFormat::Ron).unwrap();
4754        let from_json = ServerConfig::parse_with_format(json, ConfigFormat::Json).unwrap();
4755        let s_ron = from_ron.serve.unwrap();
4756        let s_json = from_json.serve.unwrap();
4757        assert_eq!(s_ron.blobs, Some(crate::backends::BlobBackend::S3));
4758        assert_eq!(s_json.blobs, Some(crate::backends::BlobBackend::S3));
4759        assert_eq!(s_ron.blobs, s_json.blobs, "the enum variant survives JSON");
4760        assert_eq!(s_ron.addr, s_json.addr);
4761        assert_eq!(s_ron.s3_bucket, s_json.s3_bucket);
4762        assert_eq!(s_json.s3_bucket.as_deref(), Some("b"));
4763    }
4764
4765    /// Equivalence (project): a `project.cfg` authored in RON and in equivalent JSON
4766    /// parses to the same publish target.
4767    #[test]
4768    fn config_json_gate_project_ron_and_json_are_equivalent() {
4769        let ron = r#"( publish: ( project: "team-x" ) )"#;
4770        let json = r#"{ "publish": { "project": "team-x" } }"#;
4771        let from_ron = ProjectConfig::parse_with_format(ron, ConfigFormat::Ron).unwrap();
4772        let from_json = ProjectConfig::parse_with_format(json, ConfigFormat::Json).unwrap();
4773        assert_eq!(from_ron.publish.project.as_deref(), Some("team-x"));
4774        assert_eq!(from_ron.publish.project, from_json.publish.project);
4775    }
4776
4777    /// `deny_unknown_fields` parity: a JSON serve config with an extra/typo'd field is
4778    /// a hard parse error, not a silent drop (the `[serve.blob_fallback]`
4779    /// `deny_unknown_fields` struct is the RON parity partner tested above).
4780    #[test]
4781    fn config_json_gate_serve_json_denies_unknown_fields() {
4782        let json = r#"{ "serve": { "blob_fallback": { "blobs": "fs", "bogus": 1 } } }"#;
4783        assert!(
4784            ServerConfig::parse_with_format(json, ConfigFormat::Json).is_err(),
4785            "an unknown JSON field must be rejected (deny_unknown_fields), same as RON"
4786        );
4787    }
4788
4789    /// No-bypass: post-parse validation runs regardless of format. A JSON serve config
4790    /// with an invalid `handlers.bindings.sql.databases` db-name (a `/`-bearing,
4791    /// non-URL-path-safe name) is rejected identically to RON — the SAME
4792    /// `ConfigError::InvalidDbName`, from the SAME `validate_sql_db_names` choke point.
4793    #[test]
4794    fn config_json_gate_json_bad_db_name_is_rejected_like_ron() {
4795        // The invalid binding name `a/b` (a path separator) fails the canonical
4796        // resource-name validator that `validate_sql_db_names` runs after the parse.
4797        let json = r#"{ "handlers": { "bindings": { "sql": {
4798            "databases": { "a/b": { "kind": "postgres", "url_env": "DB_URL" } }
4799        } } } }"#;
4800        let ron = r#"( handlers: ( bindings: ( sql: (
4801            databases: { "a/b": ( kind: "postgres", url_env: "DB_URL" ) }
4802        ) ) ) )"#;
4803        let json_err = ServerConfig::parse_with_format(json, ConfigFormat::Json)
4804            .expect_err("a bad db-name in a JSON config must be rejected");
4805        let ron_err = ServerConfig::parse_with_format(ron, ConfigFormat::Ron)
4806            .expect_err("a bad db-name in a RON config must be rejected");
4807        assert!(
4808            matches!(json_err, ConfigError::InvalidDbName { .. }),
4809            "JSON bad db-name is InvalidDbName, got {json_err:?}"
4810        );
4811        assert!(
4812            matches!(ron_err, ConfigError::InvalidDbName { .. }),
4813            "RON bad db-name is InvalidDbName, got {ron_err:?}"
4814        );
4815    }
4816
4817    /// Anti-hollow (typed, in-process): a document valid as JSON but NOT as RON MUST
4818    /// parse under `Json` and FAIL under `Ron`. If `parse_with_format` ignored `fmt`
4819    /// and always decoded RON, the JSON leg would fail — so the format selection is
4820    /// proven load-bearing, with no env var and no marker.
4821    #[test]
4822    fn config_json_gate_serve_format_selection_is_load_bearing() {
4823        // A bare JSON object is valid JSON for `ServerConfig`, not valid RON for it
4824        // (RON structs use `( … )`, not a brace map).
4825        let doc = r#"{ "serve": { "s3_bucket": "only-json" } }"#;
4826        let as_json = ServerConfig::parse_with_format(doc, ConfigFormat::Json).unwrap();
4827        assert_eq!(
4828            as_json.serve.unwrap().s3_bucket.as_deref(),
4829            Some("only-json")
4830        );
4831        assert!(
4832            ServerConfig::parse_with_format(doc, ConfigFormat::Ron).is_err(),
4833            "the same document must FAIL under Ron — else the fmt selection is hollow"
4834        );
4835    }
4836}