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