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, Serialize};
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    /// A `[serve.listeners.<name>]` (host-owned inbound-TCP listener, PLAN-handler-tcp-inbound) is
129    /// invalid: a blank `component`, a non-positive `max_conns`/timeout, a declared-but-unsupported
130    /// `tls` block (Phase 1 is plaintext-only), or a non-empty `egress_allowlist` (a
131    /// `tcp-connection-host` guest imports only `wasi:io` — it cannot hold `wasi:sockets`). Refused at
132    /// config load (fail-closed, boot-LOUD) rather than binding a listener that would silently
133    /// mislead the operator.
134    #[error("inbound TCP listener {name:?}: {reason}{cure}")]
135    InvalidListener {
136        /// The offending listener key (the `listeners` map key).
137        name: String,
138        /// Why it was rejected.
139        reason: &'static str,
140        /// A trailing remediation hint (empty unless there is a concrete cure to point at).
141        cure: &'static str,
142    },
143    /// The layered config pipeline failed to resolve/extract the merged config (a bad
144    /// numeric/addr env value that figment's lossy coercion rejects, a `[cluster]` missing
145    /// its required `listen`, etc.). The figment error is rendered to a string so
146    /// `ConfigError` stays small.
147    #[error("config resolution: {0}")]
148    Resolve(String),
149}
150
151/// Project configuration, loaded from `project.cfg` (RON) in the project folder.
152///
153/// Read by the client commands (`sync`, `build`, `bundle`, `validate`).
154/// Everything is optional; a missing file is the default.
155#[derive(Debug, Default, Deserialize)]
156#[serde(default)]
157pub struct ProjectConfig {
158    /// Where and how to publish this project.
159    pub publish: PublishConfig,
160    /// Optional build step run before `sync`.
161    pub build: Option<BuildConfig>,
162    /// Optional embedded-bundler step (`bundler` feature).
163    pub bundle: Option<BundleConfig>,
164    /// Deploy-scoped routing/handlers config. Folded into the deployment
165    /// manifest at `sync` (so it is atomic with the content and rolls back with
166    /// it). The bulk of a project's config — redirects, rewrites, headers,
167    /// handlers, consumers, crons, streams.
168    pub routing: DeployConfig,
169}
170
171impl ProjectConfig {
172    /// Parse a `project.cfg` document as **RON** (the default). Kept for the existing
173    /// callers/tests; [`Self::parse_with_format`] is the format-aware entry point.
174    pub fn parse(text: &str) -> Result<Self, ConfigError> {
175        Self::parse_with_format(text, ConfigFormat::Ron)
176    }
177
178    /// Parse a `project.cfg` document in `fmt` (RON or JSON). The deserializer is
179    /// selected by format (RON ⇒ [`ron_options`], JSON ⇒ `serde_json`) into the SAME
180    /// typed struct; the `routing` section is then compile-checked (route patterns,
181    /// cron schedules, imports) regardless of format so a bad config fails fast.
182    pub fn parse_with_format(text: &str, fmt: ConfigFormat) -> Result<Self, ConfigError> {
183        let config: Self = match fmt {
184            ConfigFormat::Ron => ron_options().from_str(text)?,
185            ConfigFormat::Json => serde_json::from_str(text)?,
186        };
187        config.routing.compile_check()?;
188        Ok(config)
189    }
190
191    /// Load from `path`, decoding as RON or JSON per [`resolve_format`] (`override_`
192    /// wins; else `.json` ⇒ JSON, everything else ⇒ RON). A missing file yields the
193    /// default config (unlike an apply manifest).
194    pub fn load(path: &Path, override_: Option<ConfigFormat>) -> Result<Self, ConfigError> {
195        let fmt = resolve_format(path, override_);
196        match std::fs::read_to_string(path) {
197            Ok(contents) => {
198                Self::parse_with_format(&contents, fmt).map_err(|err| ConfigError::File {
199                    path: path.display().to_string(),
200                    source: Box::new(err),
201                })
202            }
203            Err(err) if err.kind() == std::io::ErrorKind::NotFound => Ok(Self::default()),
204            Err(err) => Err(err.into()),
205        }
206    }
207}
208
209/// Server daemon configuration, loaded from `boatramp.cfg` (RON). Read by
210/// `boatramp serve`; flags/env override the `serve` values.
211#[derive(Debug, Default, Serialize, Deserialize)]
212#[serde(default)]
213pub struct ServerConfig {
214    /// Server defaults for `serve` (flag/env override these).
215    pub serve: Option<ServeConfig>,
216    /// Server-side handler runtime config (which backend serves each binding),
217    /// consumed only with the `handlers` feature.
218    pub handlers: Option<HandlersConfig>,
219    /// Self-hosted cluster mode (consumed only with the `cluster` feature).
220    pub cluster: Option<ClusterConfig>,
221    /// Opt-in **compute** backends. Present ⇒ this node
222    /// runs compute workloads via the backends it can offer; absent ⇒ no compute
223    /// (the reconcile loop stays a no-op).
224    pub compute: Option<ComputeConfig>,
225    /// Operator security posture (the hardening knobs): a profile
226    /// preset + overrides, resolved at startup. Absent ⇒ the strict
227    /// `multi-tenant` default. Operator-only — never part of site config.
228    pub security: Option<boatramp_core::security::SecurityConfig>,
229    /// Secrets-at-rest envelope. Absent ⇒ private
230    /// keys stored cleartext in the (replicated) control plane.
231    pub secrets: Option<SecretsConfig>,
232}
233
234/// `secrets` section — envelope encryption for private keys at rest.
235#[cfg_attr(not(feature = "cluster"), allow(dead_code))]
236#[derive(Debug, Clone, Default, Serialize, Deserialize)]
237#[serde(default, deny_unknown_fields)]
238pub struct SecretsConfig {
239    /// Backend: `"local"` (machine-local AES-256-GCM KEK) or `"vault"` (Vault
240    /// Transit). Empty/other ⇒ no wrapping. In a cluster a local KEK must be the
241    /// **same file on every node** (wrapped certs replicate); Vault avoids that.
242    pub envelope: String,
243    /// Local-KEK key file (`envelope = "local"`). Default
244    /// `<data-dir>/secrets/kek`. Auto-generated `0600` if absent.
245    pub kek_file: Option<PathBuf>,
246    /// Vault Transit config (`envelope = "vault"`).
247    pub vault: Option<VaultSecretsConfig>,
248}
249
250/// Vault Transit settings for `envelope = "vault"`. The token is read from the
251/// environment (`token_env`), never stored in the config file.
252#[cfg_attr(not(all(feature = "cluster", feature = "acme-dns")), allow(dead_code))]
253#[derive(Debug, Clone, Serialize, Deserialize)]
254#[serde(deny_unknown_fields)]
255pub struct VaultSecretsConfig {
256    /// Vault address, e.g. `https://vault:8200`.
257    pub addr: String,
258    /// Transit key name to wrap under.
259    pub key: String,
260    /// Environment variable holding the Vault token (default `VAULT_TOKEN`).
261    #[serde(default = "default_vault_token_env")]
262    pub token_env: String,
263}
264
265fn default_vault_token_env() -> String {
266    "VAULT_TOKEN".to_string()
267}
268
269impl Default for VaultSecretsConfig {
270    fn default() -> Self {
271        Self {
272            addr: String::new(),
273            key: String::new(),
274            token_env: default_vault_token_env(),
275        }
276    }
277}
278
279/// The RESERVED compute-workload name prefix (#501 Stage B LOW-2). boatramp DERIVES the
280/// per-project managed-database server workloads with this prefix
281/// (`boatramp_storage::tenant_provision::DERIVED_MANAGED_DB_PREFIX`), so an operator must
282/// NOT name a static `[handlers].bindings.sql.databases.*.compute` workload with it — a
283/// collision could shadow / alias a derived managed server. Screened fail-closed at
284/// config load ([`ServerConfig::validate_sql_db_names`]). Kept as a literal here (not the
285/// `boatramp-storage` const) so the screen holds on a build without the sql engine
286/// features; the two must stay in sync (a single source of truth would couple config
287/// loading to the optional storage dep).
288const RESERVED_MANAGED_DB_COMPUTE_PREFIX: &str = "bramp-db-";
289
290impl ServerConfig {
291    /// Parse a `boatramp.cfg` document as **RON** (the default). Kept for the existing
292    /// callers/tests; [`Self::parse_with_format`] is the format-aware entry point.
293    pub fn parse(text: &str) -> Result<Self, ConfigError> {
294        Self::parse_with_format(text, ConfigFormat::Ron)
295    }
296
297    /// Parse a `boatramp.cfg` document in `fmt` (RON or JSON). The deserializer is
298    /// selected by format (RON ⇒ [`ron_options`], JSON ⇒ `serde_json`) into the SAME
299    /// typed struct. Db-binding names declared in the file are validated here (the same
300    /// fail-closed check `load` re-runs after the env merge) **regardless of format**, so
301    /// a file-only config path — e.g. `boatramp cloudflare` rendering, or the
302    /// operator-resources loader — is guarded even without going through `load`.
303    pub fn parse_with_format(text: &str, fmt: ConfigFormat) -> Result<Self, ConfigError> {
304        let config: Self = match fmt {
305            ConfigFormat::Ron => ron_options().from_str(text)?,
306            ConfigFormat::Json => serde_json::from_str(text)?,
307        };
308        config.validate_sql_db_names()?;
309        config.validate_blob_backend_projects()?;
310        config.validate_listeners()?;
311        Ok(config)
312    }
313
314    /// Load from `path`, decoding as RON or JSON per [`resolve_format`] (`override_`
315    /// wins; else `.json` ⇒ JSON, everything else ⇒ RON), then layer `BOATRAMP_*`
316    /// environment overrides on top. A missing file yields the default config, so
317    /// `serve` can be configured entirely from the environment (12-factor deployments
318    /// where dropping a `boatramp.cfg` is awkward — fly.io / Cloudflare / containers).
319    ///
320    /// The env-override merge runs AFTER the parse for either format — JSON is only an
321    /// alternative decoder into the same typed struct; it does not change the
322    /// file < env precedence.
323    pub fn load(path: &Path, override_: Option<ConfigFormat>) -> Result<Self, ConfigError> {
324        // The ONE layered pipeline (defaults → file → env), used by serve AND every offline
325        // op. With no explicit CLI flags here, this is file + env; the serve binary passes its
326        // `ValueSource::CommandLine` flags as the top layer via `load_with_flags`.
327        figment_resolve::load_with_figment(
328            path,
329            override_,
330            &EnvSource::Process,
331            figment::value::Dict::new(),
332        )
333    }
334
335    /// Load through the pipeline with an explicit **CLI-flag** top layer. `cli_flags` is a map
336    /// `{BOATRAMP_<NAME>: raw-value}` of the args the operator set on the COMMAND LINE (the
337    /// serve binary builds it from `clap::ArgMatches`, keeping only `ValueSource::CommandLine`
338    /// — so a defaulted `--blobs fs` is absent and never clobbers file/env, subsuming the old
339    /// `--blobs` `var_os` probe). Resolution is `base-seed → file → env → these flags`. Keys
340    /// the overlay doesn't recognise (runtime/selector flags like `--tls`, the cluster-action
341    /// flags) are ignored, so they never enter the config. The binary passes a plain map —
342    /// figment types stay internal to this crate.
343    pub fn load_with_flags(
344        path: &Path,
345        override_: Option<ConfigFormat>,
346        cli_flags: &BTreeMap<String, String>,
347    ) -> Result<Self, ConfigError> {
348        let flags = figment_resolve::flag_overlay_dict(cli_flags);
349        figment_resolve::load_with_figment(path, override_, &EnvSource::Process, flags)
350    }
351
352    /// Serialize the (already-resolved) config for `boatramp config dump`, with the
353    /// secret-bearing fields REDACTED. The config is `Serialize` (for the file layer), which
354    /// would otherwise expose the control-plane root key / bootstrap secret / azure access
355    /// key / signer key / join-token in a dump. Returns pretty JSON (also a valid config
356    /// input format).
357    pub fn dump_redacted(&self) -> Result<String, ConfigError> {
358        figment_resolve::dump_redacted(self)
359    }
360
361    /// Test-only adapter: layer the `BOATRAMP_*` env overlay over `self` (the base/file) THROUGH
362    /// the real figment pipeline. The production Loader-B `apply_env_overrides` is gone; this thin
363    /// delegator keeps the pre-figment env tests — which assert specific resolved fields after
364    /// `cfg.apply_env_overrides(&env(…))` — running against the ONE pipeline (so they are genuine
365    /// figment tests, not a second implementation).
366    #[cfg(test)]
367    fn apply_env_overrides(&mut self, source: &EnvSource) -> Result<(), ConfigError> {
368        *self = figment_resolve::resolve_env_over(self, source)?;
369        Ok(())
370    }
371
372    /// Validate every configured `handlers.bindings.sql.databases` binding name
373    /// through the one canonical [`validate_resource_name`](boatramp_core::project::validate_resource_name)
374    /// (`kind = "database"`). A db-binding name is threaded verbatim into the
375    /// control-plane URL (`/api/sql/{db}/…`, `/api/migrate/{db}/…`) and the CLI
376    /// `--db`, so it must be a non-empty, path-segment-safe identifier — the same rule
377    /// project/site/function names already pass. The empty-string legacy default key
378    /// gets a targeted cure pointing at the reserved `default` name.
379    ///
380    /// Also screens each binding's `compute` field against the
381    /// [`RESERVED_MANAGED_DB_COMPUTE_PREFIX`] (#501 Stage B LOW-2): the `bramp-db-`
382    /// prefix is reserved for the derived per-project managed-DB server workloads, so an
383    /// operator may not point a static BYO binding at a `bramp-db-…` workload.
384    fn validate_sql_db_names(&self) -> Result<(), ConfigError> {
385        let Some(databases) = self
386            .handlers
387            .as_ref()
388            .and_then(|h| h.bindings.sql.as_ref())
389            .map(|s| &s.databases)
390        else {
391            return Ok(());
392        };
393        for (name, db) in databases {
394            if let Err(err) = boatramp_core::project::validate_resource_name("database", name) {
395                // The empty-string case is the pre-v0.5.0 default binding key: point
396                // at the cure (name it `default`, or set nothing and let the reserved
397                // `DEFAULT` token map to `default` automatically). Any other
398                // non-conforming name gets the v0.7.0 slug cure pointing at
399                // `project doctor`. This is a boot-LOUD refusal — an operator learns of
400                // a bad name at `serve` boot, not at the first request.
401                let cure = if name.is_empty() {
402                    " — name your default binding `default` (or set \
403                     BOATRAMP_HANDLERS_SQL_DB_DEFAULT_*, which now maps to `default` \
404                     automatically); see the v0.5.0 CHANGELOG"
405                } else {
406                    boatramp_core::project::INVALID_NAME_CURE
407                };
408                return Err(ConfigError::InvalidDbName {
409                    name: err.value,
410                    reason: err.reason,
411                    cure,
412                });
413            }
414            // #501 Stage B LOW-2: the `bramp-db-` compute-workload prefix is RESERVED for
415            // the derived per-project managed-DB server workloads
416            // (`boatramp_storage::tenant_provision::DERIVED_MANAGED_DB_PREFIX`). An operator
417            // must not point a static BYO binding at a `compute` workload with that prefix —
418            // it could shadow / alias a derived managed server. Screen it fail-closed at
419            // config load (cheap: a `starts_with` on an already-parsed field).
420            if let Some(compute) = db.compute.as_deref()
421                && compute.starts_with(RESERVED_MANAGED_DB_COMPUTE_PREFIX)
422            {
423                return Err(ConfigError::InvalidDbName {
424                    name: compute.to_string(),
425                    reason: "the `bramp-db-` compute-workload prefix is reserved for \
426                             boatramp-derived managed-database servers",
427                    cure: " — rename the `compute` workload to not start with `bramp-db-`",
428                });
429            }
430        }
431        Ok(())
432    }
433
434    /// Validate every configured `[serve.blob_backends.<project>]` key
435    /// (PLAN-per-project-blob-backend). A key must be a valid project name (the canonical
436    /// [`validate_resource_name`](boatramp_core::project::validate_resource_name), `kind = "project"`),
437    /// and must NOT be the reserved `default` project: the `default` project ALWAYS resolves the global
438    /// `[serve]` backend (invariant 5), so a `[serve.blob_backends.default]` entry would be ambiguous
439    /// (the node-wide backend is configured under `[serve]`, not here). Both are boot-LOUD refusals
440    /// (fail-closed — an operator learns of a bad name at `serve` boot, not at the first request). The
441    /// project the entry binds to is host-routed at serve time, never guest input (invariant 1).
442    fn validate_blob_backend_projects(&self) -> Result<(), ConfigError> {
443        let Some(serve) = self.serve.as_ref() else {
444            return Ok(());
445        };
446        for name in serve.blob_backends.keys() {
447            if name == boatramp_core::project::DEFAULT_PROJECT {
448                return Err(ConfigError::InvalidBlobBackendProject {
449                    name: name.clone(),
450                    reason: "the reserved `default` project always resolves the global [serve] blob \
451                             backend",
452                    cure: " — configure the node-wide backend under [serve] (blobs/s3_*), not \
453                           [serve.blob_backends.default]",
454                });
455            }
456            if let Err(err) = boatramp_core::project::validate_resource_name("project", name) {
457                return Err(ConfigError::InvalidBlobBackendProject {
458                    name: err.value,
459                    reason: err.reason,
460                    cure: boatramp_core::project::INVALID_NAME_CURE,
461                });
462            }
463        }
464        Ok(())
465    }
466
467    /// Validate every configured `[serve.listeners.<name>]` (PLAN-handler-tcp-inbound), fail-closed +
468    /// boot-LOUD on the fully merged (file + env) map. A host-owned inbound-TCP listener is a new,
469    /// unproven surface, so a half-declared or Phase-1-unsupported one REFUSES the node rather than
470    /// binding something that would silently mislead the operator:
471    /// - a blank `bind` / `component` / `project` / `site` (all required),
472    /// - a `max_conns` / `idle_timeout_ms` / `max_conn_duration_ms` explicitly set to `0`,
473    /// - a declared `tls` block (Phase 1 is plaintext-only — deferred fast-follow),
474    /// - a non-empty `egress_allowlist` (a `tcp-connection-host` guest imports only `wasi:io`; it
475    ///   cannot hold `wasi:sockets`, so per-listener outbound egress is a deferred follow-up).
476    fn validate_listeners(&self) -> Result<(), ConfigError> {
477        let Some(serve) = self.serve.as_ref() else {
478            return Ok(());
479        };
480        for (name, l) in &serve.listeners {
481            let err = |reason: &'static str, cure: &'static str| {
482                Err(ConfigError::InvalidListener {
483                    name: name.clone(),
484                    reason,
485                    cure,
486                })
487            };
488            if l.bind.is_none() {
489                return err(
490                    "missing `bind` address",
491                    " — set `bind = \"0.0.0.0:<port>\"`",
492                );
493            }
494            if l.component.trim().is_empty() {
495                return err("missing `component` (the guest .wasm path)", "");
496            }
497            if l.project.trim().is_empty() {
498                return err("missing `project`", "");
499            }
500            if l.site.trim().is_empty() {
501                return err("missing `site`", "");
502            }
503            if l.max_conns == Some(0) {
504                return err("`max_conns` must be > 0", " — omit it for the default");
505            }
506            if l.idle_timeout_ms == Some(0) {
507                return err(
508                    "`idle_timeout_ms` must be > 0",
509                    " — omit it for the default",
510                );
511            }
512            if l.max_conn_duration_ms == Some(0) {
513                return err(
514                    "`max_conn_duration_ms` must be > 0",
515                    " — omit it for the default",
516                );
517            }
518            // Host-side per-listener TLS termination (cap-req 06): a declared `tls` block is honored,
519            // but it MUST name both a cert and a key (the host loads them + terminates TLS, handing the
520            // guest a decrypted plaintext stream). This holds for BOTH implicit TLS (465/993) and
521            // STARTTLS (25/587/143) — STARTTLS still terminates TLS after the in-band upgrade.
522            if let Some(tls) = &l.tls {
523                if tls.cert_file.is_none() || tls.key_file.is_none() {
524                    return err(
525                        "listener `tls` requires both `cert_file` and `key_file`",
526                        " — set cert_file/key_file (PEM), or remove the `tls` block for a plaintext listener",
527                    );
528                }
529                // Declarative STARTTLS grammar (cap-req 06, Stage B): the one piece of protocol data.
530                if let Some(st) = &tls.starttls {
531                    if st.trigger.trim().is_empty() {
532                        return err(
533                            "listener `tls.starttls.trigger` must be non-empty",
534                            " — e.g. trigger = \"STARTTLS\" (SMTP/IMAP) or \"STLS\" (POP3)",
535                        );
536                    }
537                    if st.response.trim().is_empty() {
538                        return err(
539                            "listener `tls.starttls.response` must be non-empty",
540                            " — the line the host sends before upgrading, e.g. \"220 Ready to start TLS\"",
541                        );
542                    }
543                    // `{tag}` in the response is only meaningful when a tag is captured — otherwise the
544                    // literal `{tag}` would leak to the wire.
545                    if st.response.contains("{tag}") && !st.tag_capture {
546                        return err(
547                            "listener `tls.starttls.response` uses `{tag}` but `tag_capture` is false",
548                            " — set tag_capture = true (IMAP-style), or remove the {tag} placeholder",
549                        );
550                    }
551                    // trigger/response are matched against / written as a single line — refuse embedded
552                    // CR/LF (which would split the line and could inject a second response line).
553                    if st.trigger.contains(['\r', '\n']) || st.response.contains(['\r', '\n']) {
554                        return err(
555                            "listener `tls.starttls` trigger/response must not contain CR or LF",
556                            " — they are a single line; the host appends CRLF to the response",
557                        );
558                    }
559                }
560                // On-demand per-SNI issuance for this listener (cap-req 03 #4) shares the node's one
561                // on-demand engine — it is meaningless (and silently a no-op) unless that engine runs.
562                if tls.on_demand && !serve.on_demand_tls.as_ref().is_some_and(|o| o.enabled) {
563                    return err(
564                        "listener `tls.on_demand` requires `[serve.on_demand_tls] enabled = true`",
565                        " — enable node on-demand TLS, or set on_demand = false to serve only the static cert",
566                    );
567                }
568            }
569            if !l.egress_allowlist.is_empty() {
570                return err(
571                    "per-listener outbound `egress_allowlist` is not supported (a tcp-connection-host \
572                     guest imports only wasi:io — it cannot hold wasi:sockets)",
573                    " — remove `egress_allowlist`",
574                );
575            }
576        }
577        Ok(())
578    }
579}
580
581/// The `BOATRAMP_*` variables that populate the `[compute]` section. Kept as one
582/// list so [`ServerConfig::apply_env_overrides`] can decide whether to materialise
583/// an absent section without repeating the names.
584const COMPUTE_ENV_VARS: &[&str] = &[
585    "BOATRAMP_COMPUTE_BRIDGE",
586    "BOATRAMP_COMPUTE_SUBNET",
587    "BOATRAMP_COMPUTE_VCPUS",
588    "BOATRAMP_COMPUTE_MEM_MIB",
589    "BOATRAMP_COMPUTE_REGION",
590    "BOATRAMP_COMPUTE_SQL_SHIM_URL",
591    "BOATRAMP_COMPUTE_BLOB_SHIM_URL",
592    "BOATRAMP_COMPUTE_MESSAGING_SHIM_URL",
593    "BOATRAMP_COMPUTE_BLOB_SHIM_MAX_OBJECT_BYTES",
594    "BOATRAMP_COMPUTE_MANAGED_DB_PRIVILEGE",
595    "BOATRAMP_COMPUTE_DOCKER_ENDPOINT",
596    "BOATRAMP_COMPUTE_DOCKER_VOLUME_MODE",
597    "BOATRAMP_COMPUTE_KERNEL_SIGNING_PUBKEYS",
598    "BOATRAMP_COMPUTE_KERNEL_ALLOWED_HASHES",
599    "BOATRAMP_COMPUTE_INTERNAL_DNS",
600    "BOATRAMP_COMPUTE_DNS_UPSTREAM",
601    "BOATRAMP_COMPUTE_DNS_DOMAIN",
602    "BOATRAMP_COMPUTE_PG_CLIENT_IMAGE",
603    "BOATRAMP_COMPUTE_MYSQL_CLIENT_IMAGE",
604];
605
606/// The `BOATRAMP_*` variables that populate the `[security]` section.
607const SECURITY_ENV_VARS: &[&str] = &[
608    "BOATRAMP_SECURITY_PROFILE",
609    "BOATRAMP_SECURITY_ALLOW_UNAUTHENTICATED_PUBLIC_BIND",
610    "BOATRAMP_SECURITY_MAX_UPLOAD_BYTES",
611    "BOATRAMP_SECURITY_ALLOW_SITE_UNIX_UPSTREAMS",
612    "BOATRAMP_SECURITY_ALLOW_SITE_PRIVATE_UPSTREAMS",
613    "BOATRAMP_SECURITY_ALLOW_GUEST_PRIVATE_EGRESS",
614    "BOATRAMP_SECURITY_ALLOW_GUEST_SELF_EGRESS",
615    "BOATRAMP_SECURITY_ALLOW_GUEST_EGRESS_EXTRA_CA",
616    "BOATRAMP_SECURITY_ALLOW_GUEST_TCP_EGRESS",
617    "BOATRAMP_SECURITY_ALLOW_GUEST_TCP_LISTENER",
618    "BOATRAMP_SECURITY_MAX_HANDLER_BLOB_BYTES",
619    "BOATRAMP_SECURITY_MAX_COMPONENT_BYTES",
620    "BOATRAMP_SECURITY_OIDC_REQUIRE_AUDIENCE",
621    "BOATRAMP_SECURITY_DOMAIN_VERIFY_ALLOW_PRIVATE",
622    "BOATRAMP_SECURITY_DOMAIN_VERIFY_SELF_SERVE",
623    "BOATRAMP_SECURITY_ALLOW_SHARED_KERNEL_COMPUTE",
624    "BOATRAMP_SECURITY_ALLOW_COMPUTE_EXEC",
625    "BOATRAMP_SECURITY_ALLOW_DEV_BLOB_BIND",
626    "BOATRAMP_SECURITY_ALLOW_DEV_MESSAGING_BIND",
627    "BOATRAMP_SECURITY_RATELIMIT_FAIL_OPEN",
628    "BOATRAMP_SECURITY_ALLOW_IMPLICIT_ROUTING",
629    "BOATRAMP_SECURITY_REQUIRE_POP",
630    "BOATRAMP_SECURITY_REQUIRE_DOMAIN_VERIFICATION",
631    "BOATRAMP_SECURITY_ALLOW_ENV_SECRET_REFS",
632    "BOATRAMP_SECURITY_REQUIRE_TENANCY_DECLARATION",
633    "BOATRAMP_SECURITY_ALLOW_CROSS_TENANT_DB",
634    "BOATRAMP_SECURITY_ALLOW_GUEST_MINT_CAPABILITY",
635    "BOATRAMP_SECURITY_MAX_GUEST_CAPABILITY_TTL_SECS",
636    "BOATRAMP_SECURITY_ALLOW_GUEST_EMAIL",
637    "BOATRAMP_SECURITY_ALLOW_GUEST_ADMIN_DOMAINS",
638    "BOATRAMP_SECURITY_ALLOW_GUEST_ADMIN_EMAIL",
639    "BOATRAMP_SECURITY_ALLOW_GUEST_ADMIN_SITE",
640    "BOATRAMP_SECURITY_ALLOW_GUEST_ADMIN_SECRETS",
641];
642
643/// The `BOATRAMP_*` variables that populate `handlers.bindings.sql`.
644const SQL_ENV_VARS: &[&str] = &[
645    "BOATRAMP_HANDLERS_SQL_DIR",
646    "BOATRAMP_HANDLERS_SQL_URL",
647    "BOATRAMP_HANDLERS_SQL_ADMIN_URL",
648    "BOATRAMP_HANDLERS_SQL_REPLICA_URL",
649    "BOATRAMP_HANDLERS_SQL_TOKEN_ENV",
650    "BOATRAMP_HANDLERS_SQL_ADMIN_TOKEN_ENV",
651    "BOATRAMP_HANDLERS_SQL_PREVIEW_MODE",
652    "BOATRAMP_HANDLERS_SQL_PREVIEW_INIT",
653    "BOATRAMP_HANDLERS_SQL_DEPROVISION_GRACE_SECS",
654    "BOATRAMP_HANDLERS_SQL_MIGRATE_TRUSTED_EXTENSIONS",
655    "BOATRAMP_HANDLERS_SQL_MAX_DECLARED_DATABASES",
656    "BOATRAMP_HANDLERS_SQL_MAX_DECLARED_VOLUME_MIB",
657];
658
659/// The `[handlers]` JWKS-freshness env levers (two-tier own/foreign refresh + hard-ttl + prewarm),
660/// mirroring the `jwks_*` fields on [`HandlersConfig`]. Kept in sync by the forgot-a-knob guard test.
661const JWKS_ENV_VARS: &[&str] = &[
662    "BOATRAMP_HANDLERS_JWKS_REFRESH_SECS",
663    "BOATRAMP_HANDLERS_JWKS_HARD_TTL_SECS",
664    "BOATRAMP_HANDLERS_JWKS_FOREIGN_REFRESH_SECS",
665    "BOATRAMP_HANDLERS_JWKS_FOREIGN_HARD_TTL_SECS",
666    "BOATRAMP_HANDLERS_JWKS_PREWARM",
667];
668
669/// The `[handlers]` concurrency-lane env levers (per-component serve-admission gate + the global
670/// sync/async lane ceilings), mirroring the `serve_concurrency` / `sync_max_concurrency` /
671/// `async_max_concurrency` fields on [`HandlersConfig`]. Kept in sync by the forgot-a-knob guard test.
672const HANDLER_CONCURRENCY_ENV_VARS: &[&str] = &[
673    "BOATRAMP_HANDLERS_SERVE_CONCURRENCY",
674    "BOATRAMP_HANDLERS_SYNC_MAX_CONCURRENCY",
675    "BOATRAMP_HANDLERS_ASYNC_MAX_CONCURRENCY",
676];
677
678/// The `[handlers]` hedged-blob-read env levers (serve-path fetch-tail cut), mirroring the
679/// `blob_hedge_delay_ms` / `blob_hedge_max_inflight` fields on [`HandlersConfig`]. Kept in sync by the
680/// forgot-a-knob guard test.
681const HANDLER_BLOB_HEDGE_ENV_VARS: &[&str] = &[
682    "BOATRAMP_HANDLERS_BLOB_HEDGE_DELAY_MS",
683    "BOATRAMP_HANDLERS_BLOB_HEDGE_MAX_INFLIGHT",
684];
685
686/// The `[handlers]` cold-start env levers (cap-req 09): the warm floor + the portable AOT
687/// artifact cache, mirroring the `keep_warm_max` / `aot_artifact_cache` /
688/// `aot_artifact_max_bytes` fields on [`HandlersConfig`]. Kept in sync by the forgot-a-knob
689/// guard test.
690const HANDLER_COLDSTART_ENV_VARS: &[&str] = &[
691    "BOATRAMP_HANDLERS_KEEP_WARM_MAX",
692    "BOATRAMP_HANDLERS_AOT_ARTIFACT_CACHE",
693    "BOATRAMP_HANDLERS_AOT_ARTIFACT_MAX_BYTES",
694];
695
696/// The `[serve.s3_ingress_cloud]` env levers (the blob-upload minter's cloud-brokering policy),
697/// mirroring the fields on [`S3IngressCloud`]. Kept in sync by the forgot-a-knob guard test. These are
698/// policy toggles only; the signing credential stays the sealed `[secrets]` one.
699const S3_INGRESS_CLOUD_ENV_VARS: &[&str] = &[
700    "BOATRAMP_S3_INGRESS_CLOUD_AWS_ROLE_ARN",
701    "BOATRAMP_S3_INGRESS_CLOUD_AWS_USE_FEDERATION_TOKEN",
702    "BOATRAMP_S3_INGRESS_CLOUD_AWS_PRESIGNED_ONLY",
703    "BOATRAMP_S3_INGRESS_CLOUD_GCS_CLIENT_EMAIL",
704    "BOATRAMP_S3_INGRESS_CLOUD_AZURE_ACCOUNT",
705    "BOATRAMP_S3_INGRESS_CLOUD_AZURE_SERVICE_URL",
706    "BOATRAMP_S3_INGRESS_CLOUD_AZURE_HNS",
707];
708
709/// The fixed prefix of a keyed `handlers.bindings.sql.databases` variable —
710/// `BOATRAMP_HANDLERS_SQL_DB_<NAME>_<FIELD>`. Member names aren't known ahead of
711/// time (there is no config file to enumerate them), so they are discovered by
712/// scanning the environment for this prefix.
713const SQL_DB_ENV_PREFIX: &str = "BOATRAMP_HANDLERS_SQL_DB_";
714
715/// The recognised `_<FIELD>` suffixes of a `databases` variable, ordered so a
716/// name-isolating strip matches the **longest** suffix first (`_READ_URL_ENV`
717/// before `_URL_ENV`). Each mirrors a field of [`ExternalDatabaseConfig`].
718const SQL_DB_FIELD_SUFFIXES: &[&str] = &[
719    "_STARTUP_GRACE_SECS",
720    "_CONNECT_TIMEOUT_SECS",
721    // `_SESSION_GUC` / `_TENANT_GUC` / `_TENANT_ALL_MARKER` before `_TENANT`/`_TENANT_SCOPE`
722    // (longest-first name isolation).
723    "_SESSION_GUC",
724    "_TENANT_ALL_MARKER",
725    "_TENANT_GUC",
726    "_VOLUME_SIZE_MIB",
727    "_READ_URL_ENV",
728    "_PASSWORD_ENV",
729    "_ALLOW_PREVIEW",
730    "_URL_ENV",
731    "_DATABASE",
732    "_READ_ONLY",
733    "_POOL_MAX",
734    "_RLS_SESSION",
735    "_TENANT_SCOPE",
736    "_COMPUTE",
737    "_TENANT",
738    "_IMAGE",
739    "_KIND",
740    "_USER",
741];
742
743/// The fixed prefix of a keyed `[serve.blob_backends.<project>]` variable —
744/// `BOATRAMP_SERVE_BLOB_BACKEND_<PROJECT>_<FIELD>` (PLAN-per-project-blob-backend). Member project
745/// names aren't known ahead of time (there is no config file to enumerate them), so they are discovered
746/// by scanning the environment for this prefix — mirroring [`SQL_DB_ENV_PREFIX`].
747const BLOB_BACKEND_ENV_PREFIX: &str = "BOATRAMP_SERVE_BLOB_BACKEND_";
748
749/// The recognised `_<FIELD>` suffixes of a `[serve.blob_backends]` variable, ordered so a
750/// name-isolating strip matches the **longest** suffix first (so `_S3_SECRET_ACCESS_KEY` wins over any
751/// shorter overlap). Each mirrors a field of [`BlobBackendConfig`] (the sealed credential's two public
752/// refs are flattened as `_S3_ACCESS_KEY_ID` / `_S3_SECRET_ACCESS_KEY`). Kept in sync by the
753/// `blob_backend_env_covers_every_field` forgot-a-knob guard test.
754const BLOB_BACKEND_FIELD_SUFFIXES: &[&str] = &[
755    "_S3_SECRET_ACCESS_KEY",
756    "_S3_ACCESS_KEY_ID",
757    "_S3_PATH_STYLE",
758    "_S3_ENDPOINT",
759    "_S3_BUCKET",
760    "_S3_REGION",
761    "_KIND",
762];
763
764/// The fixed prefix of a keyed `[serve.listeners.<name>]` variable —
765/// `BOATRAMP_SERVE_LISTENER_<NAME>_<FIELD>` (PLAN-handler-tcp-inbound). Listener names aren't known
766/// ahead of time (there is no config file to enumerate them under env-only config), so they are
767/// discovered by scanning the environment for this prefix — mirroring [`BLOB_BACKEND_ENV_PREFIX`].
768const LISTENER_ENV_PREFIX: &str = "BOATRAMP_SERVE_LISTENER_";
769
770/// The recognised `_<FIELD>` suffixes of a `[serve.listeners]` variable, ordered so a name-isolating
771/// strip matches the **longest** suffix first (so `_MAX_CONN_DURATION_MS` wins over `_MAX_CONNS`). Each
772/// mirrors a SCALAR field of [`ListenerConfig`]; the structured fields (`imports`/`env`/`tenancy`) and
773/// the Phase-1-refused `tls`/`egress_allowlist` are set only from the config file. `_IMPORTS` is a
774/// comma-separated list. Kept in sync by the `listener_env_covers_every_field` forgot-a-knob guard.
775const LISTENER_FIELD_SUFFIXES: &[&str] = &[
776    "_MAX_CONN_DURATION_MS",
777    "_IDLE_TIMEOUT_MS",
778    "_MAX_CONNS",
779    "_COMPONENT",
780    "_IMPORTS",
781    "_PROJECT",
782    "_BIND",
783    "_SITE",
784];
785
786/// The `BOATRAMP_*` variables that populate the `[secrets]` section (excluding the
787/// nested `vault` sub-config, gated separately by [`SECRETS_VAULT_ENV_VARS`]).
788const SECRETS_ENV_VARS: &[&str] = &[
789    "BOATRAMP_SECRETS_ENVELOPE",
790    "BOATRAMP_SECRETS_KEK_FILE",
791    "BOATRAMP_SECRETS_VAULT_ADDR",
792    "BOATRAMP_SECRETS_VAULT_KEY",
793    "BOATRAMP_SECRETS_VAULT_TOKEN_ENV",
794];
795
796/// The `BOATRAMP_*` variables that populate the nested `[secrets.vault]` sub-config.
797const SECRETS_VAULT_ENV_VARS: &[&str] = &[
798    "BOATRAMP_SECRETS_VAULT_ADDR",
799    "BOATRAMP_SECRETS_VAULT_KEY",
800    "BOATRAMP_SECRETS_VAULT_TOKEN_ENV",
801];
802
803/// The `BOATRAMP_*` variables that populate the `[cluster]` section fields (the
804/// section's own config, distinct from the founding/joining *action* flags
805/// `BOATRAMP_CLUSTER_INIT` / `_JOIN` / `_ADVERTISE_ADDR`, which are `serve` clap
806/// args and are deliberately not listed here).
807const CLUSTER_ENV_VARS: &[&str] = &[
808    "BOATRAMP_CLUSTER_LISTEN",
809    "BOATRAMP_CLUSTER_ROOT_PUBKEYS",
810    "BOATRAMP_CLUSTER_SEEDS",
811    "BOATRAMP_CLUSTER_JOIN_TOKEN",
812    "BOATRAMP_CLUSTER_STORE_DIR",
813    "BOATRAMP_CLUSTER_MESH_KEY_FILE",
814    "BOATRAMP_CLUSTER_MESH_KEY_ROTATION",
815    "BOATRAMP_CLUSTER_MESH_JOIN_TOKEN_TTL",
816    "BOATRAMP_CLUSTER_MESH_GATE_CLIENT_WRITES",
817];
818
819/// Where env-override values come from: the real process environment, or an explicit map
820/// (the CLI-flag layer, which reuses the env overlay to turn `{BOATRAMP_<NAME>: value}`
821/// command-line flags into a figment dict; and deterministic unit tests — no racy,
822/// process-global `std::env`).
823pub(crate) enum EnvSource {
824    /// The live process environment (`std::env::var`).
825    Process,
826    /// A fixed name→value map (the CLI-flag layer + tests).
827    Map(BTreeMap<String, String>),
828}
829
830impl EnvSource {
831    /// The value of `var`, if set to a non-empty string. An empty value is treated
832    /// as unset so an accidental `VAR=` doesn't clobber a file value with `""`.
833    fn get(&self, var: &str) -> Option<String> {
834        let raw = match self {
835            Self::Process => std::env::var(var).ok(),
836            Self::Map(m) => m.get(var).cloned(),
837        };
838        raw.filter(|v| !v.is_empty())
839    }
840
841    /// Whether any of `vars` is set (to a non-empty value).
842    fn any(&self, vars: &[&str]) -> bool {
843        vars.iter().any(|v| self.get(v).is_some())
844    }
845
846    /// The full set of variable names visible to this source. Used to discover the
847    /// keyed-map member names from the environment (there is no config file to
848    /// enumerate them). Returned owned so it doesn't borrow the process env.
849    fn names(&self) -> Box<dyn Iterator<Item = String> + '_> {
850        match self {
851            Self::Process => Box::new(std::env::vars().map(|(k, _)| k)),
852            Self::Map(m) => Box::new(m.keys().cloned()),
853        }
854    }
855
856    /// The distinct `<NAME>` tokens of every `BOATRAMP_HANDLERS_SQL_DB_<NAME>_<FIELD>`
857    /// variable that is set. The name is everything between the fixed prefix and the
858    /// *last* `_<FIELD>` segment, so a database name may itself contain underscores
859    /// (the field suffix is one of a known set). Returned sorted + de-duplicated so
860    /// the map is built deterministically.
861    fn sql_database_names(&self) -> Vec<String> {
862        let mut names: Vec<String> = self
863            .names()
864            .filter(|n| n.starts_with(SQL_DB_ENV_PREFIX) && self.get(n).is_some())
865            .filter_map(|n| {
866                let rest = n.strip_prefix(SQL_DB_ENV_PREFIX)?;
867                // Strip the recognised field suffix to isolate `<NAME>`. The suffixes
868                // are matched longest-first so `READ_URL_ENV` wins over `URL_ENV`.
869                SQL_DB_FIELD_SUFFIXES
870                    .iter()
871                    .find_map(|suffix| rest.strip_suffix(suffix))
872                    .filter(|name| !name.is_empty())
873                    .map(str::to_string)
874            })
875            .collect();
876        names.sort();
877        names.dedup();
878        names
879    }
880
881    /// The distinct `<PROJECT>` tokens of every `BOATRAMP_SERVE_BLOB_BACKEND_<PROJECT>_<FIELD>`
882    /// variable that is set (PLAN-per-project-blob-backend). The name is everything between the fixed
883    /// prefix and the *last* `_<FIELD>` segment, so a project name may itself contain underscores (the
884    /// field suffix is one of a known set, matched longest-first). Returned sorted + de-duplicated so
885    /// the map is built deterministically. Mirrors [`Self::sql_database_names`].
886    fn blob_backend_projects(&self) -> Vec<String> {
887        let mut names: Vec<String> = self
888            .names()
889            .filter(|n| n.starts_with(BLOB_BACKEND_ENV_PREFIX) && self.get(n).is_some())
890            .filter_map(|n| {
891                let rest = n.strip_prefix(BLOB_BACKEND_ENV_PREFIX)?;
892                BLOB_BACKEND_FIELD_SUFFIXES
893                    .iter()
894                    .find_map(|suffix| rest.strip_suffix(suffix))
895                    .filter(|name| !name.is_empty())
896                    .map(str::to_string)
897            })
898            .collect();
899        names.sort();
900        names.dedup();
901        names
902    }
903
904    /// The distinct `<NAME>` tokens of every `BOATRAMP_SERVE_LISTENER_<NAME>_<FIELD>` variable that is
905    /// set (PLAN-handler-tcp-inbound). The name is everything between the fixed prefix and the *last*
906    /// `_<FIELD>` segment (suffixes matched longest-first), so a listener name may itself contain
907    /// underscores. Returned sorted + de-duplicated so the map is built deterministically. Mirrors
908    /// [`Self::blob_backend_projects`].
909    fn listener_names(&self) -> Vec<String> {
910        let mut names: Vec<String> = self
911            .names()
912            .filter(|n| n.starts_with(LISTENER_ENV_PREFIX) && self.get(n).is_some())
913            .filter_map(|n| {
914                let rest = n.strip_prefix(LISTENER_ENV_PREFIX)?;
915                LISTENER_FIELD_SUFFIXES
916                    .iter()
917                    .find_map(|suffix| rest.strip_suffix(suffix))
918                    .filter(|name| !name.is_empty())
919                    .map(str::to_string)
920            })
921            .collect();
922        names.sort();
923        names.dedup();
924        names
925    }
926
927    /// Parse `var` as a **comma-separated** list of non-empty trimmed items, e.g.
928    /// the kernel trust anchors. A single value (no comma) yields a one-element
929    /// list. Empty items are dropped so a trailing comma or doubled separator is
930    /// tolerated. `Ok(None)` when unset; `Some(Vec::new())` never happens (an
931    /// all-empty value is treated as unset by [`Self::get`]).
932    fn parse_list(&self, var: &str) -> Option<Vec<String>> {
933        self.get(var).map(|raw| {
934            raw.split(',')
935                .map(str::trim)
936                .filter(|s| !s.is_empty())
937                .map(str::to_string)
938                .collect()
939        })
940    }
941}
942
943/// How a **managed database** (PLAN-managed-compute-sql) runs its stock image on a
944/// shared-kernel backend, whose entrypoint would otherwise fail under the dropped-`ALL`
945/// hardening. `rootless` (the default) needs no capabilities and works under any
946/// posture; `caps` is the fallback for an image that won't run rootless.
947#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
948#[serde(rename_all = "lowercase")]
949pub enum ManagedDbPrivilege {
950    /// Run the DB as its image's user (`999:999` for the official postgres/mysql
951    /// images) against a pre-owned volume — no added capabilities, any posture.
952    #[default]
953    Rootless,
954    /// Add the minimal capability set the entrypoint needs (`CHOWN`, `DAC_OVERRIDE`,
955    /// `FOWNER`, `SETUID`, `SETGID`). Honored only under the single-tenant posture.
956    Caps,
957}
958
959/// `compute` section — opt-in compute backends. Present
960/// ⇒ `serve` registers the backends this node can offer and advertises them to
961/// the scheduler; backends are capability-detected (container on Linux, remote
962/// docker when a daemon is reachable, VMM when `/dev/kvm` exists).
963#[derive(Debug, Clone, Serialize, Deserialize)]
964#[serde(default, deny_unknown_fields)]
965pub struct ComputeConfig {
966    /// Bridge the container veths / VM taps attach to (default `br-boatramp`).
967    pub bridge: String,
968    /// Guest IP subnet (default `10.0.0.0/24`).
969    pub subnet: String,
970    /// vCPUs this node advertises as schedulable (`0` ⇒ detect from the host).
971    pub vcpus: u32,
972    /// Memory (MiB) this node advertises as schedulable (`0` ⇒ a 1 GiB default).
973    pub mem_mib: u32,
974    /// **Static** kernel-signing public keys (`"<alg>:<hex>"`) — the trust anchor
975    /// for the posture-scaled kernel bar. Under `multi-tenant`, a dynamically-
976    /// selected default kernel must carry a signature verifying against one of
977    /// these. Host-access-gated (never in the KV tier); changing it needs a
978    /// restart. Empty ⇒ no kernel may be signed-verified (strict posture then
979    /// accepts none).
980    pub kernel_signing_pubkeys: Vec<String>,
981    /// **Static** allow-list of kernel content hashes (sha256 hex) a dynamic
982    /// default may select under `multi-tenant`. Host-access-gated. Empty ⇒ no
983    /// kernel is allow-listed.
984    pub kernel_allowed_hashes: Vec<String>,
985    /// This node's **region** tag (FA-8). Advertised on the compute `Node` so a
986    /// gateway routing to a `compute:`-backed workload with `--lb nearest` sends
987    /// each request to the nearest replica by its node's region — no manual
988    /// `--region` map. `None` ⇒ region-agnostic.
989    pub region: Option<String>,
990    /// How the remote-Docker backend reports a workload's reachable endpoint.
991    /// `published` (default) publishes the container port on `127.0.0.1:<ephemeral>`
992    /// so a host-native `serve` reaches it on any daemon (incl. Docker Desktop /
993    /// macOS, where the bridge IP is not host-routable); `bridge` routes to the
994    /// container bridge IP directly (only when `serve` shares the daemon's network).
995    pub docker_endpoint: boatramp_docker::DockerEndpoint,
996    /// How the remote-Docker backend backs a workload's persistent volumes.
997    /// `named` (default) attaches a daemon-managed `docker volume` by name (portable
998    /// across daemons + Docker Desktop / macOS); `bind` bind-mounts a host directory
999    /// under `<data_dir>/compute/volumes/<name>` (local daemon only).
1000    pub docker_volume_mode: boatramp_docker::DockerVolumeMode,
1001    /// Wall-clock backstop (seconds) for one project export/import client run
1002    /// (`run_ephemeral`: a `pg_dump`/`pg_restore` container). `0` (default) keeps the
1003    /// backend's generous built-in default (6h). Raise it for a very large migration so
1004    /// the backstop never kills legitimate work; the real unreachable-DSN hang is bounded
1005    /// far tighter by the client's own connect timeout.
1006    #[serde(default)]
1007    pub docker_ephemeral_timeout_secs: u64,
1008    /// Guest-reachable base URL of the compute **sql-shim** (PLAN-compute-bindings) —
1009    /// e.g. `http://10.0.0.1:8081` (the compute bridge gateway) or the docker bridge
1010    /// gateway. Set ⇒ a workload's `--bind sql` reaches the managed database through a
1011    /// listener bound on the **host:port this URL names** (the bridge-gateway IP /
1012    /// loopback — NOT all interfaces; a token-gated tenant-SQL data plane must not be
1013    /// off-node reachable). `None` (default) ⇒ compute sql bindings off.
1014    #[serde(default, skip_serializing_if = "Option::is_none")]
1015    #[cfg_attr(not(feature = "handlers"), allow(dead_code))]
1016    pub sql_shim_url: Option<String>,
1017    /// Guest-reachable base URL of the compute **blob-shim** (PLAN-compute-bindings) —
1018    /// e.g. `http://10.0.0.1:8082` (the compute bridge gateway) or the docker bridge
1019    /// gateway. Set ⇒ a workload's `--bind blob` reaches the SAME per-site
1020    /// `hblob/{qualified-site}/…` blob namespace a `wasi:blobstore` handler sees, through a
1021    /// listener bound on the **host:port this URL names** (the bridge-gateway IP /
1022    /// loopback — NOT all interfaces; the token-gated `hblob/{site}/` data plane must not
1023    /// be off-node reachable). `None` (default) ⇒ compute blob bindings off. The direct
1024    /// analogue of [`Self::sql_shim_url`].
1025    #[serde(default, skip_serializing_if = "Option::is_none")]
1026    #[cfg_attr(not(feature = "handlers"), allow(dead_code))]
1027    pub blob_shim_url: Option<String>,
1028    /// Guest-reachable base URL of the compute **messaging-shim** (PLAN-compute-bindings) —
1029    /// e.g. `http://10.0.0.1:8083` (the compute bridge gateway) or the docker bridge gateway.
1030    /// Set ⇒ a workload's `--bind messaging` reaches BOTH halves of the SAME `{project}/bus/
1031    /// <topic>` project bus a `wasi:messaging` handler sees — `POST /publish/{topic}` AND the
1032    /// consume ops `POST /claim/{topic}`, `POST /ack`, `POST /nack` — through a listener bound
1033    /// on the **host:port this URL names** (the bridge-gateway IP / loopback — NOT all
1034    /// interfaces; the token-gated `{project}/bus/` data plane must not be off-node reachable).
1035    /// `None` (default) ⇒ compute messaging bindings off. The direct analogue of
1036    /// [`Self::sql_shim_url`] / [`Self::blob_shim_url`].
1037    #[serde(default, skip_serializing_if = "Option::is_none")]
1038    #[cfg_attr(not(feature = "handlers"), allow(dead_code))]
1039    pub messaging_shim_url: Option<String>,
1040    /// Per-object PUT ceiling (bytes) for the compute blob-shim — bounds a single write so a
1041    /// compromised/buggy workload cannot exhaust node/bucket storage with one unbounded PUT (`413`
1042    /// on an oversize PUT). `None` (default) ⇒ the shim's built-in default (5 GiB, S3's single-PUT
1043    /// limit); `Some(0)` ⇒ unlimited.
1044    #[serde(default, skip_serializing_if = "Option::is_none")]
1045    #[cfg_attr(not(feature = "handlers"), allow(dead_code))]
1046    pub blob_shim_max_object_bytes: Option<u64>,
1047    /// Privilege strategy for a managed database's stock image on a shared-kernel
1048    /// backend (see [`ManagedDbPrivilege`]). `rootless` by default.
1049    #[serde(default)]
1050    #[cfg_attr(not(feature = "handlers"), allow(dead_code))]
1051    pub managed_db_privilege: ManagedDbPrivilege,
1052    /// Per-project **internal DNS** (service discovery): run a lightweight resolver
1053    /// on the bridge gateway so a guest can reach peers by name (`<workload>` /
1054    /// `<workload>.<project>.<dns_domain>`) instead of a numeric IP, scoped to its
1055    /// own project. Default **on** — it activates only when the container backend +
1056    /// bridge come up, so a node without them is unaffected. `false` disables it and
1057    /// leaves each image's own `/etc/resolv.conf`.
1058    #[serde(default = "default_internal_dns")]
1059    pub internal_dns: bool,
1060    /// The upstream resolver the internal DNS forwards non-internal queries to
1061    /// (external names + non-`A`/`AAAA` types), so the resolver is the guest's single
1062    /// nameserver. `"host:port"`; default `1.1.1.1:53`.
1063    #[serde(default = "default_dns_upstream")]
1064    pub dns_upstream: String,
1065    /// The internal DNS suffix names live under (`<workload>.<project>.<dns_domain>`);
1066    /// also the `search` domain written into each container's resolv.conf. Default
1067    /// `boatramp.internal`.
1068    #[serde(default = "default_dns_domain")]
1069    pub dns_domain: String,
1070    /// **Air-gap override** for the project export/import **client images** the native
1071    /// container backend runs via `run_ephemeral` (a `pg_dump`/`pg_restore`/`mysqldump`/
1072    /// `mysql`/`psql` one-shot). Maps a client image reference → a **preloaded rootfs**, so
1073    /// an export/import can run with NO registry pull on an isolated node. The value is
1074    /// either an **absolute host path** to an already-unpacked rootfs directory (used
1075    /// verbatim), or a **Storage blob hash** of a rootfs tar the backend stages like any
1076    /// `RootSource::Tar`. Empty (the default) ⇒ every client image is pulled + built
1077    /// on demand over the registry HTTP API (daemonless), the same path `materialize`
1078    /// uses. Only the native `container` backend consults this; the remote `docker`
1079    /// backend pulls through its daemon. Example:
1080    ///
1081    /// ```toml
1082    /// [compute.client_image_rootfs]
1083    /// "pgvector/pgvector:pg16" = "/var/lib/boatramp/client-rootfs/pg16"
1084    /// "mysql:8.0"              = "9f86d0818...<rootfs-tar-blob-sha256>"
1085    /// ```
1086    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
1087    #[cfg_attr(not(target_os = "linux"), allow(dead_code))]
1088    pub client_image_rootfs: BTreeMap<String, String>,
1089    /// **Digest-pin / override** for the Postgres client image the project export/import + `sql exec`
1090    /// seams run via `run_ephemeral` (`pg_dump`/`pg_restore`/`psql`). When set, this image reference is
1091    /// used VERBATIM instead of the version-computed `pgvector/pgvector:pg{major}` tag — so an operator
1092    /// can pin it by digest (`pgvector/pgvector:pg16@sha256:<hex>`) and have it accepted under the
1093    /// multi-tenant posture (which refuses an un-pinned mutable-tag pull), with NO rootfs staging:
1094    /// boatramp pulls + runs it through the normal on-demand path. The lighter-weight alternative to
1095    /// [`Self::client_image_rootfs`] for a node with registry egress. `None` (default) ⇒ the computed
1096    /// tag. Env: `BOATRAMP_COMPUTE_PG_CLIENT_IMAGE`.
1097    #[serde(default, skip_serializing_if = "Option::is_none")]
1098    #[cfg_attr(not(target_os = "linux"), allow(dead_code))]
1099    pub pg_client_image: Option<String>,
1100    /// MySQL counterpart of [`Self::pg_client_image`] — pins/overrides the `mysql:<maj.min>` client
1101    /// image for the export/import/`sql exec` `run_ephemeral` (`mysqldump`/`mysql`). Env:
1102    /// `BOATRAMP_COMPUTE_MYSQL_CLIENT_IMAGE`.
1103    #[serde(default, skip_serializing_if = "Option::is_none")]
1104    #[cfg_attr(not(target_os = "linux"), allow(dead_code))]
1105    pub mysql_client_image: Option<String>,
1106}
1107
1108/// Default for [`ComputeConfig::internal_dns`] — on (activates only with the
1109/// container backend + bridge).
1110fn default_internal_dns() -> bool {
1111    true
1112}
1113
1114/// Default upstream resolver for [`ComputeConfig::dns_upstream`].
1115fn default_dns_upstream() -> String {
1116    "1.1.1.1:53".to_string()
1117}
1118
1119/// Default internal DNS suffix for [`ComputeConfig::dns_domain`].
1120fn default_dns_domain() -> String {
1121    boatramp_container::dns::DEFAULT_INTERNAL_DOMAIN.to_string()
1122}
1123
1124/// The built-in **boatramp kernel-signing public key** (`es256:…`), whose private
1125/// half lives as the `KERNEL_SIGNING_KEY` Actions secret in
1126/// [`BoatRamp/boatramp-vmlinux`](https://github.com/BoatRamp/boatramp-vmlinux).
1127/// Shipped as a default trust anchor so the first-party signed `boatramp-vmlinux`
1128/// verifies out of the box under the strict posture. An operator can replace
1129/// `kernel_signing_pubkeys` to trust only their own keys.
1130pub const BOATRAMP_KERNEL_SIGNING_PUBKEY: &str =
1131    "es256:02c4e4af2e9cba6ba6745c513f193622e6674a8b2d0187ebea5612f5b46a7eade4";
1132
1133/// The first-party signed-kernel content hashes trusted under the **strict**
1134/// posture, for this build's **guest arch**. The guest arch mirrors the host: an
1135/// x86_64 host boots x86_64 KVM guests (the embedded VMM); an Apple-silicon host
1136/// boots aarch64 guests (the Virtualization.framework `vmm-vz` backend). An x86_64
1137/// kernel can't boot an aarch64 VM (and vice versa), so each arch trusts only its
1138/// own signed `boatramp-vmlinux-<arch>` releases. Bump on each new signed release.
1139///
1140/// The **relaxed** (single-tenant) posture ignores this list — it verifies only the
1141/// content-hash pin — so an operator-supplied kernel boots there regardless of arch.
1142fn default_allowed_kernel_hashes() -> Vec<String> {
1143    #[cfg(target_arch = "x86_64")]
1144    {
1145        vec![
1146            // v0.2.0 minimal Firecracker 6.1-config kernel: boots under the
1147            // firecracker-*binary* backend (ACPI device discovery) but NOT the
1148            // in-process embedded VMM. Kept trusted so operators on the currently
1149            // published release don't fail strict verification.
1150            "cf1e590a9e642be3667131ca35fbf390378a457d8908169d2a169608e299d974".to_string(),
1151            // Same kernel + CONFIG_VIRTIO_MMIO_CMDLINE_DEVICES=y (flake `#vmlinux`),
1152            // so the embedded VMM binds its virtio-block root over the cmdline
1153            // transport. Reproducible build output (deterministic nix build,
1154            // verified on KVM); the next signed boatramp-vmlinux release — which
1155            // reuses this flake — publishes + signs it, gated by
1156            // `vmlinux-release-boot.yml`.
1157            "d0dc2098ab2a2a3c1bc72ab61dc85d9e464d798d7e55b6b80525db5ca2f00c5a".to_string(),
1158        ]
1159    }
1160    #[cfg(target_arch = "aarch64")]
1161    {
1162        vec![
1163            // `boatramp-vmlinux-aarch64` v0.2.3 (the Virtualization.framework guest
1164            // kernel, flake `#vmlinux` on aarch64-linux — a raw arm64 `Image`). This
1165            // release enables the generic PCIe host + virtio-pci so the guest actually
1166            // discovers VZ's virtio disk/net/console (the earlier v0.2.2 `be95fb0d…`
1167            // built with `CONFIG_PCI` off never booted under VZ and is dropped). This
1168            // is the hash of the **published, ES256-signed** release asset (signed by
1169            // BOATRAMP_KERNEL_SIGNING_PUBKEY), so a selected `compute.default_kernel`
1170            // clears the strict bar out of the box; the boot + scale-to-zero round-trip
1171            // was validated against this exact published kernel. NOTE: unlike x86_64,
1172            // the aarch64 build is not currently bit-reproducible across build hosts
1173            // (same config + size, different build metadata), so pin/verify against the
1174            // published `.sha256`/`.sig`, not a local rebuild. Bump on each new release.
1175            "d785a48d754e65a4630443301f1fb84cb69cf882336d3cf37055e437b3d8e21f".to_string(),
1176        ]
1177    }
1178    #[cfg(not(any(target_arch = "x86_64", target_arch = "aarch64")))]
1179    {
1180        Vec::new()
1181    }
1182}
1183
1184impl Default for ComputeConfig {
1185    fn default() -> Self {
1186        Self {
1187            bridge: "br-boatramp".to_string(),
1188            subnet: "10.0.0.0/24".to_string(),
1189            vcpus: 0,
1190            mem_mib: 0,
1191            kernel_signing_pubkeys: vec![BOATRAMP_KERNEL_SIGNING_PUBKEY.to_string()],
1192            kernel_allowed_hashes: default_allowed_kernel_hashes(),
1193            region: None,
1194            docker_endpoint: boatramp_docker::DockerEndpoint::default(),
1195            docker_volume_mode: boatramp_docker::DockerVolumeMode::default(),
1196            docker_ephemeral_timeout_secs: 0,
1197            sql_shim_url: None,
1198            blob_shim_url: None,
1199            messaging_shim_url: None,
1200            blob_shim_max_object_bytes: None,
1201            managed_db_privilege: ManagedDbPrivilege::default(),
1202            internal_dns: default_internal_dns(),
1203            dns_upstream: default_dns_upstream(),
1204            dns_domain: default_dns_domain(),
1205            client_image_rootfs: BTreeMap::new(),
1206            pg_client_image: None,
1207            mysql_client_image: None,
1208        }
1209    }
1210}
1211
1212/// `cluster` section — self-hosted **cluster mode**. Parsed in
1213/// every build so config files stay portable; only *consumed* when the `cluster`
1214/// feature is compiled in (`boatramp serve --mode cluster`).
1215#[cfg_attr(not(feature = "cluster"), allow(dead_code))]
1216#[derive(Debug, Clone, Serialize, Deserialize)]
1217pub struct ClusterConfig {
1218    /// Address to bind this node's Raft **peer mesh** on (the `/raft/*` +
1219    /// `/stream/*` endpoints) — distinct from the public `serve.addr`.
1220    pub listen: SocketAddr,
1221    /// The cluster **root anchor set** — the `es256:`/`ed25519:`-tagged public
1222    /// keys that define this cluster's identity (a cluster *is* its root key).
1223    /// Every join/trust decision verifies against this set. Empty ⇒ falls back to
1224    /// `serve.auth_root_public_key` (the single-anchor default). A *set* enables
1225    /// make-before-break root rotation.
1226    #[serde(default)]
1227    pub root_pubkeys: Vec<String>,
1228    /// **Seeds** — control-plane addresses of existing cluster members
1229    /// (`host:port`), any of which can admit this node. Present ⇒ this node
1230    /// **joins** (redeems its `join_token`); absent + no durable state + explicit
1231    /// `--cluster-init` ⇒ it **founds**. There is no peer map: members are learned
1232    /// from the root-signed join response.
1233    #[serde(default)]
1234    pub seeds: Vec<String>,
1235    /// The single-use bearer **join token** used when `seeds` are set. Keeps the
1236    /// secret out of the file via a prefix: `env:VAR`, `path:/file`, or an inline
1237    /// literal. Usually supplied via `serve --cluster-join <ticket>` instead.
1238    #[serde(default)]
1239    pub join_token: Option<String>,
1240    /// Directory for this node's **durable** Raft log/state store (node-local;
1241    /// distinct from the replicated control plane). Default
1242    /// `<data-dir>/raft`.
1243    #[serde(default)]
1244    pub store_dir: Option<PathBuf>,
1245    /// Mesh identity + TLS settings. Absent ⇒ defaults (identity key
1246    /// auto-generated under `<data-dir>/mesh/identity.key`).
1247    #[serde(default)]
1248    pub mesh: Option<MeshConfig>,
1249}
1250
1251/// `[cluster.mesh]` — mesh identity + TLS knobs.
1252#[cfg_attr(not(feature = "cluster"), allow(dead_code))]
1253#[derive(Debug, Clone, Default, Serialize, Deserialize)]
1254#[serde(default, deny_unknown_fields)]
1255pub struct MeshConfig {
1256    /// Path to this node's Ed25519 identity key (PKCS#8 DER, `0600`,
1257    /// auto-generated). Default `<data-dir>/mesh/identity.key`.
1258    pub key_file: Option<PathBuf>,
1259    /// Automatic key-rotation cadence (e.g. `"30d"`); `None` = manual only.
1260    /// Consumed by the rotation loop.
1261    pub key_rotation: Option<String>,
1262    /// TTL for a single-use join token (e.g. `"1h"`).
1263    pub join_token_ttl: Option<String>,
1264    /// Gate mesh `client-write`s behind a control-plane **cluster-write
1265    /// capability**, so a trusted peer can't inject arbitrary
1266    /// control-plane writes on mesh trust alone. Requires the token root
1267    /// **private** key on every node (each mints + presents its own capability);
1268    /// default `false`.
1269    pub gate_client_writes: Option<bool>,
1270}
1271
1272/// `handlers` section — server-side handler runtime config (read by `serve`).
1273/// Parsed in every build (so config files stay portable), but only *consumed*
1274/// when the `handlers` feature is compiled in.
1275#[cfg_attr(not(feature = "handlers"), allow(dead_code))]
1276#[derive(Debug, Clone, Default, Serialize, Deserialize)]
1277#[serde(default)]
1278pub struct HandlersConfig {
1279    /// `handlers.bindings` — which backend serves each handler binding.
1280    pub bindings: BindingsConfig,
1281    /// Use the wasmtime **pooling** instance allocator: faster
1282    /// instantiation at the cost of a large up-front virtual-memory reservation.
1283    /// Off by default — opt in and benchmark for your workload.
1284    pub pooling: bool,
1285    /// Capacity of the per-lane **warm compile cache** — how many distinct compiled+linked components
1286    /// (keyed by content hash) stay resident per lane (request / consumer / session). A component
1287    /// evicted here (LRU, once the node serves more than this many distinct components on a lane) pays
1288    /// a cold cranelift recompile on its next request. Absent ⇒ 64 (the historical default). Raise it
1289    /// on a node that serves more than ~64 components so none is evicted; the `/api/instance-stats`
1290    /// surface reports `warm_capacity` + `evictions` so the right value is measured, not guessed.
1291    #[serde(default, skip_serializing_if = "Option::is_none")]
1292    pub instance_cache_size: Option<usize>,
1293    /// **Warm floor** (cold-start cap-req 09): the maximum number of request components PINNED
1294    /// in a never-evicted set, so a latency-critical face never cold-starts under LRU capacity
1295    /// pressure. Absent/`0` ⇒ off (the plain LRU). Each activated request component is pinned
1296    /// up to this cap (first-come); size it ≥ your latency-critical handler count. Pinned
1297    /// components cost one resident instance each on top of the LRU, so keep it modest.
1298    #[serde(default, skip_serializing_if = "Option::is_none")]
1299    pub keep_warm_max: Option<usize>,
1300    /// **Portable cross-node AOT artifact cache** (cold-start cap-req 09). When `true` AND a
1301    /// `[secrets]` envelope is configured, a node publishes each request component's precompiled
1302    /// artifact (cluster-MAC-authenticated) to the shared blob store, and a FRESH replica
1303    /// hydrates it instead of recompiling from source. Default **off** (opt-in): it loads
1304    /// native code off the shared store, so it is gated on the cluster secret + a MAC check.
1305    /// A node without the envelope silently never participates (it still compiles + warm-caches).
1306    #[serde(default, skip_serializing_if = "Option::is_none")]
1307    pub aot_artifact_cache: Option<bool>,
1308    /// Per-artifact size ceiling for the AOT cache (bytes; `0` ⇒ unlimited). Native code is
1309    /// large; an artifact over this is neither published nor (beyond a hard safety ceiling)
1310    /// read. Absent ⇒ a generous default. Only consulted when `aot_artifact_cache` is on.
1311    #[serde(default, skip_serializing_if = "Option::is_none")]
1312    pub aot_artifact_max_bytes: Option<u64>,
1313    /// **Blob container-marker cache size** (entries). Every blob container open re-`HEAD`s the
1314    /// `.boatramp-container` ownership marker — a second serial object-store round-trip per serve. A
1315    /// process-wide, positive-only cache of VERIFIED markers (keyed by the fully-resolved, tenant-confined
1316    /// container prefix; invalidated on container delete) skips that HEAD for an already-verified
1317    /// container WITHOUT touching confinement (`container_access` still runs on every op). Absent ⇒ 4096;
1318    /// `0` disables the cache (every open re-HEADs). A node rarely has more than a handful of live
1319    /// containers, so the default is generous headroom.
1320    #[serde(default, skip_serializing_if = "Option::is_none")]
1321    pub blob_marker_cache_entries: Option<usize>,
1322    /// **Hedged blob-read delay** (milliseconds). When a serve's object GET has not returned within this
1323    /// many ms, the host races a SECOND GET and takes whichever lands first — cutting the serve-path
1324    /// fetch tail on an external store (measured: `blob_range` p50 ≈ 16ms but p99 ≈ 727ms, with CPU
1325    /// idle). Blob reads are idempotent, so the hedge is always safe; the loser is cancelled. Absent/`0`
1326    /// ⇒ disabled (one GET per read). Set it a little above the warm p90 (e.g. 60–100ms) so only the
1327    /// genuinely-slow tail hedges. Pairs with [`blob_hedge_max_inflight`](Self::blob_hedge_max_inflight).
1328    #[serde(default, skip_serializing_if = "Option::is_none")]
1329    pub blob_hedge_delay_ms: Option<u64>,
1330    /// **Concurrent-hedge cap** — the max number of in-flight hedge (second) reads at once. Guards against
1331    /// a hedge storm when the whole store is slow (every read would otherwise double): over the cap a slow
1332    /// read simply waits on its single request. Absent ⇒ a small internal default (16). Only meaningful
1333    /// when [`blob_hedge_delay_ms`](Self::blob_hedge_delay_ms) is set.
1334    #[serde(default, skip_serializing_if = "Option::is_none")]
1335    pub blob_hedge_max_inflight: Option<usize>,
1336    /// **Per-component serve-admission concurrency** (image-serve-latency Ask B). Caps how many
1337    /// requests to the SAME component (keyed by content hash) are concurrently inside the expensive
1338    /// `build_bindings` + instantiate + serve-to-head region; a burst beyond it (e.g. a gallery firing
1339    /// dozens of `/img` thumbnails) queues cheaply on a semaphore instead of oversubscribing the tokio
1340    /// workers, which on a small-core node makes each request's await-resumptions pile up into a
1341    /// multi-second scheduling stall (the measured `bindgap`). Absent ⇒ a host-parallelism default
1342    /// (`available_parallelism * 4`, floored at 8) so a small node is bounded out of the box; `0`
1343    /// disables the gate (legacy unbounded serve). Raise it on a big node, or lower it if one hot
1344    /// component should be tighter; `/api/instance-stats` + the `bindgap` Server-Timing phase make the
1345    /// right value measurable.
1346    #[serde(default, skip_serializing_if = "Option::is_none")]
1347    pub serve_concurrency: Option<usize>,
1348    /// Engine-wide **safety max** on a *connection-bearing* invocation (a site
1349    /// handler or a synchronous function/webhook invoke), milliseconds. A route
1350    /// or function may declare a *lower* timeout, never a higher one. Kept tight
1351    /// on purpose: a client, proxy, and the shared request pool are all blocked
1352    /// while a sync handler runs. Absent ⇒ 10s (the historical default). This is
1353    /// a node safety ceiling, not a per-invocation budget, and is distinct from
1354    /// a per-site `max_timeout_ms`.
1355    pub sync_max_timeout_ms: Option<u64>,
1356    /// Max concurrent in-flight *sync-lane* invocations node-wide — the GLOBAL ceiling every
1357    /// connection-bearing serve (site handler, synchronous invoke, and the `/graphql` gateway's
1358    /// subgraph fan-out) passes through, distinct from the PER-COMPONENT `serve_concurrency` gate.
1359    /// Absent ⇒ a host-parallelism default (`available_parallelism * 4`, floored at **64** — so it is
1360    /// unchanged on nodes up to ~16 vCPU and only scales ABOVE that). Without this, the lane was pinned
1361    /// at 64 regardless of host size, so adding vCPUs past ~16 bought no extra concurrent live
1362    /// throughput and there was no knob to lift it. Raise it on a big node to let the sync lane use more
1363    /// cores; lower it to cap aggregate live concurrency. Read once at startup. NOTE: with `[handlers]
1364    /// pooling` on, the shared instance pool is sized off the summed lane concurrencies, so a larger
1365    /// value enlarges the up-front virtual reservation (the non-pooling default sizes memory
1366    /// per-invocation and is unaffected). Unlike `serve_concurrency`, `0` is NOT "disable" — the
1367    /// global sync lane is a required safety ceiling, so a configured `0` is rejected (falls back to
1368    /// the host default, with a loud WARN at startup).
1369    pub sync_max_concurrency: Option<usize>,
1370    /// Emit the per-phase `Server-Timing` RESPONSE HEADER to clients. Default **off** (absent ⇒
1371    /// `false`): the per-phase breakdown always goes to the structured phase-timing LOG (operator
1372    /// observability), but putting it on the wire exposes internal phase structure + a timing
1373    /// side-channel to every caller. Turn it on for a debugging window (e.g. correlating a client's
1374    /// slow request to a host phase), off in production. Read once at startup.
1375    #[serde(default, skip_serializing_if = "Option::is_none")]
1376    pub server_timing: Option<bool>,
1377    /// Engine-wide safety max on a *durable async* invocation — the drain that
1378    /// runs `?mode=async` calls, workflow steps, cron/queue/blob triggers, and
1379    /// `wasi:messaging` consumers, milliseconds. No client is connected and the
1380    /// work is retried + dead-lettered, so this can be far larger than the sync
1381    /// ceiling: it is what lets a legitimately long background job (e.g. an LLM
1382    /// generation) declare and actually get minutes of runtime. Absent ⇒ 15
1383    /// minutes. Runs on its own concurrency budget (`async_max_concurrency`), so
1384    /// a long job never starves live traffic.
1385    pub async_max_timeout_ms: Option<u64>,
1386    /// Max concurrent in-flight *async-lane* invocations, kept separate from the
1387    /// (larger) request pool so a burst of long background jobs can't exhaust the
1388    /// slots live site traffic needs. Absent ⇒ 8.
1389    pub async_max_concurrency: Option<usize>,
1390    /// Optional CPU **fuel** ceiling for an async-lane invocation. A large async
1391    /// timeout bounds only wall-clock; without a fuel bound a CPU-bound guest can
1392    /// spin for the whole window. Absent ⇒ unmetered (same as the sync default).
1393    pub async_max_fuel: Option<u64>,
1394    /// Per-component WASM linear-memory **ceiling** for the *async* lane, in MiB —
1395    /// the durable `wasi:messaging` / workflow-step lane where heavy, retryable jobs
1396    /// (image decode+resize, PDF, document processing) belong. This RAISES the lane
1397    /// ceiling above the 64 MiB default; a component's own `limits.memory_mb` (or the
1398    /// site `max_memory_mb`) then clamps it back **down** from here — so an operator
1399    /// sets the lane high enough for the heaviest consumer and each component
1400    /// right-sizes itself. Absent ⇒ 64 MiB (unchanged for every existing component;
1401    /// no component can raise its own memory above this operator-set ceiling). With
1402    /// `[handlers] pooling` on, the shared pool is sized off the largest lane ceiling;
1403    /// see the virtual-reservation note on `pooling`.
1404    pub async_max_memory_mb: Option<usize>,
1405    /// Per-component WASM linear-memory ceiling for the *sync* (request) lane, MiB.
1406    /// Absent ⇒ 64 MiB. Same semantics as [`async_max_memory_mb`](Self::async_max_memory_mb)
1407    /// (raises the lane ceiling; a component clamps down). Raising the sync lane means
1408    /// many concurrent request instances can each reach this ceiling, so weigh it
1409    /// against the request pool's size.
1410    pub sync_max_memory_mb: Option<usize>,
1411    /// Per-component WASM linear-memory ceiling for the *streaming* lane, MiB.
1412    /// Absent ⇒ 64 MiB. Same semantics as [`async_max_memory_mb`](Self::async_max_memory_mb).
1413    pub streaming_max_memory_mb: Option<usize>,
1414    /// **Relaxed messaging-publish durability** — the max number of published
1415    /// messages that may be acknowledged from the in-memory buffer BEFORE a durable
1416    /// checkpoint is forced. **Absent / `0` ⇒ strong durability (the default):**
1417    /// every `publish()` returns only after the message is crash-durable — a
1418    /// *stronger* guarantee than NATS JetStream's default sync publish. Set `N > 0`
1419    /// to opt a node into fast-ack (publish returns on the buffer insert, ~10µs
1420    /// instead of ~one flush interval), at the cost of a **bounded loss window: up
1421    /// to `N` acknowledged-but-unflushed messages are lost on a process crash / OOM
1422    /// / SIGKILL / power loss** before the next flush. Affects ONLY the messaging
1423    /// bus publish path — control-plane, auth, and consumer ack/redelivery
1424    /// durability are unaffected. Single-node only (cluster durability is
1425    /// replication). A node with `N > 0` logs a warning at startup.
1426    pub messaging_max_unflushed_msgs: Option<usize>,
1427    /// **Event-driven delivery — safety-net reconcile cadence** (ms). The coarse timer the delivery
1428    /// drainer falls back to when no fast-path wake fires: it drains the durable ready-set and fires
1429    /// lease-expiry redelivery via the per-message due-heap, so a dropped wake or a time-based
1430    /// visibility never stalls delivery beyond this interval. It never scans idle topics (an idle
1431    /// fleet costs ~0). Absent ⇒ ~2 s. Lower for tighter redelivery latency at more wakeups; raise to
1432    /// quiet a large idle fleet further.
1433    pub messaging_safetynet_interval_ms: Option<u64>,
1434    /// **Event-driven delivery — ready-set rebuild cadence** (ms). The long-cadence self-heal that
1435    /// re-derives the ready-set from the authoritative message index — recovering a marker lost to a
1436    /// crash between the index write and the ready write, pruning a stale marker, and self-populating
1437    /// a fresh/upgraded node's ready-set. This is the one full-ish scan, so it runs rarely. Absent ⇒
1438    /// ~30 s. The correctness backstop for the ready-set (a lost marker costs at most one rebuild
1439    /// interval of latency, never a lost message).
1440    pub messaging_readyset_rebuild_interval_ms: Option<u64>,
1441    /// Max wall-clock for a *streaming-lane* response (a `#[handler(stream)]`
1442    /// route — SSE, chunked, agent token streaming), milliseconds. A client is
1443    /// connected but the body is written incrementally over seconds-to-minutes,
1444    /// so this is far larger than the sync ceiling. Runs on its own concurrency
1445    /// budget (`streaming_max_concurrency`), isolated from both the fast request
1446    /// pool and the async drain. Absent ⇒ 15 minutes.
1447    pub streaming_max_timeout_ms: Option<u64>,
1448    /// Max concurrent in-flight *streaming-lane* responses, kept separate from the
1449    /// request pool and the async drain so a burst of long-lived streams starves
1450    /// neither. Absent ⇒ 64.
1451    pub streaming_max_concurrency: Option<usize>,
1452    /// Optional CPU **fuel** ceiling for a streaming-lane response. Absent ⇒
1453    /// unmetered (a stream is I/O-bound on the client, not CPU-bound).
1454    pub streaming_max_fuel: Option<u64>,
1455    /// **Idle cap** for a streaming-lane response (ms): if the handler emits no body frame to the
1456    /// client for this long, the host tears the stream down and reclaims its lane slot — the
1457    /// slowloris bound for the streaming lane, so a `streaming_max_concurrency`-sized burst of
1458    /// silent streams can't hold every slot. A well-behaved SSE stream sends heartbeats well inside
1459    /// it. The absolute lifetime stays bounded by `streaming_max_timeout_ms`. Floored at 1 s. Absent
1460    /// ⇒ 600 s (matches the `[stream]` fan-out idle window).
1461    pub streaming_idle_timeout_ms: Option<u64>,
1462    /// Optional ceiling on a guest's **outbound** `wasi:http` call — the connect
1463    /// and time-to-first-byte wait — milliseconds, independent of the invocation
1464    /// timeout, so a hung upstream is bounded on its own terms. The streaming
1465    /// (between-bytes) timeout is left at wasmtime's default so a slow token
1466    /// stream is not cut mid-flight. Absent ⇒ wasmtime's default.
1467    pub outbound_timeout_ms: Option<u64>,
1468    /// **JWKS freshness — `own` (first-party) tier: background-refresh age** (seconds). The soft age at
1469    /// which a node-fixed `token_claims.jwks_url`/`jwks_env` verifier is refreshed in the BACKGROUND
1470    /// (the current keys keep serving — no request blocks on the fetch). Absent ⇒ 120 s. Floored at 60 s.
1471    #[serde(default, skip_serializing_if = "Option::is_none")]
1472    pub jwks_refresh_secs: Option<u64>,
1473    /// **JWKS freshness — `own` tier: hard TTL / revocation bound** (seconds). The age past which the
1474    /// first-party keys are no longer served and a request BLOCKS on a fresh fetch (fail-closed on
1475    /// failure) — caps how long a key revoked at the IdP can keep verifying. Absent ⇒ 600 s. Must be
1476    /// `> jwks_refresh_secs` (else clamped up, with a warning). Floored at 60 s.
1477    #[serde(default, skip_serializing_if = "Option::is_none")]
1478    pub jwks_hard_ttl_secs: Option<u64>,
1479    /// **JWKS freshness — `foreign` (user-declared multi-issuer) tier: background-refresh age**
1480    /// (seconds). As [`jwks_refresh_secs`](Self::jwks_refresh_secs) but for the multi-issuer
1481    /// (`issuer_trust`+`jwks` discovery) path, which is less trusted. Absent ⇒ 60 s. Floored at 60 s.
1482    #[serde(default, skip_serializing_if = "Option::is_none")]
1483    pub jwks_foreign_refresh_secs: Option<u64>,
1484    /// **JWKS freshness — `foreign` tier: hard TTL / revocation bound** (seconds). As
1485    /// [`jwks_hard_ttl_secs`](Self::jwks_hard_ttl_secs) but for user-declared issuers — typically set
1486    /// TIGHTER (faster revocation of a potentially-compromised foreign key). Absent ⇒ 300 s. Must be
1487    /// `> jwks_foreign_refresh_secs`. Floored at 60 s.
1488    #[serde(default, skip_serializing_if = "Option::is_none")]
1489    pub jwks_foreign_hard_ttl_secs: Option<u64>,
1490    /// **JWKS pre-warm at startup.** When on (the default), the node fetches each configured
1491    /// first-party (`own`-tier) `jwks_url` at startup so even the FIRST request is instant; foreign
1492    /// (user-declared) issuers can't be pre-warmed (they aren't known until a token arrives). Set
1493    /// `false` to skip startup JWKS fetches (the first request per issuer then pays the fetch). Absent ⇒ on.
1494    #[serde(default, skip_serializing_if = "Option::is_none")]
1495    pub jwks_prewarm: Option<bool>,
1496}
1497
1498/// `handlers.bindings` — per-binding backend configuration. kv/blob reuse the
1499/// server's own KV/Storage backends (per-site prefixed); `sql` is the single
1500/// libsql backend, whose single-node-vs-cluster split is the only choice.
1501#[cfg_attr(not(feature = "handlers"), allow(dead_code))]
1502#[derive(Debug, Clone, Default, Serialize, Deserialize)]
1503#[serde(default)]
1504pub struct BindingsConfig {
1505    /// `handlers.bindings.sql` — libsql settings. Absent ⇒ single-node,
1506    /// per-site embedded files under `<data-dir>/handlers-sql`.
1507    pub sql: Option<SqlBindingConfig>,
1508}
1509
1510/// libsql settings for the handler `sql` binding — the single SQL backend. Each
1511/// site gets a real database boundary (an embedded file per site, or a sqld
1512/// namespace per site), never schema separation (which arbitrary guest SQL
1513/// escapes). Setting `url` switches from single-node to a shared sqld cluster;
1514/// everything else stays identical.
1515#[cfg_attr(not(feature = "handlers"), allow(dead_code))]
1516#[derive(Debug, Clone, Default, Serialize, Deserialize)]
1517#[serde(default)]
1518pub struct SqlBindingConfig {
1519    /// Single-node: root directory for the per-site embedded database files
1520    /// (default `<data-dir>/handlers-sql`). Ignored when `url` is set.
1521    pub dir: Option<PathBuf>,
1522    /// Cluster: base sqld data URL (e.g. `http://sqld:8080`). When set, each
1523    /// site is a sqld namespace addressed as a subdomain of this URL; `admin_url`
1524    /// is then required.
1525    pub url: Option<String>,
1526    /// Cluster: sqld admin API base URL (e.g. `http://sqld:9090`) for creating
1527    /// per-site namespaces. Required when `url` is set.
1528    pub admin_url: Option<String>,
1529    /// Cluster: optional sqld **read-replica** data URL. When set, handlers'
1530    /// read-only `sql` transactions (`open-read-only`) route to this endpoint
1531    /// while writes stay on `url` (reads → replicas, writes → primary).
1532    /// Reads may lag (eventually consistent). Ignored in
1533    /// single-node mode (no `url`).
1534    pub replica_url: Option<String>,
1535    /// Name of the env var holding the sqld data auth token (optional; never
1536    /// the token itself in-file).
1537    pub token_env: Option<String>,
1538    /// Name of the env var holding the sqld admin API auth key (optional).
1539    pub admin_token_env: Option<String>,
1540    /// How preview deployments get their SQL database: `empty` (default — a
1541    /// fresh isolated db), `branch` (a consistent copy of the site's live db;
1542    /// single-node only), or `shared` (the site's live db). See
1543    /// `boatramp_core::sql::PreviewSqlMode`.
1544    pub preview_mode: Option<String>,
1545    /// Path to an idempotent SQL script run when an `empty` preview database is
1546    /// first opened (e.g. schema/seed). Ignored in `branch`/`shared` modes.
1547    pub preview_init: Option<PathBuf>,
1548    /// `handlers.bindings.sql.databases` — external **bring-your-own** databases,
1549    /// each opened by name via `sql.open("<name>")`. An operator-configured
1550    /// Postgres/MySQL whose *isolation is the operator's* (it's their database),
1551    /// so these bypass the per-site libsql boundary and are reachable by any
1552    /// handler/function granted the `sql` binding. Needs the `sql-postgres` /
1553    /// `sql-mysql` build feature for the engine. A name here shadows the same
1554    /// name on the managed libsql default.
1555    pub databases: BTreeMap<String, ExternalDatabaseConfig>,
1556    /// **Soft-delete grace window** for a per-tenant managed database, in seconds
1557    /// (env `BOATRAMP_HANDLERS_SQL_DEPROVISION_GRACE_SECS`). When a project/site is
1558    /// deleted, a **Shared + Postgres** tenant is *soft*-deleted (its database is
1559    /// renamed aside and its role disabled) and stays recoverable for this long
1560    /// before a reaper hard-drops it — see
1561    /// [`tenant_sql`](crate::tenant_sql). `None` ⇒ the 7-day default
1562    /// (`DEFAULT_DEPROVISION_GRACE_SECS`); `0` ⇒ disable the soft path (immediate,
1563    /// irreversible hard drop everywhere). MySQL and all `Single` tenants always
1564    /// hard-drop immediately (the engine/cell can't be renamed aside safely), so this
1565    /// knob only affects the Shared-Postgres cell.
1566    pub deprovision_grace_secs: Option<u64>,
1567    /// **Trusted-extension allowlist** for the owner-gated schema-migration surface — the ONLY
1568    /// Postgres extensions a migration `Extension` step may enable (a name not here is refused
1569    /// fail-closed). A raw `sql` migration step may not `CREATE EXTENSION` at all, so this list is
1570    /// the single, operator-controlled gate on which extensions a project can install via
1571    /// migrations. Empty / `None` ⇒ no extension may be enabled through a migration (the safest
1572    /// default). Keep it tight (e.g. `["pgcrypto", "uuid-ossp", "citext"]`); an entry like
1573    /// `dblink`/`postgres_fdw` deliberately widens cross-database reach, so add those only knowingly.
1574    ///
1575    /// Env-settable (12-factor parity) via **`BOATRAMP_HANDLERS_SQL_MIGRATE_TRUSTED_EXTENSIONS`** —
1576    /// a comma-separated list (`pg_trgm,pgcrypto`), env-over-file, unset ⇒ the file value. Only an
1577    /// input path; the allowlist semantics (the `Extension`-step gate, the fail-closed refusal of an
1578    /// unlisted name, the `sql`-step `CREATE EXTENSION` ban) are unchanged.
1579    pub migrate_trusted_extensions: Option<Vec<String>>,
1580    /// **Per-project declared-database COUNT ceiling** (#501 Stage B MEDIUM-1 — the
1581    /// disk-exhaustion / errno-28 guard). The maximum number of `databases:` entries a
1582    /// single project may declare; a declare that would exceed it is refused fail-closed
1583    /// (a 422-class error). Each declared DB eagerly provisions a 10–200 GiB volume, so
1584    /// without this a `Project·Admin` could declare an unbounded number and exhaust the
1585    /// node's disk. `None` ⇒ the built-in default
1586    /// (`apply_db_caps::DEFAULT_MAX_DECLARED_DATABASES_PER_PROJECT`, 16); `0` ⇒ declaring
1587    /// any managed database is disabled on this node. Env-settable via
1588    /// **`BOATRAMP_HANDLERS_SQL_MAX_DECLARED_DATABASES`** (env-over-file).
1589    pub max_declared_databases: Option<usize>,
1590    /// **Per-project aggregate declared-VOLUME ceiling**, in MiB (#501 Stage B
1591    /// MEDIUM-1). The maximum SUM of `volume_size_mib` across all of a project's declared
1592    /// databases; a declare whose incoming volume would push the project's total past
1593    /// this is refused fail-closed. `None` ⇒ the built-in default
1594    /// (`apply_db_caps::DEFAULT_MAX_DECLARED_VOLUME_MIB`, 512 GiB); `0` ⇒ disable managed
1595    /// declarations on this node (the aggregate can never fit a non-zero volume). Env-settable via
1596    /// **`BOATRAMP_HANDLERS_SQL_MAX_DECLARED_VOLUME_MIB`** (env-over-file).
1597    pub max_declared_volume_mib: Option<u64>,
1598}
1599
1600/// One external SQL database for the handler `sql` binding. Its **source** is one
1601/// of two mutually-exclusive forms:
1602///  - `url_env` — a **bring-your-own** database: the connection URL is a secret,
1603///    named indirectly by an env var (never written in the config file).
1604///  - `compute` — a database **boatramp runs** as a compute workload: boatramp
1605///    derives the connection from the workload's live endpoint (host\:port) plus
1606///    the `database`/`user`/`password_env` here, so there is no URL to hand-map and
1607///    it follows the workload across restarts (PLAN-managed-compute-sql).
1608#[cfg_attr(not(feature = "handlers"), allow(dead_code))]
1609#[derive(Debug, Clone, Default, Serialize, Deserialize)]
1610#[serde(default)]
1611pub struct ExternalDatabaseConfig {
1612    /// Engine: `postgres` (aliases `postgresql`/`pg`), `mysql` (alias
1613    /// `mariadb`), or `libsql` (aliases `sqlite`/`sqlite3`) — the embedded
1614    /// SQLite-compatible engine (single-node file, or a remote sqld primary via
1615    /// `url_env`). A `libsql` entry needs neither `compute` nor an external URL for
1616    /// the single-node case: it names an on-disk file via [`path`](Self::path).
1617    pub kind: String,
1618    /// Name of the env var holding the connection URL (e.g.
1619    /// `postgres://user:pw@host/db`). Required unless `compute` is set — or, for a
1620    /// single-node `libsql` database, unless `path` is set (an embedded file needs
1621    /// no URL/secret).
1622    pub url_env: String,
1623    /// Optional env var holding a **read-replica** connection URL. When set,
1624    /// `open-read-only` transactions route there; writes stay on `url_env`.
1625    pub read_url_env: Option<String>,
1626    /// Optional env var holding a **DDL/migration** connection URL for the
1627    /// **owner-role analog** of the schema-migration surface — a login that is
1628    /// DDL-capable *and distinct from the runtime binding user* (`user` /
1629    /// `url_env`). Its whole purpose is to keep migration DDL off the runtime
1630    /// tenant identity, mirroring the Postgres owner-role split (Postgres mints a
1631    /// per-tenant non-superuser owner role automatically; MySQL has no such role
1632    /// model, so the DDL identity must be supplied explicitly).
1633    ///
1634    /// **MySQL:** required to run schema migrations. Point it at an admin/DDL
1635    /// login (e.g. `mysql://root:…@host/db` or a purpose-made `_migrate` grant
1636    /// with `CREATE, ALTER, DROP, INDEX, REFERENCES` on the schema) that is **not**
1637    /// the runtime `user`. If it is unset (or resolves to the same identity as the
1638    /// runtime binding), migrate **refuses** fail-closed rather than run owner-DDL
1639    /// as the runtime tenant user — there is no owner/runtime split to fall back
1640    /// on. Ignored by the normal handler `sql` path; read only by the migration
1641    /// runner.
1642    ///
1643    /// **Postgres:** ignored — the per-project non-superuser owner role +
1644    /// its sealed credential are minted automatically at provision, so no
1645    /// operator-supplied DDL URL is needed (a set value is harmless and unused).
1646    pub migration_url_env: Option<String>,
1647    /// The name of a **compute workload** (a Postgres/MySQL server boatramp runs)
1648    /// to source this database from, instead of `url_env`. boatramp resolves the
1649    /// workload's live endpoint and builds the connection. Mutually exclusive with
1650    /// `url_env`.
1651    ///
1652    /// **Reserved prefix (#501 Stage B LOW-2):** do NOT name a static workload with the
1653    /// `bramp-db-` prefix — it is reserved for the per-project managed-database servers
1654    /// boatramp derives for declarative `databases:` entries
1655    /// (`boatramp_storage::tenant_provision::DERIVED_MANAGED_DB_PREFIX`). A `bramp-db-…`
1656    /// value here is refused fail-closed at config load
1657    /// ([`ConfigError::InvalidDbName`](crate::config::ConfigError::InvalidDbName)).
1658    pub compute: Option<String>,
1659    /// The database name inside the compute-backed server (non-secret).
1660    pub database: Option<String>,
1661    /// The connecting user for the compute-backed server (non-secret).
1662    pub user: Option<String>,
1663    /// Env var holding the password for `user` on the compute-backed server.
1664    /// **Omit to let boatramp fully manage the credential** (PLAN-managed-compute-sql
1665    /// Phase 2): it generates a strong password once, seals it with the `[secrets]`
1666    /// envelope, injects it into the DB workload's server-init env at launch, and
1667    /// connects the handler with it — the operator sets no DB secret at all. Set it
1668    /// only to bring your own password for the compute-backed server.
1669    pub password_env: Option<String>,
1670    /// Maximum pooled connections (default 8).
1671    pub pool_max: Option<u32>,
1672    /// Open every transaction `READ ONLY` (the engine rejects writes) — for a
1673    /// database functions should only read.
1674    pub read_only: bool,
1675    /// Permit **preview** deployments to reach this database. Default `false`: a
1676    /// preview is refused, so it can never touch the operator's live external DB.
1677    pub allow_preview: bool,
1678    /// Connection/acquire timeout in seconds (default 10).
1679    pub connect_timeout_secs: Option<u64>,
1680    /// The stock OCI image for a **managed co-located** database (`compute` set, no
1681    /// `password_env`). When omitted, boatramp auto-registers the workload from the
1682    /// engine's default image (`pgvector/pgvector:pg16` for postgres, `mysql:8.0`
1683    /// for mysql). Ignored for a bring-your-own (`url_env`) database.
1684    pub image: Option<String>,
1685    /// The persistent data-volume size in MiB for a **managed co-located** database
1686    /// (default 10240 = 10 GiB). Ignored for a bring-your-own database.
1687    pub volume_size_mib: Option<u32>,
1688    /// Startup grace (seconds) for a **managed co-located** database: how long a
1689    /// freshly launched server has to finish its first `initdb` before the reconcile
1690    /// loop treats a still-unhealthy replica as a broken launch to stop + relaunch.
1691    /// When set it overrides the engine default the synthesizer picks (Postgres 60,
1692    /// MySQL 120). Omit to use that default. Ignored for a bring-your-own database.
1693    pub startup_grace_secs: Option<u32>,
1694    /// **Isolation mechanism** for a compute-backed managed database (2×2 axis 1).
1695    /// `single` (default) — a *dedicated* database server (its own container) per
1696    /// tenant; `shared` — *one* server hosting a permission-separated database + role
1697    /// per tenant. Ignored for a bring-your-own (`url_env`) database.
1698    pub tenant: TenantIsolation,
1699    /// **Tenant grain** for a compute-backed managed database (2×2 axis 2). `project`
1700    /// (default) — a tenant is a project; `site` — a tenant is a site. A tenant may
1701    /// hold several databases (one per binding that names it); it gets one login role
1702    /// and sealed credential per (tenant, server), granted on all its own databases
1703    /// and none of another tenant's. The reserved `default` project uses the plain
1704    /// configured name, so a single-tenant install is just one ordinary database.
1705    pub tenant_scope: TenantScope,
1706    /// **Opt-in** (default `false`): inject the request's `boatramp.project` /
1707    /// `boatramp.site` into the SQL session at each transaction start (Postgres
1708    /// `set_config` GUC, MySQL session var), so hand-written **native RLS** policies
1709    /// can key on them per-request. The GraphQL data connector's row-level policy is
1710    /// claim-sourced and needs nothing here; this is for hand-rolled RLS on the plain
1711    /// `sql.open` path (Postgres — the engine with native row-level security).
1712    ///
1713    /// # Trust model — read before relying on this for isolation
1714    ///
1715    /// `rls_session` **provides** the request's tenant to the SQL session for an app's
1716    /// RLS to key on. It is **not** a general hostile-guest boundary:
1717    ///
1718    /// - The reserved keys (`boatramp.*` / `@boatramp_*`) are **protected** from guest
1719    ///   override — a handler statement that tries to `set_config('boatramp.…', …)` /
1720    ///   `SET boatramp.… ` / `SET @boatramp_… ` (or `RESET`/`DISCARD` them) is refused,
1721    ///   so a guest cannot spoof its injected tenant.
1722    /// - But the **real tenant-isolation boundary** is the **per-tenant database +
1723    ///   role** (`tenant = single` / `shared`), which a compromised handler cannot
1724    ///   cross regardless of what it does in-session. `rls_session` is a convenience
1725    ///   for app-authored RLS *within* a tenant's own database, layered on top of that
1726    ///   boundary — not a substitute for it.
1727    /// - For untrusted data, prefer **claim-sourced** enforcement (the GraphQL data
1728    ///   connector's row-level policy), which derives the tenant from the verified
1729    ///   request, not from anything the handler's SQL can influence.
1730    pub rls_session: bool,
1731    /// The Postgres session GUC name an app's RLS policies read for the host-resolved **tenant**
1732    /// (e.g. `app.tenant_id`), set per request/write on the `rls_session` path so RLS mirrors
1733    /// boatramp's injected predicate as a defense-in-depth backstop (v0.4.20). Only honored when
1734    /// `rls_session` is on and the backend is Postgres. `None` ⇒ not exposed (today's behavior).
1735    /// The guest can never set this GUC itself (its namespace becomes reserved).
1736    #[serde(default)]
1737    pub tenant_guc: Option<String>,
1738    /// The session GUC name for the anonymous **session** axis (e.g. `app.session_id`), the
1739    /// disjoint-column sibling of `tenant_guc` for `TenantOrSession` tables. `None` ⇒ not exposed.
1740    #[serde(default)]
1741    pub session_guc: Option<String>,
1742    /// A reserved sentinel value written to `tenant_guc` on an **`all`-scoped READ** (v0.4.21), so a
1743    /// table that opts in with `USING (… OR current_setting(tenant_guc, true) = '<marker>')` opens
1744    /// cross-tenant for the audited `all` twins. Pick a value that can **never** be a real tenant id
1745    /// (e.g. `*` or `__all__`). Only honored with `tenant_guc` set + `rls_session` on + Postgres.
1746    /// `None`/empty ⇒ `all` reads leave the GUC untouched (v0.4.20 fail-closed behavior). The guest
1747    /// can never set it — the `tenant_guc` namespace is already reserved against guest writes.
1748    #[serde(default)]
1749    pub tenant_all_marker: Option<String>,
1750    /// The on-disk file path for a single-node **`libsql`** database (`kind: "libsql"`), e.g.
1751    /// `/data/app.db`. The parent directory is created if absent. Used only by the embedded engine;
1752    /// ignored for `postgres`/`mysql` and for a remote-sqld `libsql` binding (which uses `url_env`).
1753    /// A `libsql` entry sets exactly one of `path` (single-node file) or `url_env` (remote sqld).
1754    #[serde(default)]
1755    pub path: Option<PathBuf>,
1756}
1757
1758/// How a managed compute-backed database is physically isolated per tenant (2×2 axis
1759/// 1). `Single` = a dedicated server (container) per tenant (isolation by separate
1760/// process); `Shared` = one server with a per-tenant database + login role (isolation
1761/// by grants — Postgres `REVOKE CONNECT FROM PUBLIC` + owner grant; MySQL per-schema
1762/// grant), so a tenant's role cannot connect to another tenant's database.
1763#[cfg_attr(not(feature = "handlers"), allow(dead_code))]
1764#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
1765#[serde(rename_all = "lowercase")]
1766pub enum TenantIsolation {
1767    /// A dedicated database server (its own container) per tenant. The default.
1768    #[default]
1769    Single,
1770    /// One shared server hosting a per-tenant database + role (grant-isolated).
1771    Shared,
1772}
1773
1774/// The grain of a tenant for a managed compute-backed database (2×2 axis 2) —
1775/// `Project` (default) or `Site`. The two grains are parallel; the isolation
1776/// mechanism is [`TenantIsolation`].
1777#[cfg_attr(not(feature = "handlers"), allow(dead_code))]
1778#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
1779#[serde(rename_all = "lowercase")]
1780pub enum TenantScope {
1781    /// A tenant is a **project** (the default).
1782    #[default]
1783    Project,
1784    /// A tenant is a **site** (finer than project).
1785    Site,
1786}
1787
1788impl ExternalDatabaseConfig {
1789    /// Validate the source is well-formed: **exactly one** of `url_env` /
1790    /// `compute`, and a `compute`-backed database has the connection details
1791    /// boatramp can't infer (`database` + `user`). `password_env` is **optional** —
1792    /// omit it to let boatramp manage the credential (Phase 2). `name` is the
1793    /// binding name, for the error message.
1794    #[cfg_attr(not(feature = "handlers"), allow(dead_code))]
1795    pub fn validate(&self, name: &str) -> Result<(), String> {
1796        let has_url = !self.url_env.is_empty();
1797        let has_compute = self.compute.as_deref().is_some_and(|c| !c.is_empty());
1798        let has_path = self
1799            .path
1800            .as_deref()
1801            .is_some_and(|p| !p.as_os_str().is_empty());
1802
1803        // A `libsql`/`sqlite` entry is the embedded engine: single-node via `path`, or remote sqld
1804        // via `url_env` — never `compute` (boatramp doesn't run a libsql server workload). Validate
1805        // it on its own axis (exactly one of `path` / `url_env`), and reject `path` on the external
1806        // engines (a Postgres/MySQL binding has no on-disk file).
1807        let is_libsql = matches!(
1808            self.kind.trim().to_ascii_lowercase().as_str(),
1809            "libsql" | "sqlite" | "sqlite3"
1810        );
1811        if is_libsql {
1812            if has_compute {
1813                return Err(format!(
1814                    "sql database {name:?}: a `libsql` database is the embedded engine — set `path` \
1815                     (single-node file) or `url_env` (remote sqld), not `compute`"
1816                ));
1817            }
1818            return match (has_path, has_url) {
1819                (true, true) => Err(format!(
1820                    "sql database {name:?}: a `libsql` database sets exactly one of `path` \
1821                     (single-node file) or `url_env` (remote sqld), not both"
1822                )),
1823                (false, false) => Err(format!(
1824                    "sql database {name:?}: a `libsql` database needs a source — set `path` \
1825                     (single-node file) or `url_env` (remote sqld)"
1826                )),
1827                _ => Ok(()),
1828            };
1829        }
1830        if has_path {
1831            return Err(format!(
1832                "sql database {name:?}: `path` is only valid for a `libsql` database (the embedded \
1833                 engine); a {} binding uses `url_env` or `compute`",
1834                self.kind
1835            ));
1836        }
1837
1838        match (has_url, has_compute) {
1839            (true, true) => Err(format!(
1840                "sql database {name:?}: set exactly one of `url_env` or `compute`, not both"
1841            )),
1842            (false, false) => Err(format!(
1843                "sql database {name:?}: needs a source — set `url_env` (bring-your-own) or \
1844                 `compute` (a database boatramp runs)"
1845            )),
1846            (false, true) => {
1847                // `database` + `user` are non-secret and can't be inferred; a missing
1848                // `password_env` is *not* an error — it selects the managed credential.
1849                for (field, val) in [("database", &self.database), ("user", &self.user)] {
1850                    if val.as_deref().is_none_or(str::is_empty) {
1851                        return Err(format!(
1852                            "sql database {name:?}: a `compute`-backed database requires `{field}`"
1853                        ));
1854                    }
1855                }
1856                Ok(())
1857            }
1858            (true, false) => Ok(()),
1859        }
1860    }
1861
1862    /// Whether this compute-backed database uses a **boatramp-managed** credential
1863    /// (Phase 2): `compute` is set and no `password_env` was supplied.
1864    #[cfg_attr(not(feature = "handlers"), allow(dead_code))]
1865    pub fn is_managed_credential(&self) -> bool {
1866        self.compute.as_deref().is_some_and(|c| !c.is_empty())
1867            && self.password_env.as_deref().is_none_or(str::is_empty)
1868    }
1869}
1870
1871/// The signing algorithm for a signer that can choose one (`Local`, `Vault`,
1872/// `Pkcs11`). ES256 is the portable default; the cloud KMS backends are ES256-only
1873/// and ignore this. Written as a RON enum: `alg: Es256` / `alg: Ed25519`.
1874#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize)]
1875pub enum SignerAlg {
1876    /// ECDSA P-256 (COSE ES256) — the default.
1877    #[default]
1878    Es256,
1879    /// Ed25519 (COSE EdDSA).
1880    Ed25519,
1881}
1882
1883impl SignerAlg {
1884    fn to_token_alg(self) -> boatramp_core::cose::TokenAlg {
1885        match self {
1886            Self::Es256 => boatramp_core::cose::TokenAlg::Es256,
1887            Self::Ed25519 => boatramp_core::cose::TokenAlg::Ed25519,
1888        }
1889    }
1890}
1891
1892/// External token signer selector (`serve.signer`). Maps to
1893/// [`boatramp_server::signer::SignerConfig`]; secrets (tokens/PINs) are resolved
1894/// from the named env vars at startup, never stored in config. Written as a RON
1895/// enum — `signer: Vault(...)`, `signer: AwsKms(...)`, `signer: Pkcs11(...)`, ….
1896#[derive(Debug, Clone, Serialize, Deserialize)]
1897#[serde(deny_unknown_fields)]
1898pub enum AuthSignerConfig {
1899    /// In-process key (`"<alg>:<hex>"`).
1900    Local {
1901        /// The private key spec, `"<alg>:<hex>"`.
1902        private_key: String,
1903    },
1904    /// HashiCorp Vault Transit key.
1905    Vault {
1906        /// Vault base address.
1907        address: String,
1908        /// The Transit key name.
1909        key: String,
1910        /// Env var holding the Vault token.
1911        token_env: String,
1912        /// The key algorithm.
1913        #[serde(default)]
1914        alg: SignerAlg,
1915    },
1916    /// AWS KMS asymmetric key (ES256).
1917    AwsKms {
1918        /// The KMS key id or ARN.
1919        key_id: String,
1920        /// Optional region override.
1921        #[serde(default)]
1922        region: Option<String>,
1923    },
1924    /// GCP Cloud KMS key version (ES256).
1925    GcpKms {
1926        /// The key-version resource name.
1927        key_version: String,
1928        /// Env var holding a GCP OAuth2 access token.
1929        access_token_env: String,
1930    },
1931    /// Azure Key Vault key (ES256).
1932    AzureKv {
1933        /// The vault base URL.
1934        vault_url: String,
1935        /// The key name.
1936        key: String,
1937        /// The key version.
1938        key_version: String,
1939        /// Env var holding an Azure AD access token.
1940        access_token_env: String,
1941    },
1942    /// PKCS#11 HSM key.
1943    Pkcs11 {
1944        /// Path to the PKCS#11 module.
1945        module: String,
1946        /// The token label.
1947        token_label: String,
1948        /// The key's `CKA_LABEL`.
1949        key_label: String,
1950        /// Env var holding the user PIN.
1951        pin_env: String,
1952        /// The key algorithm.
1953        #[serde(default)]
1954        alg: SignerAlg,
1955    },
1956}
1957
1958impl AuthSignerConfig {
1959    /// Map the config-file form to the server's runtime [`SignerConfig`].
1960    pub fn to_signer_config(&self) -> boatramp_server::signer::SignerConfig {
1961        use boatramp_server::signer::SignerConfig;
1962        match self {
1963            Self::Local { private_key } => SignerConfig::Local {
1964                private_key: private_key.clone(),
1965            },
1966            Self::Vault {
1967                address,
1968                key,
1969                token_env,
1970                alg,
1971            } => SignerConfig::Vault {
1972                address: address.clone(),
1973                key: key.clone(),
1974                token_env: token_env.clone(),
1975                alg: alg.to_token_alg(),
1976            },
1977            Self::AwsKms { key_id, region } => SignerConfig::AwsKms {
1978                key_id: key_id.clone(),
1979                region: region.clone(),
1980            },
1981            Self::GcpKms {
1982                key_version,
1983                access_token_env,
1984            } => SignerConfig::GcpKms {
1985                key_version: key_version.clone(),
1986                access_token_env: access_token_env.clone(),
1987            },
1988            Self::AzureKv {
1989                vault_url,
1990                key,
1991                key_version,
1992                access_token_env,
1993            } => SignerConfig::AzureKv {
1994                vault_url: vault_url.clone(),
1995                key: key.clone(),
1996                key_version: key_version.clone(),
1997                access_token_env: access_token_env.clone(),
1998            },
1999            Self::Pkcs11 {
2000                module,
2001                token_label,
2002                key_label,
2003                pin_env,
2004                alg,
2005            } => SignerConfig::Pkcs11 {
2006                module: module.clone(),
2007                token_label: token_label.clone(),
2008                key_label: key_label.clone(),
2009                pin_env: pin_env.clone(),
2010                alg: alg.to_token_alg(),
2011            },
2012        }
2013    }
2014}
2015
2016/// `serve` section — server defaults, overridden by flags/env.
2017#[derive(Debug, Clone, Default, Serialize, Deserialize)]
2018#[serde(default)]
2019pub struct ServeConfig {
2020    /// Bind address (e.g. `0.0.0.0:8080`).
2021    pub addr: Option<SocketAddr>,
2022    /// Data directory for filesystem backends.
2023    pub data_dir: Option<PathBuf>,
2024    /// Blob object-store backend (`fs`/`s3`/`gcs`/`azure`) — the config-level analog of the
2025    /// `--blobs` flag. Absent ⇒ the flag/env decides (`--blobs`/`BOATRAMP_BLOBS`, default `fs`).
2026    /// The flag/env still wins over this (uniform `serve` precedence). Read primarily by `boatramp
2027    /// blob migrate`, which builds a source/destination backend from a config file alone; `serve`
2028    /// also honours it as the config-level fallback under the flag.
2029    pub blobs: Option<crate::backends::BlobBackend>,
2030    /// S3 bucket (`--blobs s3`). Config-level fallback for `--s3-bucket`/`BOATRAMP_S3_BUCKET`.
2031    pub s3_bucket: Option<String>,
2032    /// S3 endpoint URL (e.g. a MinIO/R2/Tigris endpoint). Fallback for `--s3-endpoint`.
2033    pub s3_endpoint: Option<String>,
2034    /// S3 region. Fallback for `--s3-region`.
2035    pub s3_region: Option<String>,
2036    /// Use S3 path-style addressing (required by MinIO). Fallback for `--s3-path-style`.
2037    pub s3_path_style: bool,
2038    /// GCS bucket (`--blobs gcs`). Fallback for `--gcs-bucket`.
2039    pub gcs_bucket: Option<String>,
2040    /// GCS storage endpoint URL (e.g. a `fake-gcs-server` emulator). Fallback for `--gcs-endpoint`.
2041    pub gcs_endpoint: Option<String>,
2042    /// Skip GCS credential resolution (anonymous — the emulator). Fallback for `--gcs-anonymous`.
2043    pub gcs_anonymous: bool,
2044    /// Azure storage account name (`--blobs azure`). Fallback for `--azure-account`.
2045    pub azure_account: Option<String>,
2046    /// Azure container name (`--blobs azure`). Fallback for `--azure-container`.
2047    pub azure_container: Option<String>,
2048    /// Azure storage account access key (shared-key auth). Fallback for `--azure-access-key`.
2049    /// Prefer the env/flag over persisting a key in the config file.
2050    pub azure_access_key: Option<String>,
2051    /// Use the Azurite emulator (well-known dev credentials + local endpoint). Fallback for
2052    /// `--azure-emulator`.
2053    pub azure_emulator: bool,
2054    /// `[serve.blob_fallback]` — a **read-only SECONDARY blob backend** for a zero-downtime
2055    /// backend switch (blob-backend migration Part 2). When set, serving reads the PRIMARY (the
2056    /// `blobs`/`s3_*`/`gcs_*`/`azure_*` fields above) first and, on a definitive miss for a
2057    /// boatramp-owned key, falls through to this secondary — so a `--blobs` switch (fs→cloud,
2058    /// provider→provider, region→region) has no serving gap while `boatramp blob migrate` drains
2059    /// the secondary into the primary. **Writes are primary-only**; the secondary is never written
2060    /// or deleted. This is a **bounded transition aid**: drain, verify, then remove this block and
2061    /// restart (the node logs a prominent startup WARNING while it is active, and GC prune is
2062    /// refused). Absent ⇒ no fallback (unchanged). See [`BlobFallbackConfig`].
2063    pub blob_fallback: Option<BlobFallbackConfig>,
2064    /// `[serve.blob_backends.<project>]` — **per-project** blob object-store overrides
2065    /// (PLAN-per-project-blob-backend). A project named here serves its `wasi:blobstore` data from its
2066    /// OWN bucket/endpoint/credential instead of the one node-wide `[serve]` backend; a project with NO
2067    /// entry — and the reserved `default` project — resolves the global default (invariant 5: an
2068    /// all-global deployment is byte-for-byte unchanged). Operator-configured (node config + sealed
2069    /// `[secrets]`), mirroring `[handlers.bindings.sql.databases]`; a project OWNER declaring its own
2070    /// backend is out of scope for this cut. Each entry's sealed S3 credential is a secret **reference**
2071    /// (`boatramp:`/`env:`), never inlined (invariant 3). Empty ⇒ no overrides (the common case). See
2072    /// [`BlobBackendConfig`]. Env parity: `BOATRAMP_SERVE_BLOB_BACKEND_<PROJECT>_*`.
2073    pub blob_backends: BTreeMap<String, BlobBackendConfig>,
2074    /// Token root **private** key (hex) — issuing node: verifies *and* mints
2075    /// tokens / OIDC exchanges.
2076    pub auth_root_private_key: Option<String>,
2077    /// Token root **public** key (hex) — verify-only node.
2078    pub auth_root_public_key: Option<String>,
2079    /// Single-use bootstrap secret enabling `POST /api/tokens/bootstrap` (mint the
2080    /// first token without an admin bearer). Prefer the `BOATRAMP_BOOTSTRAP_SECRET`
2081    /// env / `--bootstrap-secret` flag so it isn't persisted in the config file.
2082    pub bootstrap_secret: Option<String>,
2083    /// External token signer (`[serve.signer]`): mint with a
2084    /// KMS/HSM/Vault-held root key instead of an in-process `auth_root_private_key`.
2085    /// Absent ⇒ the in-process key. When set, its public half is the trust anchor.
2086    pub signer: Option<AuthSignerConfig>,
2087    /// Reject blob uploads larger than this many bytes.
2088    pub max_upload_bytes: Option<u64>,
2089    /// Abort an upload that stalls for longer than this many seconds.
2090    pub upload_idle_timeout_secs: Option<u64>,
2091    /// Cap on simultaneous blob uploads.
2092    pub max_concurrent_uploads: Option<usize>,
2093    /// In a TLS mode, bind this plain-HTTP address on a second listener that
2094    /// redirects to HTTPS (dual-listener). Only read in `tls` builds.
2095    #[cfg_attr(not(feature = "tls"), allow(dead_code))]
2096    pub http_redirect_addr: Option<SocketAddr>,
2097    /// Site to serve for a `Host` matching no domain, instead of 404.
2098    pub default_site: Option<String>,
2099    /// The fleet's canonical public origin (e.g. `https://cp.example.com`) that a
2100    /// per-request proof-of-possession must bind to (`aud`). Required for
2101    /// holder-bound (`cnf`/PoP) tokens to be usable — a proof's origin is compared
2102    /// against this value, never against a `Host`/`X-Forwarded-*` header.
2103    pub pop_origin: Option<String>,
2104    /// Require a valid control-plane token to view deployment previews.
2105    pub protect_previews: bool,
2106    /// Rate-limit cluster-wide via the control-plane KV instead of per node.
2107    pub cluster_rate_limit: bool,
2108    /// Keep the config cache coherent across processes sharing one KV via the
2109    /// changelog.
2110    pub shared_cache_coherence: bool,
2111    /// Cloud blob-change notification provisioning tier (FA-5b2): how boatramp
2112    /// obtains the native event pipeline (S3→SQS) that backs a `blob` trigger —
2113    /// `dry-run` (print the recipe), `provision` (create + retract), `verify-only`
2114    /// (operator pre-wired), or `refuse` (fail closed). Absent ⇒ no provisioning:
2115    /// `blob` triggers then work only on a self-watching backend (fs). Only wired
2116    /// for the S3 backend (`--features s3`).
2117    pub blob_notify_tier: Option<boatramp_core::blob_notify::ProvisionTier>,
2118    /// The AWS account id used to scope the provisioned SQS queue's `SendMessage`
2119    /// policy (`aws:SourceAccount`). Required when `blob_notify_tier` provisions.
2120    pub blob_notify_account_id: Option<String>,
2121    /// `[serve.console]` — the embedded web management console. Absent (or
2122    /// `enabled: false`) ⇒ not served. This is the **baseline** for the dynamic
2123    /// `console.*` daemon-config override, which can enable/move it at runtime
2124    /// (`boatramp config set console.enabled true`) without a restart.
2125    pub console: Option<ConsoleConfig>,
2126    /// Bind address for the **dedicated local S3-ingress listener** (PLAN-blob-s3-ingress,
2127    /// Architect HIGH-4). Absent ⇒ the local S3 face is NOT served (it is opt-in — a deployment that
2128    /// only mints cloud-brokered credentials never needs it). This is a SEPARATE listener from the
2129    /// control-plane `addr`: it has its own SigV4 auth surface and never reaches `serve_by_host` or
2130    /// the `/api` router.
2131    pub s3_ingress_addr: Option<SocketAddr>,
2132    /// Path to the **dedicated S3-ingress root secret** file (raw 32 bytes) — the independently-
2133    /// rotatable HKDF root for `secret_access_key` derivation (hard domain separation from the
2134    /// `[secrets]` KEK + the COSE signing key). Like `[secrets].kek_file`, this holds a *path*, never
2135    /// key material in the config text, and (in a cluster) the **same file must be present on every
2136    /// node** so every node derives the same `secret_access_key`. Absent on a single node ⇒ an
2137    /// ephemeral per-process root is auto-generated; absent on a **multi-node** deployment ⇒ the S3
2138    /// face is refused to enable (fail-closed — credentials would otherwise be un-verifiable across
2139    /// nodes). Prefer the `BOATRAMP_S3_INGRESS_SECRET_FILE` env / flag so the path stays out of the
2140    /// committed config where that matters operationally.
2141    pub s3_ingress_secret_file: Option<PathBuf>,
2142    /// The publicly-reachable base URL an external client targets for the local S3 face — what a
2143    /// **minted** upload credential (`boatramp:handlers/blob-upload` guest mint / `boatramp blob
2144    /// mint-upload` operator) embeds as its endpoint (a presigned-put URL prefix, or the SDK endpoint
2145    /// for temp-credentials). Absent ⇒ derived from `s3_ingress_addr` as `http://<addr>` (fine for a
2146    /// same-host dev/test loop; set it explicitly to the TLS-terminated public URL in production).
2147    /// Only consulted when guest/operator upload minting is wired (`blob-upload` feature + the face
2148    /// enabled).
2149    pub s3_ingress_public_url: Option<String>,
2150    /// Operator ceiling (seconds) on a minted upload credential's TTL — a guest/operator can only
2151    /// request a SHORTER lifetime (the mint clamps to this). Absent ⇒ a conservative default
2152    /// ([`DEFAULT_S3_INGRESS_MINT_MAX_TTL_SECS`]). A `0` disables minting entirely (the binding is
2153    /// never attached).
2154    pub s3_ingress_mint_max_ttl_secs: Option<u64>,
2155    /// Operator ceiling (bytes) on a minted credential's `max_bytes` constraint — a guest can only
2156    /// request a SMALLER cap (clamped to this). Absent ⇒ no host-side max-bytes clamp (the per-container
2157    /// ceiling at the face still applies).
2158    pub s3_ingress_mint_max_bytes: Option<u64>,
2159    /// **Cloud brokering** (M4): when the node's blob backend is a cloud object store (S3/GCS/Azure)
2160    /// and this is set, minting brokers a NATIVE scoped credential (STS session policy / signed URL +
2161    /// CAB / user-delegation SAS) so the client uploads DIRECTLY to the real store (bytes never transit
2162    /// the node) — INSTEAD of the local S3 face. Absent ⇒ the local face is used (an fs/in-memory
2163    /// backend, or a cloud backend that re-transits through the local face). See [`S3IngressCloud`].
2164    pub s3_ingress_cloud: Option<S3IngressCloud>,
2165    /// **Node-level base S3 credential source** (`[serve.s3_credential]`, task #505). When set, BOTH the
2166    /// S3 blob **object backend** (`--blobs s3`) and the AWS blob-upload **cloud minter**
2167    /// (`[serve.s3_ingress_cloud]`) source their base AWS credential from boatramp's `[secrets]` sealed
2168    /// store instead of the ambient `AWS_ACCESS_KEY_ID`/`AWS_SECRET_ACCESS_KEY` env chain. ONE shared
2169    /// source (both consumers read the SAME bucket key). Absent ⇒ the ambient AWS env chain (current
2170    /// behavior, non-breaking). Requires a `[secrets]` envelope when the `secret_access_key` is a sealed
2171    /// `boatramp:`/`env:` ref — a configured ref with no envelope is a **startup error** (fail-closed, no
2172    /// silent env fallback). See [`S3CredentialConfig`].
2173    pub s3_credential: Option<S3CredentialConfig>,
2174    /// `[serve.kv]` — control-plane SlateDB KV durability cadence + shutdown budget (v0.9.0
2175    /// KV-recovery). Absent ⇒ the defaults (periodic checkpoint ON at
2176    /// [`DEFAULT_KV_CHECKPOINT_INTERVAL_SECS`], close budget [`DEFAULT_KV_CLOSE_DEADLINE_SECS`]).
2177    /// See [`KvConfig`].
2178    pub kv: Option<KvConfig>,
2179    /// `[serve.listeners.<name>]` — host-owned **inbound-TCP listeners** (PLAN-handler-tcp-inbound).
2180    /// Each declares a bind address + a target guest `tcp-connection-handler` component (pinned to a
2181    /// project + site + Dimension-0 tenancy): the node binds + listens + accepts and re-enters the
2182    /// guest once per ALREADY-ACCEPTED connection, handing it only the connection's `wasi:io` streams
2183    /// (the guest NEVER receives `wasi:sockets`). GATED on the posture `allow_guest_tcp_listener` (off
2184    /// under multi-tenant) AND the declaration here — both must hold. Empty ⇒ no listeners (the common
2185    /// case; serving is byte-for-byte unchanged). Env parity: `BOATRAMP_SERVE_LISTENER_<NAME>_*`. See
2186    /// [`ListenerConfig`].
2187    #[serde(default)]
2188    pub listeners: BTreeMap<String, ListenerConfig>,
2189    /// `[serve.on_demand_tls]` — on-demand per-SNI ACME issuance at scale (cap-req 03). Absent or
2190    /// `enabled = false` ⇒ OFF (the static `--tls acme-dns` resolver is byte-for-byte unchanged). When
2191    /// on, the edge issues + caches a cert on the first TLS handshake for an unknown-but-#02-**verified**
2192    /// custom domain, gated so an arbitrary/unverified SNI is refused (fail-closed). File-configured.
2193    /// See [`OnDemandTlsConfig`].
2194    #[serde(default, skip_serializing_if = "Option::is_none")]
2195    pub on_demand_tls: Option<OnDemandTlsConfig>,
2196}
2197
2198/// `[serve.on_demand_tls]` — on-demand per-SNI TLS issuance (cap-req 03). Off unless `enabled`. When
2199/// on, an unknown-but-#02-verified SNI triggers issuance at handshake time (the client retries once
2200/// the cert is warm); an unauthorized SNI is refused, so a flood of unknown names can't become an ACME
2201/// storm. The ACME account + issued certs persist in the control-plane cert store and replicate across
2202/// the cluster (the leader issues; followers serve the replicated cert).
2203#[derive(Debug, Clone, Default, Serialize, Deserialize)]
2204#[serde(default, deny_unknown_fields)]
2205pub struct OnDemandTlsConfig {
2206    /// Master toggle. `false` (default) ⇒ the whole feature is off.
2207    pub enabled: bool,
2208    /// How to prove control of a name to the CA. `tls-alpn-01` (default) validates on the 443 edge (no
2209    /// extra port); `dns-01` uses the node's configured ACME DNS provider (an operator-controlled zone).
2210    pub challenge: OnDemandChallenge,
2211    /// ACME directory URL. Absent ⇒ the ACME client default (Let's Encrypt production).
2212    #[serde(skip_serializing_if = "Option::is_none")]
2213    pub directory_url: Option<String>,
2214    /// ACME account contact email (optional).
2215    #[serde(skip_serializing_if = "Option::is_none")]
2216    pub contact_email: Option<String>,
2217    /// Max concurrent in-flight issuances (global). Absent ⇒ 4.
2218    #[serde(skip_serializing_if = "Option::is_none")]
2219    pub max_inflight: Option<usize>,
2220    /// How long a refused/failed SNI is negatively cached (seconds). Absent ⇒ 300.
2221    #[serde(skip_serializing_if = "Option::is_none")]
2222    pub negative_ttl_secs: Option<u64>,
2223    /// Max CA orders per rolling hour (the account rate-limit floor). Absent ⇒ 50; `0` ⇒ unlimited.
2224    #[serde(skip_serializing_if = "Option::is_none")]
2225    pub rate_limit_per_hour: Option<u32>,
2226}
2227
2228/// How [`OnDemandTlsConfig`] proves control of a name to the CA.
2229#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
2230#[serde(rename_all = "kebab-case")]
2231pub enum OnDemandChallenge {
2232    /// TLS-ALPN-01 on the 443 edge (default) — no extra port.
2233    #[default]
2234    TlsAlpn01,
2235    /// DNS-01 via the node's configured ACME DNS provider (an operator-controlled zone / wildcard).
2236    Dns01,
2237}
2238
2239/// `[serve.listeners.<name>]` — a **host-owned inbound-TCP listener** (PLAN-handler-tcp-inbound). The
2240/// node binds + listens + accepts on `bind` and dispatches each accepted connection to the guest
2241/// `component`'s `tcp-connection-handler` export, with tenancy OPERATOR-PINNED here (a raw socket
2242/// carries no Host/path/principal, so there is nothing per-connection to resolve). The guest is handed
2243/// only the connection's `wasi:io` byte streams — it holds NO `wasi:sockets` authority (bind stays
2244/// host-side). Modeled on [`boatramp_core::function::FunctionConfig`] / the session route config.
2245///
2246/// Phase 1 is **plaintext-only** and **no per-listener egress**: a declared `tls` block or a non-empty
2247/// `egress_allowlist` is REFUSED at config load (fail-closed, boot-LOUD) rather than silently ignored —
2248/// per-listener host-TLS and outbound egress are deferred follow-ups. See [`validate_listeners`].
2249#[derive(Debug, Clone, Default, Serialize, Deserialize)]
2250#[serde(default, deny_unknown_fields)]
2251pub struct ListenerConfig {
2252    /// The address the node binds + listens + accepts on (e.g. `0.0.0.0:9000`). **Required** (a blank
2253    /// `bind` is refused at config load).
2254    pub bind: Option<SocketAddr>,
2255    /// Path to the guest `.wasm` within the pinned site's deployment (exports `tcp-connection-handler`).
2256    /// **Required**.
2257    pub component: String,
2258    /// The project this listener's component is deployed under (host-resolved, never guest input). The
2259    /// active deployment of `project`/`site` is what the accept loop serves. **Required**.
2260    pub project: String,
2261    /// The site within `project` whose active deployment holds `component`. **Required**.
2262    pub site: String,
2263    /// Requested capabilities (interface names; see `KNOWN_IMPORTS`). A listener component declares
2264    /// whatever `sql`/`orm`/`kv`/… it uses per connection — NOT `wasi:sockets` (the host owns the
2265    /// socket; a `tcp-connection-host` guest imports only `wasi:io`, handed the accepted streams).
2266    #[serde(default, skip_serializing_if = "Vec::is_empty")]
2267    pub imports: Vec<String>,
2268    /// Static environment variables injected into the component (never secrets).
2269    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
2270    pub env: BTreeMap<String, String>,
2271    /// DEFERRED (Phase 1): a per-listener outbound-TCP allowlist. A `tcp-connection-host` guest imports
2272    /// ONLY `wasi:io` — it cannot hold `wasi:sockets` — so this is unusable in Phase 1 and a non-empty
2273    /// value is REFUSED at config load (fail-closed) rather than silently dropped. Kept for forward
2274    /// parity with the handler/session `egress_allowlist`.
2275    #[serde(default, skip_serializing_if = "Vec::is_empty")]
2276    pub egress_allowlist: Vec<String>,
2277    /// Operator-pinned Dimension-0 tenancy for this listener's `sql`/`orm` (resolved once from this
2278    /// config, carried on every connection — nothing per-connection to resolve from). Absent ⇒ plain
2279    /// (project = database).
2280    #[serde(
2281        default,
2282        deserialize_with = "boatramp_core::tenancy::de_opt_tenancy",
2283        skip_serializing_if = "Option::is_none"
2284    )]
2285    pub tenancy: Option<boatramp_core::tenancy::Tenancy>,
2286    /// DEFERRED (Phase 1): per-listener host-TLS. Phase 1 ships plaintext-only; a declared `tls` block
2287    /// is REFUSED at config load (fail-closed) so an operator is never misled into thinking a listener
2288    /// terminates TLS when it does not. Terminate TLS in front of boatramp, or wait for the fast-follow.
2289    #[serde(default, skip_serializing_if = "Option::is_none")]
2290    pub tls: Option<ListenerTlsConfig>,
2291    /// Cap on simultaneously-live connections for THIS listener (a per-listener DoS bound on top of the
2292    /// engine's conn-lane ceiling). `0` is refused; absent ⇒ [`DEFAULT_LISTENER_MAX_CONNS`].
2293    pub max_conns: Option<usize>,
2294    /// Tear a connection down after this many milliseconds with NO bytes in either direction (idle
2295    /// timeout — the conn lane replaces the per-invocation epoch deadline with this). `0` is refused;
2296    /// absent ⇒ [`DEFAULT_LISTENER_IDLE_TIMEOUT_MS`].
2297    pub idle_timeout_ms: Option<u64>,
2298    /// Absolute cap (milliseconds) on a single connection's lifetime regardless of activity. `0` is
2299    /// refused; absent ⇒ [`DEFAULT_LISTENER_MAX_CONN_DURATION_MS`].
2300    pub max_conn_duration_ms: Option<u64>,
2301    /// How the accepted connection is driven (cap-req 08). [`ListenerMode::Connection`] (default) is the
2302    /// long-lived model: the guest's `tcp-connection-handler` holds the connection — and ONE wasm
2303    /// instance — for the connection's whole life. [`ListenerMode::Session`] drives the connection
2304    /// through the re-entrant **session** model instead: the host owns the socket, re-enters the guest's
2305    /// `session-handler` per inbound batch carrying a host-held checkpoint, and holds NO instance between
2306    /// batches — so thousands of mostly-idle connections (IMAP IDLE, long-poll) cost ~a socket each, not
2307    /// an instance each, and a protocol-idle-but-alive connection is never torn down for inactivity
2308    /// (only a dead peer or `max_conn_duration` reaps it). The component must export `session-handler`,
2309    /// not `tcp-connection-handler`. Additive + back-compat: absent ⇒ `Connection` (unchanged).
2310    #[serde(default)]
2311    pub mode: ListenerMode,
2312}
2313
2314/// How a `[serve.listeners.<name>]` drives each accepted connection (cap-req 08). See
2315/// [`ListenerConfig::mode`].
2316#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
2317#[serde(rename_all = "kebab-case")]
2318pub enum ListenerMode {
2319    /// Long-lived `tcp-connection-handler` — one wasm instance pinned per connection for its whole life
2320    /// (the original inbound-TCP model). The default.
2321    #[default]
2322    Connection,
2323    /// Re-entrant `session-handler` — the host owns the socket and drives it through the session model,
2324    /// holding NO instance between inbound batches (idle ⇒ socket + checkpoint only). A quiet, PARKED
2325    /// connection (blocked on the socket read between batches) is NOT evicted for inactivity — only the
2326    /// absolute `max_conn_duration_ms` cap and dead-peer detection (EOF) end it, so a protocol-idle but
2327    /// alive peer (IMAP IDLE) survives. In this mode `idle_timeout_ms` is reinterpreted as the
2328    /// per-re-entry **processing deadline** — the max wall-clock ONE re-entry may spend (instantiate +
2329    /// handle + write its response) — bounding a guest stalled on a slow/zero-window peer so it cannot
2330    /// pin a session-pool slot + instance; a re-entry that exceeds it is cancelled and the connection
2331    /// closed. Re-entries run on a DEDICATED concurrency pool, never the shared async lane.
2332    Session,
2333}
2334
2335/// Per-listener host-side TLS material (cap-req 06). The host terminates TLS and hands the guest a
2336/// decrypted plaintext stream (the guest does no crypto). With `starttls` absent this is **implicit
2337/// TLS** (handshake at accept — 465/993); with `starttls` present it is **STARTTLS** (plaintext
2338/// dialog, in-band upgrade on the declared trigger — 25/587/143). Either way requires both
2339/// `cert_file` and `key_file`. File-only (never set from the env overlay).
2340#[derive(Debug, Clone, Default, Serialize, Deserialize)]
2341#[serde(deny_unknown_fields)]
2342pub struct ListenerTlsConfig {
2343    /// PEM certificate chain path.
2344    pub cert_file: Option<PathBuf>,
2345    /// PEM private-key path.
2346    pub key_file: Option<PathBuf>,
2347    /// Absent ⇒ implicit TLS (handshake at accept). Present ⇒ STARTTLS (plaintext until the declared
2348    /// trigger, then an in-band upgrade). Still requires `cert_file` + `key_file`.
2349    #[serde(default, skip_serializing_if = "Option::is_none")]
2350    pub starttls: Option<ListenerStarttlsConfig>,
2351    /// Opt this listener into **on-demand per-SNI issuance** (cap-req 03 #4): a client that negotiates
2352    /// TLS with a verified custom-domain SNI terminating here gets a cert issued the same way the public
2353    /// edge does, sharing the one `[serve.on_demand_tls]` engine (one issuance budget, one cluster
2354    /// certreq single-flight). Requires `[serve.on_demand_tls]` enabled at the node. The listener's own
2355    /// `cert_file` still serves `server_names` (and an SNI-less handshake). Default `false` ⇒ the static
2356    /// cert alone (unchanged). This is transport-level only — it carries no notion of what protocol runs
2357    /// over the listener.
2358    ///
2359    /// **Project-scoped** (Security review Finding B): a listener is bound to exactly one project (its
2360    /// `project`), and that project may front many domains (its tenants/sites). On-demand serving here
2361    /// is restricted to SNIs whose owning project is *this* project — the listener never serves (nor
2362    /// routes to its guest) a cert for another project's domain, even though all certs share the one
2363    /// engine + cache. Point an `on_demand` listener only at a guest that is meant to handle that whole
2364    /// project's domains.
2365    #[serde(default)]
2366    pub on_demand: bool,
2367    /// SNI names the listener's own static `cert_file` serves directly (an SNI match here wins before
2368    /// on-demand). Absent/empty ⇒ the static cert serves only SNI-less handshakes (via the no-SNI
2369    /// fallback); every presented SNI then goes to on-demand. Only meaningful with `on_demand = true`.
2370    #[serde(default, skip_serializing_if = "Option::is_none")]
2371    pub server_names: Option<Vec<String>>,
2372}
2373
2374/// Declarative STARTTLS grammar (cap-req 06, Stage B) — protocol-agnostic **data**. The host runs a
2375/// generic trigger→response→wrap engine driven entirely by these fields; no SMTP/IMAP/POP3 shapes are
2376/// hardcoded in the server. Examples:
2377/// SMTP — `(trigger: "STARTTLS", response: "220 2.0.0 Ready to start TLS")`;
2378/// POP3 — `(trigger: "STLS", response: "+OK begin TLS negotiation")`;
2379/// IMAP — `(trigger: "STARTTLS", response: "{tag} OK begin TLS negotiation", tag_capture: true)`.
2380#[derive(Debug, Clone, Default, Serialize, Deserialize)]
2381#[serde(deny_unknown_fields)]
2382pub struct ListenerStarttlsConfig {
2383    /// The command the host watches for in the client→server direction, matched at a line boundary,
2384    /// ASCII-case-insensitively. With `tag_capture` this is the token AFTER the leading tag.
2385    pub trigger: String,
2386    /// The single line the host writes to the client right before the handshake. `{tag}` is
2387    /// substituted with the captured tag (only valid when `tag_capture`); the host appends CRLF.
2388    pub response: String,
2389    /// IMAP-shaped: capture the leading whitespace-delimited token of the trigger line and echo it
2390    /// (verbatim) into `{tag}`.
2391    #[serde(default)]
2392    pub tag_capture: bool,
2393}
2394
2395/// Default per-listener live-connection cap when `[serve.listeners.<name>] max_conns` is unset
2396/// (PLAN-handler-tcp-inbound). 256 — a generous but bounded ceiling on top of the engine conn lane.
2397pub const DEFAULT_LISTENER_MAX_CONNS: usize = 256;
2398
2399/// Default per-listener idle timeout (ms) when `idle_timeout_ms` is unset — 60s. A connection with no
2400/// bytes in either direction for this long is torn down (so a connection that opens and sends nothing
2401/// can't hold a store + instance + conn-lane permit forever).
2402pub const DEFAULT_LISTENER_IDLE_TIMEOUT_MS: u64 = 60_000;
2403
2404/// Default per-listener absolute max-connection-duration (ms) when `max_conn_duration_ms` is unset —
2405/// 1h. Bounds a single connection's lifetime regardless of activity (CPU is wall-clock-bounded here,
2406/// since the conn lane disables the per-invocation CPU-fuel budget).
2407pub const DEFAULT_LISTENER_MAX_CONN_DURATION_MS: u64 = 3_600_000;
2408
2409/// `[serve.s3_credential]` — a **node-level base S3 credential source** (#505) sourcing the base AWS
2410/// credential from boatramp's `[secrets]` sealed store rather than the ambient env chain. Consumed by
2411/// BOTH the S3 blob object backend and the AWS blob-upload cloud minter (one shared source, since it is
2412/// the same bucket key). Additive/non-breaking: absent ⇒ the ambient AWS env chain (unchanged).
2413///
2414/// The `access_key_id` is a public identifier (plain config). The `secret_access_key` is a **secret
2415/// reference** in the same scheme the guest `secrets` map uses: `boatramp:<name>` (the project-scoped
2416/// sealed store, resolved under the reserved default project — multi-tenant-safe, never the host env),
2417/// `env:<VAR>` / a bare `<VAR>` (the operator's own environment — honored only when the posture's
2418/// `allow_env_secret_refs` is set), unsealed at serve startup via the `[secrets]` [`KeyEnvelope`]. The
2419/// resolved plaintext is held **in memory only** (never env/argv/git/logs); see the redacted
2420/// `SealedS3Credential` the resolver produces.
2421#[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize)]
2422#[serde(deny_unknown_fields)]
2423pub struct S3CredentialConfig {
2424    /// The AWS **access key id** — a public identifier, not a secret, so it is plain config (mirrors
2425    /// how an `access_key_id` is a public value in the S3-ingress credential model). Empty is refused
2426    /// at resolution.
2427    pub access_key_id: String,
2428    /// The **secret access key**, expressed as a secret **reference** (never the raw secret in the
2429    /// config text): `boatramp:<name>` (the project-scoped sealed store), `env:<VAR>` or a bare `<VAR>`
2430    /// (the operator env, posture-gated by `allow_env_secret_refs`). Unsealed at startup via the
2431    /// `[secrets]` envelope; the resolved value is redacted from `Debug`/logs. A `boatramp:`/`env:`
2432    /// ref configured with NO `[secrets]` envelope is a fail-closed startup error.
2433    pub secret_access_key: String,
2434}
2435
2436/// `[serve.blob_backends.<project>]` — a **per-project** blob object-store backend
2437/// (PLAN-per-project-blob-backend). Same backend-descriptor shape as the `[serve]` primary's S3 fields
2438/// plus its OWN sealed base S3 credential (`#505` path), so project ACME can point its `wasi:blobstore`
2439/// at its own bucket/endpoint/account. Key-prefix confinement (`container_access`) still runs on top —
2440/// a separate bucket adds PHYSICAL isolation, it does not replace the confinement (invariant 2).
2441///
2442/// Operator-configured; the backend is bound to the serve's **host-resolved** project at serve wiring,
2443/// never to guest input (invariant 1). The sealed credential is resolved under THIS project's sealed
2444/// `[secrets]` store at wiring; a declared backend whose credential/bucket cannot be built REFUSES the
2445/// serve (fail-closed — never a silent fallback to the global or another project's backend, invariant
2446/// 4). First cut is S3 (and `fs`, which is degenerate — it shares the node blob dir, so only a cloud
2447/// bucket gives physical isolation); a per-project `gcs`/`azure` needs its own descriptor fields and is
2448/// a follow-up (declaring one fails closed at build — the required bucket/account is absent).
2449#[derive(Debug, Clone, Default, Serialize, Deserialize)]
2450#[serde(deny_unknown_fields)]
2451pub struct BlobBackendConfig {
2452    /// The backend kind (`fs`/`s3`/`gcs`/`azure`). **Required** (mirrors the SQL binding's required
2453    /// `kind`): a per-project backend with no explicit kind is a startup error, so a forgotten
2454    /// `blobs = "s3"` can't silently build an `fs` backend at the shared node dir that would NOT
2455    /// isolate the project's blobs. Resolved at serve wiring (fail-closed when absent).
2456    pub blobs: Option<crate::backends::BlobBackend>,
2457    /// S3 bucket (`blobs = s3`) — the project's OWN bucket.
2458    pub s3_bucket: Option<String>,
2459    /// S3 endpoint URL (a MinIO/R2/Tigris endpoint) for this project's backend.
2460    pub s3_endpoint: Option<String>,
2461    /// S3 region for this project's backend.
2462    pub s3_region: Option<String>,
2463    /// Use S3 path-style addressing (MinIO) for this project's backend.
2464    #[serde(default)]
2465    pub s3_path_style: bool,
2466    /// This project's OWN sealed base S3 credential (`#505`) — resolved through the SAME
2467    /// `resolve_s3_credential` path as the node primary, but keyed under THIS project's sealed store
2468    /// (`boatramp:<name>` resolves against `project`'s secrets, not the node default). The
2469    /// `access_key_id` is a public identifier; `secret_access_key` is a `boatramp:`/`env:` **reference**
2470    /// (never the raw secret in config, invariant 3). Absent ⇒ the ambient AWS env chain.
2471    pub s3_credential: Option<S3CredentialConfig>,
2472}
2473
2474/// `[serve.blob_fallback]` — a **read-only SECONDARY blob backend** for a zero-downtime backend switch
2475/// (blob-backend migration Part 2). Same backend-descriptor shape as the PRIMARY (`[serve]`'s
2476/// `blobs`/`s3_*`/`gcs_*`/`azure_*` fields) so a source/dest is fully described by config, plus its OWN
2477/// optional `s3_credential` (the secondary can source its base S3 credential from the sealed `[secrets]`
2478/// store via its own `boatramp:`/`env:` ref, #505). Constructed exactly like the primary but with NO
2479/// watcher provisioning (a read-only drain source never watches). Serving wraps
2480/// `FallbackStorage::new(primary, secondary, …)` so a primary miss on a boatramp-owned key falls through
2481/// to this secondary; writes/deletes are primary-only.
2482///
2483/// The secondary is **never** handed to the blob-upload/STS minter — external ingress mints against the
2484/// PRIMARY only (the new backend the client should upload to), so this credential never reaches the
2485/// minter path.
2486#[derive(Debug, Clone, Default, Serialize, Deserialize)]
2487#[serde(deny_unknown_fields)]
2488pub struct BlobFallbackConfig {
2489    /// The secondary blob backend (`fs`/`s3`/`gcs`/`azure`) — the OLD backend to fall back to on a
2490    /// primary miss. Absent ⇒ `fs` (the default, matching the primary's `blobs` default).
2491    pub blobs: Option<crate::backends::BlobBackend>,
2492    /// S3 bucket (secondary `blobs = s3`).
2493    pub s3_bucket: Option<String>,
2494    /// S3 endpoint URL (a MinIO/R2/Tigris endpoint) for the secondary.
2495    pub s3_endpoint: Option<String>,
2496    /// S3 region for the secondary.
2497    pub s3_region: Option<String>,
2498    /// Use S3 path-style addressing (MinIO) for the secondary.
2499    #[serde(default)]
2500    pub s3_path_style: bool,
2501    /// The secondary's OWN node-level sealed base S3 credential source (#505) — resolved through the
2502    /// SAME `resolve_s3_credential` path as the primary (same fail-closed posture, no second parser).
2503    /// Absent ⇒ the ambient AWS env chain (unchanged).
2504    pub s3_credential: Option<S3CredentialConfig>,
2505    /// GCS bucket (secondary `blobs = gcs`).
2506    pub gcs_bucket: Option<String>,
2507    /// GCS storage endpoint URL (a `fake-gcs-server` emulator) for the secondary.
2508    pub gcs_endpoint: Option<String>,
2509    /// Skip GCS credential resolution (anonymous — the emulator) for the secondary.
2510    #[serde(default)]
2511    pub gcs_anonymous: bool,
2512    /// Azure storage account name (secondary `blobs = azure`).
2513    pub azure_account: Option<String>,
2514    /// Azure container name for the secondary.
2515    pub azure_container: Option<String>,
2516    /// Azure storage account access key (shared-key auth) for the secondary.
2517    pub azure_access_key: Option<String>,
2518    /// Use the Azurite emulator for the secondary.
2519    #[serde(default)]
2520    pub azure_emulator: bool,
2521    /// Bound (seconds) on each secondary read so a wedged secondary degrades a primary miss to
2522    /// `NotFound` instead of hanging the serve path. Absent ⇒ [`DEFAULT_BLOB_FALLBACK_TIMEOUT_SECS`].
2523    pub secondary_timeout_secs: Option<u64>,
2524}
2525
2526/// Default bound (seconds) on a `[serve.blob_fallback]` secondary read when
2527/// `secondary_timeout_secs` is unset: 5s — long enough for a cloud round-trip, short enough that a
2528/// wedged secondary degrades a primary miss to `NotFound` promptly rather than hanging serving.
2529pub const DEFAULT_BLOB_FALLBACK_TIMEOUT_SECS: u64 = 5;
2530
2531/// Default control-plane KV **periodic checkpoint** cadence (seconds) when `[serve.kv]
2532/// checkpoint_interval` is unset (v0.9.0 KV-recovery, C1). The cadence advances the durable frontier
2533/// (WAL→L0 MemTable freeze) so the self-heal-on-open trailing-tail loss window is bounded to at most
2534/// this interval for anything NOT already frontier-synced by a crown-jewel write. 10s balances a tiny
2535/// loss window against manifest-PUT churn; an idle store's checkpoint is a dirty-gated no-op regardless.
2536pub const DEFAULT_KV_CHECKPOINT_INTERVAL_SECS: u64 = 10;
2537
2538/// Default **graceful-close budget** (seconds) when `[serve.kv] close_deadline` is unset (v0.9.0
2539/// KV-recovery, C12). The shutdown drain+close is abandoned only after this budget — GENEROUS (not the
2540/// old hardcoded 3s, which self-exited BEFORE fly's SIGKILL grace and left the frontier un-advanced =
2541/// the exact torn tail we prevent). With continuous checkpointing (C1/C2) the close is cheap, so this
2542/// budget rarely bites; operators should still raise fly `kill_timeout` to ≥ their measured drain+close.
2543pub const DEFAULT_KV_CLOSE_DEADLINE_SECS: u64 = 20;
2544
2545/// Default control-plane SlateDB **online maintenance-GC** cadence (seconds) when `[serve.kv.slatedb]
2546/// gc_interval` is unset (kv-data-observability durable fix). The supervised writer task reclaims the
2547/// stale manifest/compactions/WAL/compacted objects the embedded GC would — SURVIVING the transient
2548/// tick error that kills the unsupervised embedded GC permanently (the 16.5 GB manifest-retention
2549/// leak). 900s (15 min) matches the cadence of the embedded GC's own protective-checkpoint window, so
2550/// freshly-superseded SSTs age out of their checkpoint before the next reclaim; a 0 DISABLES the task.
2551pub const DEFAULT_KV_GC_INTERVAL_SECS: u64 = 900;
2552
2553/// Default **minimum object age** (seconds) before the online maintenance GC will reclaim an object,
2554/// when `[serve.kv.slatedb] gc_min_age` is unset. 3600s (1h) is deliberately CONSERVATIVE: the online
2555/// GC only deletes objects the latest manifest no longer references, but a read replica polling the
2556/// shared store could still be mid-scan over a manifest generation that just became stale — a min_age
2557/// this large guarantees such a needed-but-unreferenced object is never a deletion candidate while any
2558/// plausible replica scan is in flight. A 0 (or unset) falls back to this default — it is never zero
2559/// (a zero min_age would reintroduce exactly the mid-scan deletion hazard this bound closes).
2560pub const DEFAULT_KV_GC_MIN_AGE_SECS: u64 = 3600;
2561
2562/// `[serve.kv]` — control-plane KV configuration. The backend itself is selected by `--kv` /
2563/// `BOATRAMP_KV` (`slatedb` default, `sql`, `memory`, `cloudflare`); this block holds the
2564/// backend-specific settings, nested so a knob can never silently mislead under the wrong backend
2565/// (UX-C3): the SlateDB durability knobs live under [`slatedb`](Self::slatedb), and the SQL
2566/// connection under [`sql`](Self::sql). Absent block ⇒ the SlateDB defaults apply.
2567#[derive(Debug, Clone, Default, Serialize, Deserialize)]
2568#[serde(default, deny_unknown_fields)]
2569pub struct KvConfig {
2570    /// `[serve.kv.slatedb]` — SlateDB-specific durability knobs (checkpoint cadence + close budget).
2571    /// Nested under `slatedb` (UX-C3) so they don't appear to apply under `--kv sql` / `--kv memory`.
2572    /// Absent ⇒ both defaults (checkpoint cadence ON, generous close budget).
2573    pub slatedb: Option<SlatedbKvConfig>,
2574    /// `[serve.kv.sql]` — the SQL KV backend's connection (`--kv sql`). Absent under `--kv sql` ⇒ the
2575    /// backend is configured entirely by the `BOATRAMP_KV_SQL_*` env (resolved at serve wiring).
2576    pub sql: Option<SqlKvConfig>,
2577}
2578
2579impl KvConfig {
2580    /// The resolved periodic-checkpoint interval (SlateDB): `None` ⇒ cadence DISABLED (explicit `0`);
2581    /// else the configured seconds, or [`DEFAULT_KV_CHECKPOINT_INTERVAL_SECS`] when unset/absent.
2582    pub fn checkpoint_interval(&self) -> Option<std::time::Duration> {
2583        match self.slatedb.as_ref().and_then(|s| s.checkpoint_interval) {
2584            Some(0) => None,
2585            Some(secs) => Some(std::time::Duration::from_secs(secs)),
2586            None => Some(std::time::Duration::from_secs(
2587                DEFAULT_KV_CHECKPOINT_INTERVAL_SECS,
2588            )),
2589        }
2590    }
2591
2592    /// The resolved graceful-close budget (SlateDB). A configured `0` (or unset/absent) falls back to
2593    /// [`DEFAULT_KV_CLOSE_DEADLINE_SECS`] — the budget must be positive so a genuinely-wedged close
2594    /// still cannot hang shutdown forever, while never being the too-tight 3s that caused the incident.
2595    pub fn close_deadline(&self) -> std::time::Duration {
2596        match self.slatedb.as_ref().and_then(|s| s.close_deadline) {
2597            Some(secs) if secs > 0 => std::time::Duration::from_secs(secs),
2598            _ => std::time::Duration::from_secs(DEFAULT_KV_CLOSE_DEADLINE_SECS),
2599        }
2600    }
2601
2602    /// The resolved online maintenance-GC cadence (SlateDB): `None` ⇒ the task is DISABLED (explicit
2603    /// `0`); else the configured seconds, or [`DEFAULT_KV_GC_INTERVAL_SECS`] when unset/absent.
2604    pub fn gc_interval(&self) -> Option<std::time::Duration> {
2605        match self.slatedb.as_ref().and_then(|s| s.gc_interval) {
2606            Some(0) => None,
2607            Some(secs) => Some(std::time::Duration::from_secs(secs)),
2608            None => Some(std::time::Duration::from_secs(DEFAULT_KV_GC_INTERVAL_SECS)),
2609        }
2610    }
2611
2612    /// The resolved online maintenance-GC minimum object age (SlateDB). A configured `0` (or
2613    /// unset/absent) falls back to [`DEFAULT_KV_GC_MIN_AGE_SECS`] — never zero, so a reader replica
2614    /// mid-scan over a just-superseded manifest generation is always protected.
2615    pub fn gc_min_age(&self) -> std::time::Duration {
2616        match self.slatedb.as_ref().and_then(|s| s.gc_min_age) {
2617            Some(secs) if secs > 0 => std::time::Duration::from_secs(secs),
2618            _ => std::time::Duration::from_secs(DEFAULT_KV_GC_MIN_AGE_SECS),
2619        }
2620    }
2621}
2622
2623/// `[serve.kv.slatedb]` — control-plane SlateDB KV durability knobs (v0.9.0 KV-recovery). Both are
2624/// backstops/tuning: the crown-jewel per-write frontier-sync (C2) is unconditional and independent of
2625/// these. Absent ⇒ both defaults apply (checkpoint cadence ON, generous close budget). (v0.12.0 UX-C3:
2626/// MOVED here from the `[serve.kv]` top level so they do not appear to apply under a non-SlateDB
2627/// backend; with `deny_unknown_fields` a pre-v0.12.0 top-level knob now fails loud rather than
2628/// silently misleading.)
2629#[derive(Debug, Clone, Default, Serialize, Deserialize)]
2630#[serde(default, deny_unknown_fields)]
2631pub struct SlatedbKvConfig {
2632    /// Periodic checkpoint cadence, seconds. Unset ⇒ [`DEFAULT_KV_CHECKPOINT_INTERVAL_SECS`] (ON).
2633    /// `0` DISABLES the cadence (the crown-jewel per-write frontier-sync still runs; only the
2634    /// backstop that bounds the loss window for derived/relaxed writes is off).
2635    pub checkpoint_interval: Option<u64>,
2636    /// Graceful drain+close budget, seconds. Unset ⇒ [`DEFAULT_KV_CLOSE_DEADLINE_SECS`]. `0` is
2637    /// rejected up to the default (a zero budget would abandon every close, guaranteeing a torn tail).
2638    pub close_deadline: Option<u64>,
2639    /// **Online maintenance-GC cadence**, seconds (kv-data-observability durable fix). Unset ⇒
2640    /// [`DEFAULT_KV_GC_INTERVAL_SECS`] (ON). `0` DISABLES the supervised GC task entirely (leaving only
2641    /// SlateDB's embedded GC — which dies permanently on its first transient tick error, the leak this
2642    /// task works around; disable only if you run an external offline `boatramp kv compact` cadence).
2643    pub gc_interval: Option<u64>,
2644    /// **Online maintenance-GC minimum object age**, seconds. Unset (or `0`) ⇒
2645    /// [`DEFAULT_KV_GC_MIN_AGE_SECS`] (1h) — never zero, so a reader replica mid-scan over a
2646    /// just-superseded manifest generation can never have a needed object reclaimed out from under it.
2647    /// A tuned positive value is honored (e.g. a single-node deploy with no read replicas may lower it).
2648    /// CAVEAT: lowering it is UNSAFE whenever ANY read replica polls this shared store — a value below
2649    /// the time a replica may spend mid-scan reintroduces the "object reclaimed out from under a
2650    /// reader" hazard. Only lower it on a node you are certain has no read replicas.
2651    pub gc_min_age: Option<u64>,
2652}
2653
2654/// `[serve.kv.sql]` — the **SQL control-plane KV** backend connection (`--kv sql`). The connection
2655/// URL is NEVER written in the config (UX-C2): a bring-your-own / remote engine names the env var
2656/// holding it via [`url_env`](Self::url_env) (mirroring `ExternalDatabaseConfig`), while an embedded
2657/// single-node SQLite database names an on-disk file via [`path`](Self::path). Every field is also
2658/// settable by `BOATRAMP_KV_SQL_*` env (resolved at serve wiring). **This workstream (build-order
2659/// step 1) wires `sqlite` (libsql-local) only**; `postgres`/`mysql` are later workstreams.
2660#[derive(Debug, Clone, Default, Serialize, Deserialize)]
2661#[serde(default, deny_unknown_fields)]
2662pub struct SqlKvConfig {
2663    /// Engine: `sqlite` (aliases `sqlite3`/`libsql`) — the embedded single-node file; `postgres`
2664    /// (aliases `postgresql`/`pg`) or `mysql` (alias `mariadb`) — the multi-writer engines (later
2665    /// workstreams), the same alias set as the `databases:` block. Empty ⇒ `sqlite`.
2666    pub kind: String,
2667    /// Name of the env var holding the connection URL (e.g. `postgres://…`, or a remote sqld URL) —
2668    /// NEVER a raw URL in the config. Unused for an embedded single-node `sqlite` database (which
2669    /// uses [`path`](Self::path)).
2670    pub url_env: Option<String>,
2671    /// On-disk file path for an embedded single-node `sqlite` KV (e.g. `/data/kv.db`). The parent
2672    /// directory is created if absent. Ignored for `postgres`/`mysql` and for a remote-sqld URL.
2673    pub path: Option<String>,
2674    /// Maximum pooled connections for a `postgres`/`mysql` KV (later workstreams). Ignored for the
2675    /// embedded `sqlite` path (one `Database` handle, connections opened per op).
2676    pub pool_max: Option<u32>,
2677}
2678
2679/// `[serve.s3_ingress_cloud]` — the cloud-brokering knobs for the M4 blob-upload minter (which native
2680/// credential the mint brokers when the node's blob backend is a cloud object store). Only the fields
2681/// for the active blob backend are consulted; a `None` here ⇒ the local S3 face mints.
2682#[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize)]
2683pub struct S3IngressCloud {
2684    /// **AWS**: the IAM role ARN the base credential assumes to broker the scoped session-policy
2685    /// credential (`sts:AssumeRole`, the default). Absent AND `aws_use_federation_token = true` ⇒
2686    /// `sts:GetFederationToken` is used instead (for an IAM-user base credential).
2687    pub aws_role_arn: Option<String>,
2688    /// **AWS**: use `sts:GetFederationToken` instead of `AssumeRole` (IAM-user deployments). Requires
2689    /// the base credential to be a real IAM user, not itself a session.
2690    #[serde(default)]
2691    pub aws_use_federation_token: bool,
2692    /// **AWS**: the S3-compatible backend has NO STS (Tigris/R2/MinIO): mint single-object presigned PUTs
2693    /// only. Prefix/multipart mints are refused (they require STS). Mutually exclusive with
2694    /// `aws_role_arn`/`aws_use_federation_token` (a misconfiguration that set both fails loud at wiring,
2695    /// never silently picks one). The presigned PUT is signed from the node's base S3 credential — the
2696    /// SAME source the S3 blob backend uses — so no new credential is needed. Default `false`.
2697    #[serde(default)]
2698    pub aws_presigned_only: bool,
2699    /// **GCS**: the service-account client email whose V4 signed URLs / IAM-signed uploads the minter
2700    /// produces (used in the signing scope). Absent ⇒ resolved from ADC.
2701    pub gcs_client_email: Option<String>,
2702    /// **Azure**: the storage account name (for the SAS signature + the blob URL). Absent ⇒ taken from
2703    /// the `azure_account` blob-backend arg.
2704    pub azure_account: Option<String>,
2705    /// **Azure**: the blob service URL (`https://{account}.blob.core.windows.net/`). Absent ⇒ derived
2706    /// from the account name.
2707    pub azure_service_url: Option<String>,
2708    /// **Azure**: declare the storage account has a **hierarchical namespace** (HNS/ADLS-Gen2). A
2709    /// directory-scoped SAS only actually confines to a sub-prefix on an HNS account; on a flat account
2710    /// it silently degrades to container-wide (Security LOW-1). So a PREFIX mint is refused unless this
2711    /// is `true`. Default `false` (fail-closed). A single-key mint is unaffected.
2712    #[serde(default)]
2713    pub azure_hns: bool,
2714}
2715
2716/// The default operator ceiling on a minted S3 upload credential's TTL when
2717/// `[serve].s3_ingress_mint_max_ttl_secs` is unset: 1 hour — long enough for a browser UGC upload or a
2718/// bulk-agent burst, short enough to bound a leaked short-lived credential.
2719pub const DEFAULT_S3_INGRESS_MINT_MAX_TTL_SECS: u64 = 3600;
2720
2721/// `[serve.console]` — the embedded web console (a Wasm SPA baked into the
2722/// binary with the `console` build feature). Opt-in: the static shell holds no
2723/// secrets and the `/api` it drives is token-gated, so it is served
2724/// **unauthenticated** at a deliberately obscure path (a bearer token can't gate
2725/// a top-level browser navigation anyway — the path is the obscurity, the token
2726/// is the real gate).
2727#[cfg_attr(not(feature = "console"), allow(dead_code))]
2728#[derive(Debug, Clone, Default, Serialize, Deserialize)]
2729#[serde(default, deny_unknown_fields)]
2730pub struct ConsoleConfig {
2731    /// Serve the embedded console (default `false`). Requires the `console` build
2732    /// feature; enabling it in a build without that feature is a logged no-op.
2733    pub enabled: bool,
2734    /// Host(s) the console answers on: `*` (any host, the default), an exact host
2735    /// (`console.example.com`), or a leading-wildcard (`*.example.com`).
2736    pub host: Option<String>,
2737    /// URL path prefix the console mounts at (default `/_console`). Kept under the
2738    /// reserved `/_` namespace so it never collides with a published site path.
2739    pub path: Option<String>,
2740}
2741
2742/// `publish` section — where and what to deploy (the `sync` target).
2743#[derive(Debug, Default, Deserialize)]
2744#[serde(default)]
2745pub struct PublishConfig {
2746    /// Base URL of the boatramp server (e.g. `https://pad.example.com`).
2747    pub server: Option<String>,
2748    /// Site name to publish to.
2749    pub site: Option<String>,
2750    /// API token for the control plane (or set `BOATRAMP_TOKEN`).
2751    pub token: Option<String>,
2752    /// Project this site belongs to (overrides with `--project` / `BOATRAMP_PROJECT`).
2753    pub project: Option<String>,
2754}
2755
2756/// `build` section.
2757#[derive(Debug, Clone, Deserialize, serde::Serialize)]
2758pub struct BuildConfig {
2759    /// Shell command to run (e.g. `npm run build`).
2760    pub command: String,
2761    /// Directory the build emits, published by `sync` (e.g. `dist`).
2762    #[serde(default, skip_serializing_if = "Option::is_none")]
2763    pub output: Option<String>,
2764}
2765
2766/// `bundle` section — the in-process Rust bundler (`bundler` feature).
2767#[derive(Debug, Clone, Default, Deserialize)]
2768#[serde(default)]
2769pub struct BundleConfig {
2770    /// Output directory for bundled assets (e.g. `dist`).
2771    #[serde(default = "default_bundle_outdir")]
2772    pub outdir: String,
2773    /// JS/TS entry points bundled by Rolldown (tree-shaken, code-split).
2774    pub js: Vec<String>,
2775    /// CSS entry points bundled by lightningcss (`@import` inlined).
2776    pub css: Vec<String>,
2777    /// Minify output (default true).
2778    #[serde(default = "default_true")]
2779    pub minify: bool,
2780}
2781
2782fn default_bundle_outdir() -> String {
2783    "dist".to_string()
2784}
2785
2786fn default_true() -> bool {
2787    true
2788}
2789
2790#[cfg(test)]
2791mod tests {
2792    use super::*;
2793
2794    fn project(text: &str) -> ProjectConfig {
2795        ron_options().from_str(text).unwrap()
2796    }
2797
2798    fn server(text: &str) -> ServerConfig {
2799        ron_options().from_str(text).unwrap()
2800    }
2801
2802    /// Build an [`EnvSource::Map`] from `(name, value)` pairs for deterministic
2803    /// override tests (no process-global `std::env` mutation).
2804    fn env(pairs: &[(&str, &str)]) -> EnvSource {
2805        EnvSource::Map(
2806            pairs
2807                .iter()
2808                .map(|(k, v)| (k.to_string(), v.to_string()))
2809                .collect(),
2810        )
2811    }
2812
2813    #[test]
2814    fn env_overrides_configure_all_three_sections_with_no_file() {
2815        // The crux of the ask: with NO `boatramp.cfg` at all (the default config),
2816        // env vars alone materialise + populate the compute, security, and handler
2817        // `sql` sections. `ServerConfig::default()` has all three absent.
2818        let mut cfg = ServerConfig::default();
2819        assert!(cfg.compute.is_none() && cfg.security.is_none() && cfg.handlers.is_none());
2820
2821        cfg.apply_env_overrides(&env(&[
2822            ("BOATRAMP_COMPUTE_VCPUS", "8"),
2823            ("BOATRAMP_COMPUTE_MEM_MIB", "4096"),
2824            ("BOATRAMP_COMPUTE_REGION", "eu-central"),
2825            ("BOATRAMP_SECURITY_PROFILE", "single-tenant"),
2826            ("BOATRAMP_SECURITY_ALLOW_SITE_PRIVATE_UPSTREAMS", "true"),
2827            ("BOATRAMP_SECURITY_MAX_UPLOAD_BYTES", "1048576"),
2828            ("BOATRAMP_HANDLERS_SQL_URL", "http://sqld:8080"),
2829            ("BOATRAMP_HANDLERS_SQL_ADMIN_URL", "http://sqld:9090"),
2830        ]))
2831        .expect("valid env overrides apply");
2832
2833        // compute: the section now exists with the env values (and defaults elsewhere).
2834        let compute = cfg.compute.expect("compute materialised from env");
2835        assert_eq!(compute.vcpus, 8);
2836        assert_eq!(compute.mem_mib, 4096);
2837        assert_eq!(compute.region.as_deref(), Some("eu-central"));
2838        assert_eq!(compute.bridge, "br-boatramp"); // untouched default
2839
2840        // security: profile + an override both took, and the posture resolves.
2841        let security = cfg.security.expect("security materialised from env");
2842        assert_eq!(security.profile.as_deref(), Some("single-tenant"));
2843        let posture = security.resolve().expect("resolves");
2844        assert!(posture.allow_site_private_upstreams);
2845        assert_eq!(posture.max_upload_bytes, 1_048_576);
2846
2847        // handler sql: the nested handlers.bindings.sql chain was created.
2848        let sql = cfg
2849            .handlers
2850            .expect("handlers materialised from env")
2851            .bindings
2852            .sql
2853            .expect("sql binding materialised from env");
2854        assert_eq!(sql.url.as_deref(), Some("http://sqld:8080"));
2855        assert_eq!(sql.admin_url.as_deref(), Some("http://sqld:9090"));
2856    }
2857
2858    #[test]
2859    fn internal_dns_defaults_on_with_the_standard_upstream_and_domain() {
2860        // The `[compute]` defaults: internal DNS on, forwarding to 1.1.1.1:53, names
2861        // under `boatramp.internal`.
2862        let compute = ComputeConfig::default();
2863        assert!(compute.internal_dns, "internal DNS is on by default");
2864        assert_eq!(compute.dns_upstream, "1.1.1.1:53");
2865        assert_eq!(compute.dns_domain, "boatramp.internal");
2866    }
2867
2868    #[test]
2869    fn internal_dns_knobs_parse_from_a_file() {
2870        // A file can turn it off and override the upstream + domain.
2871        let cfg = server(
2872            r#"(
2873                compute: ( internal_dns: false, dns_upstream: "10.0.0.53:53", dns_domain: "svc.internal" ),
2874            )"#,
2875        );
2876        let compute = cfg.compute.expect("compute section");
2877        assert!(!compute.internal_dns);
2878        assert_eq!(compute.dns_upstream, "10.0.0.53:53");
2879        assert_eq!(compute.dns_domain, "svc.internal");
2880    }
2881
2882    #[test]
2883    fn internal_dns_knobs_are_env_settable() {
2884        // Env alone materialises `[compute]` and sets each internal-DNS knob (and an
2885        // unrecognised bool spelling is a clear error, exercised by parse_bool).
2886        let mut cfg = ServerConfig::default();
2887        cfg.apply_env_overrides(&env(&[
2888            ("BOATRAMP_COMPUTE_INTERNAL_DNS", "off"),
2889            ("BOATRAMP_COMPUTE_DNS_UPSTREAM", "9.9.9.9:53"),
2890            ("BOATRAMP_COMPUTE_DNS_DOMAIN", "corp.internal"),
2891        ]))
2892        .expect("valid env overrides apply");
2893        let compute = cfg.compute.expect("compute materialised from env");
2894        assert!(!compute.internal_dns, "env `off` disables internal DNS");
2895        assert_eq!(compute.dns_upstream, "9.9.9.9:53");
2896        assert_eq!(compute.dns_domain, "corp.internal");
2897    }
2898
2899    #[test]
2900    fn env_override_wins_over_file_value_but_unset_defers() {
2901        // A file that set each section; env then overrides one field per section
2902        // and leaves the rest of the file value in place (precedence: env > file).
2903        let mut cfg = server(
2904            r#"(
2905                compute: ( vcpus: 2, mem_mib: 512, region: "us-east" ),
2906                security: ( profile: "multi-tenant" ),
2907                handlers: ( bindings: ( sql: ( url: "http://file:8080", admin_url: "http://file:9090" ) ) ),
2908            )"#,
2909        );
2910
2911        cfg.apply_env_overrides(&env(&[
2912            ("BOATRAMP_COMPUTE_VCPUS", "16"),
2913            ("BOATRAMP_SECURITY_PROFILE", "dev"),
2914            ("BOATRAMP_HANDLERS_SQL_URL", "http://env:8080"),
2915        ]))
2916        .expect("valid env overrides apply");
2917
2918        let compute = cfg.compute.unwrap();
2919        assert_eq!(compute.vcpus, 16, "env wins over the file vcpus");
2920        assert_eq!(compute.mem_mib, 512, "unset env defers to the file mem_mib");
2921        assert_eq!(
2922            compute.region.as_deref(),
2923            Some("us-east"),
2924            "unset env defers to the file region"
2925        );
2926
2927        assert_eq!(
2928            cfg.security.unwrap().profile.as_deref(),
2929            Some("dev"),
2930            "env profile wins over the file profile"
2931        );
2932
2933        let sql = cfg.handlers.unwrap().bindings.sql.unwrap();
2934        assert_eq!(
2935            sql.url.as_deref(),
2936            Some("http://env:8080"),
2937            "env wins over the file sql url"
2938        );
2939        assert_eq!(
2940            sql.admin_url.as_deref(),
2941            Some("http://file:9090"),
2942            "unset env defers to the file sql admin_url"
2943        );
2944    }
2945
2946    #[test]
2947    fn env_overrides_leave_unmentioned_sections_absent() {
2948        // With no relevant env vars set, an empty config stays empty — the sections
2949        // are materialised only on demand, so an unset environment adds nothing.
2950        let mut cfg = ServerConfig::default();
2951        cfg.apply_env_overrides(&env(&[("SOME_UNRELATED_VAR", "x")]))
2952            .expect("no-op env applies");
2953        assert!(cfg.compute.is_none());
2954        assert!(cfg.security.is_none());
2955        assert!(cfg.handlers.is_none());
2956        assert!(cfg.secrets.is_none());
2957        assert!(cfg.cluster.is_none());
2958    }
2959
2960    #[test]
2961    fn env_bool_accepts_common_spellings_and_rejects_garbage() {
2962        // Truthy/falsey spellings all parse.
2963        for (raw, want) in [
2964            ("true", true),
2965            ("1", true),
2966            ("YES", true),
2967            ("On", true),
2968            ("false", false),
2969            ("0", false),
2970            ("no", false),
2971            ("OFF", false),
2972        ] {
2973            let mut cfg = ServerConfig::default();
2974            cfg.apply_env_overrides(&env(&[("BOATRAMP_SECURITY_REQUIRE_POP", raw)]))
2975                .expect("boolean parses");
2976            assert_eq!(
2977                cfg.security.unwrap().overrides.require_pop,
2978                Some(want),
2979                "{raw:?} ⇒ {want}"
2980            );
2981        }
2982        // A non-boolean value is a clear error, not a silent default. (The pipeline rejects it
2983        // LOUDLY at extract as a `Resolve` error — figment's message names the field path, not
2984        // the env var, but a malformed value is never silently defaulted.)
2985        let mut cfg = ServerConfig::default();
2986        let err = cfg
2987            .apply_env_overrides(&env(&[("BOATRAMP_SECURITY_REQUIRE_POP", "maybe")]))
2988            .expect_err("garbage boolean is rejected");
2989        assert!(
2990            matches!(err, ConfigError::Resolve(_)),
2991            "garbage bool must fail loudly, got {err:?}"
2992        );
2993    }
2994
2995    #[test]
2996    fn env_number_parse_error_is_loud() {
2997        // A non-numeric numeric var is rejected LOUDLY (never silently defaulted).
2998        let mut cfg = ServerConfig::default();
2999        let err = cfg
3000            .apply_env_overrides(&env(&[("BOATRAMP_COMPUTE_VCPUS", "lots")]))
3001            .expect_err("garbage number is rejected");
3002        assert!(
3003            matches!(err, ConfigError::Resolve(_)),
3004            "garbage number must fail loudly, got {err:?}"
3005        );
3006    }
3007
3008    #[test]
3009    fn empty_env_value_is_treated_as_unset() {
3010        // `VAR=` (empty) must not clobber a file value with an empty string.
3011        let mut cfg = server(r#"( compute: ( region: "us-east" ) )"#);
3012        cfg.apply_env_overrides(&env(&[("BOATRAMP_COMPUTE_REGION", "")]))
3013            .expect("empty env applies as a no-op");
3014        assert_eq!(
3015            cfg.compute.unwrap().region.as_deref(),
3016            Some("us-east"),
3017            "an empty env value leaves the file value in place"
3018        );
3019    }
3020
3021    #[test]
3022    fn env_configures_managed_postgres_secrets_and_privilege_with_no_file() {
3023        // The construens acceptance case: with NO `boatramp.cfg` at all, the
3024        // environment alone stands up a managed co-located Postgres. It configures
3025        // the default (`"default"`-named, v0.5.0) database in
3026        // `handlers.bindings.sql.databases` (kind=postgres, compute=pg, database+user
3027        // set), the `[secrets]` envelope (local + a kek path so the managed credential
3028        // can be sealed), and `compute.managed_db_privilege = rootless`. All three
3029        // sections start absent.
3030        let mut cfg = ServerConfig::default();
3031        assert!(cfg.handlers.is_none() && cfg.secrets.is_none() && cfg.compute.is_none());
3032
3033        cfg.apply_env_overrides(&env(&[
3034            // The default database is addressed by the reserved `DEFAULT` token,
3035            // which maps to the reserved real name `"default"` (v0.5.0).
3036            ("BOATRAMP_HANDLERS_SQL_DB_DEFAULT_KIND", "postgres"),
3037            ("BOATRAMP_HANDLERS_SQL_DB_DEFAULT_COMPUTE", "pg"),
3038            ("BOATRAMP_HANDLERS_SQL_DB_DEFAULT_DATABASE", "appdb"),
3039            ("BOATRAMP_HANDLERS_SQL_DB_DEFAULT_USER", "app"),
3040            // Secrets: the local envelope + a KEK path (never key material).
3041            ("BOATRAMP_SECRETS_ENVELOPE", "local"),
3042            ("BOATRAMP_SECRETS_KEK_FILE", "/var/lib/boatramp/secrets/kek"),
3043            // The shared-kernel DB privilege strategy.
3044            ("BOATRAMP_COMPUTE_MANAGED_DB_PRIVILEGE", "rootless"),
3045        ]))
3046        .expect("valid env overrides apply");
3047
3048        // The default (`"default"`-keyed) managed database exists with the right source.
3049        let sql = cfg
3050            .handlers
3051            .expect("handlers materialised from env")
3052            .bindings
3053            .sql
3054            .expect("sql binding materialised from env");
3055        let db = sql
3056            .databases
3057            .get(boatramp_core::project::DEFAULT_DB_NAME)
3058            .expect("the default `default`-named database was created from DEFAULT");
3059        assert!(
3060            !sql.databases.contains_key(""),
3061            "the empty-string key is never produced (v0.5.0)"
3062        );
3063        assert_eq!(db.kind, "postgres");
3064        assert_eq!(db.compute.as_deref(), Some("pg"));
3065        assert_eq!(db.database.as_deref(), Some("appdb"));
3066        assert_eq!(db.user.as_deref(), Some("app"));
3067        // No `password_env` ⇒ boatramp manages the credential (Phase 2), and the
3068        // compute-backed source validates.
3069        assert!(db.password_env.is_none());
3070        assert!(db.is_managed_credential());
3071        assert!(db.validate("").is_ok());
3072
3073        // The secrets envelope + KEK path took (the path is a location, not a key).
3074        let secrets = cfg.secrets.expect("secrets materialised from env");
3075        assert_eq!(secrets.envelope, "local");
3076        assert_eq!(
3077            secrets.kek_file.as_deref(),
3078            Some(Path::new("/var/lib/boatramp/secrets/kek"))
3079        );
3080        assert!(
3081            secrets.vault.is_none(),
3082            "no vault vars ⇒ no vault sub-config"
3083        );
3084
3085        // The managed-DB privilege strategy resolved from its lowercase variant.
3086        let compute = cfg.compute.expect("compute materialised from env");
3087        assert_eq!(compute.managed_db_privilege, ManagedDbPrivilege::Rootless);
3088    }
3089
3090    #[test]
3091    fn env_declares_named_databases_and_merges_over_the_file() {
3092        // A file declares one database; the env overrides one of its fields and
3093        // ADDS a second, discovering both member names from the environment.
3094        let mut cfg = server(
3095            r#"(
3096                handlers: ( bindings: ( sql: (
3097                    databases: {
3098                        "analytics": ( kind: "postgres", url_env: "FILE_PG_URL", pool_max: 4 ),
3099                    },
3100                ) ) ),
3101            )"#,
3102        );
3103        cfg.apply_env_overrides(&env(&[
3104            // Override the file database's pool size (merge by key, per field).
3105            ("BOATRAMP_HANDLERS_SQL_DB_analytics_POOL_MAX", "32"),
3106            // Add a brand-new database whose name has an underscore, exercising the
3107            // longest-suffix name isolation (`_READ_URL_ENV`, not `_URL_ENV`).
3108            ("BOATRAMP_HANDLERS_SQL_DB_events_log_KIND", "mysql"),
3109            ("BOATRAMP_HANDLERS_SQL_DB_events_log_URL_ENV", "EVENTS_URL"),
3110            (
3111                "BOATRAMP_HANDLERS_SQL_DB_events_log_READ_URL_ENV",
3112                "EVENTS_RO_URL",
3113            ),
3114            ("BOATRAMP_HANDLERS_SQL_DB_events_log_READ_ONLY", "true"),
3115        ]))
3116        .expect("valid env overrides apply");
3117
3118        let sql = cfg.handlers.unwrap().bindings.sql.unwrap();
3119        assert_eq!(sql.databases.len(), 2);
3120
3121        let analytics = &sql.databases["analytics"];
3122        assert_eq!(
3123            analytics.pool_max,
3124            Some(32),
3125            "env pool_max wins over the file"
3126        );
3127        assert_eq!(
3128            analytics.url_env, "FILE_PG_URL",
3129            "the file's url_env survives (env didn't touch it)"
3130        );
3131
3132        let events = &sql.databases["events_log"];
3133        assert_eq!(events.kind, "mysql");
3134        assert_eq!(events.url_env, "EVENTS_URL");
3135        assert_eq!(events.read_url_env.as_deref(), Some("EVENTS_RO_URL"));
3136        assert!(events.read_only);
3137    }
3138
3139    #[test]
3140    fn default_token_maps_to_the_reserved_default_name_not_empty() {
3141        // v0.5.0 breaking change: the reserved `DEFAULT` env token maps to the real
3142        // name `"default"` (a valid URL path segment), never the empty string. This is
3143        // what makes the default binding addressable as `--db default` and keeps every
3144        // db-name ingress path-segment-safe.
3145        let mut cfg = ServerConfig::default();
3146        cfg.apply_env_overrides(&env(&[
3147            ("BOATRAMP_HANDLERS_SQL_DB_DEFAULT_KIND", "postgres"),
3148            ("BOATRAMP_HANDLERS_SQL_DB_DEFAULT_URL_ENV", "PG_URL"),
3149        ]))
3150        .expect("valid env overrides apply");
3151        let databases = cfg.handlers.unwrap().bindings.sql.unwrap().databases;
3152        assert!(
3153            databases.contains_key(boatramp_core::project::DEFAULT_DB_NAME),
3154            "DEFAULT → the reserved `default` key"
3155        );
3156        assert!(
3157            !databases.contains_key(""),
3158            "the empty-string key is never produced"
3159        );
3160    }
3161
3162    #[test]
3163    fn empty_string_db_binding_name_is_rejected_with_a_cure() {
3164        // A `boatramp.cfg` that literally writes the legacy empty-string default key
3165        // fails closed on load (it would emit a `//` control-plane path), and the
3166        // error points at the cure (`default`).
3167        let err = ServerConfig::parse(
3168            r#"(
3169                handlers: ( bindings: ( sql: (
3170                    databases: {
3171                        "": ( kind: "postgres", url_env: "PG_URL" ),
3172                    },
3173                ) ) ),
3174            )"#,
3175        )
3176        .expect_err("an empty-string db binding name is refused");
3177        match err {
3178            ConfigError::InvalidDbName { name, reason, cure } => {
3179                assert_eq!(name, "");
3180                assert!(reason.contains("empty"), "reason names the emptiness");
3181                assert!(
3182                    cure.contains("default") && cure.contains("CHANGELOG"),
3183                    "the cure points at `default` + the CHANGELOG"
3184                );
3185            }
3186            other => panic!("expected ConfigError::InvalidDbName, got {other:?}"),
3187        }
3188    }
3189
3190    #[test]
3191    fn path_separator_db_binding_name_is_rejected() {
3192        // A non-slug name (contains `/`) is refused with the v0.7.0 slug reason and the
3193        // slug cure (pointing at `project doctor`) — NOT the empty-default cure (the fix
3194        // is to rename it to a valid slug, not adopt `default`). Boot-LOUD.
3195        let err = ServerConfig::parse(
3196            r#"(
3197                handlers: ( bindings: ( sql: (
3198                    databases: {
3199                        "a/b": ( kind: "postgres", url_env: "PG_URL" ),
3200                    },
3201                ) ) ),
3202            )"#,
3203        )
3204        .expect_err("a `/`-bearing db binding name is refused");
3205        match err {
3206            ConfigError::InvalidDbName { name, reason, cure } => {
3207                assert_eq!(name, "a/b");
3208                // The v0.7.0 slug reason (a positive statement of the allowlist).
3209                assert!(
3210                    reason.contains("valid slug"),
3211                    "reason states the slug rule, got {reason:?}"
3212                );
3213                // The slug cure points at `project doctor`, not the empty-default cure.
3214                assert_eq!(cure, boatramp_core::project::INVALID_NAME_CURE);
3215                assert!(!cure.contains("CHANGELOG"), "not the empty-default cure");
3216            }
3217            other => panic!("expected ConfigError::InvalidDbName, got {other:?}"),
3218        }
3219    }
3220
3221    #[test]
3222    fn reserved_bramp_db_compute_prefix_is_rejected() {
3223        // #501 Stage B LOW-2: a static BYO binding may not point `compute` at a
3224        // `bramp-db-…` workload (reserved for derived managed-DB servers) — refused
3225        // fail-closed at config load.
3226        let err = ServerConfig::parse(
3227            r#"(
3228                handlers: ( bindings: ( sql: (
3229                    databases: {
3230                        "byo": ( kind: "postgres", compute: "bramp-db-acme-app", database: "d", user: "u" ),
3231                    },
3232                ) ) ),
3233            )"#,
3234        )
3235        .expect_err("a `bramp-db-` compute workload is refused");
3236        match err {
3237            ConfigError::InvalidDbName { name, reason, cure } => {
3238                assert_eq!(name, "bramp-db-acme-app");
3239                assert!(reason.contains("reserved"), "reason names the reservation");
3240                assert!(cure.contains("bramp-db-"), "the cure names the prefix");
3241            }
3242            other => panic!("expected ConfigError::InvalidDbName, got {other:?}"),
3243        }
3244        // A NON-reserved compute workload for a BYO binding still loads fine.
3245        ServerConfig::parse(
3246            r#"(
3247                handlers: ( bindings: ( sql: (
3248                    databases: {
3249                        "byo": ( kind: "postgres", compute: "my-pg", database: "d", user: "u" ),
3250                    },
3251                ) ) ),
3252            )"#,
3253        )
3254        .expect("a non-reserved compute workload loads");
3255    }
3256
3257    #[test]
3258    fn env_sets_managed_db_startup_grace() {
3259        // The per-binding startup-grace override is env-settable like the other
3260        // managed scalars, discovered by the `_STARTUP_GRACE_SECS` suffix.
3261        let mut cfg = ServerConfig::default();
3262        cfg.apply_env_overrides(&env(&[
3263            ("BOATRAMP_HANDLERS_SQL_DB_DEFAULT_KIND", "postgres"),
3264            ("BOATRAMP_HANDLERS_SQL_DB_DEFAULT_COMPUTE", "pg"),
3265            ("BOATRAMP_HANDLERS_SQL_DB_DEFAULT_DATABASE", "appdb"),
3266            ("BOATRAMP_HANDLERS_SQL_DB_DEFAULT_USER", "app"),
3267            ("BOATRAMP_HANDLERS_SQL_DB_DEFAULT_STARTUP_GRACE_SECS", "90"),
3268        ]))
3269        .expect("valid env overrides apply");
3270        let db = &cfg.handlers.unwrap().bindings.sql.unwrap().databases
3271            [boatramp_core::project::DEFAULT_DB_NAME];
3272        assert_eq!(db.startup_grace_secs, Some(90));
3273    }
3274
3275    #[test]
3276    fn env_sets_rls_gucs_and_all_marker_without_suffix_collision() {
3277        // The RLS GUC names + the v0.4.21 all-read marker are env-settable. `_TENANT_ALL_MARKER`
3278        // and `_TENANT_GUC` must NOT be shadowed by the shorter `_TENANT` suffix (longest-first
3279        // isolation) — a `_TENANT` value would otherwise swallow the DB-name split.
3280        let mut cfg = ServerConfig::default();
3281        cfg.apply_env_overrides(&env(&[
3282            ("BOATRAMP_HANDLERS_SQL_DB_DEFAULT_KIND", "postgres"),
3283            ("BOATRAMP_HANDLERS_SQL_DB_DEFAULT_DATABASE", "appdb"),
3284            (
3285                "BOATRAMP_HANDLERS_SQL_DB_DEFAULT_TENANT_GUC",
3286                "app.tenant_id",
3287            ),
3288            (
3289                "BOATRAMP_HANDLERS_SQL_DB_DEFAULT_SESSION_GUC",
3290                "app.session_id",
3291            ),
3292            ("BOATRAMP_HANDLERS_SQL_DB_DEFAULT_TENANT_ALL_MARKER", "*"),
3293        ]))
3294        .expect("valid env overrides apply");
3295        let db = &cfg.handlers.unwrap().bindings.sql.unwrap().databases
3296            [boatramp_core::project::DEFAULT_DB_NAME];
3297        assert_eq!(db.tenant_guc.as_deref(), Some("app.tenant_id"));
3298        assert_eq!(db.session_guc.as_deref(), Some("app.session_id"));
3299        assert_eq!(db.tenant_all_marker.as_deref(), Some("*"));
3300    }
3301
3302    #[test]
3303    fn env_enum_parse_error_is_loud() {
3304        // An unknown enum value is rejected LOUDLY at extract (never silently defaulted). The
3305        // pipeline's `Resolve` error carries figment's message (which names the field + the
3306        // unknown variant), not the old hand-built "one of rootless/caps" text.
3307        let mut cfg = ServerConfig::default();
3308        let err = cfg
3309            .apply_env_overrides(&env(&[(
3310                "BOATRAMP_COMPUTE_MANAGED_DB_PRIVILEGE",
3311                "superuser",
3312            )]))
3313            .expect_err("unknown enum variant is rejected");
3314        assert!(
3315            matches!(err, ConfigError::Resolve(_)),
3316            "unknown enum variant must fail loudly, got {err:?}"
3317        );
3318        // The docker enums map their lowercase serde variants too.
3319        let mut cfg = ServerConfig::default();
3320        cfg.apply_env_overrides(&env(&[
3321            ("BOATRAMP_COMPUTE_DOCKER_ENDPOINT", "bridge"),
3322            ("BOATRAMP_COMPUTE_DOCKER_VOLUME_MODE", "bind"),
3323        ]))
3324        .expect("known enum variants parse");
3325        let compute = cfg.compute.unwrap();
3326        assert_eq!(
3327            compute.docker_endpoint,
3328            boatramp_docker::DockerEndpoint::Bridge
3329        );
3330        assert_eq!(
3331            compute.docker_volume_mode,
3332            boatramp_docker::DockerVolumeMode::Bind
3333        );
3334    }
3335
3336    #[test]
3337    fn env_trust_anchors_parse_as_a_comma_separated_list() {
3338        // The kernel trust anchors are comma-separated (whitespace trimmed, empty
3339        // items dropped so a trailing comma is tolerated). A file default is
3340        // fully replaced, not appended to.
3341        let mut cfg = ServerConfig::default();
3342        cfg.apply_env_overrides(&env(&[
3343            (
3344                "BOATRAMP_COMPUTE_KERNEL_SIGNING_PUBKEYS",
3345                " es256:aa , es256:bb ,",
3346            ),
3347            ("BOATRAMP_COMPUTE_KERNEL_ALLOWED_HASHES", "deadbeef"),
3348        ]))
3349        .expect("valid list env applies");
3350        let compute = cfg.compute.unwrap();
3351        assert_eq!(
3352            compute.kernel_signing_pubkeys,
3353            vec!["es256:aa".to_string(), "es256:bb".to_string()],
3354            "trimmed, comma-split, trailing-empty dropped, defaults replaced"
3355        );
3356        assert_eq!(
3357            compute.kernel_allowed_hashes,
3358            vec!["deadbeef".to_string()],
3359            "a single value is a one-element list"
3360        );
3361    }
3362
3363    #[test]
3364    fn env_configures_secrets_vault_subconfig() {
3365        // The vault sub-config materialises only when a vault var is set, and the
3366        // token stays indirected via a variable NAME (`token_env`), never inline.
3367        let mut cfg = ServerConfig::default();
3368        cfg.apply_env_overrides(&env(&[
3369            ("BOATRAMP_SECRETS_ENVELOPE", "vault"),
3370            ("BOATRAMP_SECRETS_VAULT_ADDR", "https://vault:8200"),
3371            ("BOATRAMP_SECRETS_VAULT_KEY", "certs"),
3372        ]))
3373        .expect("valid env overrides apply");
3374        let secrets = cfg.secrets.unwrap();
3375        assert_eq!(secrets.envelope, "vault");
3376        let vault = secrets.vault.expect("vault sub-config materialised");
3377        assert_eq!(vault.addr, "https://vault:8200");
3378        assert_eq!(vault.key, "certs");
3379        // token_env defaults to VAULT_TOKEN when not overridden.
3380        assert_eq!(vault.token_env, "VAULT_TOKEN");
3381    }
3382
3383    #[test]
3384    fn env_materialises_and_overrides_the_cluster_section() {
3385        // With no file, a `BOATRAMP_CLUSTER_LISTEN` materialises the section; the
3386        // remaining fields (lists, join token, mesh) layer on. The founding/joining
3387        // action flags (`BOATRAMP_CLUSTER_INIT`/`_JOIN`) are separate `serve` args
3388        // and are not part of this section.
3389        let mut cfg = ServerConfig::default();
3390        cfg.apply_env_overrides(&env(&[
3391            ("BOATRAMP_CLUSTER_LISTEN", "10.0.0.2:7000"),
3392            ("BOATRAMP_CLUSTER_ROOT_PUBKEYS", "es256:aa,es256:bb"),
3393            ("BOATRAMP_CLUSTER_SEEDS", "https://10.0.0.1:8080"),
3394            ("BOATRAMP_CLUSTER_JOIN_TOKEN", "env:BOATRAMP_JOIN_TOKEN"),
3395            ("BOATRAMP_CLUSTER_STORE_DIR", "/var/lib/boatramp/raft"),
3396            ("BOATRAMP_CLUSTER_MESH_GATE_CLIENT_WRITES", "true"),
3397        ]))
3398        .expect("valid env overrides apply");
3399        let cluster = cfg.cluster.expect("cluster materialised from env");
3400        assert_eq!(
3401            cluster.listen,
3402            "10.0.0.2:7000".parse::<std::net::SocketAddr>().unwrap()
3403        );
3404        assert_eq!(
3405            cluster.root_pubkeys,
3406            vec!["es256:aa".to_string(), "es256:bb".to_string()]
3407        );
3408        assert_eq!(cluster.seeds, vec!["https://10.0.0.1:8080".to_string()]);
3409        assert_eq!(
3410            cluster.join_token.as_deref(),
3411            Some("env:BOATRAMP_JOIN_TOKEN")
3412        );
3413        assert_eq!(
3414            cluster.store_dir.as_deref(),
3415            Some(Path::new("/var/lib/boatramp/raft"))
3416        );
3417        assert_eq!(
3418            cluster.mesh.expect("mesh sub-config").gate_client_writes,
3419            Some(true)
3420        );
3421
3422        // Decision 4: a `[cluster]` without its required `listen` (here: a non-listen cluster
3423        // var alone, no file section) now FAILS LOUDLY at extract — the old loader silently
3424        // dropped the section, which could mask a misconfigured cluster.
3425        let mut cfg = ServerConfig::default();
3426        let err = cfg
3427            .apply_env_overrides(&env(&[("BOATRAMP_CLUSTER_SEEDS", "https://10.0.0.1:8080")]))
3428            .expect_err("a cluster section without `listen` must fail loudly");
3429        assert!(
3430            matches!(err, ConfigError::Resolve(_)),
3431            "cluster-without-listen must be a loud resolution error, got {err:?}"
3432        );
3433    }
3434
3435    #[test]
3436    fn env_cluster_listen_overrides_a_file_section() {
3437        // A file `[cluster]` section: env overrides `listen` and adds seeds.
3438        let mut cfg = server(r#"( cluster: ( listen: "0.0.0.0:7000" ) )"#);
3439        cfg.apply_env_overrides(&env(&[
3440            ("BOATRAMP_CLUSTER_LISTEN", "10.0.0.9:7000"),
3441            ("BOATRAMP_CLUSTER_SEEDS", "https://seed:8080"),
3442        ]))
3443        .expect("applies");
3444        let cluster = cfg.cluster.unwrap();
3445        assert_eq!(
3446            cluster.listen,
3447            "10.0.0.9:7000".parse::<std::net::SocketAddr>().unwrap(),
3448            "env listen wins over the file"
3449        );
3450        assert_eq!(cluster.seeds, vec!["https://seed:8080".to_string()]);
3451    }
3452
3453    #[test]
3454    fn empty_project_config_is_default() {
3455        let cfg = project("()");
3456        assert!(cfg.publish.server.is_none());
3457        assert!(cfg.publish.site.is_none());
3458        assert!(cfg.build.is_none());
3459        assert!(cfg.bundle.is_none());
3460        // Routing defaults: schema v1, the single default index candidate.
3461        assert_eq!(cfg.routing.version, 1);
3462        assert_eq!(cfg.routing.index, vec!["index.html".to_string()]);
3463    }
3464
3465    #[test]
3466    fn serve_signer_config_parses_and_maps_each_backend() {
3467        use boatramp_core::cose::TokenAlg;
3468        use boatramp_server::signer::SignerConfig;
3469
3470        // RON-native enum tagging (`Vault(...)`); `IMPLICIT_SOME` lets the optional
3471        // fields (region) take a bare value or be omitted (→ None). This is the
3472        // exact RON documented in the Authentication guide.
3473        let vault = server(
3474            r#"( serve: ( signer: Vault(
3475                address: "https://vault.example:8200",
3476                key: "boatramp-root",
3477                token_env: "VAULT_TOKEN",
3478                alg: Ed25519,
3479            ) ) )"#,
3480        );
3481        match vault.serve.unwrap().signer.unwrap().to_signer_config() {
3482            SignerConfig::Vault {
3483                address,
3484                key,
3485                token_env,
3486                alg,
3487            } => {
3488                assert_eq!(address, "https://vault.example:8200");
3489                assert_eq!(key, "boatramp-root");
3490                assert_eq!(token_env, "VAULT_TOKEN");
3491                assert_eq!(alg, TokenAlg::Ed25519);
3492            }
3493            other => panic!("expected Vault, got {other:?}"),
3494        }
3495
3496        // AWS KMS: region omitted → None; PKCS#11: alg omitted → the ES256 default.
3497        let aws =
3498            server(r#"( serve: ( signer: AwsKms(key_id: "arn:aws:kms:eu-west-1:1:key/abc") ) )"#);
3499        assert!(matches!(
3500            aws.serve.unwrap().signer.unwrap().to_signer_config(),
3501            SignerConfig::AwsKms { region: None, .. }
3502        ));
3503
3504        let hsm = server(
3505            r#"( serve: ( signer: Pkcs11(
3506                module: "/usr/lib/softhsm/libsofthsm2.so",
3507                token_label: "boatramp",
3508                key_label: "root",
3509                pin_env: "HSM_PIN",
3510            ) ) )"#,
3511        );
3512        match hsm.serve.unwrap().signer.unwrap().to_signer_config() {
3513            SignerConfig::Pkcs11 { alg, .. } => assert_eq!(alg, TokenAlg::Es256),
3514            other => panic!("expected Pkcs11, got {other:?}"),
3515        }
3516    }
3517
3518    #[test]
3519    fn project_config_parses_publish_build_and_routing() {
3520        let cfg = project(
3521            r#"(
3522                publish: ( server: "http://127.0.0.1:8080", site: "demo" ),
3523                build: ( command: "npm run build", output: "dist" ),
3524                routing: (
3525                    clean_urls: true,
3526                    redirects: [ (from: "/old/:slug", to: "/new/:slug", status: 301) ],
3527                ),
3528            )"#,
3529        );
3530        assert_eq!(cfg.publish.server.as_deref(), Some("http://127.0.0.1:8080"));
3531        assert_eq!(cfg.publish.site.as_deref(), Some("demo"));
3532        let build = cfg.build.unwrap();
3533        assert_eq!(build.command, "npm run build");
3534        assert_eq!(build.output.as_deref(), Some("dist"));
3535        assert!(cfg.routing.clean_urls);
3536        assert_eq!(cfg.routing.redirects.len(), 1);
3537        assert_eq!(cfg.routing.redirects[0].status, 301);
3538    }
3539
3540    #[test]
3541    fn project_config_rejects_bad_routing_pattern() {
3542        // The same compile-check `load` runs: a bad route pattern is an error.
3543        let cfg = project(r#"( routing: ( redirects: [ (from: "/a/**/b/**", to: "/x") ] ) )"#);
3544        assert!(cfg.routing.compile_check().is_err());
3545    }
3546
3547    #[test]
3548    fn empty_server_config_has_no_sections() {
3549        let cfg = server("()");
3550        assert!(cfg.serve.is_none());
3551        assert!(cfg.handlers.is_none());
3552        assert!(cfg.cluster.is_none());
3553        assert!(cfg.security.is_none());
3554    }
3555
3556    #[test]
3557    fn security_section_parses_and_resolves() {
3558        // A profile plus an override that wins over it.
3559        let cfg = server(
3560            r#"(
3561                security: (
3562                    profile: "dev",
3563                    overrides: (
3564                        oidc_require_audience: true,
3565                        max_upload_bytes: 0,
3566                    ),
3567                )
3568            )"#,
3569        );
3570        let posture = cfg.security.unwrap().resolve().expect("resolves");
3571        // `dev` is loose...
3572        assert!(posture.allow_unauthenticated_public_bind);
3573        // ...but the explicit override wins over the profile.
3574        assert!(posture.oidc_require_audience);
3575        assert_eq!(posture.max_upload_bytes, 0); // unlimited
3576    }
3577
3578    #[test]
3579    fn env_wires_allow_env_secret_refs_over_the_multi_tenant_default() {
3580        // With no file, the multi-tenant default leaves host-env secret refs off;
3581        // the env knob re-enables them (env > default), same as the other posture bools.
3582        let mut cfg = ServerConfig::default();
3583        cfg.apply_env_overrides(&env(&[("BOATRAMP_SECURITY_ALLOW_ENV_SECRET_REFS", "true")]))
3584            .expect("valid env override applies");
3585        let posture = cfg
3586            .security
3587            .expect("security materialised from env")
3588            .resolve()
3589            .expect("resolves");
3590        assert!(posture.allow_env_secret_refs);
3591    }
3592
3593    #[test]
3594    fn env_wires_the_multi_tenant_subknobs_over_the_default() {
3595        // Gap 4b: the four multi-tenant sub-knobs were file-only; env now sets them (env > the
3596        // multi-tenant preset default), so a 12-factor deploy can tune tenancy isolation + guest
3597        // capability minting with no `boatramp.cfg`. Verified: strict declaration stays on while
3598        // cross-tenant `all` twins + guest cap-mint are permitted (they compose — Gap 4.3).
3599        let mut cfg = ServerConfig::default();
3600        cfg.apply_env_overrides(&env(&[
3601            ("BOATRAMP_SECURITY_PROFILE", "multi-tenant"),
3602            ("BOATRAMP_SECURITY_REQUIRE_TENANCY_DECLARATION", "true"),
3603            ("BOATRAMP_SECURITY_ALLOW_CROSS_TENANT_DB", "true"),
3604            ("BOATRAMP_SECURITY_ALLOW_GUEST_MINT_CAPABILITY", "true"),
3605            ("BOATRAMP_SECURITY_MAX_GUEST_CAPABILITY_TTL_SECS", "1800"),
3606        ]))
3607        .expect("valid env overrides apply");
3608        let posture = cfg
3609            .security
3610            .expect("security materialised from env")
3611            .resolve()
3612            .expect("resolves");
3613        assert!(posture.require_tenancy_declaration);
3614        assert!(posture.allow_cross_tenant_db);
3615        assert!(posture.allow_guest_mint_capability);
3616        assert_eq!(posture.max_guest_capability_ttl_secs, 1800);
3617    }
3618
3619    #[test]
3620    fn env_wires_the_remaining_guest_feature_knobs_over_the_multi_tenant_default() {
3621        // v0.4.18 env parity: `allow_guest_email` (which regressed prod SMTP on the P48 cutover —
3622        // multi-tenant defaults it OFF and there was no env lever), its egress sibling
3623        // `allow_guest_egress_extra_ca` (shipped config-only in v0.4.17), and the four
3624        // `allow_guest_admin_*` self-config knobs were all missing from the env map. Each preset
3625        // defaults them OFF under `multi-tenant`; the env knob must now flip each back on for a
3626        // 12-factor env-only fleet, exactly like `allow_guest_mint_capability`.
3627        let mut cfg = ServerConfig::default();
3628        cfg.apply_env_overrides(&env(&[
3629            ("BOATRAMP_SECURITY_PROFILE", "multi-tenant"),
3630            ("BOATRAMP_SECURITY_ALLOW_GUEST_EMAIL", "true"),
3631            ("BOATRAMP_SECURITY_ALLOW_GUEST_EGRESS_EXTRA_CA", "true"),
3632            ("BOATRAMP_SECURITY_ALLOW_GUEST_ADMIN_DOMAINS", "true"),
3633            ("BOATRAMP_SECURITY_ALLOW_GUEST_ADMIN_EMAIL", "true"),
3634            ("BOATRAMP_SECURITY_ALLOW_GUEST_ADMIN_SITE", "true"),
3635            ("BOATRAMP_SECURITY_ALLOW_GUEST_ADMIN_SECRETS", "true"),
3636        ]))
3637        .expect("valid env overrides apply");
3638        let security = cfg.security.expect("security materialised from env");
3639        let posture = security.resolve().expect("resolves");
3640        // Every one flips on over the multi-tenant preset default (which is `false` for all six).
3641        assert!(posture.allow_guest_email, "guest email re-enabled via env");
3642        assert!(posture.allow_guest_egress_extra_ca);
3643        assert!(posture.allow_guest_admin_domains);
3644        assert!(posture.allow_guest_admin_email);
3645        assert!(posture.allow_guest_admin_site);
3646        assert!(posture.allow_guest_admin_secrets);
3647        // `security explain` attributes each to the override/env source (not the profile preset).
3648        let explained = security.explain().expect("explains");
3649        for knob in [
3650            "allow_guest_email",
3651            "allow_guest_egress_extra_ca",
3652            "allow_guest_admin_domains",
3653            "allow_guest_admin_email",
3654            "allow_guest_admin_site",
3655            "allow_guest_admin_secrets",
3656        ] {
3657            assert!(
3658                explained
3659                    .lines()
3660                    .any(|l| l.contains(knob) && l.contains("true") && l.contains("(override)")),
3661                "explain shows {knob} = true (override): \n{explained}"
3662            );
3663        }
3664    }
3665
3666    #[test]
3667    fn each_guest_feature_env_var_moves_its_own_posture_field() {
3668        // Cross-wiring guard: set each of the guest-feature vars ALONE over the multi-tenant
3669        // default and assert THAT var's own resolved field flips — so a copy-paste arm mapping a var
3670        // to the wrong field (or an unregistered var that never materialises the section) fails here.
3671        // Complements `every_posture_override_field_has_an_env_mapping` below (which proves coverage
3672        // by field name but not that each arm targets the right field).
3673        for (var, check) in [
3674            (
3675                "BOATRAMP_SECURITY_ALLOW_GUEST_EMAIL",
3676                (|p: &boatramp_core::security::SecurityPosture| p.allow_guest_email)
3677                    as fn(&boatramp_core::security::SecurityPosture) -> bool,
3678            ),
3679            ("BOATRAMP_SECURITY_ALLOW_GUEST_EGRESS_EXTRA_CA", |p| {
3680                p.allow_guest_egress_extra_ca
3681            }),
3682            ("BOATRAMP_SECURITY_ALLOW_GUEST_TCP_EGRESS", |p| {
3683                p.allow_guest_tcp_egress
3684            }),
3685            ("BOATRAMP_SECURITY_ALLOW_GUEST_TCP_LISTENER", |p| {
3686                p.allow_guest_tcp_listener
3687            }),
3688            ("BOATRAMP_SECURITY_ALLOW_GUEST_ADMIN_DOMAINS", |p| {
3689                p.allow_guest_admin_domains
3690            }),
3691            ("BOATRAMP_SECURITY_ALLOW_GUEST_ADMIN_EMAIL", |p| {
3692                p.allow_guest_admin_email
3693            }),
3694            ("BOATRAMP_SECURITY_ALLOW_GUEST_ADMIN_SITE", |p| {
3695                p.allow_guest_admin_site
3696            }),
3697            ("BOATRAMP_SECURITY_ALLOW_GUEST_ADMIN_SECRETS", |p| {
3698                p.allow_guest_admin_secrets
3699            }),
3700        ] {
3701            let mut cfg = ServerConfig::default();
3702            cfg.apply_env_overrides(&env(&[
3703                ("BOATRAMP_SECURITY_PROFILE", "multi-tenant"),
3704                (var, "true"),
3705            ]))
3706            .unwrap_or_else(|e| panic!("{var} applies: {e}"));
3707            let posture = cfg
3708                .security
3709                .unwrap_or_else(|| panic!("{var} materialises the security section"))
3710                .resolve()
3711                .expect("resolves");
3712            assert!(check(&posture), "{var} did not flip the resolved posture");
3713        }
3714    }
3715
3716    #[test]
3717    fn every_posture_override_field_has_an_env_mapping() {
3718        // Exhaustive guard against the EXACT class of gap v0.4.18 closes — a `PostureOverrides`
3719        // field a 12-factor fleet can set in `[security.overrides]` but NOT via env — for EVERY
3720        // field, now and in the future. Enumerate the struct's fields structurally (serialize a
3721        // default instance; every field renders as a key) and assert each maps to a registered
3722        // `BOATRAMP_SECURITY_<UPPER(field)>` in `SECURITY_ENV_VARS`. A new override field added
3723        // without an env var (or a var left out of the registry) fails here — so the omission that
3724        // regressed `allow_guest_email` can't silently recur. The registry entry is load-bearing:
3725        // `apply_env_overrides` only materialises the section when `source.any(SECURITY_ENV_VARS)`.
3726        let all = serde_json::to_value(boatramp_core::security::PostureOverrides::default())
3727            .expect("PostureOverrides serializes");
3728        let fields = all.as_object().expect("a struct is a JSON object");
3729        assert!(!fields.is_empty(), "expected some override fields");
3730        for field in fields.keys() {
3731            let var = format!("BOATRAMP_SECURITY_{}", field.to_uppercase());
3732            assert!(
3733                SECURITY_ENV_VARS.contains(&var.as_str()),
3734                "PostureOverrides field `{field}` has no env mapping — add `{var}` to \
3735                 SECURITY_ENV_VARS + an arm in apply_env_overrides (the v0.4.18 forgot-a-knob guard)"
3736            );
3737        }
3738    }
3739
3740    #[test]
3741    fn cluster_section_parses_the_dynamic_join_shape() {
3742        let cfg = server(
3743            r#"(
3744                cluster: (
3745                    listen: "10.0.0.2:7000",
3746                    root_pubkeys: ["es256:03a1"],
3747                    seeds: ["https://10.0.0.1:8080"],
3748                    join_token: "env:BOATRAMP_JOIN_TOKEN",
3749                ),
3750            )"#,
3751        );
3752        let cluster = cfg.cluster.unwrap();
3753        assert_eq!(
3754            cluster.listen,
3755            "10.0.0.2:7000".parse::<std::net::SocketAddr>().unwrap()
3756        );
3757        assert_eq!(cluster.root_pubkeys, vec!["es256:03a1".to_string()]);
3758        assert_eq!(cluster.seeds, vec!["https://10.0.0.1:8080".to_string()]);
3759        assert_eq!(
3760            cluster.join_token.as_deref(),
3761            Some("env:BOATRAMP_JOIN_TOKEN")
3762        );
3763        // store_dir defaults to None (→ <data-dir>/raft at serve time).
3764        assert!(cluster.store_dir.is_none());
3765    }
3766
3767    #[test]
3768    fn cluster_section_founds_with_just_a_listen_addr() {
3769        // A founder needs no seeds/token — just where to bind the mesh.
3770        let cfg = server(r#"( cluster: ( listen: "0.0.0.0:7000" ) )"#);
3771        let cluster = cfg.cluster.unwrap();
3772        assert!(cluster.seeds.is_empty());
3773        assert!(cluster.root_pubkeys.is_empty());
3774        assert!(cluster.join_token.is_none());
3775    }
3776
3777    #[test]
3778    fn sql_binding_single_node_defaults() {
3779        // A bare section (or none) means single-node: no url, default dir.
3780        let cfg = server(r#"( handlers: ( bindings: ( sql: () ) ) )"#);
3781        let sql = cfg.handlers.unwrap().bindings.sql.unwrap();
3782        assert!(sql.url.is_none());
3783        assert!(sql.dir.is_none());
3784    }
3785
3786    #[test]
3787    fn sql_binding_single_node_custom_dir() {
3788        let cfg =
3789            server(r#"( handlers: ( bindings: ( sql: ( dir: "/var/lib/boatramp/sql" ) ) ) )"#);
3790        let sql = cfg.handlers.unwrap().bindings.sql.unwrap();
3791        assert_eq!(sql.dir.as_deref(), Some(Path::new("/var/lib/boatramp/sql")));
3792        assert!(sql.url.is_none());
3793    }
3794
3795    #[test]
3796    fn sql_binding_cluster() {
3797        let cfg = server(
3798            r#"(
3799                handlers: ( bindings: ( sql: (
3800                    url: "http://sqld:8080",
3801                    admin_url: "http://sqld:9090",
3802                    token_env: "BOATRAMP_SQL_TOKEN",
3803                ) ) ),
3804            )"#,
3805        );
3806        let sql = cfg.handlers.unwrap().bindings.sql.unwrap();
3807        assert_eq!(sql.url.as_deref(), Some("http://sqld:8080"));
3808        assert_eq!(sql.admin_url.as_deref(), Some("http://sqld:9090"));
3809        assert_eq!(sql.token_env.as_deref(), Some("BOATRAMP_SQL_TOKEN"));
3810        assert_eq!(sql.admin_token_env, None);
3811    }
3812
3813    #[test]
3814    fn sql_binding_env_only_sets_trusted_extensions_and_declared_caps() {
3815        // The crux of the ask: with NO `boatramp.cfg`, env vars alone materialise + populate the
3816        // sql binding's migration trusted-extension allowlist (a parse_list, comma-separated +
3817        // trimmed) and the declared-DB ceilings — so a fly `[env]`-only fleet can allowlist
3818        // `pg_trgm` without a `[[files]] boatramp.cfg` edit + a server roll.
3819        let mut cfg = ServerConfig::default();
3820        assert!(cfg.handlers.is_none());
3821        cfg.apply_env_overrides(&env(&[
3822            (
3823                "BOATRAMP_HANDLERS_SQL_MIGRATE_TRUSTED_EXTENSIONS",
3824                "pg_trgm, pgcrypto",
3825            ),
3826            ("BOATRAMP_HANDLERS_SQL_MAX_DECLARED_DATABASES", "32"),
3827            ("BOATRAMP_HANDLERS_SQL_MAX_DECLARED_VOLUME_MIB", "1048576"),
3828        ]))
3829        .expect("valid env overrides apply");
3830        let sql = cfg
3831            .handlers
3832            .expect("handlers materialised from env")
3833            .bindings
3834            .sql
3835            .expect("sql binding materialised from the trusted-extensions var alone");
3836        assert_eq!(
3837            sql.migrate_trusted_extensions.as_deref(),
3838            Some(&["pg_trgm".to_string(), "pgcrypto".to_string()][..]),
3839            "the allowlist is the comma-split, trimmed env list (source = env)"
3840        );
3841        assert_eq!(sql.max_declared_databases, Some(32));
3842        assert_eq!(sql.max_declared_volume_mib, Some(1_048_576));
3843    }
3844
3845    #[test]
3846    fn sql_binding_env_over_file_for_trusted_extensions() {
3847        // Field-level env-over-file precedence: a file allowlist is overridden ONLY for the var that
3848        // is set; an unset var keeps the file value (never clobbered to empty).
3849        let mut cfg = server(
3850            r#"(
3851                handlers: ( bindings: ( sql: (
3852                    migrate_trusted_extensions: ["citext"],
3853                    max_declared_databases: 8,
3854                ) ) ),
3855            )"#,
3856        );
3857        cfg.apply_env_overrides(&env(&[(
3858            "BOATRAMP_HANDLERS_SQL_MIGRATE_TRUSTED_EXTENSIONS",
3859            "pg_trgm",
3860        )]))
3861        .expect("env overrides apply");
3862        let sql = cfg.handlers.unwrap().bindings.sql.unwrap();
3863        assert_eq!(
3864            sql.migrate_trusted_extensions.as_deref(),
3865            Some(&["pg_trgm".to_string()][..]),
3866            "env wins over the file allowlist for the var that is set"
3867        );
3868        assert_eq!(
3869            sql.max_declared_databases,
3870            Some(8),
3871            "a var left unset keeps the file value (not clobbered)"
3872        );
3873    }
3874
3875    #[test]
3876    fn every_sql_binding_scalar_has_an_env_mapping() {
3877        // Forgot-a-knob guard (the v0.4.18 shape, for `handlers.bindings.sql`): every env-mappable
3878        // SCALAR field on SqlBindingConfig must have a `BOATRAMP_HANDLERS_SQL_*` entry in
3879        // SQL_ENV_VARS, so a file-less (fly `[env]`-only) fleet can set it without a `boatramp.cfg`
3880        // + server roll — the EXACT gap that left `migrate_trusted_extensions` env-unsettable. The
3881        // destructure is the compile-time half: a NEW field added to SqlBindingConfig breaks this
3882        // test until it is classified below (a scalar → add a var here + a registry entry + an
3883        // overlay arm; or the `databases` map, which is discovered by the
3884        // `BOATRAMP_HANDLERS_SQL_DB_<NAME>_*` prefix scan, not a scalar var). The loop is the runtime
3885        // half: each classified scalar is actually registered.
3886        let SqlBindingConfig {
3887            dir: _,
3888            url: _,
3889            admin_url: _,
3890            replica_url: _,
3891            token_env: _,
3892            admin_token_env: _,
3893            preview_mode: _,
3894            preview_init: _,
3895            // NOT a scalar env var: the keyed external-database map, discovered by prefix scan.
3896            databases: _,
3897            deprovision_grace_secs: _,
3898            migrate_trusted_extensions: _,
3899            max_declared_databases: _,
3900            max_declared_volume_mib: _,
3901        } = SqlBindingConfig::default();
3902        for var in [
3903            "BOATRAMP_HANDLERS_SQL_DIR",
3904            "BOATRAMP_HANDLERS_SQL_URL",
3905            "BOATRAMP_HANDLERS_SQL_ADMIN_URL",
3906            "BOATRAMP_HANDLERS_SQL_REPLICA_URL",
3907            "BOATRAMP_HANDLERS_SQL_TOKEN_ENV",
3908            "BOATRAMP_HANDLERS_SQL_ADMIN_TOKEN_ENV",
3909            "BOATRAMP_HANDLERS_SQL_PREVIEW_MODE",
3910            "BOATRAMP_HANDLERS_SQL_PREVIEW_INIT",
3911            "BOATRAMP_HANDLERS_SQL_DEPROVISION_GRACE_SECS",
3912            "BOATRAMP_HANDLERS_SQL_MIGRATE_TRUSTED_EXTENSIONS",
3913            "BOATRAMP_HANDLERS_SQL_MAX_DECLARED_DATABASES",
3914            "BOATRAMP_HANDLERS_SQL_MAX_DECLARED_VOLUME_MIB",
3915        ] {
3916            assert!(
3917                SQL_ENV_VARS.contains(&var),
3918                "{var} missing from SQL_ENV_VARS — a sql-binding scalar lost its env lever \
3919                 (the forgot-a-knob gap); add it to the registry + an overlay arm"
3920            );
3921        }
3922    }
3923
3924    #[test]
3925    fn env_wires_the_jwks_freshness_knobs_over_the_default() {
3926        // The two-tier JWKS freshness knobs are env-settable (12-factor parity), and every lever is
3927        // registered in JWKS_ENV_VARS — a forgot-a-knob guard so a new `jwks_*` field can't silently
3928        // lose its env override.
3929        let mut cfg = ServerConfig::default();
3930        assert!(cfg.handlers.is_none());
3931        cfg.apply_env_overrides(&env(&[
3932            ("BOATRAMP_HANDLERS_JWKS_REFRESH_SECS", "90"),
3933            ("BOATRAMP_HANDLERS_JWKS_HARD_TTL_SECS", "450"),
3934            ("BOATRAMP_HANDLERS_JWKS_FOREIGN_REFRESH_SECS", "30"),
3935            ("BOATRAMP_HANDLERS_JWKS_FOREIGN_HARD_TTL_SECS", "150"),
3936            ("BOATRAMP_HANDLERS_JWKS_PREWARM", "false"),
3937        ]))
3938        .expect("valid env overrides apply");
3939        let h = cfg.handlers.expect("handlers materialised from env");
3940        assert_eq!(h.jwks_refresh_secs, Some(90));
3941        assert_eq!(h.jwks_hard_ttl_secs, Some(450));
3942        assert_eq!(h.jwks_foreign_refresh_secs, Some(30));
3943        assert_eq!(h.jwks_foreign_hard_ttl_secs, Some(150));
3944        assert_eq!(h.jwks_prewarm, Some(false));
3945        for var in [
3946            "BOATRAMP_HANDLERS_JWKS_REFRESH_SECS",
3947            "BOATRAMP_HANDLERS_JWKS_HARD_TTL_SECS",
3948            "BOATRAMP_HANDLERS_JWKS_FOREIGN_REFRESH_SECS",
3949            "BOATRAMP_HANDLERS_JWKS_FOREIGN_HARD_TTL_SECS",
3950            "BOATRAMP_HANDLERS_JWKS_PREWARM",
3951        ] {
3952            assert!(
3953                JWKS_ENV_VARS.contains(&var),
3954                "{var} missing from JWKS_ENV_VARS — a JWKS freshness knob lost its env lever"
3955            );
3956        }
3957    }
3958
3959    #[test]
3960    fn env_wires_the_handler_concurrency_knobs_over_the_default() {
3961        // The per-component serve-admission gate + the two lane ceilings are env-settable (12-factor
3962        // parity), and every lever is registered in HANDLER_CONCURRENCY_ENV_VARS — a forgot-a-knob guard
3963        // so a new concurrency field can't silently lose its env override and get pinned back into a
3964        // `boatramp.cfg`. `serve_concurrency = 0` is the MEANINGFUL "disable the gate" value and must
3965        // round-trip as `Some(0)`, not be dropped.
3966        let mut cfg = ServerConfig::default();
3967        assert!(cfg.handlers.is_none());
3968        cfg.apply_env_overrides(&env(&[
3969            ("BOATRAMP_HANDLERS_SERVE_CONCURRENCY", "0"),
3970            ("BOATRAMP_HANDLERS_SYNC_MAX_CONCURRENCY", "128"),
3971            ("BOATRAMP_HANDLERS_ASYNC_MAX_CONCURRENCY", "16"),
3972        ]))
3973        .expect("valid env overrides apply");
3974        let h = cfg.handlers.expect("handlers materialised from env");
3975        assert_eq!(h.serve_concurrency, Some(0), "0 = disable must round-trip");
3976        assert_eq!(h.sync_max_concurrency, Some(128));
3977        assert_eq!(h.async_max_concurrency, Some(16));
3978        for var in [
3979            "BOATRAMP_HANDLERS_SERVE_CONCURRENCY",
3980            "BOATRAMP_HANDLERS_SYNC_MAX_CONCURRENCY",
3981            "BOATRAMP_HANDLERS_ASYNC_MAX_CONCURRENCY",
3982        ] {
3983            assert!(
3984                HANDLER_CONCURRENCY_ENV_VARS.contains(&var),
3985                "{var} missing from HANDLER_CONCURRENCY_ENV_VARS — a concurrency knob lost its env lever"
3986            );
3987        }
3988    }
3989
3990    #[test]
3991    fn env_wires_the_blob_hedge_knobs_over_the_default() {
3992        // The hedged-read tail knobs are env-settable so a file-less fleet can turn hedging on and tune
3993        // it; every lever is registered in HANDLER_BLOB_HEDGE_ENV_VARS (forgot-a-knob guard).
3994        let mut cfg = ServerConfig::default();
3995        assert!(cfg.handlers.is_none());
3996        cfg.apply_env_overrides(&env(&[
3997            ("BOATRAMP_HANDLERS_BLOB_HEDGE_DELAY_MS", "80"),
3998            ("BOATRAMP_HANDLERS_BLOB_HEDGE_MAX_INFLIGHT", "24"),
3999        ]))
4000        .expect("valid env overrides apply");
4001        let h = cfg.handlers.expect("handlers materialised from env");
4002        assert_eq!(h.blob_hedge_delay_ms, Some(80));
4003        assert_eq!(h.blob_hedge_max_inflight, Some(24));
4004        for var in [
4005            "BOATRAMP_HANDLERS_BLOB_HEDGE_DELAY_MS",
4006            "BOATRAMP_HANDLERS_BLOB_HEDGE_MAX_INFLIGHT",
4007        ] {
4008            assert!(
4009                HANDLER_BLOB_HEDGE_ENV_VARS.contains(&var),
4010                "{var} missing from HANDLER_BLOB_HEDGE_ENV_VARS — a hedge knob lost its env lever"
4011            );
4012        }
4013    }
4014
4015    #[test]
4016    fn env_wires_the_coldstart_knobs_over_the_default() {
4017        // The warm floor + portable AOT cache (cap-req 09) are env-settable (12-factor parity);
4018        // every lever is registered in HANDLER_COLDSTART_ENV_VARS — a forgot-a-knob guard.
4019        let mut cfg = ServerConfig::default();
4020        assert!(cfg.handlers.is_none());
4021        cfg.apply_env_overrides(&env(&[
4022            ("BOATRAMP_HANDLERS_KEEP_WARM_MAX", "8"),
4023            ("BOATRAMP_HANDLERS_AOT_ARTIFACT_CACHE", "true"),
4024            ("BOATRAMP_HANDLERS_AOT_ARTIFACT_MAX_BYTES", "268435456"),
4025        ]))
4026        .expect("valid env overrides apply");
4027        let h = cfg.handlers.expect("handlers materialised from env");
4028        assert_eq!(h.keep_warm_max, Some(8));
4029        assert_eq!(h.aot_artifact_cache, Some(true));
4030        assert_eq!(h.aot_artifact_max_bytes, Some(268_435_456));
4031        for var in [
4032            "BOATRAMP_HANDLERS_KEEP_WARM_MAX",
4033            "BOATRAMP_HANDLERS_AOT_ARTIFACT_CACHE",
4034            "BOATRAMP_HANDLERS_AOT_ARTIFACT_MAX_BYTES",
4035        ] {
4036            assert!(
4037                HANDLER_COLDSTART_ENV_VARS.contains(&var),
4038                "{var} missing from HANDLER_COLDSTART_ENV_VARS — a cold-start knob lost its env lever"
4039            );
4040        }
4041    }
4042
4043    #[test]
4044    fn env_wires_the_s3_ingress_cloud_knobs_over_the_default() {
4045        // The blob-upload minter's cloud-brokering policy is env-settable, so the Tigris presigned-only
4046        // deployment needs no `boatramp.cfg` for it. Every lever is registered in
4047        // S3_INGRESS_CLOUD_ENV_VARS (forgot-a-knob guard). The signing credential is NOT here — it stays
4048        // the sealed `[secrets]` one; these are policy toggles only.
4049        let mut cfg = ServerConfig::default();
4050        assert!(cfg.serve.is_none());
4051        cfg.apply_env_overrides(&env(&[(
4052            "BOATRAMP_S3_INGRESS_CLOUD_AWS_PRESIGNED_ONLY",
4053            "true",
4054        )]))
4055        .expect("valid env overrides apply");
4056        let ic = cfg
4057            .serve
4058            .expect("serve materialised from env")
4059            .s3_ingress_cloud
4060            .expect("s3_ingress_cloud materialised from env");
4061        assert!(ic.aws_presigned_only, "presigned-only toggled on via env");
4062        assert!(
4063            !ic.aws_use_federation_token,
4064            "untouched toggle stays default"
4065        );
4066        assert!(ic.aws_role_arn.is_none(), "untouched field stays None");
4067        for var in S3_INGRESS_CLOUD_ENV_VARS {
4068            assert!(
4069                var.starts_with("BOATRAMP_S3_INGRESS_CLOUD_"),
4070                "{var} is not an s3_ingress_cloud lever"
4071            );
4072        }
4073    }
4074
4075    #[test]
4076    fn env_wires_the_per_project_blob_backend_over_the_default() {
4077        // PLAN-per-project-blob-backend: a keyed `[serve.blob_backends.<project>]` map discovered from
4078        // the env with NO config file, mirroring the SQL `databases` map. The project name may contain
4079        // underscores (name isolation strips the LONGEST field suffix). The sealed credential is a
4080        // REFERENCE (`boatramp:`/`env:`), never the raw secret (invariant 3).
4081        let mut cfg = ServerConfig::default();
4082        assert!(cfg.serve.is_none());
4083        cfg.apply_env_overrides(&env(&[
4084            ("BOATRAMP_SERVE_BLOB_BACKEND_acme_eu_KIND", "s3"),
4085            (
4086                "BOATRAMP_SERVE_BLOB_BACKEND_acme_eu_S3_BUCKET",
4087                "acme-eu-blobs",
4088            ),
4089            (
4090                "BOATRAMP_SERVE_BLOB_BACKEND_acme_eu_S3_ENDPOINT",
4091                "https://s3.eu.example.com",
4092            ),
4093            ("BOATRAMP_SERVE_BLOB_BACKEND_acme_eu_S3_REGION", "eu-west-1"),
4094            ("BOATRAMP_SERVE_BLOB_BACKEND_acme_eu_S3_PATH_STYLE", "true"),
4095            (
4096                "BOATRAMP_SERVE_BLOB_BACKEND_acme_eu_S3_ACCESS_KEY_ID",
4097                "AKIAACME",
4098            ),
4099            (
4100                "BOATRAMP_SERVE_BLOB_BACKEND_acme_eu_S3_SECRET_ACCESS_KEY",
4101                "boatramp:acme-eu-s3",
4102            ),
4103        ]))
4104        .expect("valid per-project blob-backend env overrides apply");
4105        let serve = cfg.serve.expect("serve materialised from env");
4106        let be = serve.blob_backends.get("acme_eu").expect(
4107            "the acme_eu per-project backend was discovered from env (underscore survives name \
4108             isolation)",
4109        );
4110        assert_eq!(be.blobs, Some(crate::backends::BlobBackend::S3));
4111        assert_eq!(be.s3_bucket.as_deref(), Some("acme-eu-blobs"));
4112        assert_eq!(be.s3_endpoint.as_deref(), Some("https://s3.eu.example.com"));
4113        assert_eq!(be.s3_region.as_deref(), Some("eu-west-1"));
4114        assert!(be.s3_path_style);
4115        let cred = be
4116            .s3_credential
4117            .as_ref()
4118            .expect("sealed credential materialised from its two refs");
4119        assert_eq!(cred.access_key_id, "AKIAACME");
4120        // The secret is the REFERENCE as written — never an inlined secret value (invariant 3).
4121        assert_eq!(cred.secret_access_key, "boatramp:acme-eu-s3");
4122    }
4123
4124    #[test]
4125    fn blob_backend_env_covers_every_field() {
4126        // Forgot-a-knob guard (mirrors the SQL-DB + hedge guards): every field of `BlobBackendConfig`
4127        // reachable from config MUST have an env suffix in `BLOB_BACKEND_FIELD_SUFFIXES`, so a newly
4128        // added field can't silently lose its env lever. Set every suffix for one project and assert
4129        // each field landed; assert the suffix set is exactly the expected one (no stale/missing lever).
4130        let expected: &[&str] = &[
4131            "_KIND",
4132            "_S3_BUCKET",
4133            "_S3_ENDPOINT",
4134            "_S3_REGION",
4135            "_S3_PATH_STYLE",
4136            "_S3_ACCESS_KEY_ID",
4137            "_S3_SECRET_ACCESS_KEY",
4138        ];
4139        for suffix in expected {
4140            assert!(
4141                BLOB_BACKEND_FIELD_SUFFIXES.contains(suffix),
4142                "{suffix} missing from BLOB_BACKEND_FIELD_SUFFIXES — a blob-backend field lost its \
4143                 env lever"
4144            );
4145        }
4146        assert_eq!(
4147            BLOB_BACKEND_FIELD_SUFFIXES.len(),
4148            expected.len(),
4149            "BLOB_BACKEND_FIELD_SUFFIXES has a suffix with no matching expected field (stale lever)"
4150        );
4151    }
4152
4153    #[test]
4154    fn env_wires_an_inbound_tcp_listener_with_no_file() {
4155        // PLAN-handler-tcp-inbound: a keyed `[serve.listeners.<name>]` map discovered from env with NO
4156        // config file (mirrors the blob-backend map). The listener name may contain underscores (name
4157        // isolation strips the LONGEST field suffix — `edge_api` survives).
4158        let mut cfg = ServerConfig::default();
4159        assert!(cfg.serve.is_none());
4160        cfg.apply_env_overrides(&env(&[
4161            ("BOATRAMP_SERVE_LISTENER_edge_api_BIND", "0.0.0.0:9000"),
4162            ("BOATRAMP_SERVE_LISTENER_edge_api_COMPONENT", "echo.wasm"),
4163            ("BOATRAMP_SERVE_LISTENER_edge_api_PROJECT", "acme"),
4164            ("BOATRAMP_SERVE_LISTENER_edge_api_SITE", "prod"),
4165            (
4166                "BOATRAMP_SERVE_LISTENER_edge_api_IMPORTS",
4167                "sql,wasi:keyvalue",
4168            ),
4169            ("BOATRAMP_SERVE_LISTENER_edge_api_MAX_CONNS", "32"),
4170            ("BOATRAMP_SERVE_LISTENER_edge_api_IDLE_TIMEOUT_MS", "15000"),
4171            (
4172                "BOATRAMP_SERVE_LISTENER_edge_api_MAX_CONN_DURATION_MS",
4173                "120000",
4174            ),
4175        ]))
4176        .expect("valid inbound-TCP listener env overrides apply + validate");
4177        let serve = cfg.serve.expect("serve materialised from env");
4178        let l = serve.listeners.get("edge_api").expect(
4179            "the edge_api listener was discovered from env (underscore survives isolation)",
4180        );
4181        assert_eq!(l.bind, Some("0.0.0.0:9000".parse().unwrap()));
4182        assert_eq!(l.component, "echo.wasm");
4183        assert_eq!(l.project, "acme");
4184        assert_eq!(l.site, "prod");
4185        assert_eq!(
4186            l.imports,
4187            vec!["sql".to_string(), "wasi:keyvalue".to_string()]
4188        );
4189        assert_eq!(l.max_conns, Some(32));
4190        assert_eq!(l.idle_timeout_ms, Some(15000));
4191        assert_eq!(l.max_conn_duration_ms, Some(120000));
4192    }
4193
4194    #[test]
4195    fn listener_validation_fails_closed() {
4196        // A half-declared or Phase-1-unsupported listener REFUSES the node (boot-LOUD), never binds
4197        // something that would silently mislead the operator (PLAN-handler-tcp-inbound).
4198        // (a) a missing bind.
4199        let err = ServerConfig::parse(
4200            r#"( serve: ( listeners: { "l": ( component: "c.wasm", project: "p", site: "s" ) } ) )"#,
4201        )
4202        .expect_err("a listener with no bind must be refused");
4203        assert!(
4204            matches!(err, ConfigError::InvalidListener { .. }),
4205            "{err:?}"
4206        );
4207        // (b) a `tls` block MISSING cert_file/key_file is refused (cap-req 06: host-TLS needs both).
4208        let err = ServerConfig::parse(
4209            r#"( serve: ( listeners: { "l": ( bind: "0.0.0.0:9000", component: "c.wasm", project: "p", site: "s", tls: ( cert_file: "x.pem" ) ) } ) )"#,
4210        )
4211        .expect_err("a tls block without a key_file must be refused");
4212        assert!(
4213            matches!(err, ConfigError::InvalidListener { .. }),
4214            "{err:?}"
4215        );
4216        // (c) a non-empty egress_allowlist (a tcp-connection-host guest can't hold wasi:sockets).
4217        let err = ServerConfig::parse(
4218            r#"( serve: ( listeners: { "l": ( bind: "0.0.0.0:9000", component: "c.wasm", project: "p", site: "s", egress_allowlist: ["x:443"] ) } ) )"#,
4219        )
4220        .expect_err("a non-empty per-listener egress_allowlist must be refused in Phase 1");
4221        assert!(
4222            matches!(err, ConfigError::InvalidListener { .. }),
4223            "{err:?}"
4224        );
4225        // (d) a valid plaintext listener parses.
4226        ServerConfig::parse(
4227            r#"( serve: ( listeners: { "l": ( bind: "0.0.0.0:9000", component: "c.wasm", project: "p", site: "s" ) } ) )"#,
4228        )
4229        .expect("a fully-declared plaintext listener is valid");
4230        // (e) a well-formed TLS listener (cert + key) now PARSES (cap-req 06).
4231        ServerConfig::parse(
4232            r#"( serve: ( listeners: { "l": ( bind: "0.0.0.0:9000", component: "c.wasm", project: "p", site: "s", tls: ( cert_file: "x.pem", key_file: "y.pem" ) ) } ) )"#,
4233        )
4234        .expect("a TLS listener with cert_file + key_file is valid");
4235        // (f) a well-formed STARTTLS listener (cert + key + grammar) PARSES (cap-req 06, Stage B) —
4236        //     SMTP-shaped and IMAP tag-capture-shaped.
4237        ServerConfig::parse(
4238            r#"( serve: ( listeners: { "l": ( bind: "0.0.0.0:587", component: "c.wasm", project: "p", site: "s", tls: ( cert_file: "x.pem", key_file: "y.pem", starttls: ( trigger: "STARTTLS", response: "220 2.0.0 Ready to start TLS" ) ) ) } ) )"#,
4239        )
4240        .expect("a well-formed SMTP STARTTLS listener is valid");
4241        ServerConfig::parse(
4242            r#"( serve: ( listeners: { "l": ( bind: "0.0.0.0:143", component: "c.wasm", project: "p", site: "s", tls: ( cert_file: "x.pem", key_file: "y.pem", starttls: ( trigger: "STARTTLS", response: "{tag} OK begin TLS", tag_capture: true ) ) ) } ) )"#,
4243        )
4244        .expect("a well-formed IMAP tag-capture STARTTLS listener is valid");
4245        // (g) `{tag}` in the response without tag_capture is refused (the literal would leak to the wire).
4246        let err = ServerConfig::parse(
4247            r#"( serve: ( listeners: { "l": ( bind: "0.0.0.0:587", component: "c.wasm", project: "p", site: "s", tls: ( cert_file: "x.pem", key_file: "y.pem", starttls: ( trigger: "STARTTLS", response: "{tag} OK" ) ) ) } ) )"#,
4248        )
4249        .expect_err("`{tag}` without tag_capture must be refused");
4250        assert!(
4251            matches!(err, ConfigError::InvalidListener { .. }),
4252            "{err:?}"
4253        );
4254        // (h) an empty trigger is refused.
4255        let err = ServerConfig::parse(
4256            r#"( serve: ( listeners: { "l": ( bind: "0.0.0.0:587", component: "c.wasm", project: "p", site: "s", tls: ( cert_file: "x.pem", key_file: "y.pem", starttls: ( trigger: "", response: "220 ok" ) ) ) } ) )"#,
4257        )
4258        .expect_err("an empty STARTTLS trigger must be refused");
4259        assert!(
4260            matches!(err, ConfigError::InvalidListener { .. }),
4261            "{err:?}"
4262        );
4263        // (i) a STARTTLS grammar WITHOUT cert/key is refused (STARTTLS still terminates TLS).
4264        let err = ServerConfig::parse(
4265            r#"( serve: ( listeners: { "l": ( bind: "0.0.0.0:587", component: "c.wasm", project: "p", site: "s", tls: ( starttls: ( trigger: "STARTTLS", response: "220 ok" ) ) ) } ) )"#,
4266        )
4267        .expect_err("a STARTTLS grammar without cert/key must be refused");
4268        assert!(
4269            matches!(err, ConfigError::InvalidListener { .. }),
4270            "{err:?}"
4271        );
4272        // (j) a listener `tls.on_demand = true` WITHOUT node on-demand TLS enabled is refused (cap-req
4273        //     03 #4): the per-SNI engine it would share does not exist, so it would silently no-op.
4274        let err = ServerConfig::parse(
4275            r#"( serve: ( listeners: { "l": ( bind: "0.0.0.0:465", component: "c.wasm", project: "p", site: "s", tls: ( cert_file: "x.pem", key_file: "y.pem", on_demand: true ) ) } ) )"#,
4276        )
4277        .expect_err("listener on_demand without [serve.on_demand_tls] enabled must be refused");
4278        assert!(
4279            matches!(err, ConfigError::InvalidListener { .. }),
4280            "{err:?}"
4281        );
4282        // (k) the same listener WITH node on-demand TLS enabled (+ its own cert/key + server_names)
4283        //     parses — it shares the one engine.
4284        ServerConfig::parse(
4285            r#"( serve: ( on_demand_tls: ( enabled: true ), listeners: { "l": ( bind: "0.0.0.0:465", component: "c.wasm", project: "p", site: "s", tls: ( cert_file: "x.pem", key_file: "y.pem", on_demand: true, server_names: ["mail.example.test"] ) ) } ) )"#,
4286        )
4287        .expect("a listener on_demand with node on-demand TLS enabled is valid");
4288    }
4289
4290    #[test]
4291    fn listener_env_covers_every_scalar_field() {
4292        // Forgot-a-knob guard (mirrors the blob-backend guard): every SCALAR field of `ListenerConfig`
4293        // with an env lever MUST have a suffix in `LISTENER_FIELD_SUFFIXES`, so a newly added scalar
4294        // can't silently lose its env knob. (The structured `imports`/`env`/`tenancy` + Phase-1-refused
4295        // `tls`/`egress_allowlist` are deliberately file-only; `_IMPORTS` is the one list lever.)
4296        let expected: &[&str] = &[
4297            "_BIND",
4298            "_COMPONENT",
4299            "_PROJECT",
4300            "_SITE",
4301            "_IMPORTS",
4302            "_MAX_CONNS",
4303            "_IDLE_TIMEOUT_MS",
4304            "_MAX_CONN_DURATION_MS",
4305        ];
4306        for suffix in expected {
4307            assert!(
4308                LISTENER_FIELD_SUFFIXES.contains(suffix),
4309                "{suffix} missing from LISTENER_FIELD_SUFFIXES — a listener field lost its env lever"
4310            );
4311        }
4312        assert_eq!(
4313            LISTENER_FIELD_SUFFIXES.len(),
4314            expected.len(),
4315            "LISTENER_FIELD_SUFFIXES has a suffix with no matching expected field (stale lever)"
4316        );
4317    }
4318
4319    #[test]
4320    fn blob_backend_rejects_the_reserved_default_project() {
4321        // Invariant 5: the reserved `default` project ALWAYS resolves the global `[serve]` backend, so
4322        // a `[serve.blob_backends.default]` entry is refused at load (fail-closed, boot-loud) — the
4323        // node-wide backend is configured under `[serve]`, not here.
4324        let err = ServerConfig::parse(
4325            r#"( serve: ( blob_backends: { "default": ( blobs: s3, s3_bucket: "x" ) } ) )"#,
4326        )
4327        .expect_err("a `default`-keyed per-project blob backend must be refused");
4328        assert!(
4329            matches!(err, ConfigError::InvalidBlobBackendProject { .. }),
4330            "reserved-default blob backend is InvalidBlobBackendProject, got {err:?}"
4331        );
4332    }
4333
4334    #[test]
4335    fn blob_backend_rejects_an_unsafe_project_name() {
4336        // A `blob_backends` key is a project name threaded into the per-project data-plane scope, so it
4337        // runs the canonical slug validator (fail-closed on a path-traversal / injection shape).
4338        let err = ServerConfig::parse(
4339            r#"( serve: ( blob_backends: { "../evil": ( blobs: s3, s3_bucket: "x" ) } ) )"#,
4340        )
4341        .expect_err("a path-traversal project key must be refused");
4342        assert!(
4343            matches!(err, ConfigError::InvalidBlobBackendProject { .. }),
4344            "unsafe blob-backend project name is InvalidBlobBackendProject, got {err:?}"
4345        );
4346    }
4347
4348    #[test]
4349    fn blob_backend_config_rejects_unknown_fields_and_inlined_secret_stays_a_ref() {
4350        // `deny_unknown_fields` on `BlobBackendConfig` + its `S3CredentialConfig` catches a typo'd key
4351        // at load; and the sealed credential's `secret_access_key` is stored verbatim as the REFERENCE
4352        // the operator wrote (a `boatramp:` name), never re-interpreted into a raw secret.
4353        let cfg = ServerConfig::parse(
4354            r#"( serve: ( blob_backends: { "acme": (
4355                blobs: s3,
4356                s3_bucket: "acme-blobs",
4357                s3_credential: ( access_key_id: "AKIA", secret_access_key: "boatramp:acme" ),
4358            ) } ) )"#,
4359        )
4360        .expect("a well-formed per-project blob backend parses");
4361        let be = cfg
4362            .serve
4363            .unwrap()
4364            .blob_backends
4365            .remove("acme")
4366            .expect("acme backend parsed");
4367        assert_eq!(be.blobs, Some(crate::backends::BlobBackend::S3));
4368        assert_eq!(
4369            be.s3_credential.unwrap().secret_access_key,
4370            "boatramp:acme",
4371            "the secret stays the indirect reference, never an inlined secret"
4372        );
4373        let bad = ServerConfig::parse(
4374            r#"( serve: ( blob_backends: { "acme": ( blobs: s3, bogus: 1 ) } ) )"#,
4375        );
4376        assert!(
4377            bad.is_err(),
4378            "an unknown [serve.blob_backends.<p>] field must be rejected (deny_unknown_fields)"
4379        );
4380    }
4381
4382    #[test]
4383    fn sql_binding_preview_policy() {
4384        let cfg = server(
4385            r#"(
4386                handlers: ( bindings: ( sql: (
4387                    preview_mode: "branch",
4388                    preview_init: "/etc/boatramp/seed.sql",
4389                ) ) ),
4390            )"#,
4391        );
4392        let sql = cfg.handlers.unwrap().bindings.sql.unwrap();
4393        assert_eq!(sql.preview_mode.as_deref(), Some("branch"));
4394        assert_eq!(
4395            sql.preview_init.as_deref(),
4396            Some(Path::new("/etc/boatramp/seed.sql"))
4397        );
4398    }
4399
4400    #[test]
4401    fn sql_binding_external_databases() {
4402        let cfg = server(
4403            r#"(
4404                handlers: ( bindings: ( sql: (
4405                    databases: {
4406                        "analytics": (
4407                            kind: "postgres",
4408                            url_env: "ANALYTICS_PG_URL",
4409                            pool_max: 16,
4410                            read_only: true,
4411                        ),
4412                        "events": (
4413                            kind: "mysql",
4414                            url_env: "EVENTS_MYSQL_URL",
4415                            read_url_env: "EVENTS_MYSQL_REPLICA_URL",
4416                            allow_preview: true,
4417                        ),
4418                    },
4419                ) ) ),
4420            )"#,
4421        );
4422        let sql = cfg.handlers.unwrap().bindings.sql.unwrap();
4423        assert_eq!(sql.databases.len(), 2);
4424
4425        let analytics = &sql.databases["analytics"];
4426        assert_eq!(analytics.kind, "postgres");
4427        assert_eq!(analytics.url_env, "ANALYTICS_PG_URL");
4428        assert_eq!(analytics.pool_max, Some(16));
4429        assert!(analytics.read_only);
4430        assert!(!analytics.allow_preview);
4431        assert!(analytics.read_url_env.is_none());
4432
4433        let events = &sql.databases["events"];
4434        assert_eq!(events.kind, "mysql");
4435        assert_eq!(
4436            events.read_url_env.as_deref(),
4437            Some("EVENTS_MYSQL_REPLICA_URL")
4438        );
4439        assert!(events.allow_preview);
4440        assert!(!events.read_only);
4441    }
4442
4443    #[test]
4444    fn sql_binding_compute_backed_database() {
4445        let cfg = server(
4446            r#"(
4447                handlers: ( bindings: ( sql: (
4448                    databases: {
4449                        "analytics": (
4450                            kind: "postgres",
4451                            compute: "pg",
4452                            database: "analytics",
4453                            user: "app",
4454                            password_env: "PG_APP_PW",
4455                        ),
4456                    },
4457                ) ) ),
4458            )"#,
4459        );
4460        let db = &cfg.handlers.unwrap().bindings.sql.unwrap().databases["analytics"];
4461        assert_eq!(db.kind, "postgres");
4462        assert_eq!(db.compute.as_deref(), Some("pg"));
4463        assert_eq!(db.database.as_deref(), Some("analytics"));
4464        assert_eq!(db.user.as_deref(), Some("app"));
4465        assert_eq!(db.password_env.as_deref(), Some("PG_APP_PW"));
4466        assert!(db.url_env.is_empty(), "compute-backed has no url_env");
4467        assert!(db.validate("analytics").is_ok());
4468    }
4469
4470    #[test]
4471    fn sql_binding_source_is_exactly_one_of_url_or_compute() {
4472        // Neither source → error.
4473        assert!(ExternalDatabaseConfig::default().validate("db").is_err());
4474        // Both sources → error.
4475        let both = ExternalDatabaseConfig {
4476            kind: "postgres".into(),
4477            url_env: "PG_URL".into(),
4478            compute: Some("pg".into()),
4479            ..Default::default()
4480        };
4481        assert!(both.validate("db").is_err());
4482        // `url_env` only → ok.
4483        let url = ExternalDatabaseConfig {
4484            kind: "postgres".into(),
4485            url_env: "PG_URL".into(),
4486            ..Default::default()
4487        };
4488        assert!(url.validate("db").is_ok());
4489        // `compute` without the connection details boatramp can't infer → error.
4490        let bare = ExternalDatabaseConfig {
4491            kind: "postgres".into(),
4492            compute: Some("pg".into()),
4493            ..Default::default()
4494        };
4495        assert!(bare.validate("db").is_err());
4496        // `compute` with database/user + a bring-your-own `password_env` → ok, and
4497        // is *not* a managed credential.
4498        let byo = ExternalDatabaseConfig {
4499            kind: "postgres".into(),
4500            compute: Some("pg".into()),
4501            database: Some("analytics".into()),
4502            user: Some("app".into()),
4503            password_env: Some("PG_APP_PW".into()),
4504            ..Default::default()
4505        };
4506        assert!(byo.validate("db").is_ok());
4507        assert!(!byo.is_managed_credential());
4508        // `compute` with database/user but NO `password_env` → ok, and boatramp
4509        // manages the credential (Phase 2).
4510        let managed = ExternalDatabaseConfig {
4511            kind: "postgres".into(),
4512            compute: Some("pg".into()),
4513            database: Some("analytics".into()),
4514            user: Some("app".into()),
4515            ..Default::default()
4516        };
4517        assert!(managed.validate("db").is_ok());
4518        assert!(managed.is_managed_credential());
4519    }
4520
4521    #[test]
4522    fn libsql_source_is_exactly_one_of_path_or_url() {
4523        // A single-node `libsql` file (path only) → ok.
4524        let file = ExternalDatabaseConfig {
4525            kind: "libsql".into(),
4526            path: Some("/data/app.db".into()),
4527            ..Default::default()
4528        };
4529        assert!(file.validate("app").is_ok());
4530        // `sqlite` alias works the same.
4531        let sqlite = ExternalDatabaseConfig {
4532            kind: "sqlite".into(),
4533            path: Some("/data/app.db".into()),
4534            ..Default::default()
4535        };
4536        assert!(sqlite.validate("app").is_ok());
4537        // A remote-sqld `libsql` (url_env only) → ok.
4538        let remote = ExternalDatabaseConfig {
4539            kind: "libsql".into(),
4540            url_env: "LIBSQL_URL".into(),
4541            ..Default::default()
4542        };
4543        assert!(remote.validate("app").is_ok());
4544        // Neither `path` nor `url_env` → error.
4545        let neither = ExternalDatabaseConfig {
4546            kind: "libsql".into(),
4547            ..Default::default()
4548        };
4549        assert!(neither.validate("app").is_err());
4550        // Both `path` and `url_env` → error (exactly one).
4551        let both = ExternalDatabaseConfig {
4552            kind: "libsql".into(),
4553            path: Some("/data/app.db".into()),
4554            url_env: "LIBSQL_URL".into(),
4555            ..Default::default()
4556        };
4557        assert!(both.validate("app").is_err());
4558        // `compute` on a `libsql` binding → error (boatramp doesn't run a libsql server workload).
4559        let compute = ExternalDatabaseConfig {
4560            kind: "libsql".into(),
4561            compute: Some("x".into()),
4562            path: Some("/data/app.db".into()),
4563            ..Default::default()
4564        };
4565        assert!(compute.validate("app").is_err());
4566        // `path` on a NON-libsql (postgres) binding → error (only libsql has an on-disk file).
4567        let pg_path = ExternalDatabaseConfig {
4568            kind: "postgres".into(),
4569            url_env: "PG_URL".into(),
4570            path: Some("/data/app.db".into()),
4571            ..Default::default()
4572        };
4573        assert!(pg_path.validate("db").is_err());
4574    }
4575
4576    /// Path to a file at the repo root (two levels up from this crate).
4577    fn repo_root_file(name: &str) -> PathBuf {
4578        Path::new(env!("CARGO_MANIFEST_DIR"))
4579            .join("../..")
4580            .join(name)
4581    }
4582
4583    #[test]
4584    fn shipped_project_example_parses() {
4585        // The example we ship must always parse + compile-check, so it can't drift
4586        // from the schema.
4587        let text = std::fs::read_to_string(repo_root_file("examples/site/project.cfg.example"))
4588            .expect("example project config is present");
4589        let cfg = ProjectConfig::parse(&text).expect("example project config parses");
4590        assert_eq!(cfg.publish.server.as_deref(), Some("http://127.0.0.1:8080"));
4591        assert_eq!(cfg.build.as_ref().unwrap().command, "npm run build");
4592        assert_eq!(
4593            cfg.routing.error_documents.get(&404).map(String::as_str),
4594            Some("/404.html")
4595        );
4596    }
4597
4598    #[test]
4599    fn shipped_server_example_parses() {
4600        let text = std::fs::read_to_string(repo_root_file("boatramp.cfg.example"))
4601            .expect("example server config is present");
4602        let cfg = ServerConfig::parse(&text).expect("example server config parses");
4603        let serve = cfg.serve.expect("example sets a serve section");
4604        assert_eq!(
4605            serve.addr,
4606            Some("0.0.0.0:8080".parse::<std::net::SocketAddr>().unwrap())
4607        );
4608    }
4609
4610    #[test]
4611    fn secrets_section_parses_local_and_vault() {
4612        let local = server(r#"( secrets: ( envelope: "local", kek_file: "/k/kek" ) )"#)
4613            .secrets
4614            .expect("secrets section");
4615        assert_eq!(local.envelope, "local");
4616        assert_eq!(
4617            local.kek_file.as_deref(),
4618            Some(std::path::Path::new("/k/kek"))
4619        );
4620
4621        let vault = server(
4622            r#"( secrets: ( envelope: "vault", vault: ( addr: "https://vault:8200", key: "certs" ) ) )"#,
4623        )
4624        .secrets
4625        .expect("secrets section");
4626        let v = vault.vault.expect("vault subsection");
4627        assert_eq!(v.addr, "https://vault:8200");
4628        assert_eq!(v.key, "certs");
4629        // The token env defaults to VAULT_TOKEN and is never in the file.
4630        assert_eq!(v.token_env, "VAULT_TOKEN");
4631    }
4632
4633    #[test]
4634    fn serve_section_partial_parses() {
4635        // A partial `serve` section parses — unset fields take their defaults.
4636        let cfg = server(r#"( serve: ( addr: "0.0.0.0:8080", protect_previews: true ) )"#);
4637        let serve = cfg.serve.unwrap();
4638        assert_eq!(
4639            serve.addr,
4640            Some("0.0.0.0:8080".parse::<std::net::SocketAddr>().unwrap())
4641        );
4642        assert!(serve.protect_previews);
4643        assert!(!serve.cluster_rate_limit);
4644        assert!(serve.data_dir.is_none());
4645    }
4646
4647    #[test]
4648    fn serve_console_config_parses() {
4649        // Absent ⇒ no console.
4650        let cfg = server(r#"( serve: ( addr: "0.0.0.0:8080" ) )"#);
4651        assert!(cfg.serve.unwrap().console.is_none());
4652        // Explicit console block with host + path.
4653        let cfg = server(
4654            r#"( serve: ( console: (
4655                enabled: true,
4656                host: "console.example.com",
4657                path: "/_console",
4658            ) ) )"#,
4659        );
4660        let console = cfg.serve.unwrap().console.unwrap();
4661        assert!(console.enabled);
4662        assert_eq!(console.host.as_deref(), Some("console.example.com"));
4663        assert_eq!(console.path.as_deref(), Some("/_console"));
4664        // Bare `enabled` ⇒ host/path take their (server-side) defaults.
4665        let cfg = server(r#"( serve: ( console: ( enabled: true ) ) )"#);
4666        let console = cfg.serve.unwrap().console.unwrap();
4667        assert!(console.enabled);
4668        assert!(console.host.is_none() && console.path.is_none());
4669    }
4670
4671    #[test]
4672    fn serve_s3_credential_config_parses() {
4673        // #505: absent ⇒ no sealed source (the ambient AWS env chain).
4674        let cfg = server(r#"( serve: ( addr: "0.0.0.0:8080" ) )"#);
4675        assert!(cfg.serve.unwrap().s3_credential.is_none());
4676        // An explicit `[serve.s3_credential]`: a plain `access_key_id` + a `boatramp:` sealed
4677        // `secret_access_key` ref (the config text carries only the REFERENCE, never the secret).
4678        let cfg = server(
4679            r#"( serve: ( s3_credential: (
4680                access_key_id: "tid_public_akid",
4681                secret_access_key: "boatramp:tigris-secret",
4682            ) ) )"#,
4683        );
4684        let cred = cfg.serve.unwrap().s3_credential.unwrap();
4685        assert_eq!(cred.access_key_id, "tid_public_akid");
4686        assert_eq!(cred.secret_access_key, "boatramp:tigris-secret");
4687        // An unknown field is rejected (`deny_unknown_fields`) — a fat-fingered key fails fast.
4688        let err: Result<ServerConfig, _> = ron_options().from_str(
4689            r#"( serve: ( s3_credential: ( access_key_id: "x", secret_access_key: "boatramp:y", bogus: 1 ) ) )"#,
4690        );
4691        assert!(
4692            err.is_err(),
4693            "unknown [serve.s3_credential] field must be rejected"
4694        );
4695    }
4696
4697    #[test]
4698    fn serve_blob_fallback_config_parses() {
4699        // Blob-backend migration Part 2: absent ⇒ no fallback (the read-through composite is not wired).
4700        let cfg = server(r#"( serve: ( addr: "0.0.0.0:8080" ) )"#);
4701        assert!(cfg.serve.unwrap().blob_fallback.is_none());
4702        // A `[serve.blob_fallback]` secondary: the OLD fs backend to drain while the primary is s3,
4703        // with its own sealed S3 credential ref and a custom secondary timeout.
4704        let cfg = server(
4705            r#"( serve: (
4706                blobs: s3,
4707                s3_bucket: "new-bucket",
4708                blob_fallback: (
4709                    blobs: fs,
4710                    secondary_timeout_secs: 3,
4711                    s3_credential: (
4712                        access_key_id: "old_akid",
4713                        secret_access_key: "boatramp:old-secret",
4714                    ),
4715                ),
4716            ) )"#,
4717        );
4718        let serve = cfg.serve.unwrap();
4719        let fb = serve.blob_fallback.unwrap();
4720        assert_eq!(fb.blobs, Some(crate::backends::BlobBackend::Fs));
4721        assert_eq!(fb.secondary_timeout_secs, Some(3));
4722        let cred = fb.s3_credential.unwrap();
4723        assert_eq!(cred.access_key_id, "old_akid");
4724        assert_eq!(cred.secret_access_key, "boatramp:old-secret");
4725        // An unknown field is rejected (`deny_unknown_fields`).
4726        let err: Result<ServerConfig, _> =
4727            ron_options().from_str(r#"( serve: ( blob_fallback: ( blobs: fs, bogus: 1 ) ) )"#);
4728        assert!(
4729            err.is_err(),
4730            "unknown [serve.blob_fallback] field must be rejected"
4731        );
4732    }
4733
4734    #[test]
4735    fn serve_kv_config_parses_and_defaults() {
4736        // Absent `[serve.kv]` ⇒ the defaults: periodic checkpoint ON at the default cadence, and the
4737        // generous default close budget (NOT the old 3s).
4738        let cfg = server(r#"( serve: ( addr: "0.0.0.0:8080" ) )"#);
4739        assert!(cfg.serve.unwrap().kv.is_none());
4740        let default_kv = super::KvConfig::default();
4741        assert_eq!(
4742            default_kv.checkpoint_interval(),
4743            Some(std::time::Duration::from_secs(
4744                super::DEFAULT_KV_CHECKPOINT_INTERVAL_SECS
4745            )),
4746            "an absent/unset checkpoint_interval defaults to the ON cadence"
4747        );
4748        assert_eq!(
4749            default_kv.close_deadline(),
4750            std::time::Duration::from_secs(super::DEFAULT_KV_CLOSE_DEADLINE_SECS),
4751            "an absent/unset close_deadline defaults to the generous budget"
4752        );
4753        // The online maintenance-GC knobs default ON (15 min) with a conservative 1h min_age.
4754        assert_eq!(
4755            default_kv.gc_interval(),
4756            Some(std::time::Duration::from_secs(
4757                super::DEFAULT_KV_GC_INTERVAL_SECS
4758            )),
4759            "an absent/unset gc_interval defaults to the ON cadence"
4760        );
4761        assert_eq!(
4762            default_kv.gc_min_age(),
4763            std::time::Duration::from_secs(super::DEFAULT_KV_GC_MIN_AGE_SECS),
4764            "an absent/unset gc_min_age defaults to the conservative 1h floor"
4765        );
4766
4767        // An explicit block: a tuned cadence + a tuned close budget + tuned GC knobs, now nested under
4768        // `slatedb` (UX-C3) so they never appear to apply under a non-SlateDB backend.
4769        let cfg = server(
4770            r#"( serve: ( kv: ( slatedb: ( checkpoint_interval: 5, close_deadline: 30, gc_interval: 300, gc_min_age: 600 ) ) ) )"#,
4771        );
4772        let kv = cfg.serve.unwrap().kv.unwrap();
4773        assert_eq!(
4774            kv.checkpoint_interval(),
4775            Some(std::time::Duration::from_secs(5))
4776        );
4777        assert_eq!(kv.close_deadline(), std::time::Duration::from_secs(30));
4778        assert_eq!(kv.gc_interval(), Some(std::time::Duration::from_secs(300)));
4779        assert_eq!(kv.gc_min_age(), std::time::Duration::from_secs(600));
4780
4781        // checkpoint_interval = 0 DISABLES the cadence; a 0 close_deadline falls back to the default
4782        // (a zero close budget would abandon every close, guaranteeing a torn tail — never allowed).
4783        // gc_interval = 0 DISABLES the maintenance task; a 0 gc_min_age clamps up to the default (a
4784        // zero min_age would reintroduce the reader-mid-scan deletion hazard — never allowed).
4785        let cfg = server(
4786            r#"( serve: ( kv: ( slatedb: ( checkpoint_interval: 0, close_deadline: 0, gc_interval: 0, gc_min_age: 0 ) ) ) )"#,
4787        );
4788        let kv = cfg.serve.unwrap().kv.unwrap();
4789        assert_eq!(kv.checkpoint_interval(), None, "0 disables the cadence");
4790        assert_eq!(
4791            kv.close_deadline(),
4792            std::time::Duration::from_secs(super::DEFAULT_KV_CLOSE_DEADLINE_SECS),
4793            "a 0 close_deadline is clamped up to the default, never zero"
4794        );
4795        assert_eq!(kv.gc_interval(), None, "0 disables the maintenance GC task");
4796        assert_eq!(
4797            kv.gc_min_age(),
4798            std::time::Duration::from_secs(super::DEFAULT_KV_GC_MIN_AGE_SECS),
4799            "a 0 gc_min_age is clamped up to the conservative default, never zero"
4800        );
4801
4802        // The SQL KV backend connection parses under `sql` (UX-C2: `url_env`, never a raw URL).
4803        let cfg = server(r#"( serve: ( kv: ( sql: ( kind: "sqlite", path: "/data/kv.db" ) ) ) )"#);
4804        let sql = cfg.serve.unwrap().kv.unwrap().sql.unwrap();
4805        assert_eq!(sql.kind, "sqlite");
4806        assert_eq!(sql.path.as_deref(), Some("/data/kv.db"));
4807
4808        // UX-C3: a pre-v0.12.0 TOP-LEVEL durability knob now fails loud (it moved under `slatedb`),
4809        // never silently mislead — `deny_unknown_fields` rejects it at the `[serve.kv]` level.
4810        let err: Result<ServerConfig, _> =
4811            ron_options().from_str(r#"( serve: ( kv: ( checkpoint_interval: 5 ) ) )"#);
4812        assert!(
4813            err.is_err(),
4814            "a top-level checkpoint_interval must be rejected (moved under [serve.kv.slatedb])"
4815        );
4816
4817        // An unknown field inside the `slatedb` sub-block is rejected (`deny_unknown_fields`).
4818        let err: Result<ServerConfig, _> = ron_options()
4819            .from_str(r#"( serve: ( kv: ( slatedb: ( checkpoint_interval: 5, bogus: 1 ) ) ) )"#);
4820        assert!(
4821            err.is_err(),
4822            "unknown [serve.kv.slatedb] field must be rejected"
4823        );
4824    }
4825
4826    // =======================================================================
4827    // JSON config input gate (v0.6.5) — serve/project config + detection half.
4828    //
4829    // ROBUST-successor gate (continuing the v0.6.4 blob-purge style): a `#[test]`
4830    // battery whose sole CI contract is the ordinary `cargo test` exit code — NO
4831    // grepped uppercase marker, NO bash env-var mutation loop. Every test is prefixed
4832    // `config_json_gate_` so the CI lane filters with `cargo test … config_json`. The
4833    // apply-manifest half (version current-schema-only, bad-route compile-check) lives
4834    // in `boatramp::apply`'s test module under the same prefix.
4835    // =======================================================================
4836
4837    /// Detection: `resolve_format` follows the explicit-override-wins, else
4838    /// `.json`⇒Json / everything-else⇒Ron rule (no content-sniffing).
4839    #[test]
4840    fn config_json_gate_resolve_format_table() {
4841        use std::path::Path;
4842        // Auto by extension.
4843        assert_eq!(
4844            resolve_format(Path::new("boatramp.json"), None),
4845            ConfigFormat::Json
4846        );
4847        assert_eq!(
4848            resolve_format(Path::new("apply.cfg"), None),
4849            ConfigFormat::Ron
4850        );
4851        assert_eq!(
4852            resolve_format(Path::new("apply.ron"), None),
4853            ConfigFormat::Ron
4854        );
4855        // No extension ⇒ Ron.
4856        assert_eq!(resolve_format(Path::new("apply"), None), ConfigFormat::Ron);
4857        // Case-insensitive `.json`.
4858        assert_eq!(
4859            resolve_format(Path::new("x.JSON"), None),
4860            ConfigFormat::Json
4861        );
4862        // Explicit override wins BOTH ways.
4863        assert_eq!(
4864            resolve_format(Path::new("x.json"), Some(ConfigFormat::Ron)),
4865            ConfigFormat::Ron
4866        );
4867        assert_eq!(
4868            resolve_format(Path::new("x.cfg"), Some(ConfigFormat::Json)),
4869            ConfigFormat::Json
4870        );
4871    }
4872
4873    /// Equivalence: a representative serve config authored in RON and in equivalent
4874    /// JSON parses to the SAME field values — including the externally-tagged
4875    /// enum-variant field `[serve].blobs` (`BlobBackend::S3`; RON `s3` ≡ JSON `"s3"`),
4876    /// proving variant-name fidelity through the JSON decoder.
4877    #[test]
4878    fn config_json_gate_serve_ron_and_json_are_equivalent() {
4879        let ron = r#"( serve: ( addr: "0.0.0.0:8080", blobs: s3, s3_bucket: "b" ) )"#;
4880        let json = r#"{ "serve": { "addr": "0.0.0.0:8080", "blobs": "s3", "s3_bucket": "b" } }"#;
4881        let from_ron = ServerConfig::parse_with_format(ron, ConfigFormat::Ron).unwrap();
4882        let from_json = ServerConfig::parse_with_format(json, ConfigFormat::Json).unwrap();
4883        let s_ron = from_ron.serve.unwrap();
4884        let s_json = from_json.serve.unwrap();
4885        assert_eq!(s_ron.blobs, Some(crate::backends::BlobBackend::S3));
4886        assert_eq!(s_json.blobs, Some(crate::backends::BlobBackend::S3));
4887        assert_eq!(s_ron.blobs, s_json.blobs, "the enum variant survives JSON");
4888        assert_eq!(s_ron.addr, s_json.addr);
4889        assert_eq!(s_ron.s3_bucket, s_json.s3_bucket);
4890        assert_eq!(s_json.s3_bucket.as_deref(), Some("b"));
4891    }
4892
4893    /// Equivalence (project): a `project.cfg` authored in RON and in equivalent JSON
4894    /// parses to the same publish target.
4895    #[test]
4896    fn config_json_gate_project_ron_and_json_are_equivalent() {
4897        let ron = r#"( publish: ( project: "team-x" ) )"#;
4898        let json = r#"{ "publish": { "project": "team-x" } }"#;
4899        let from_ron = ProjectConfig::parse_with_format(ron, ConfigFormat::Ron).unwrap();
4900        let from_json = ProjectConfig::parse_with_format(json, ConfigFormat::Json).unwrap();
4901        assert_eq!(from_ron.publish.project.as_deref(), Some("team-x"));
4902        assert_eq!(from_ron.publish.project, from_json.publish.project);
4903    }
4904
4905    /// `deny_unknown_fields` parity: a JSON serve config with an extra/typo'd field is
4906    /// a hard parse error, not a silent drop (the `[serve.blob_fallback]`
4907    /// `deny_unknown_fields` struct is the RON parity partner tested above).
4908    #[test]
4909    fn config_json_gate_serve_json_denies_unknown_fields() {
4910        let json = r#"{ "serve": { "blob_fallback": { "blobs": "fs", "bogus": 1 } } }"#;
4911        assert!(
4912            ServerConfig::parse_with_format(json, ConfigFormat::Json).is_err(),
4913            "an unknown JSON field must be rejected (deny_unknown_fields), same as RON"
4914        );
4915    }
4916
4917    /// No-bypass: post-parse validation runs regardless of format. A JSON serve config
4918    /// with an invalid `handlers.bindings.sql.databases` db-name (a `/`-bearing,
4919    /// non-URL-path-safe name) is rejected identically to RON — the SAME
4920    /// `ConfigError::InvalidDbName`, from the SAME `validate_sql_db_names` choke point.
4921    #[test]
4922    fn config_json_gate_json_bad_db_name_is_rejected_like_ron() {
4923        // The invalid binding name `a/b` (a path separator) fails the canonical
4924        // resource-name validator that `validate_sql_db_names` runs after the parse.
4925        let json = r#"{ "handlers": { "bindings": { "sql": {
4926            "databases": { "a/b": { "kind": "postgres", "url_env": "DB_URL" } }
4927        } } } }"#;
4928        let ron = r#"( handlers: ( bindings: ( sql: (
4929            databases: { "a/b": ( kind: "postgres", url_env: "DB_URL" ) }
4930        ) ) ) )"#;
4931        let json_err = ServerConfig::parse_with_format(json, ConfigFormat::Json)
4932            .expect_err("a bad db-name in a JSON config must be rejected");
4933        let ron_err = ServerConfig::parse_with_format(ron, ConfigFormat::Ron)
4934            .expect_err("a bad db-name in a RON config must be rejected");
4935        assert!(
4936            matches!(json_err, ConfigError::InvalidDbName { .. }),
4937            "JSON bad db-name is InvalidDbName, got {json_err:?}"
4938        );
4939        assert!(
4940            matches!(ron_err, ConfigError::InvalidDbName { .. }),
4941            "RON bad db-name is InvalidDbName, got {ron_err:?}"
4942        );
4943    }
4944
4945    /// Anti-hollow (typed, in-process): a document valid as JSON but NOT as RON MUST
4946    /// parse under `Json` and FAIL under `Ron`. If `parse_with_format` ignored `fmt`
4947    /// and always decoded RON, the JSON leg would fail — so the format selection is
4948    /// proven load-bearing, with no env var and no marker.
4949    #[test]
4950    fn config_json_gate_serve_format_selection_is_load_bearing() {
4951        // A bare JSON object is valid JSON for `ServerConfig`, not valid RON for it
4952        // (RON structs use `( … )`, not a brace map).
4953        let doc = r#"{ "serve": { "s3_bucket": "only-json" } }"#;
4954        let as_json = ServerConfig::parse_with_format(doc, ConfigFormat::Json).unwrap();
4955        assert_eq!(
4956            as_json.serve.unwrap().s3_bucket.as_deref(),
4957            Some("only-json")
4958        );
4959        assert!(
4960            ServerConfig::parse_with_format(doc, ConfigFormat::Ron).is_err(),
4961            "the same document must FAIL under Ron — else the fmt selection is hollow"
4962        );
4963    }
4964}
4965
4966// ============================================================================
4967// The single figment-based config resolver (serve + every offline op).
4968// ============================================================================
4969//
4970// This module is the config system (shipped in v0.35.0; design record in
4971// docs/config-figment-migration.md). `load_with_figment` merges, in order,
4972//   base-seed → file → `BOATRAMP_*` env → explicit CLI flags
4973// into ONE `ServerConfig`, used by `ServerConfig::load` (serve AND the offline ops:
4974// `migrate`, `blob`, `token`). It REPLACED the three hand-rolled env loaders:
4975//
4976//   A. the serve clap `#[arg(env = …)]` layer (serve-only),
4977//   B. `apply_env_overrides` (ran in `load`, so everywhere), and
4978//   C. ad-hoc `std::env::var` reads in serve (serve-only).
4979//
4980// The core bug it fixed: A & C were serve-only, so `BOATRAMP_S3_BUCKET` (and the
4981// serve/kv knobs) were honored by `serve` but NOT by `migrate`/`blob` — the offline
4982// ops that most need them. Now the env surface is uniform across all subcommands.
4983//
4984// ## Design: emit strings, extract lossy
4985//
4986// The env/flag overlay emits every scalar as a STRING value (trimmed), lists as
4987// arrays, and the (rare) rename_all enums as their lowercased token. Nothing is
4988// parsed here, so the overlay is infallible. At extraction `Figment::extract_lossy`
4989// coerces each string to the target field's type:
4990//   * bool fields  — via `Value::to_bool_lossy` (`true/yes/1/on` + `false/no/0/off`,
4991//     case-insensitive — the spellings the old `parse_bool` accepted);
4992//   * numeric fields — via `to_num_lossy` (a non-numeric value fails to deserialize
4993//     LOUDLY — a malformed value is rejected, never silently defaulted);
4994//   * string / enum / path / socket-addr fields read the string directly.
4995// A string destined for a string field is never coerced (lossy only fires when the
4996// TARGET is bool/number), so a numeric-looking bucket name or region survives.
4997//
4998// ## Faithful, drift-proof mapping
4999//
5000// The fixed-var overlay is DRIVEN BY the `*_ENV_VARS` const tables (+ the explicit
5001// `SERVE_SCALARS` / `SERVE_KV` alias tables for the irregular serve names), deriving
5002// each config path by the section's rule (drop `serve`, drop `bindings`, drop
5003// `overrides`, …). Those tables are now the SINGLE source of truth; the forgot-a-knob
5004// guard tests assert every struct field has a table entry, and the drift guards assert
5005// every table entry is honored by the overlay — field ↔ var ↔ overlay, no drift.
5006pub(crate) mod figment_resolve {
5007    use super::*;
5008    use figment::providers::Serialized;
5009    use figment::value::{Dict, Map as FigMap, Tag, Value};
5010    use figment::{Error, Figment, Metadata, Profile, Provider};
5011
5012    /// Vars whose value is a comma-separated list (trimmed, empty items dropped —
5013    /// `EnvSource::parse_list` semantics), emitted as a figment `Array`.
5014    const LIST_VARS: &[&str] = &[
5015        "BOATRAMP_COMPUTE_KERNEL_SIGNING_PUBKEYS",
5016        "BOATRAMP_COMPUTE_KERNEL_ALLOWED_HASHES",
5017        "BOATRAMP_HANDLERS_SQL_MIGRATE_TRUSTED_EXTENSIONS",
5018        "BOATRAMP_CLUSTER_ROOT_PUBKEYS",
5019        "BOATRAMP_CLUSTER_SEEDS",
5020    ];
5021
5022    /// Vars whose target is a `rename_all = "lowercase"` enum with no `FromStr`.
5023    /// `apply_env_overrides` matches these case-insensitively against a lowercase
5024    /// variant table; we emit the lowercased token so serde deserializes the same
5025    /// variant. (The per-backend `_KIND` inside the blob-backends map is handled inline.)
5026    const ENUM_VARS: &[&str] = &[
5027        "BOATRAMP_BLOBS",
5028        "BOATRAMP_COMPUTE_MANAGED_DB_PRIVILEGE",
5029        "BOATRAMP_COMPUTE_DOCKER_ENDPOINT",
5030        "BOATRAMP_COMPUTE_DOCKER_VOLUME_MODE",
5031    ];
5032
5033    /// The `serve.*` scalar aliases (the former Loader-A clap `#[arg(env)]` surface,
5034    /// unified here). Explicit (env → path) pairs because the env names are irregular —
5035    /// they drop the `serve` segment (`BOATRAMP_ADDR`, not `BOATRAMP_SERVE_ADDR`) and one
5036    /// is a field-name mismatch (`BOATRAMP_UPLOAD_IDLE_TIMEOUT` → `upload_idle_timeout_secs`)
5037    /// — so the mapping is aliased, never path-derived (risk P1). Bool/numeric fields are
5038    /// emitted as strings and coerced by `extract_lossy`; `blobs` is in `ENUM_VARS`.
5039    /// (The file-only serve fields — `s3_ingress_*`, `blob_notify_*`, `console`, `signer`,
5040    /// `blob_fallback`, `s3_credential` — have no clap/env today and stay file-only, carried
5041    /// by the figment file layer.) `auth_root_private_key` / `bootstrap_secret` /
5042    /// `azure_access_key` are secret-bearing config fields (as they are today via clap); they
5043    /// resolve into the config but are REDACTED by `config dump`/`explain`.
5044    const SERVE_SCALARS: &[(&str, &[&str])] = &[
5045        ("BOATRAMP_BLOBS", &["serve", "blobs"]),
5046        ("BOATRAMP_S3_BUCKET", &["serve", "s3_bucket"]),
5047        ("BOATRAMP_S3_ENDPOINT", &["serve", "s3_endpoint"]),
5048        ("BOATRAMP_S3_REGION", &["serve", "s3_region"]),
5049        ("BOATRAMP_S3_PATH_STYLE", &["serve", "s3_path_style"]),
5050        ("BOATRAMP_ADDR", &["serve", "addr"]),
5051        ("BOATRAMP_DATA_DIR", &["serve", "data_dir"]),
5052        ("BOATRAMP_GCS_BUCKET", &["serve", "gcs_bucket"]),
5053        ("BOATRAMP_GCS_ENDPOINT", &["serve", "gcs_endpoint"]),
5054        ("BOATRAMP_GCS_ANONYMOUS", &["serve", "gcs_anonymous"]),
5055        ("BOATRAMP_AZURE_ACCOUNT", &["serve", "azure_account"]),
5056        ("BOATRAMP_AZURE_CONTAINER", &["serve", "azure_container"]),
5057        ("BOATRAMP_AZURE_ACCESS_KEY", &["serve", "azure_access_key"]),
5058        ("BOATRAMP_AZURE_EMULATOR", &["serve", "azure_emulator"]),
5059        (
5060            "BOATRAMP_AUTH_ROOT_PRIVATE_KEY",
5061            &["serve", "auth_root_private_key"],
5062        ),
5063        (
5064            "BOATRAMP_AUTH_ROOT_PUBLIC_KEY",
5065            &["serve", "auth_root_public_key"],
5066        ),
5067        ("BOATRAMP_BOOTSTRAP_SECRET", &["serve", "bootstrap_secret"]),
5068        ("BOATRAMP_MAX_UPLOAD_BYTES", &["serve", "max_upload_bytes"]),
5069        (
5070            "BOATRAMP_UPLOAD_IDLE_TIMEOUT",
5071            &["serve", "upload_idle_timeout_secs"],
5072        ),
5073        (
5074            "BOATRAMP_MAX_CONCURRENT_UPLOADS",
5075            &["serve", "max_concurrent_uploads"],
5076        ),
5077        (
5078            "BOATRAMP_HTTP_REDIRECT_ADDR",
5079            &["serve", "http_redirect_addr"],
5080        ),
5081        ("BOATRAMP_DEFAULT_SITE", &["serve", "default_site"]),
5082        ("BOATRAMP_POP_ORIGIN", &["serve", "pop_origin"]),
5083        ("BOATRAMP_PROTECT_PREVIEWS", &["serve", "protect_previews"]),
5084        (
5085            "BOATRAMP_CLUSTER_RATE_LIMIT",
5086            &["serve", "cluster_rate_limit"],
5087        ),
5088        (
5089            "BOATRAMP_SHARED_CACHE_COHERENCE",
5090            &["serve", "shared_cache_coherence"],
5091        ),
5092    ];
5093
5094    /// The `serve.kv.*` aliases (the former Loader-C ad-hoc `std::env::var` surface). The env
5095    /// names drop BOTH `serve` and (for slatedb) the `slatedb` segment, so they are aliased
5096    /// explicitly (risk P1/P10). The `0`-disables-cadence semantics are preserved by
5097    /// `KvConfig::{checkpoint_interval,gc_interval}` reading the resolved `Some(0)`.
5098    /// (The Loader-C RUNTIME knobs that are NOT config fields — `BOATRAMP_KV_AUTHZ_FENCE_SECS`,
5099    /// `BOATRAMP_POD_NAME`, `BOATRAMP_COMPUTE_RECONCILE_TICK_MS`/`_NET_DEBUG` — stay as direct
5100    /// serve reads and are intentionally NOT mapped into the config, matching today.)
5101    const SERVE_KV: &[(&str, &[&str])] = &[
5102        (
5103            "BOATRAMP_KV_CHECKPOINT_INTERVAL",
5104            &["serve", "kv", "slatedb", "checkpoint_interval"],
5105        ),
5106        (
5107            "BOATRAMP_KV_CLOSE_DEADLINE",
5108            &["serve", "kv", "slatedb", "close_deadline"],
5109        ),
5110        (
5111            "BOATRAMP_KV_GC_INTERVAL",
5112            &["serve", "kv", "slatedb", "gc_interval"],
5113        ),
5114        (
5115            "BOATRAMP_KV_GC_MIN_AGE",
5116            &["serve", "kv", "slatedb", "gc_min_age"],
5117        ),
5118        ("BOATRAMP_KV_SQL_KIND", &["serve", "kv", "sql", "kind"]),
5119        ("BOATRAMP_KV_SQL_PATH", &["serve", "kv", "sql", "path"]),
5120        (
5121            "BOATRAMP_KV_SQL_URL_ENV",
5122            &["serve", "kv", "sql", "url_env"],
5123        ),
5124        (
5125            "BOATRAMP_KV_SQL_POOL_MAX",
5126            &["serve", "kv", "sql", "pool_max"],
5127        ),
5128    ];
5129
5130    /// Insert `value` at the nested `path`, creating intermediate dicts as needed.
5131    fn put(dict: &mut Dict, path: &[&str], value: Value) {
5132        let (last, parents) = path.split_last().expect("path is non-empty");
5133        let mut cursor = dict;
5134        for seg in parents {
5135            let entry = cursor
5136                .entry((*seg).to_string())
5137                .or_insert_with(|| Value::Dict(Tag::Default, Dict::new()));
5138            if !matches!(entry, Value::Dict(..)) {
5139                *entry = Value::Dict(Tag::Default, Dict::new());
5140            }
5141            cursor = match entry {
5142                Value::Dict(_, inner) => inner,
5143                _ => unreachable!("entry was just forced to a Dict"),
5144            };
5145        }
5146        cursor.insert((*last).to_string(), value);
5147    }
5148
5149    /// Emit the right value KIND for `var` (list / enum / plain scalar) at `path`,
5150    /// iff the var is set to a non-empty value.
5151    ///
5152    /// Scalar values are **trimmed**: the legacy `parse_bool`/`parse`/`parse_enum` all did
5153    /// `.trim()`, and figment's `to_bool_lossy` does NOT trim — so without this a templated
5154    /// `BOATRAMP_..._BOOL="true\n"` (fly.toml / k8s block scalar) would fail to coerce
5155    /// instead of parsing `true`. Trimming the string scalars too is harmless (a config
5156    /// value's surrounding whitespace is never meaningful, and `get` already treats a
5157    /// whitespace-only value as unset). A trimmed-to-empty value is dropped (unset).
5158    fn emit(dict: &mut Dict, source: &EnvSource, var: &str, path: &[&str]) {
5159        if LIST_VARS.contains(&var) {
5160            if let Some(items) = source.parse_list(var) {
5161                put(dict, path, Value::from(items));
5162            }
5163        } else if ENUM_VARS.contains(&var) {
5164            if let Some(v) = source.get(var) {
5165                put(dict, path, Value::from(v.trim().to_ascii_lowercase()));
5166            }
5167        } else if let Some(v) = source.get(var) {
5168            let trimmed = v.trim();
5169            if !trimmed.is_empty() {
5170                put(dict, path, Value::from(trimmed.to_string()));
5171            }
5172        }
5173    }
5174
5175    /// `var` with `prefix` stripped, lowercased — the config field name for the
5176    /// section whose env vars are `<prefix><FIELD>` (the inverse of the uppercasing
5177    /// the forgot-a-knob guards assert).
5178    fn field_of(var: &str, prefix: &str) -> String {
5179        var.strip_prefix(prefix)
5180            .expect("var belongs to this section's prefix")
5181            .to_ascii_lowercase()
5182    }
5183
5184    /// Build the `BOATRAMP_*` environment overlay as a figment `Dict`. Infallible
5185    /// (see the module docs); a malformed value is rejected at `extract_lossy`.
5186    pub(crate) fn env_overlay_dict(source: &EnvSource) -> Dict {
5187        let mut d = Dict::new();
5188
5189        // --- serve.* scalars (former Loader-A) + serve.kv.* (former Loader-C) ----
5190        for (var, path) in SERVE_SCALARS.iter().chain(SERVE_KV) {
5191            emit(&mut d, source, var, path);
5192        }
5193
5194        // --- compute (`compute.<field>`) ----------------------------------------
5195        for var in COMPUTE_ENV_VARS {
5196            let field = field_of(var, "BOATRAMP_COMPUTE_");
5197            emit(&mut d, source, var, &["compute", field.as_str()]);
5198        }
5199
5200        // --- security (`security.profile` + `security.overrides.<field>`) -------
5201        for var in SECURITY_ENV_VARS {
5202            if *var == "BOATRAMP_SECURITY_PROFILE" {
5203                emit(&mut d, source, var, &["security", "profile"]);
5204            } else {
5205                let field = field_of(var, "BOATRAMP_SECURITY_");
5206                emit(
5207                    &mut d,
5208                    source,
5209                    var,
5210                    &["security", "overrides", field.as_str()],
5211                );
5212            }
5213        }
5214
5215        // --- handlers: sql binding scalars (`handlers.bindings.sql.<field>`) ----
5216        // (`bindings` is dropped from the env name — the P1 rename the alias rule
5217        // reproduces.)
5218        for var in SQL_ENV_VARS {
5219            let field = field_of(var, "BOATRAMP_HANDLERS_SQL_");
5220            emit(
5221                &mut d,
5222                source,
5223                var,
5224                &["handlers", "bindings", "sql", field.as_str()],
5225            );
5226        }
5227
5228        // --- handlers: jwks / concurrency / blob-hedge scalars (`handlers.<f>`) --
5229        for var in JWKS_ENV_VARS
5230            .iter()
5231            .chain(HANDLER_CONCURRENCY_ENV_VARS)
5232            .chain(HANDLER_BLOB_HEDGE_ENV_VARS)
5233            .chain(HANDLER_COLDSTART_ENV_VARS)
5234        {
5235            let field = field_of(var, "BOATRAMP_HANDLERS_");
5236            emit(&mut d, source, var, &["handlers", field.as_str()]);
5237        }
5238
5239        // --- serve.s3_ingress_cloud (`serve` dropped from the env name) ---------
5240        for var in S3_INGRESS_CLOUD_ENV_VARS {
5241            let field = field_of(var, "BOATRAMP_S3_INGRESS_CLOUD_");
5242            emit(
5243                &mut d,
5244                source,
5245                var,
5246                &["serve", "s3_ingress_cloud", field.as_str()],
5247            );
5248        }
5249
5250        // --- secrets (+ nested vault) -------------------------------------------
5251        for var in SECRETS_ENV_VARS {
5252            if let Some(rest) = var.strip_prefix("BOATRAMP_SECRETS_VAULT_") {
5253                emit(
5254                    &mut d,
5255                    source,
5256                    var,
5257                    &["secrets", "vault", rest.to_ascii_lowercase().as_str()],
5258                );
5259            } else {
5260                let field = field_of(var, "BOATRAMP_SECRETS_");
5261                emit(&mut d, source, var, &["secrets", field.as_str()]);
5262            }
5263        }
5264
5265        // --- cluster (+ nested mesh) --------------------------------------------
5266        // The overlay always emits a cluster field when set; the `listen`
5267        // requirement (ClusterConfig has no Default) is enforced LOUDLY at extract,
5268        // rather than silently dropped as `apply_env_overrides` did for an env-only
5269        // cluster without a listen. See the plan's parity notes.
5270        for var in CLUSTER_ENV_VARS {
5271            if let Some(rest) = var.strip_prefix("BOATRAMP_CLUSTER_MESH_") {
5272                emit(
5273                    &mut d,
5274                    source,
5275                    var,
5276                    &["cluster", "mesh", rest.to_ascii_lowercase().as_str()],
5277                );
5278            } else {
5279                let field = field_of(var, "BOATRAMP_CLUSTER_");
5280                emit(&mut d, source, var, &["cluster", field.as_str()]);
5281            }
5282        }
5283
5284        // --- dynamic maps (P0: the generic Env provider cannot do these) --------
5285        blob_backends_overlay(&mut d, source);
5286        sql_databases_overlay(&mut d, source);
5287        listeners_overlay(&mut d, source);
5288
5289        d
5290    }
5291
5292    /// `[serve.blob_backends.<project>]` — keyed by project, member names scanned
5293    /// from the environment (there is no file to enumerate them). Mirrors the
5294    /// `apply_env_overrides` block, flattening the sealed credential's two public
5295    /// refs under `s3_credential`.
5296    fn blob_backends_overlay(d: &mut Dict, source: &EnvSource) {
5297        for name in source.blob_backend_projects() {
5298            let prefix = format!("{BLOB_BACKEND_ENV_PREFIX}{name}_");
5299            let n = name.as_str();
5300            if let Some(v) = source.get(&format!("{prefix}KIND")) {
5301                put(
5302                    d,
5303                    &["serve", "blob_backends", n, "blobs"],
5304                    Value::from(v.trim().to_ascii_lowercase()),
5305                );
5306            }
5307            for (suffix, field) in [
5308                ("S3_BUCKET", "s3_bucket"),
5309                ("S3_ENDPOINT", "s3_endpoint"),
5310                ("S3_REGION", "s3_region"),
5311                ("S3_PATH_STYLE", "s3_path_style"),
5312            ] {
5313                if let Some(v) = source.get(&format!("{prefix}{suffix}")) {
5314                    put(d, &["serve", "blob_backends", n, field], Value::from(v));
5315                }
5316            }
5317            if let Some(v) = source.get(&format!("{prefix}S3_ACCESS_KEY_ID")) {
5318                put(
5319                    d,
5320                    &[
5321                        "serve",
5322                        "blob_backends",
5323                        name.as_str(),
5324                        "s3_credential",
5325                        "access_key_id",
5326                    ],
5327                    Value::from(v),
5328                );
5329            }
5330            if let Some(v) = source.get(&format!("{prefix}S3_SECRET_ACCESS_KEY")) {
5331                put(
5332                    d,
5333                    &[
5334                        "serve",
5335                        "blob_backends",
5336                        name.as_str(),
5337                        "s3_credential",
5338                        "secret_access_key",
5339                    ],
5340                    Value::from(v),
5341                );
5342            }
5343        }
5344    }
5345
5346    /// `handlers.bindings.sql.databases.<name>` — keyed external-DB map. The
5347    /// reserved `DEFAULT` env token maps to the real key `"default"`
5348    /// (`DEFAULT_DB_NAME`); every other name is used verbatim.
5349    fn sql_databases_overlay(d: &mut Dict, source: &EnvSource) {
5350        for name in source.sql_database_names() {
5351            let key = if name == "DEFAULT" {
5352                boatramp_core::project::DEFAULT_DB_NAME.to_string()
5353            } else {
5354                name.clone()
5355            };
5356            let prefix = format!("{SQL_DB_ENV_PREFIX}{name}_");
5357            let k = key.as_str();
5358            // scalar string fields
5359            for (suffix, field) in [
5360                ("KIND", "kind"),
5361                ("URL_ENV", "url_env"),
5362                ("READ_URL_ENV", "read_url_env"),
5363                ("COMPUTE", "compute"),
5364                ("DATABASE", "database"),
5365                ("USER", "user"),
5366                ("PASSWORD_ENV", "password_env"),
5367                ("POOL_MAX", "pool_max"),
5368                ("READ_ONLY", "read_only"),
5369                ("ALLOW_PREVIEW", "allow_preview"),
5370                ("CONNECT_TIMEOUT_SECS", "connect_timeout_secs"),
5371                ("IMAGE", "image"),
5372                ("VOLUME_SIZE_MIB", "volume_size_mib"),
5373                ("STARTUP_GRACE_SECS", "startup_grace_secs"),
5374                ("RLS_SESSION", "rls_session"),
5375                ("TENANT_GUC", "tenant_guc"),
5376                ("SESSION_GUC", "session_guc"),
5377                ("TENANT_ALL_MARKER", "tenant_all_marker"),
5378            ] {
5379                if let Some(v) = source.get(&format!("{prefix}{suffix}")) {
5380                    put(
5381                        d,
5382                        &["handlers", "bindings", "sql", "databases", k, field],
5383                        Value::from(v),
5384                    );
5385                }
5386            }
5387            // enum fields (lowercased token)
5388            for (suffix, field) in [("TENANT", "tenant"), ("TENANT_SCOPE", "tenant_scope")] {
5389                if let Some(v) = source.get(&format!("{prefix}{suffix}")) {
5390                    put(
5391                        d,
5392                        &["handlers", "bindings", "sql", "databases", k, field],
5393                        Value::from(v.trim().to_ascii_lowercase()),
5394                    );
5395                }
5396            }
5397        }
5398    }
5399
5400    /// `[serve.listeners.<name>]` — keyed inbound-TCP listeners. Only the SCALAR +
5401    /// `imports` (list) fields are env-settable; structured fields (tenancy/env/tls)
5402    /// are file-only.
5403    fn listeners_overlay(d: &mut Dict, source: &EnvSource) {
5404        for name in source.listener_names() {
5405            let prefix = format!("{LISTENER_ENV_PREFIX}{name}_");
5406            let n = name.as_str();
5407            for (suffix, field) in [
5408                ("BIND", "bind"),
5409                ("COMPONENT", "component"),
5410                ("PROJECT", "project"),
5411                ("SITE", "site"),
5412                ("MAX_CONNS", "max_conns"),
5413                ("IDLE_TIMEOUT_MS", "idle_timeout_ms"),
5414                ("MAX_CONN_DURATION_MS", "max_conn_duration_ms"),
5415            ] {
5416                if let Some(v) = source.get(&format!("{prefix}{suffix}")) {
5417                    put(d, &["serve", "listeners", n, field], Value::from(v));
5418                }
5419            }
5420            if let Some(items) = source.parse_list(&format!("{prefix}IMPORTS")) {
5421                put(d, &["serve", "listeners", n, "imports"], Value::from(items));
5422            }
5423        }
5424    }
5425
5426    /// A figment [`Provider`] carrying the `BOATRAMP_*` environment overlay. Merged
5427    /// into the pipeline ABOVE the file layer (env overrides file) and BELOW the
5428    /// explicit-flag layer.
5429    pub(crate) struct BoatrampEnv(Dict);
5430
5431    impl BoatrampEnv {
5432        pub(crate) fn new(source: &EnvSource) -> Self {
5433            Self(env_overlay_dict(source))
5434        }
5435    }
5436
5437    impl Provider for BoatrampEnv {
5438        fn metadata(&self) -> Metadata {
5439            Metadata::named("BOATRAMP_* environment")
5440        }
5441
5442        fn data(&self) -> Result<FigMap<Profile, Dict>, Error> {
5443            let mut map = FigMap::new();
5444            map.insert(Profile::Default, self.0.clone());
5445            Ok(map)
5446        }
5447    }
5448
5449    /// A figment [`Provider`] wrapping a prebuilt `Dict` at the default profile — used
5450    /// for the base-seed, file, and flag layers.
5451    struct DictLayer {
5452        name: &'static str,
5453        dict: Dict,
5454    }
5455
5456    impl Provider for DictLayer {
5457        fn metadata(&self) -> Metadata {
5458            Metadata::named(self.name)
5459        }
5460        fn data(&self) -> Result<FigMap<Profile, Dict>, Error> {
5461            let mut map = FigMap::new();
5462            map.insert(Profile::Default, self.dict.clone());
5463            Ok(map)
5464        }
5465    }
5466
5467    /// Recursively drop `Empty` (figment's serialized `None`) entries from a dict, so the
5468    /// file layer never clobbers a lower layer's value with a null (figment merge replaces
5469    /// a dict with a non-dict). This is what lets the base-seed layer (decision 2) survive
5470    /// under a file that simply omits the section.
5471    fn prune_empty(dict: Dict) -> Dict {
5472        dict.into_iter()
5473            .filter_map(|(k, v)| match v {
5474                Value::Empty(..) => None,
5475                Value::Dict(t, inner) => Some((k, Value::Dict(t, prune_empty(inner)))),
5476                other => Some((k, other)),
5477            })
5478            .collect()
5479    }
5480
5481    /// Serialize `value` to a figment `Dict` via figment's OWN serializer (decision 1 — no
5482    /// serde_json bridge). The error is boxed because `figment::Error` is large
5483    /// (`clippy::result_large_err`).
5484    fn to_dict(value: &impl Serialize) -> Result<Dict, Box<Error>> {
5485        let mut data = Serialized::defaults(value).data().map_err(Box::new)?;
5486        Ok(data
5487            .remove(&Profile::Default)
5488            .or_else(|| data.into_values().next())
5489            .unwrap_or_default())
5490    }
5491
5492    /// The parsed config file as a pruned figment layer (decision 1). Absent `Option`
5493    /// sections serialize to `Empty` and are pruned so they don't clobber the base-seed.
5494    fn file_layer(cfg: &ServerConfig) -> Result<Dict, Box<Error>> {
5495        Ok(prune_empty(to_dict(cfg)?))
5496    }
5497
5498    /// Decision 2: the two `deny_unknown_fields` sub-structs with a REQUIRED field
5499    /// (`VaultSecretsConfig` has `addr`/`key`; `S3CredentialConfig` has
5500    /// `access_key_id`/`secret_access_key`) cannot deserialize from a partial env sub-dict.
5501    /// Seed their COMPLETE defaults in a layer BELOW the file, so file + env field overrides
5502    /// layer on top without a partial ever reaching extract — and WITHOUT clobbering a
5503    /// file-provided field (the file layer, merged above this, wins per-key; env wins above
5504    /// that). Seeded only when env actually references the sub-struct (so an unset section
5505    /// stays absent, matching `apply_env_overrides`' lazy materialization).
5506    fn base_seed(source: &EnvSource) -> Result<Dict, Box<Error>> {
5507        let mut d = Dict::new();
5508        if source.any(SECRETS_VAULT_ENV_VARS) {
5509            put(
5510                &mut d,
5511                &["secrets", "vault"],
5512                Value::Dict(Tag::Default, to_dict(&VaultSecretsConfig::default())?),
5513            );
5514        }
5515        for name in source.blob_backend_projects() {
5516            let prefix = format!("{BLOB_BACKEND_ENV_PREFIX}{name}_");
5517            let has_cred = source.get(&format!("{prefix}S3_ACCESS_KEY_ID")).is_some()
5518                || source
5519                    .get(&format!("{prefix}S3_SECRET_ACCESS_KEY"))
5520                    .is_some();
5521            if has_cred {
5522                put(
5523                    &mut d,
5524                    &["serve", "blob_backends", name.as_str(), "s3_credential"],
5525                    Value::Dict(Tag::Default, to_dict(&S3CredentialConfig::default())?),
5526                );
5527            }
5528        }
5529        Ok(d)
5530    }
5531
5532    /// The single layered config resolution — `base-seed → file → env → explicit flags` —
5533    /// used by `ServerConfig::load` (serve + every offline op). `flags` is the caller's
5534    /// explicit-CLI layer (empty for the offline ops; the serve binary passes its
5535    /// `ValueSource::CommandLine` args, which is what keeps a defaulted `--blobs fs` from
5536    /// clobbering file/env — risk P3#14). Replaces `apply_env_overrides` + the serve clap
5537    /// `#[arg(env)]` + ad-hoc `std::env::var` loaders (the parity battery asserts the SAME
5538    /// result as `apply_env_overrides` across the whole surface).
5539    pub(crate) fn load_with_figment(
5540        path: &Path,
5541        override_: Option<ConfigFormat>,
5542        source: &EnvSource,
5543        flags: Dict,
5544    ) -> Result<ServerConfig, ConfigError> {
5545        // File: parsed with the existing RON/JSON decoder + its own validation (a file-only
5546        // config still fails at parse exactly as today). Decision 3 re-validates the MERGED
5547        // result below.
5548        let fmt = resolve_format(path, override_);
5549        let file_cfg = match std::fs::read_to_string(path) {
5550            Ok(contents) => ServerConfig::parse_with_format(&contents, fmt).map_err(|err| {
5551                ConfigError::File {
5552                    path: path.display().to_string(),
5553                    source: Box::new(err),
5554                }
5555            })?,
5556            Err(err) if err.kind() == std::io::ErrorKind::NotFound => ServerConfig::default(),
5557            Err(err) => return Err(err.into()),
5558        };
5559
5560        let base = base_seed(source).map_err(|e| ConfigError::Resolve(e.to_string()))?;
5561        let file = file_layer(&file_cfg).map_err(|e| ConfigError::Resolve(e.to_string()))?;
5562
5563        // Decision 4: a `[cluster]` missing its required `listen` has no `ClusterConfig`
5564        // default, so extract fails LOUDLY here (we do not preserve the old silent-drop).
5565        let cfg: ServerConfig = Figment::new()
5566            .merge(DictLayer {
5567                name: "base defaults",
5568                dict: base,
5569            })
5570            .merge(DictLayer {
5571                name: "config file",
5572                dict: file,
5573            })
5574            .merge(BoatrampEnv::new(source))
5575            .merge(DictLayer {
5576                name: "cli flags",
5577                dict: flags,
5578            })
5579            .extract_lossy()
5580            .map_err(|e| ConfigError::Resolve(e.to_string()))?;
5581
5582        // Decision 3: run the fail-closed validators on the fully merged (file + env + flags)
5583        // result — stricter than `apply_env_overrides`, which only re-validated the db-name /
5584        // blob-project / listener maps (this also validates a file-introduced entry).
5585        cfg.validate_sql_db_names()?;
5586        cfg.validate_blob_backend_projects()?;
5587        cfg.validate_listeners()?;
5588        Ok(cfg)
5589    }
5590
5591    /// Resolve the `BOATRAMP_*` env overlay OVER an already-parsed base config (the base
5592    /// standing in for the file layer): `base-seed → base → env`. Equivalent to
5593    /// [`load_with_figment`] with the file already read into `base` and no flags. Test-only —
5594    /// it backs the `#[cfg(test)]` `apply_env_overrides` adapter so the pre-figment env tests
5595    /// (which layer env over a parsed `boatramp.cfg` struct) run THROUGH the real pipeline.
5596    #[cfg(test)]
5597    pub(crate) fn resolve_env_over(
5598        base: &ServerConfig,
5599        source: &EnvSource,
5600    ) -> Result<ServerConfig, ConfigError> {
5601        let seed = base_seed(source).map_err(|e| ConfigError::Resolve(e.to_string()))?;
5602        let file = file_layer(base).map_err(|e| ConfigError::Resolve(e.to_string()))?;
5603        let cfg: ServerConfig = Figment::new()
5604            .merge(DictLayer {
5605                name: "base defaults",
5606                dict: seed,
5607            })
5608            .merge(DictLayer {
5609                name: "base config",
5610                dict: file,
5611            })
5612            .merge(BoatrampEnv::new(source))
5613            .extract_lossy()
5614            .map_err(|e| ConfigError::Resolve(e.to_string()))?;
5615        cfg.validate_sql_db_names()?;
5616        cfg.validate_blob_backend_projects()?;
5617        cfg.validate_listeners()?;
5618        Ok(cfg)
5619    }
5620
5621    /// Build the explicit-CLI-**flag** figment layer from a `{BOATRAMP_<NAME>: value}` map
5622    /// of the args the operator set on the command line. Reuses [`env_overlay_dict`] (a
5623    /// flag's name→path mapping is the SAME as its env var's), so only recognised config
5624    /// knobs produce entries and the runtime/selector flags (`--tls`, cluster-actions, …)
5625    /// are ignored. This dict is merged as the TOP layer (above the Process env), so an
5626    /// explicit flag wins over env + file — matching clap's `flag > env` precedence today.
5627    pub(crate) fn flag_overlay_dict(cli_flags: &BTreeMap<String, String>) -> Dict {
5628        env_overlay_dict(&EnvSource::Map(cli_flags.clone()))
5629    }
5630
5631    /// Config-tree field names whose VALUES are raw secret material — redacted by
5632    /// [`dump_redacted`]. Secret *references* and env-var-NAME fields (`token_env`,
5633    /// `url_env`, `pin_env`, `password_env`, `access_token_env`) are NOT secrets and are
5634    /// left intact; only the fields that can hold raw key/secret bytes are masked.
5635    const SECRET_FIELDS: &[&str] = &[
5636        "auth_root_private_key",
5637        "bootstrap_secret",
5638        "azure_access_key",
5639        "secret_access_key",
5640        // The external token signer's in-process root key (`[serve.signer] Local { private_key }`)
5641        // is raw key material in the config — mask it (Security MEDIUM).
5642        "private_key",
5643        // `[cluster] join_token` is a secret REFERENCE by convention (`env:`/`path:`), but the
5644        // schema allows a raw-inlined token, so mask it to be safe (Security MEDIUM).
5645        "join_token",
5646    ];
5647
5648    fn redact(value: &mut serde_json::Value) {
5649        match value {
5650            serde_json::Value::Object(map) => {
5651                for (k, v) in map.iter_mut() {
5652                    if SECRET_FIELDS.contains(&k.as_str()) && !v.is_null() {
5653                        *v = serde_json::Value::String("<redacted>".to_string());
5654                    } else {
5655                        redact(v);
5656                    }
5657                }
5658            }
5659            serde_json::Value::Array(items) => items.iter_mut().for_each(redact),
5660            _ => {}
5661        }
5662    }
5663
5664    /// Serialize the resolved [`ServerConfig`] for `boatramp config dump`, REDACTING the
5665    /// secret-bearing fields ([`SECRET_FIELDS`]). The config is `Serialize` for the figment
5666    /// file layer, which would otherwise expose the control-plane root key / bootstrap
5667    /// secret / azure access key / sealed-cred ref in a dump. Pretty JSON (also a valid
5668    /// config input).
5669    pub(crate) fn dump_redacted(cfg: &ServerConfig) -> Result<String, ConfigError> {
5670        let mut v = serde_json::to_value(cfg).map_err(ConfigError::Json)?;
5671        redact(&mut v);
5672        serde_json::to_string_pretty(&v).map_err(ConfigError::Json)
5673    }
5674
5675    /// Resolve a [`ServerConfig`] from the environment overlay ALONE (no file, no
5676    /// flags) — a thin test helper for the sections that deserialize from a partial env
5677    /// dict. Sections needing the base-seed (decision 2) are tested through
5678    /// [`load_with_figment`] instead.
5679    #[cfg(test)]
5680    pub(crate) fn resolve_from_env(source: &EnvSource) -> Result<ServerConfig, Box<Error>> {
5681        Figment::new()
5682            .merge(BoatrampEnv::new(source))
5683            .extract_lossy()
5684            .map_err(Box::new)
5685    }
5686
5687    #[cfg(test)]
5688    mod tests {
5689        use super::*;
5690
5691        fn map(pairs: &[(&str, &str)]) -> EnvSource {
5692            EnvSource::Map(
5693                pairs
5694                    .iter()
5695                    .map(|(k, v)| ((*k).to_string(), (*v).to_string()))
5696                    .collect(),
5697            )
5698        }
5699
5700        /// The keystone drift guard: EVERY fixed `BOATRAMP_*` var the old loader
5701        /// (`apply_env_overrides`) honors must also be produced by the new overlay.
5702        /// Because the overlay iterates the same `*_ENV_VARS` const tables, this
5703        /// holds by construction — the test is the regression guard that a future
5704        /// edit can't quietly drop a section's table from the overlay loop, and
5705        /// that no const var escapes classification. (The forgot-a-knob guards in
5706        /// the parent module already prove every struct FIELD has a const-table
5707        /// var; together they chain field → var → overlay entry.)
5708        #[test]
5709        fn overlay_honors_every_loader_b_fixed_var() {
5710            let all: Vec<&str> = COMPUTE_ENV_VARS
5711                .iter()
5712                .chain(SECURITY_ENV_VARS)
5713                .chain(SQL_ENV_VARS)
5714                .chain(JWKS_ENV_VARS)
5715                .chain(HANDLER_CONCURRENCY_ENV_VARS)
5716                .chain(HANDLER_BLOB_HEDGE_ENV_VARS)
5717                .chain(HANDLER_COLDSTART_ENV_VARS)
5718                .chain(S3_INGRESS_CLOUD_ENV_VARS)
5719                .chain(SECRETS_ENV_VARS)
5720                .chain(CLUSTER_ENV_VARS)
5721                .copied()
5722                .collect();
5723            let mut unhandled = Vec::new();
5724            for var in all {
5725                // A socket-addr-ish sample keeps the value non-empty; the overlay
5726                // emits strings (no parse), so any non-empty value exercises it.
5727                let dict = env_overlay_dict(&map(&[(var, "x")]));
5728                if dict.is_empty() {
5729                    unhandled.push(var);
5730                }
5731            }
5732            assert!(
5733                unhandled.is_empty(),
5734                "overlay produced nothing for these registered Loader-B vars \
5735                 (a drift gap — wire them into env_overlay_dict): {unhandled:?}"
5736            );
5737        }
5738
5739        /// P4: the overlay's bool spellings match `parse_bool` end-to-end, via
5740        /// figment's `to_bool_lossy` at `extract_lossy`.
5741        #[test]
5742        fn bool_spellings_round_trip_like_parse_bool() {
5743            for (raw, expect) in [
5744                ("on", true),
5745                ("1", true),
5746                ("yes", true),
5747                ("TRUE", true),
5748                ("off", false),
5749                ("0", false),
5750                ("no", false),
5751            ] {
5752                let cfg = resolve_from_env(&map(&[(
5753                    "BOATRAMP_SECURITY_ALLOW_SHARED_KERNEL_COMPUTE",
5754                    raw,
5755                )]))
5756                .expect("extract");
5757                assert_eq!(
5758                    cfg.security
5759                        .expect("security materialised")
5760                        .overrides
5761                        .allow_shared_kernel_compute,
5762                    Some(expect),
5763                    "bool spelling {raw:?} must parse like parse_bool"
5764                );
5765            }
5766        }
5767
5768        /// Empty env value = UNSET (never clobbers to `""`), matching `EnvSource::get`.
5769        #[test]
5770        fn empty_value_is_unset() {
5771            let dict = env_overlay_dict(&map(&[("BOATRAMP_S3_BUCKET", "")]));
5772            assert!(dict.is_empty(), "an empty value must be treated as unset");
5773        }
5774
5775        /// `[compute]` resolves from env across str / int / list / enum / bool field kinds
5776        /// (`ComputeConfig` is `#[serde(default)]`, so a partial env dict fills the rest).
5777        #[test]
5778        fn compute_resolves_from_env() {
5779            let c = resolve_from_env(&map(&[
5780                ("BOATRAMP_COMPUTE_VCPUS", "4"),
5781                ("BOATRAMP_COMPUTE_MEM_MIB", "2048"),
5782                ("BOATRAMP_COMPUTE_REGION", "ams"),
5783                (
5784                    "BOATRAMP_COMPUTE_KERNEL_SIGNING_PUBKEYS",
5785                    "es256:aa, es256:bb",
5786                ),
5787                ("BOATRAMP_COMPUTE_MANAGED_DB_PRIVILEGE", "rootless"),
5788                ("BOATRAMP_COMPUTE_INTERNAL_DNS", "on"),
5789            ]))
5790            .expect("figment extract")
5791            .compute
5792            .expect("compute materialised from env");
5793            assert_eq!(c.vcpus, 4);
5794            assert_eq!(c.mem_mib, 2048);
5795            assert_eq!(c.region.as_deref(), Some("ams"));
5796            assert_eq!(
5797                c.kernel_signing_pubkeys,
5798                vec!["es256:aa".to_string(), "es256:bb".to_string()],
5799                "comma-list trimmed + split"
5800            );
5801            assert_eq!(c.managed_db_privilege, ManagedDbPrivilege::Rootless);
5802            assert!(c.internal_dns, "bool coerced from \"on\"");
5803        }
5804
5805        /// The serve S3 scalars (the construens finalize concern) resolve from env —
5806        /// `ServeConfig` is `#[serde(default)]`. Asserts ALL FIVE top-level `[serve]` S3-backend
5807        /// levers (`blobs`/`s3_bucket`/`s3_endpoint`/`s3_region`/`s3_path_style`) resolve — the
5808        /// enum, three strings, and the bool. This resolves through the pipeline with NO flag layer
5809        /// (`resolve_from_env`), i.e. exactly the way the OFFLINE ops (`migrate`/`blob rehome`) see
5810        /// the object store from the environment — the parity that v0.34.0's hand-added Loader-B
5811        /// `SERVE_S3_BACKEND_ENV_VARS` arm provided and the figment overlay (`SERVE_SCALARS`) now
5812        /// subsumes. So a file-less fleet (the Tigris-only construens deployment) needs no
5813        /// `boatramp.cfg` for its object store.
5814        #[test]
5815        fn serve_s3_scalars_extract() {
5816            let cfg = resolve_from_env(&map(&[
5817                ("BOATRAMP_BLOBS", "s3"),
5818                ("BOATRAMP_S3_BUCKET", "construens-blobs"),
5819                ("BOATRAMP_S3_ENDPOINT", "https://fly.storage.tigris.dev"),
5820                ("BOATRAMP_S3_REGION", "auto"),
5821                ("BOATRAMP_S3_PATH_STYLE", "true"),
5822            ]))
5823            .expect("extract");
5824            let serve = cfg.serve.expect("serve materialised from env");
5825            assert_eq!(serve.blobs, Some(crate::backends::BlobBackend::S3));
5826            assert_eq!(serve.s3_bucket.as_deref(), Some("construens-blobs"));
5827            assert_eq!(
5828                serve.s3_endpoint.as_deref(),
5829                Some("https://fly.storage.tigris.dev")
5830            );
5831            assert_eq!(serve.s3_region.as_deref(), Some("auto"));
5832            assert!(serve.s3_path_style, "s3_path_style coerced from \"true\"");
5833        }
5834
5835        /// P0#2: the dynamic blob-backends map populates at the right nested path,
5836        /// including the flattened sealed-credential public ref.
5837        #[test]
5838        fn blob_backends_dynamic_map_shape() {
5839            let dict = env_overlay_dict(&map(&[
5840                ("BOATRAMP_SERVE_BLOB_BACKEND_myproj_KIND", "s3"),
5841                ("BOATRAMP_SERVE_BLOB_BACKEND_myproj_S3_BUCKET", "p-blobs"),
5842                (
5843                    "BOATRAMP_SERVE_BLOB_BACKEND_myproj_S3_ACCESS_KEY_ID",
5844                    "AKIA",
5845                ),
5846            ]));
5847            let serve = match dict.get("serve") {
5848                Some(Value::Dict(_, s)) => s,
5849                _ => panic!("serve dict present"),
5850            };
5851            let backends = match serve.get("blob_backends") {
5852                Some(Value::Dict(_, b)) => b,
5853                _ => panic!("blob_backends dict present"),
5854            };
5855            let myproj = match backends.get("myproj") {
5856                Some(Value::Dict(_, p)) => p,
5857                _ => panic!("myproj backend present"),
5858            };
5859            assert!(matches!(myproj.get("blobs"), Some(Value::String(_, s)) if s == "s3"));
5860            assert!(matches!(myproj.get("s3_bucket"), Some(Value::String(_, s)) if s == "p-blobs"));
5861            match myproj.get("s3_credential") {
5862                Some(Value::Dict(_, cred)) => assert!(
5863                    matches!(cred.get("access_key_id"), Some(Value::String(_, s)) if s == "AKIA")
5864                ),
5865                _ => panic!("s3_credential flattened under the backend"),
5866            }
5867        }
5868
5869        /// P0#1: the SQL `databases` map resolves the reserved `DEFAULT` token to
5870        /// the real key `"default"`.
5871        #[test]
5872        fn sql_db_default_token_maps_to_default_key() {
5873            let dict = env_overlay_dict(&map(&[(
5874                "BOATRAMP_HANDLERS_SQL_DB_DEFAULT_KIND",
5875                "postgres",
5876            )]));
5877            // handlers.bindings.sql.databases.default.kind == "postgres"
5878            let mut cur = &dict;
5879            for seg in ["handlers", "bindings", "sql", "databases", "default"] {
5880                cur = match cur.get(seg) {
5881                    Some(Value::Dict(_, inner)) => inner,
5882                    _ => panic!("missing dict segment {seg}"),
5883                };
5884            }
5885            assert!(matches!(cur.get("kind"), Some(Value::String(_, s)) if s == "postgres"));
5886        }
5887
5888        // The figment pipeline resolves an offline op's config (base-seed + env, no file, no
5889        // flags) — `figment_env` — used by the direct section/serve tests below. (The old
5890        // full-surface parity battery, which compared this to `apply_env_overrides`, retired
5891        // with Loader B; its equivalence was proven green at the cutover, and the direct
5892        // per-section tests — here + the `env_wires_*` tests in `config::tests`, which now run
5893        // THROUGH the pipeline via the test adapter — are the spec going forward.)
5894
5895        /// The figment pipeline an offline op takes: base-seed + env, no file, no flags.
5896        fn figment_env(pairs: &[(&str, &str)]) -> ServerConfig {
5897            load_with_figment(
5898                std::path::Path::new("/nonexistent/boatramp.cfg"),
5899                None,
5900                &map(pairs),
5901                Dict::new(),
5902            )
5903            .expect("figment load_with_figment")
5904        }
5905
5906        // --- serve.* scalars + serve.kv.* (former Loader A / C) -------------------
5907        // The pipeline resolves these (the serve-only clap `#[arg(env)]` + ad-hoc env reads
5908        // the rewrite subsumed) into their ServeConfig fields, asserted directly below.
5909
5910        /// Env-only figment resolution via the full pipeline (base-seed + env), so the
5911        /// serve-scalar secrets' deny-unknown neighbours aren't an issue (serve is
5912        /// `#[serde(default)]`).
5913        fn serve_from_env(pairs: &[(&str, &str)]) -> ServeConfig {
5914            figment_env(pairs)
5915                .serve
5916                .expect("serve materialised from env")
5917        }
5918
5919        #[test]
5920        fn serve_scalars_full_extract() {
5921            let s = serve_from_env(&[
5922                ("BOATRAMP_ADDR", "0.0.0.0:8080"),
5923                ("BOATRAMP_DATA_DIR", "/data"),
5924                ("BOATRAMP_BLOBS", "s3"),
5925                ("BOATRAMP_S3_BUCKET", "b"),
5926                ("BOATRAMP_S3_PATH_STYLE", "true"),
5927                ("BOATRAMP_GCS_BUCKET", "gb"),
5928                ("BOATRAMP_GCS_ENDPOINT", "http://gcs"),
5929                ("BOATRAMP_GCS_ANONYMOUS", "yes"),
5930                ("BOATRAMP_AZURE_ACCOUNT", "acct"),
5931                ("BOATRAMP_AZURE_CONTAINER", "cont"),
5932                ("BOATRAMP_AZURE_ACCESS_KEY", "secret-key"),
5933                ("BOATRAMP_AZURE_EMULATOR", "true"),
5934                ("BOATRAMP_AUTH_ROOT_PRIVATE_KEY", "deadbeef"),
5935                ("BOATRAMP_AUTH_ROOT_PUBLIC_KEY", "cafe"),
5936                ("BOATRAMP_BOOTSTRAP_SECRET", "boot"),
5937                ("BOATRAMP_MAX_UPLOAD_BYTES", "1048576"),
5938                ("BOATRAMP_UPLOAD_IDLE_TIMEOUT", "30"),
5939                ("BOATRAMP_MAX_CONCURRENT_UPLOADS", "16"),
5940                ("BOATRAMP_HTTP_REDIRECT_ADDR", "0.0.0.0:80"),
5941                ("BOATRAMP_DEFAULT_SITE", "construens"),
5942                ("BOATRAMP_POP_ORIGIN", "https://cp.example.com"),
5943                ("BOATRAMP_PROTECT_PREVIEWS", "true"),
5944                ("BOATRAMP_CLUSTER_RATE_LIMIT", "true"),
5945                ("BOATRAMP_SHARED_CACHE_COHERENCE", "true"),
5946            ]);
5947            assert_eq!(s.addr, Some("0.0.0.0:8080".parse().unwrap()));
5948            assert_eq!(s.data_dir.as_deref(), Some(std::path::Path::new("/data")));
5949            assert!(matches!(s.blobs, Some(crate::backends::BlobBackend::S3)));
5950            assert_eq!(s.s3_bucket.as_deref(), Some("b"));
5951            assert!(s.s3_path_style);
5952            assert_eq!(s.gcs_bucket.as_deref(), Some("gb"));
5953            assert!(s.gcs_anonymous, "GCS anonymous coerced from \"yes\"");
5954            assert_eq!(s.azure_account.as_deref(), Some("acct"));
5955            assert_eq!(s.azure_access_key.as_deref(), Some("secret-key"));
5956            assert!(s.azure_emulator);
5957            assert_eq!(s.auth_root_private_key.as_deref(), Some("deadbeef"));
5958            assert_eq!(s.auth_root_public_key.as_deref(), Some("cafe"));
5959            assert_eq!(s.bootstrap_secret.as_deref(), Some("boot"));
5960            assert_eq!(s.max_upload_bytes, Some(1_048_576));
5961            // The field-name mismatch: env UPLOAD_IDLE_TIMEOUT → field upload_idle_timeout_secs.
5962            assert_eq!(s.upload_idle_timeout_secs, Some(30));
5963            assert_eq!(s.max_concurrent_uploads, Some(16));
5964            assert_eq!(s.http_redirect_addr, Some("0.0.0.0:80".parse().unwrap()));
5965            assert_eq!(s.default_site.as_deref(), Some("construens"));
5966            assert_eq!(s.pop_origin.as_deref(), Some("https://cp.example.com"));
5967            assert!(s.protect_previews);
5968            assert!(s.cluster_rate_limit);
5969            assert!(s.shared_cache_coherence);
5970        }
5971
5972        #[test]
5973        fn serve_kv_knobs_full_extract() {
5974            let s = serve_from_env(&[
5975                ("BOATRAMP_KV_CHECKPOINT_INTERVAL", "0"),
5976                ("BOATRAMP_KV_CLOSE_DEADLINE", "30"),
5977                ("BOATRAMP_KV_GC_INTERVAL", "600"),
5978                ("BOATRAMP_KV_GC_MIN_AGE", "3600"),
5979                ("BOATRAMP_KV_SQL_KIND", "sqlite"),
5980                ("BOATRAMP_KV_SQL_PATH", "/data/kv.db"),
5981                ("BOATRAMP_KV_SQL_URL_ENV", "KV_URL"),
5982                ("BOATRAMP_KV_SQL_POOL_MAX", "8"),
5983            ]);
5984            let kv = s.kv.expect("serve.kv materialised");
5985            // `0` round-trips as Some(0) (the meaningful "disable cadence" value — KvConfig
5986            // maps Some(0) → None at resolve time, preserving Loader-C semantics). Checked on
5987            // the resolver BEFORE moving the sub-structs out.
5988            assert_eq!(
5989                kv.checkpoint_interval(),
5990                None,
5991                "Some(0) disables the cadence"
5992            );
5993            let slate = kv.slatedb.clone().expect("serve.kv.slatedb materialised");
5994            assert_eq!(slate.checkpoint_interval, Some(0));
5995            assert_eq!(slate.close_deadline, Some(30));
5996            assert_eq!(slate.gc_interval, Some(600));
5997            assert_eq!(slate.gc_min_age, Some(3600));
5998            let sql = kv.sql.expect("serve.kv.sql materialised");
5999            assert_eq!(sql.kind, "sqlite");
6000            assert_eq!(sql.path.as_deref(), Some("/data/kv.db"));
6001            assert_eq!(sql.url_env.as_deref(), Some("KV_URL"));
6002            assert_eq!(sql.pool_max, Some(8));
6003        }
6004
6005        /// Drift guard for the serve surface: every SERVE_SCALARS + SERVE_KV var produces
6006        /// an overlay entry (the Loader-A/C analog of `overlay_honors_every_loader_b_fixed_var`).
6007        #[test]
6008        fn overlay_honors_every_serve_var() {
6009            let mut unhandled = Vec::new();
6010            for (var, _) in SERVE_SCALARS.iter().chain(SERVE_KV) {
6011                if env_overlay_dict(&map(&[(var, "x")])).is_empty() {
6012                    unhandled.push(*var);
6013                }
6014            }
6015            assert!(
6016                unhandled.is_empty(),
6017                "overlay produced nothing for these serve vars: {unhandled:?}"
6018            );
6019        }
6020
6021        // --- the flag layer: precedence + the config dump redaction ---------------
6022
6023        /// `flag > env > file` precedence (matching clap's `flag > env` + the file fallback),
6024        /// resolved through the full pipeline.
6025        #[test]
6026        fn flag_env_file_precedence() {
6027            let path = std::env::temp_dir().join(format!(
6028                "brtest-figment-{}-{:?}.cfg",
6029                std::process::id(),
6030                std::thread::current().id()
6031            ));
6032            std::fs::write(
6033                &path,
6034                r#"( serve: ( s3_bucket: "from-file", s3_region: "file-region", s3_endpoint: "file-endpoint" ) )"#,
6035            )
6036            .unwrap();
6037
6038            let env = map(&[
6039                ("BOATRAMP_S3_BUCKET", "from-env"),
6040                ("BOATRAMP_S3_ENDPOINT", "from-env-endpoint"),
6041            ]);
6042            let flags: BTreeMap<String, String> =
6043                [("BOATRAMP_S3_BUCKET".to_string(), "from-flag".to_string())]
6044                    .into_iter()
6045                    .collect();
6046            let cfg =
6047                load_with_figment(&path, None, &env, flag_overlay_dict(&flags)).expect("resolve");
6048            let serve = cfg.serve.expect("serve");
6049            assert_eq!(
6050                serve.s3_bucket.as_deref(),
6051                Some("from-flag"),
6052                "flag beats env+file"
6053            );
6054            assert_eq!(
6055                serve.s3_endpoint.as_deref(),
6056                Some("from-env-endpoint"),
6057                "env beats file when no flag"
6058            );
6059            assert_eq!(
6060                serve.s3_region.as_deref(),
6061                Some("file-region"),
6062                "file survives when neither env nor flag set it"
6063            );
6064            std::fs::remove_file(&path).ok();
6065        }
6066
6067        /// `config dump` must redact the raw-secret fields (the control-plane root key,
6068        /// bootstrap secret, azure access key, sealed-cred ref) — never emit their values.
6069        #[test]
6070        fn dump_redacts_secrets() {
6071            let cfg = figment_env(&[
6072                ("BOATRAMP_AUTH_ROOT_PRIVATE_KEY", "deadbeefsecret"),
6073                ("BOATRAMP_BOOTSTRAP_SECRET", "topsecretboot"),
6074                ("BOATRAMP_AZURE_ACCESS_KEY", "azuresecretkey"),
6075                ("BOATRAMP_DEFAULT_SITE", "construens"),
6076            ]);
6077            let dump = dump_redacted(&cfg).expect("dump");
6078            for leaked in ["deadbeefsecret", "topsecretboot", "azuresecretkey"] {
6079                assert!(
6080                    !dump.contains(leaked),
6081                    "config dump leaked a secret value: {leaked}\n{dump}"
6082                );
6083            }
6084            assert!(dump.contains("<redacted>"), "secrets shown as <redacted>");
6085            // A non-secret field is still shown in full.
6086            assert!(dump.contains("construens"), "non-secret values are shown");
6087        }
6088
6089        /// Security MEDIUM: the external signer's in-process `private_key` and a raw-inlined
6090        /// `cluster.join_token` must be redacted in a dump (the config is `Serialize`, so a raw
6091        /// dump would otherwise print the signing key / join secret in cleartext).
6092        #[test]
6093        fn dump_redacts_signer_key_and_join_token() {
6094            let file = r#"(
6095                serve: ( signer: Local( private_key: "SIGNERPRIVKEYSECRET" ) ),
6096                cluster: ( listen: "10.0.0.2:7000", join_token: "RAWJOINTOKENSECRET" ),
6097            )"#;
6098            let cfg = ServerConfig::parse_with_format(file, ConfigFormat::Ron).expect("parse");
6099            let dump = cfg.dump_redacted().expect("dump");
6100            assert!(
6101                !dump.contains("SIGNERPRIVKEYSECRET"),
6102                "signer private_key leaked:\n{dump}"
6103            );
6104            assert!(
6105                !dump.contains("RAWJOINTOKENSECRET"),
6106                "cluster join_token leaked:\n{dump}"
6107            );
6108            assert!(dump.contains("<redacted>"));
6109        }
6110
6111        /// Security LOW (bool trim): a templated env value with trailing whitespace
6112        /// (`"true\n"` from a fly.toml / k8s block scalar) must still coerce — the overlay
6113        /// trims scalar values so figment's non-trimming `to_bool_lossy` sees `true`. Also
6114        /// covers an enum with surrounding whitespace.
6115        #[test]
6116        fn trailing_whitespace_on_bool_and_enum_still_parses() {
6117            let cfg = resolve_from_env(&map(&[
6118                ("BOATRAMP_SECURITY_REQUIRE_TENANCY_DECLARATION", "true\n"),
6119                ("BOATRAMP_COMPUTE_MANAGED_DB_PRIVILEGE", "  rootless \n"),
6120            ]))
6121            .expect("extract despite trailing whitespace");
6122            assert_eq!(
6123                cfg.security
6124                    .expect("security")
6125                    .overrides
6126                    .require_tenancy_declaration,
6127                Some(true),
6128                "a trailing-newline bool must parse as true"
6129            );
6130            assert_eq!(
6131                cfg.compute.expect("compute").managed_db_privilege,
6132                ManagedDbPrivilege::Rootless,
6133                "a whitespace-padded enum must parse"
6134            );
6135        }
6136
6137        /// Security LOW (file round-trip): the file-only, isolation-bearing structured fields
6138        /// must survive the file → derived-`Serialize` → `extract_lossy` path intact — the
6139        /// riskiest being a listener `tenancy: Scoped{…}` (custom `de_opt_tenancy` + an
6140        /// internally-tagged enum), plus a `security.profiles` and a `security.projects` entry.
6141        #[test]
6142        fn file_only_structured_fields_round_trip() {
6143            let file = r#"(
6144                serve: ( listeners: {
6145                    "edge": (
6146                        component: "tcp-echo", project: "proj", site: "site",
6147                        bind: "0.0.0.0:7100",
6148                        tenancy: (mode: "scoped", column: "tenant_id"),
6149                    ),
6150                } ),
6151                security: (
6152                    profile: "multi-tenant",
6153                    profiles: { "preview": ( allow_guest_email: true ) },
6154                    projects: { "proj": ( allow_cross_tenant_db: true ) },
6155                ),
6156            )"#;
6157            // The pipeline path a file-configured serve takes (file → figment → extract), no env.
6158            let cfg = load_with_figment(
6159                write_temp_cfg(file).as_path(),
6160                None,
6161                &EnvSource::Map(BTreeMap::new()),
6162                Dict::new(),
6163            )
6164            .expect("resolve file through the pipeline");
6165            let serve = cfg.serve.expect("serve");
6166            let l = serve.listeners.get("edge").expect("listener edge survived");
6167            assert_eq!(l.component, "tcp-echo");
6168            match l.tenancy.as_ref().expect("tenancy survived (Some)") {
6169                boatramp_core::tenancy::Tenancy::Scoped { column, .. } => {
6170                    assert_eq!(column, "tenant_id");
6171                }
6172                other => panic!("tenancy did not round-trip as Scoped: {other:?}"),
6173            }
6174            let sec = cfg.security.expect("security");
6175            assert!(
6176                sec.profiles
6177                    .get("preview")
6178                    .expect("profile survived")
6179                    .allow_guest_email
6180                    == Some(true)
6181            );
6182            assert!(
6183                sec.projects
6184                    .get("proj")
6185                    .expect("project override survived")
6186                    .allow_cross_tenant_db
6187                    == Some(true)
6188            );
6189        }
6190
6191        /// Write `text` to a unique temp `.cfg` and return its path (leaked into the temp dir;
6192        /// fine for a test process). Used by the file round-trip test.
6193        fn write_temp_cfg(text: &str) -> std::path::PathBuf {
6194            use std::sync::atomic::{AtomicU32, Ordering};
6195            static N: AtomicU32 = AtomicU32::new(0);
6196            let path = std::env::temp_dir().join(format!(
6197                "brtest-rt-{}-{}.cfg",
6198                std::process::id(),
6199                N.fetch_add(1, Ordering::Relaxed)
6200            ));
6201            std::fs::write(&path, text).expect("write temp cfg");
6202            path
6203        }
6204    }
6205}