Skip to main content

boatramp_node/
config.rs

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