Skip to main content

boatramp_node/
config.rs

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