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/// A failure loading or parsing a local config file (`project.cfg` / `boatramp.cfg`).
30#[derive(Debug, thiserror::Error)]
31pub enum ConfigError {
32    /// Wraps an underlying error with the file path it came from.
33    #[error("{path}: {source}")]
34    File {
35        path: String,
36        #[source]
37        source: Box<Self>,
38    },
39    /// The RON document failed to parse.
40    #[error("invalid config syntax: {0}")]
41    Ron(#[from] ron::error::SpannedError),
42    /// The `routing` section failed its compile-check.
43    #[error("routing: {0}")]
44    Routing(#[from] boatramp_core::ConfigError),
45    /// Reading the file failed (other than not-found, which yields defaults).
46    #[error(transparent)]
47    Io(#[from] std::io::Error),
48    /// An environment-variable override could not be parsed (bad number/bool).
49    #[error("environment variable {var}: {reason}")]
50    Env {
51        /// The offending `BOATRAMP_*` variable. Owned because some names are built
52        /// dynamically (the keyed `databases` map, whose members aren't known at
53        /// compile time).
54        var: String,
55        /// Why the value was rejected.
56        reason: String,
57    },
58    /// A `handlers.bindings.sql.databases` binding name is not a safe URL path
59    /// segment — it is threaded verbatim into `/api/sql/{db}/…` and `--db`, so an
60    /// empty/`//`-collapsing or path-separator-bearing name is refused at load
61    /// (fail-closed) rather than emitting a malformed control-plane path.
62    #[error("SQL database binding {name:?}: {reason}{cure}")]
63    InvalidDbName {
64        /// The offending binding name (the `databases` map key).
65        name: String,
66        /// Why it was rejected (from the canonical validator).
67        reason: &'static str,
68        /// A trailing remediation hint (empty unless this is the legacy empty-name
69        /// default case, where it points at the `default` cure).
70        cure: &'static str,
71    },
72}
73
74/// Project configuration, loaded from `project.cfg` (RON) in the project folder.
75///
76/// Read by the client commands (`sync`, `build`, `bundle`, `validate`).
77/// Everything is optional; a missing file is the default.
78#[derive(Debug, Default, Deserialize)]
79#[serde(default)]
80pub struct ProjectConfig {
81    /// Where and how to publish this project.
82    pub publish: PublishConfig,
83    /// Optional build step run before `sync`.
84    pub build: Option<BuildConfig>,
85    /// Optional embedded-bundler step (`bundler` feature).
86    pub bundle: Option<BundleConfig>,
87    /// Deploy-scoped routing/handlers config. Folded into the deployment
88    /// manifest at `sync` (so it is atomic with the content and rolls back with
89    /// it). The bulk of a project's config — redirects, rewrites, headers,
90    /// handlers, consumers, crons, streams.
91    pub routing: DeployConfig,
92}
93
94impl ProjectConfig {
95    /// Parse a `project.cfg` document (RON). The `routing` section is
96    /// compile-checked (route patterns, cron schedules, imports) so a bad config
97    /// fails fast.
98    pub fn parse(text: &str) -> Result<Self, ConfigError> {
99        let config: Self = ron_options().from_str(text)?;
100        config.routing.compile_check()?;
101        Ok(config)
102    }
103
104    /// Load from `path` (RON). A missing file yields the default config.
105    pub fn load(path: &Path) -> Result<Self, ConfigError> {
106        match std::fs::read_to_string(path) {
107            Ok(contents) => Self::parse(&contents).map_err(|err| ConfigError::File {
108                path: path.display().to_string(),
109                source: Box::new(err),
110            }),
111            Err(err) if err.kind() == std::io::ErrorKind::NotFound => Ok(Self::default()),
112            Err(err) => Err(err.into()),
113        }
114    }
115}
116
117/// Server daemon configuration, loaded from `boatramp.cfg` (RON). Read by
118/// `boatramp serve`; flags/env override the `serve` values.
119#[derive(Debug, Default, Deserialize)]
120#[serde(default)]
121pub struct ServerConfig {
122    /// Server defaults for `serve` (flag/env override these).
123    pub serve: Option<ServeConfig>,
124    /// Server-side handler runtime config (which backend serves each binding),
125    /// consumed only with the `handlers` feature.
126    pub handlers: Option<HandlersConfig>,
127    /// Self-hosted cluster mode (consumed only with the `cluster` feature).
128    pub cluster: Option<ClusterConfig>,
129    /// Opt-in **compute** backends. Present ⇒ this node
130    /// runs compute workloads via the backends it can offer; absent ⇒ no compute
131    /// (the reconcile loop stays a no-op).
132    pub compute: Option<ComputeConfig>,
133    /// Operator security posture (the hardening knobs): a profile
134    /// preset + overrides, resolved at startup. Absent ⇒ the strict
135    /// `multi-tenant` default. Operator-only — never part of site config.
136    pub security: Option<boatramp_core::security::SecurityConfig>,
137    /// Secrets-at-rest envelope. Absent ⇒ private
138    /// keys stored cleartext in the (replicated) control plane.
139    pub secrets: Option<SecretsConfig>,
140}
141
142/// `secrets` section — envelope encryption for private keys at rest.
143#[cfg_attr(not(feature = "cluster"), allow(dead_code))]
144#[derive(Debug, Clone, Default, Deserialize)]
145#[serde(default, deny_unknown_fields)]
146pub struct SecretsConfig {
147    /// Backend: `"local"` (machine-local AES-256-GCM KEK) or `"vault"` (Vault
148    /// Transit). Empty/other ⇒ no wrapping. In a cluster a local KEK must be the
149    /// **same file on every node** (wrapped certs replicate); Vault avoids that.
150    pub envelope: String,
151    /// Local-KEK key file (`envelope = "local"`). Default
152    /// `<data-dir>/secrets/kek`. Auto-generated `0600` if absent.
153    pub kek_file: Option<PathBuf>,
154    /// Vault Transit config (`envelope = "vault"`).
155    pub vault: Option<VaultSecretsConfig>,
156}
157
158/// Vault Transit settings for `envelope = "vault"`. The token is read from the
159/// environment (`token_env`), never stored in the config file.
160#[cfg_attr(not(all(feature = "cluster", feature = "acme-dns")), allow(dead_code))]
161#[derive(Debug, Clone, Deserialize)]
162#[serde(deny_unknown_fields)]
163pub struct VaultSecretsConfig {
164    /// Vault address, e.g. `https://vault:8200`.
165    pub addr: String,
166    /// Transit key name to wrap under.
167    pub key: String,
168    /// Environment variable holding the Vault token (default `VAULT_TOKEN`).
169    #[serde(default = "default_vault_token_env")]
170    pub token_env: String,
171}
172
173fn default_vault_token_env() -> String {
174    "VAULT_TOKEN".to_string()
175}
176
177impl Default for VaultSecretsConfig {
178    fn default() -> Self {
179        Self {
180            addr: String::new(),
181            key: String::new(),
182            token_env: default_vault_token_env(),
183        }
184    }
185}
186
187impl ServerConfig {
188    /// Parse a `boatramp.cfg` document (RON). Db-binding names declared in the file
189    /// are validated here (the same fail-closed check `load` re-runs after the env
190    /// merge), so a file-only config path — e.g. `boatramp cloudflare` rendering, or
191    /// the operator-resources loader — is guarded even without going through `load`.
192    pub fn parse(text: &str) -> Result<Self, ConfigError> {
193        let config: Self = ron_options().from_str(text)?;
194        config.validate_sql_db_names()?;
195        Ok(config)
196    }
197
198    /// Load from `path` (RON), then layer `BOATRAMP_*` environment overrides on
199    /// top. A missing file yields the default config, so `serve` can be configured
200    /// entirely from the environment (12-factor deployments where dropping a
201    /// `boatramp.cfg` is awkward — fly.io / Cloudflare / containers).
202    pub fn load(path: &Path) -> Result<Self, ConfigError> {
203        let mut config = match std::fs::read_to_string(path) {
204            Ok(contents) => Self::parse(&contents).map_err(|err| ConfigError::File {
205                path: path.display().to_string(),
206                source: Box::new(err),
207            })?,
208            Err(err) if err.kind() == std::io::ErrorKind::NotFound => Self::default(),
209            Err(err) => return Err(err.into()),
210        };
211        config.apply_env_overrides(&EnvSource::Process)?;
212        Ok(config)
213    }
214
215    /// Layer `BOATRAMP_*` environment overrides onto the loaded config for the
216    /// `compute`, `security`, and handler-`sql` sections — the operational knobs
217    /// that were previously reachable only through the `boatramp.cfg` file.
218    ///
219    /// **Precedence: env overrides file.** This matches the existing `serve`
220    /// section (its `#[arg(long, env = …)]` flags already let an env var win over
221    /// the file value), keeping the resolution rule uniform. A set variable
222    /// updates the field even when the file also set it; an unset variable leaves
223    /// the file (or built-in default) untouched. When a section is absent from the
224    /// file but any of its variables are set, the section is materialised from its
225    /// defaults first — so no config file is required to configure it.
226    ///
227    /// `source` supplies the variables (the process environment in production; an
228    /// explicit map in tests), so this stays a pure function of its inputs.
229    fn apply_env_overrides(&mut self, source: &EnvSource) -> Result<(), ConfigError> {
230        // --- compute ---------------------------------------------------------
231        // Materialise `[compute]` only if at least one of its variables is set, so
232        // an unset environment leaves an absent section absent (⇒ no compute).
233        if source.any(COMPUTE_ENV_VARS) {
234            let compute = self.compute.get_or_insert_with(ComputeConfig::default);
235            if let Some(v) = source.get("BOATRAMP_COMPUTE_BRIDGE") {
236                compute.bridge = v;
237            }
238            if let Some(v) = source.get("BOATRAMP_COMPUTE_SUBNET") {
239                compute.subnet = v;
240            }
241            if let Some(v) = source.parse("BOATRAMP_COMPUTE_VCPUS")? {
242                compute.vcpus = v;
243            }
244            if let Some(v) = source.parse("BOATRAMP_COMPUTE_MEM_MIB")? {
245                compute.mem_mib = v;
246            }
247            if let Some(v) = source.get("BOATRAMP_COMPUTE_REGION") {
248                compute.region = Some(v);
249            }
250            if let Some(v) = source.get("BOATRAMP_COMPUTE_SQL_SHIM_URL") {
251                compute.sql_shim_url = Some(v);
252            }
253            // The two shared-kernel enums have no `FromStr`, only a serde
254            // `rename_all = "lowercase"`; map their variants by that same spelling.
255            if let Some(v) = source.parse_enum(
256                "BOATRAMP_COMPUTE_MANAGED_DB_PRIVILEGE",
257                &[
258                    ("rootless", ManagedDbPrivilege::Rootless),
259                    ("caps", ManagedDbPrivilege::Caps),
260                ],
261            )? {
262                compute.managed_db_privilege = v;
263            }
264            if let Some(v) = source.parse_enum(
265                "BOATRAMP_COMPUTE_DOCKER_ENDPOINT",
266                &[
267                    ("published", boatramp_docker::DockerEndpoint::Published),
268                    ("bridge", boatramp_docker::DockerEndpoint::Bridge),
269                ],
270            )? {
271                compute.docker_endpoint = v;
272            }
273            if let Some(v) = source.parse_enum(
274                "BOATRAMP_COMPUTE_DOCKER_VOLUME_MODE",
275                &[
276                    ("named", boatramp_docker::DockerVolumeMode::Named),
277                    ("bind", boatramp_docker::DockerVolumeMode::Bind),
278                ],
279            )? {
280                compute.docker_volume_mode = v;
281            }
282            // Kernel trust anchors — comma-separated lists. These are
283            // security-critical: they are the trust anchor for the posture-scaled
284            // kernel bar, so a value here decides which kernels a `multi-tenant`
285            // node will boot. In a 12-factor deployment the environment IS the
286            // operator's trusted config source (a fly.toml `[env]` is committed the
287            // same as a file), so they are exposed here — but an operator should
288            // know the environment is *more* visible than a file (it leaks through
289            // `/proc/<pid>/environ` and is inherited by every subprocess), so a
290            // file remains the better home for them when one is available.
291            if let Some(v) = source.parse_list("BOATRAMP_COMPUTE_KERNEL_SIGNING_PUBKEYS") {
292                compute.kernel_signing_pubkeys = v;
293            }
294            if let Some(v) = source.parse_list("BOATRAMP_COMPUTE_KERNEL_ALLOWED_HASHES") {
295                compute.kernel_allowed_hashes = v;
296            }
297            // Internal DNS (per-project service discovery on the bridge gateway).
298            if let Some(v) = source.parse_bool("BOATRAMP_COMPUTE_INTERNAL_DNS")? {
299                compute.internal_dns = v;
300            }
301            if let Some(v) = source.get("BOATRAMP_COMPUTE_DNS_UPSTREAM") {
302                compute.dns_upstream = v;
303            }
304            if let Some(v) = source.get("BOATRAMP_COMPUTE_DNS_DOMAIN") {
305                compute.dns_domain = v;
306            }
307        }
308
309        // --- security --------------------------------------------------------
310        // Always materialise `[security]` when any knob is set: an absent section
311        // resolves to the strict `multi-tenant` default, and an env override then
312        // layers over that exactly as a file `overrides` block would.
313        if source.any(SECURITY_ENV_VARS) {
314            let security = self
315                .security
316                .get_or_insert_with(boatramp_core::security::SecurityConfig::default);
317            if let Some(v) = source.get("BOATRAMP_SECURITY_PROFILE") {
318                security.profile = Some(v);
319            }
320            let o = &mut security.overrides;
321            if let Some(v) =
322                source.parse_bool("BOATRAMP_SECURITY_ALLOW_UNAUTHENTICATED_PUBLIC_BIND")?
323            {
324                o.allow_unauthenticated_public_bind = Some(v);
325            }
326            if let Some(v) = source.parse("BOATRAMP_SECURITY_MAX_UPLOAD_BYTES")? {
327                o.max_upload_bytes = Some(v);
328            }
329            if let Some(v) = source.parse_bool("BOATRAMP_SECURITY_ALLOW_SITE_UNIX_UPSTREAMS")? {
330                o.allow_site_unix_upstreams = Some(v);
331            }
332            if let Some(v) = source.parse_bool("BOATRAMP_SECURITY_ALLOW_SITE_PRIVATE_UPSTREAMS")? {
333                o.allow_site_private_upstreams = Some(v);
334            }
335            if let Some(v) = source.parse_bool("BOATRAMP_SECURITY_ALLOW_GUEST_PRIVATE_EGRESS")? {
336                o.allow_guest_private_egress = Some(v);
337            }
338            if let Some(v) = source.parse_bool("BOATRAMP_SECURITY_ALLOW_GUEST_SELF_EGRESS")? {
339                o.allow_guest_self_egress = Some(v);
340            }
341            if let Some(v) = source.parse_bool("BOATRAMP_SECURITY_ALLOW_GUEST_EGRESS_EXTRA_CA")? {
342                o.allow_guest_egress_extra_ca = Some(v);
343            }
344            if let Some(v) = source.parse("BOATRAMP_SECURITY_MAX_HANDLER_BLOB_BYTES")? {
345                o.max_handler_blob_bytes = Some(v);
346            }
347            if let Some(v) = source.parse("BOATRAMP_SECURITY_MAX_COMPONENT_BYTES")? {
348                o.max_component_bytes = Some(v);
349            }
350            if let Some(v) = source.parse_bool("BOATRAMP_SECURITY_OIDC_REQUIRE_AUDIENCE")? {
351                o.oidc_require_audience = Some(v);
352            }
353            if let Some(v) = source.parse_bool("BOATRAMP_SECURITY_DOMAIN_VERIFY_ALLOW_PRIVATE")? {
354                o.domain_verify_allow_private = Some(v);
355            }
356            if let Some(v) = source.parse_bool("BOATRAMP_SECURITY_DOMAIN_VERIFY_SELF_SERVE")? {
357                o.domain_verify_self_serve = Some(v);
358            }
359            if let Some(v) = source.parse_bool("BOATRAMP_SECURITY_ALLOW_SHARED_KERNEL_COMPUTE")? {
360                o.allow_shared_kernel_compute = Some(v);
361            }
362            if let Some(v) = source.parse_bool("BOATRAMP_SECURITY_ALLOW_COMPUTE_EXEC")? {
363                o.allow_compute_exec = Some(v);
364            }
365            if let Some(v) = source.parse_bool("BOATRAMP_SECURITY_RATELIMIT_FAIL_OPEN")? {
366                o.ratelimit_fail_open = Some(v);
367            }
368            if let Some(v) = source.parse_bool("BOATRAMP_SECURITY_ALLOW_IMPLICIT_ROUTING")? {
369                o.allow_implicit_routing = Some(v);
370            }
371            if let Some(v) = source.parse_bool("BOATRAMP_SECURITY_REQUIRE_POP")? {
372                o.require_pop = Some(v);
373            }
374            if let Some(v) = source.parse_bool("BOATRAMP_SECURITY_REQUIRE_DOMAIN_VERIFICATION")? {
375                o.require_domain_verification = Some(v);
376            }
377            if let Some(v) = source.parse_bool("BOATRAMP_SECURITY_ALLOW_ENV_SECRET_REFS")? {
378                o.allow_env_secret_refs = Some(v);
379            }
380            // The multi-tenant sub-knobs (Gap 4b): previously file-only, now env-settable so a
381            // 12-factor deployment can tune tenancy isolation + guest capability minting without a
382            // `boatramp.cfg`. Fleet-scoped (a per-project override still lives in the config file).
383            if let Some(v) = source.parse_bool("BOATRAMP_SECURITY_REQUIRE_TENANCY_DECLARATION")? {
384                o.require_tenancy_declaration = Some(v);
385            }
386            if let Some(v) = source.parse_bool("BOATRAMP_SECURITY_ALLOW_CROSS_TENANT_DB")? {
387                o.allow_cross_tenant_db = Some(v);
388            }
389            if let Some(v) = source.parse_bool("BOATRAMP_SECURITY_ALLOW_GUEST_MINT_CAPABILITY")? {
390                o.allow_guest_mint_capability = Some(v);
391            }
392            if let Some(v) = source.parse("BOATRAMP_SECURITY_MAX_GUEST_CAPABILITY_TTL_SECS")? {
393                o.max_guest_capability_ttl_secs = Some(v);
394            }
395            // Remaining guest-feature knobs — env parity for a 12-factor fleet that runs env-only
396            // (no `boatramp.cfg`). Each preset defaults these OFF under `multi-tenant`, so an
397            // env-only multi-tenant deployment had no lever to opt a guest feature back on. The
398            // override field + `apply()` + `explain()` already exist for every one; only the env
399            // mapping was missing (`allow_guest_email` regressed prod SMTP on the P48 cutover).
400            if let Some(v) = source.parse_bool("BOATRAMP_SECURITY_ALLOW_GUEST_EMAIL")? {
401                o.allow_guest_email = Some(v);
402            }
403            if let Some(v) = source.parse_bool("BOATRAMP_SECURITY_ALLOW_GUEST_ADMIN_DOMAINS")? {
404                o.allow_guest_admin_domains = Some(v);
405            }
406            if let Some(v) = source.parse_bool("BOATRAMP_SECURITY_ALLOW_GUEST_ADMIN_EMAIL")? {
407                o.allow_guest_admin_email = Some(v);
408            }
409            if let Some(v) = source.parse_bool("BOATRAMP_SECURITY_ALLOW_GUEST_ADMIN_SITE")? {
410                o.allow_guest_admin_site = Some(v);
411            }
412            if let Some(v) = source.parse_bool("BOATRAMP_SECURITY_ALLOW_GUEST_ADMIN_SECRETS")? {
413                o.allow_guest_admin_secrets = Some(v);
414            }
415        }
416
417        // --- handler sql (`handlers.bindings.sql`) ---------------------------
418        // Materialise the nested `handlers.bindings.sql` chain only when a `sql`
419        // variable is set, so an unset environment doesn't conjure an empty
420        // handlers section. The variables mirror the config path
421        // (`BOATRAMP_HANDLERS_SQL_*`) and cover the cluster-vs-single-node knobs;
422        // secrets stay indirected via `*_TOKEN_ENV` names, never the token itself.
423        if source.any(SQL_ENV_VARS) {
424            let handlers = self.handlers.get_or_insert_with(HandlersConfig::default);
425            let sql = handlers
426                .bindings
427                .sql
428                .get_or_insert_with(SqlBindingConfig::default);
429            if let Some(v) = source.get("BOATRAMP_HANDLERS_SQL_DIR") {
430                sql.dir = Some(PathBuf::from(v));
431            }
432            if let Some(v) = source.get("BOATRAMP_HANDLERS_SQL_URL") {
433                sql.url = Some(v);
434            }
435            if let Some(v) = source.get("BOATRAMP_HANDLERS_SQL_ADMIN_URL") {
436                sql.admin_url = Some(v);
437            }
438            if let Some(v) = source.get("BOATRAMP_HANDLERS_SQL_REPLICA_URL") {
439                sql.replica_url = Some(v);
440            }
441            if let Some(v) = source.get("BOATRAMP_HANDLERS_SQL_TOKEN_ENV") {
442                sql.token_env = Some(v);
443            }
444            if let Some(v) = source.get("BOATRAMP_HANDLERS_SQL_ADMIN_TOKEN_ENV") {
445                sql.admin_token_env = Some(v);
446            }
447            if let Some(v) = source.get("BOATRAMP_HANDLERS_SQL_PREVIEW_MODE") {
448                sql.preview_mode = Some(v);
449            }
450            if let Some(v) = source.get("BOATRAMP_HANDLERS_SQL_PREVIEW_INIT") {
451                sql.preview_init = Some(PathBuf::from(v));
452            }
453            if let Some(v) = source.parse("BOATRAMP_HANDLERS_SQL_DEPROVISION_GRACE_SECS")? {
454                sql.deprovision_grace_secs = Some(v);
455            }
456        }
457
458        // --- handler sql external databases (`handlers.bindings.sql.databases`) ---
459        // The bring-your-own / managed-compute DB map, keyed by name. There is no
460        // config file to enumerate the members, so the member names are discovered
461        // from the environment: any `BOATRAMP_HANDLERS_SQL_DB_<NAME>_<FIELD>`
462        // variable declares database `<NAME>`. Each env-declared DB is merged into
463        // (overriding, per field, by key) whatever the file already declared under
464        // that name — the same env-over-file precedence as the scalars.
465        //
466        // The default database (the binding a handler opens as `sql.open("")`) is
467        // addressed by the reserved `DEFAULT` token, which can't appear as a literal
468        // in a variable name: `BOATRAMP_HANDLERS_SQL_DB_DEFAULT_KIND` populates the
469        // reserved [`DEFAULT_DB_NAME`](boatramp_core::project::DEFAULT_DB_NAME) key
470        // (`"default"`). As of v0.5.0 this is a real, path-segment-safe name (never the
471        // empty string), so the binding is addressable as `--db default` and every
472        // db-name ingress carries a valid URL path segment. The guest-facing
473        // `sql.open("")` contract is preserved by aliasing `"" ⇄ "default"` at the
474        // backend-resolution boundary — external bindings are a pure label over their
475        // connection params, so the renamed binding points at the SAME physical DB.
476        if source.any_with_prefix(SQL_DB_ENV_PREFIX) {
477            let handlers = self.handlers.get_or_insert_with(HandlersConfig::default);
478            let sql = handlers
479                .bindings
480                .sql
481                .get_or_insert_with(SqlBindingConfig::default);
482            for name in source.sql_database_names() {
483                // `DEFAULT` is the reserved token for the default database; it maps to
484                // the reserved real name `"default"` (v0.5.0; was the empty string).
485                let key = if name == "DEFAULT" {
486                    boatramp_core::project::DEFAULT_DB_NAME.to_string()
487                } else {
488                    name.clone()
489                };
490                let db = sql.databases.entry(key).or_default();
491                let prefix = format!("{SQL_DB_ENV_PREFIX}{name}_");
492                if let Some(v) = source.get(&format!("{prefix}KIND")) {
493                    db.kind = v;
494                }
495                if let Some(v) = source.get(&format!("{prefix}URL_ENV")) {
496                    db.url_env = v;
497                }
498                if let Some(v) = source.get(&format!("{prefix}READ_URL_ENV")) {
499                    db.read_url_env = Some(v);
500                }
501                if let Some(v) = source.get(&format!("{prefix}COMPUTE")) {
502                    db.compute = Some(v);
503                }
504                if let Some(v) = source.get(&format!("{prefix}DATABASE")) {
505                    db.database = Some(v);
506                }
507                if let Some(v) = source.get(&format!("{prefix}USER")) {
508                    db.user = Some(v);
509                }
510                if let Some(v) = source.get(&format!("{prefix}PASSWORD_ENV")) {
511                    db.password_env = Some(v);
512                }
513                if let Some(v) = source.parse(&format!("{prefix}POOL_MAX"))? {
514                    db.pool_max = Some(v);
515                }
516                if let Some(v) = source.parse_bool(&format!("{prefix}READ_ONLY"))? {
517                    db.read_only = v;
518                }
519                if let Some(v) = source.parse_bool(&format!("{prefix}ALLOW_PREVIEW"))? {
520                    db.allow_preview = v;
521                }
522                if let Some(v) = source.parse(&format!("{prefix}CONNECT_TIMEOUT_SECS"))? {
523                    db.connect_timeout_secs = Some(v);
524                }
525                if let Some(v) = source.get(&format!("{prefix}IMAGE")) {
526                    db.image = Some(v);
527                }
528                if let Some(v) = source.parse(&format!("{prefix}VOLUME_SIZE_MIB"))? {
529                    db.volume_size_mib = Some(v);
530                }
531                if let Some(v) = source.parse(&format!("{prefix}STARTUP_GRACE_SECS"))? {
532                    db.startup_grace_secs = Some(v);
533                }
534                if let Some(v) = source.parse_enum(
535                    &format!("{prefix}TENANT"),
536                    &[
537                        ("single", TenantIsolation::Single),
538                        ("shared", TenantIsolation::Shared),
539                    ],
540                )? {
541                    db.tenant = v;
542                }
543                if let Some(v) = source.parse_enum(
544                    &format!("{prefix}TENANT_SCOPE"),
545                    &[
546                        ("project", TenantScope::Project),
547                        ("site", TenantScope::Site),
548                    ],
549                )? {
550                    db.tenant_scope = v;
551                }
552                if let Some(v) = source.parse_bool(&format!("{prefix}RLS_SESSION"))? {
553                    db.rls_session = v;
554                }
555                if let Some(v) = source.get(&format!("{prefix}TENANT_GUC")) {
556                    db.tenant_guc = Some(v);
557                }
558                if let Some(v) = source.get(&format!("{prefix}SESSION_GUC")) {
559                    db.session_guc = Some(v);
560                }
561                if let Some(v) = source.get(&format!("{prefix}TENANT_ALL_MARKER")) {
562                    db.tenant_all_marker = Some(v);
563                }
564            }
565        }
566
567        // --- secrets (`[secrets]`) -------------------------------------------
568        // Envelope encryption for private keys at rest. `kek_file` holds a *path*
569        // (never key material) and the Vault token stays indirected via
570        // `token_env` (a variable name, not the token). Materialise the nested
571        // `vault` sub-config only when a vault variable is set.
572        if source.any(SECRETS_ENV_VARS) {
573            let secrets = self.secrets.get_or_insert_with(SecretsConfig::default);
574            if let Some(v) = source.get("BOATRAMP_SECRETS_ENVELOPE") {
575                secrets.envelope = v;
576            }
577            if let Some(v) = source.get("BOATRAMP_SECRETS_KEK_FILE") {
578                secrets.kek_file = Some(PathBuf::from(v));
579            }
580            if source.any(SECRETS_VAULT_ENV_VARS) {
581                let vault = secrets
582                    .vault
583                    .get_or_insert_with(VaultSecretsConfig::default);
584                if let Some(v) = source.get("BOATRAMP_SECRETS_VAULT_ADDR") {
585                    vault.addr = v;
586                }
587                if let Some(v) = source.get("BOATRAMP_SECRETS_VAULT_KEY") {
588                    vault.key = v;
589                }
590                if let Some(v) = source.get("BOATRAMP_SECRETS_VAULT_TOKEN_ENV") {
591                    vault.token_env = v;
592                }
593            }
594        }
595
596        // --- cluster (`[cluster]`) -------------------------------------------
597        // The self-hosted cluster section's own fields. The founding/joining
598        // *actions* already have their own `serve` flags with env
599        // (`BOATRAMP_CLUSTER_INIT` / `_JOIN` / `_ADVERTISE_ADDR`); those are
600        // distinct from — and not duplicated by — the `[cluster]` section fields
601        // exposed here. `join_token` keeps a secret out of plain sight via the
602        // usual `env:VAR` / `path:/file` prefix, so the env holds the *reference*,
603        // not the token. `ClusterConfig` has no `Default` (a founder needs at least
604        // a `listen`), so a `BOATRAMP_CLUSTER_LISTEN` is required to materialise an
605        // absent section from the environment.
606        if source.any(CLUSTER_ENV_VARS) {
607            // Materialise an absent section only if a bind address is supplied;
608            // otherwise there is no valid `ClusterConfig` to build (it has no
609            // `Default` — a node must know where to bind its mesh). When the file
610            // already declared `[cluster]`, its `listen` stands and the other env
611            // fields layer over it even without `BOATRAMP_CLUSTER_LISTEN`.
612            let listen = source.parse::<SocketAddr>("BOATRAMP_CLUSTER_LISTEN")?;
613            if self.cluster.is_none() {
614                if let Some(listen) = listen {
615                    self.cluster = Some(ClusterConfig {
616                        listen,
617                        root_pubkeys: Vec::new(),
618                        seeds: Vec::new(),
619                        join_token: None,
620                        store_dir: None,
621                        mesh: None,
622                    });
623                }
624            }
625            if let Some(cluster) = self.cluster.as_mut() {
626                // A `listen` override applies to an already-present section too (a
627                // freshly materialised one already carries it).
628                if let Some(v) = listen {
629                    cluster.listen = v;
630                }
631                if let Some(v) = source.parse_list("BOATRAMP_CLUSTER_ROOT_PUBKEYS") {
632                    cluster.root_pubkeys = v;
633                }
634                if let Some(v) = source.parse_list("BOATRAMP_CLUSTER_SEEDS") {
635                    cluster.seeds = v;
636                }
637                if let Some(v) = source.get("BOATRAMP_CLUSTER_JOIN_TOKEN") {
638                    cluster.join_token = Some(v);
639                }
640                if let Some(v) = source.get("BOATRAMP_CLUSTER_STORE_DIR") {
641                    cluster.store_dir = Some(PathBuf::from(v));
642                }
643                if source.any(CLUSTER_MESH_ENV_VARS) {
644                    let mesh = cluster.mesh.get_or_insert_with(MeshConfig::default);
645                    if let Some(v) = source.get("BOATRAMP_CLUSTER_MESH_KEY_FILE") {
646                        mesh.key_file = Some(PathBuf::from(v));
647                    }
648                    if let Some(v) = source.get("BOATRAMP_CLUSTER_MESH_KEY_ROTATION") {
649                        mesh.key_rotation = Some(v);
650                    }
651                    if let Some(v) = source.get("BOATRAMP_CLUSTER_MESH_JOIN_TOKEN_TTL") {
652                        mesh.join_token_ttl = Some(v);
653                    }
654                    if let Some(v) =
655                        source.parse_bool("BOATRAMP_CLUSTER_MESH_GATE_CLIENT_WRITES")?
656                    {
657                        mesh.gate_client_writes = Some(v);
658                    }
659                }
660            }
661        }
662
663        // Fail closed on any db-binding name that is not a safe URL path segment.
664        // Runs on the fully merged (file + env) `databases` map, so it catches a name
665        // from either source — and (crucially) the legacy empty-string default key,
666        // which is no longer produced by the `DEFAULT` token but could still be
667        // written literally in a `boatramp.cfg` file.
668        self.validate_sql_db_names()?;
669        Ok(())
670    }
671
672    /// Validate every configured `handlers.bindings.sql.databases` binding name
673    /// through the one canonical [`validate_resource_name`](boatramp_core::project::validate_resource_name)
674    /// (`kind = "database"`). A db-binding name is threaded verbatim into the
675    /// control-plane URL (`/api/sql/{db}/…`, `/api/migrate/{db}/…`) and the CLI
676    /// `--db`, so it must be a non-empty, path-segment-safe identifier — the same rule
677    /// project/site/function names already pass. The empty-string legacy default key
678    /// gets a targeted cure pointing at the reserved `default` name.
679    fn validate_sql_db_names(&self) -> Result<(), ConfigError> {
680        let Some(databases) = self
681            .handlers
682            .as_ref()
683            .and_then(|h| h.bindings.sql.as_ref())
684            .map(|s| &s.databases)
685        else {
686            return Ok(());
687        };
688        for name in databases.keys() {
689            if let Err(err) = boatramp_core::project::validate_resource_name("database", name) {
690                // The empty-string case is the pre-v0.5.0 default binding key: point
691                // at the cure (name it `default`, or set nothing and let the reserved
692                // `DEFAULT` token map to `default` automatically).
693                let cure = if name.is_empty() {
694                    " — name your default binding `default` (or set \
695                     BOATRAMP_HANDLERS_SQL_DB_DEFAULT_*, which now maps to `default` \
696                     automatically); see the v0.5.0 CHANGELOG"
697                } else {
698                    ""
699                };
700                return Err(ConfigError::InvalidDbName {
701                    name: err.value,
702                    reason: err.reason,
703                    cure,
704                });
705            }
706        }
707        Ok(())
708    }
709}
710
711/// The `BOATRAMP_*` variables that populate the `[compute]` section. Kept as one
712/// list so [`ServerConfig::apply_env_overrides`] can decide whether to materialise
713/// an absent section without repeating the names.
714const COMPUTE_ENV_VARS: &[&str] = &[
715    "BOATRAMP_COMPUTE_BRIDGE",
716    "BOATRAMP_COMPUTE_SUBNET",
717    "BOATRAMP_COMPUTE_VCPUS",
718    "BOATRAMP_COMPUTE_MEM_MIB",
719    "BOATRAMP_COMPUTE_REGION",
720    "BOATRAMP_COMPUTE_SQL_SHIM_URL",
721    "BOATRAMP_COMPUTE_MANAGED_DB_PRIVILEGE",
722    "BOATRAMP_COMPUTE_DOCKER_ENDPOINT",
723    "BOATRAMP_COMPUTE_DOCKER_VOLUME_MODE",
724    "BOATRAMP_COMPUTE_KERNEL_SIGNING_PUBKEYS",
725    "BOATRAMP_COMPUTE_KERNEL_ALLOWED_HASHES",
726    "BOATRAMP_COMPUTE_INTERNAL_DNS",
727    "BOATRAMP_COMPUTE_DNS_UPSTREAM",
728    "BOATRAMP_COMPUTE_DNS_DOMAIN",
729];
730
731/// The `BOATRAMP_*` variables that populate the `[security]` section.
732const SECURITY_ENV_VARS: &[&str] = &[
733    "BOATRAMP_SECURITY_PROFILE",
734    "BOATRAMP_SECURITY_ALLOW_UNAUTHENTICATED_PUBLIC_BIND",
735    "BOATRAMP_SECURITY_MAX_UPLOAD_BYTES",
736    "BOATRAMP_SECURITY_ALLOW_SITE_UNIX_UPSTREAMS",
737    "BOATRAMP_SECURITY_ALLOW_SITE_PRIVATE_UPSTREAMS",
738    "BOATRAMP_SECURITY_ALLOW_GUEST_PRIVATE_EGRESS",
739    "BOATRAMP_SECURITY_ALLOW_GUEST_SELF_EGRESS",
740    "BOATRAMP_SECURITY_ALLOW_GUEST_EGRESS_EXTRA_CA",
741    "BOATRAMP_SECURITY_MAX_HANDLER_BLOB_BYTES",
742    "BOATRAMP_SECURITY_MAX_COMPONENT_BYTES",
743    "BOATRAMP_SECURITY_OIDC_REQUIRE_AUDIENCE",
744    "BOATRAMP_SECURITY_DOMAIN_VERIFY_ALLOW_PRIVATE",
745    "BOATRAMP_SECURITY_DOMAIN_VERIFY_SELF_SERVE",
746    "BOATRAMP_SECURITY_ALLOW_SHARED_KERNEL_COMPUTE",
747    "BOATRAMP_SECURITY_ALLOW_COMPUTE_EXEC",
748    "BOATRAMP_SECURITY_RATELIMIT_FAIL_OPEN",
749    "BOATRAMP_SECURITY_ALLOW_IMPLICIT_ROUTING",
750    "BOATRAMP_SECURITY_REQUIRE_POP",
751    "BOATRAMP_SECURITY_REQUIRE_DOMAIN_VERIFICATION",
752    "BOATRAMP_SECURITY_ALLOW_ENV_SECRET_REFS",
753    "BOATRAMP_SECURITY_REQUIRE_TENANCY_DECLARATION",
754    "BOATRAMP_SECURITY_ALLOW_CROSS_TENANT_DB",
755    "BOATRAMP_SECURITY_ALLOW_GUEST_MINT_CAPABILITY",
756    "BOATRAMP_SECURITY_MAX_GUEST_CAPABILITY_TTL_SECS",
757    "BOATRAMP_SECURITY_ALLOW_GUEST_EMAIL",
758    "BOATRAMP_SECURITY_ALLOW_GUEST_ADMIN_DOMAINS",
759    "BOATRAMP_SECURITY_ALLOW_GUEST_ADMIN_EMAIL",
760    "BOATRAMP_SECURITY_ALLOW_GUEST_ADMIN_SITE",
761    "BOATRAMP_SECURITY_ALLOW_GUEST_ADMIN_SECRETS",
762];
763
764/// The `BOATRAMP_*` variables that populate `handlers.bindings.sql`.
765const SQL_ENV_VARS: &[&str] = &[
766    "BOATRAMP_HANDLERS_SQL_DIR",
767    "BOATRAMP_HANDLERS_SQL_URL",
768    "BOATRAMP_HANDLERS_SQL_ADMIN_URL",
769    "BOATRAMP_HANDLERS_SQL_REPLICA_URL",
770    "BOATRAMP_HANDLERS_SQL_TOKEN_ENV",
771    "BOATRAMP_HANDLERS_SQL_ADMIN_TOKEN_ENV",
772    "BOATRAMP_HANDLERS_SQL_PREVIEW_MODE",
773    "BOATRAMP_HANDLERS_SQL_PREVIEW_INIT",
774    "BOATRAMP_HANDLERS_SQL_DEPROVISION_GRACE_SECS",
775];
776
777/// The fixed prefix of a keyed `handlers.bindings.sql.databases` variable —
778/// `BOATRAMP_HANDLERS_SQL_DB_<NAME>_<FIELD>`. Member names aren't known ahead of
779/// time (there is no config file to enumerate them), so they are discovered by
780/// scanning the environment for this prefix.
781const SQL_DB_ENV_PREFIX: &str = "BOATRAMP_HANDLERS_SQL_DB_";
782
783/// The recognised `_<FIELD>` suffixes of a `databases` variable, ordered so a
784/// name-isolating strip matches the **longest** suffix first (`_READ_URL_ENV`
785/// before `_URL_ENV`). Each mirrors a field of [`ExternalDatabaseConfig`].
786const SQL_DB_FIELD_SUFFIXES: &[&str] = &[
787    "_STARTUP_GRACE_SECS",
788    "_CONNECT_TIMEOUT_SECS",
789    // `_SESSION_GUC` / `_TENANT_GUC` / `_TENANT_ALL_MARKER` before `_TENANT`/`_TENANT_SCOPE`
790    // (longest-first name isolation).
791    "_SESSION_GUC",
792    "_TENANT_ALL_MARKER",
793    "_TENANT_GUC",
794    "_VOLUME_SIZE_MIB",
795    "_READ_URL_ENV",
796    "_PASSWORD_ENV",
797    "_ALLOW_PREVIEW",
798    "_URL_ENV",
799    "_DATABASE",
800    "_READ_ONLY",
801    "_POOL_MAX",
802    "_RLS_SESSION",
803    "_TENANT_SCOPE",
804    "_COMPUTE",
805    "_TENANT",
806    "_IMAGE",
807    "_KIND",
808    "_USER",
809];
810
811/// The `BOATRAMP_*` variables that populate the `[secrets]` section (excluding the
812/// nested `vault` sub-config, gated separately by [`SECRETS_VAULT_ENV_VARS`]).
813const SECRETS_ENV_VARS: &[&str] = &[
814    "BOATRAMP_SECRETS_ENVELOPE",
815    "BOATRAMP_SECRETS_KEK_FILE",
816    "BOATRAMP_SECRETS_VAULT_ADDR",
817    "BOATRAMP_SECRETS_VAULT_KEY",
818    "BOATRAMP_SECRETS_VAULT_TOKEN_ENV",
819];
820
821/// The `BOATRAMP_*` variables that populate the nested `[secrets.vault]` sub-config.
822const SECRETS_VAULT_ENV_VARS: &[&str] = &[
823    "BOATRAMP_SECRETS_VAULT_ADDR",
824    "BOATRAMP_SECRETS_VAULT_KEY",
825    "BOATRAMP_SECRETS_VAULT_TOKEN_ENV",
826];
827
828/// The `BOATRAMP_*` variables that populate the `[cluster]` section fields (the
829/// section's own config, distinct from the founding/joining *action* flags
830/// `BOATRAMP_CLUSTER_INIT` / `_JOIN` / `_ADVERTISE_ADDR`, which are `serve` clap
831/// args and are deliberately not listed here).
832const CLUSTER_ENV_VARS: &[&str] = &[
833    "BOATRAMP_CLUSTER_LISTEN",
834    "BOATRAMP_CLUSTER_ROOT_PUBKEYS",
835    "BOATRAMP_CLUSTER_SEEDS",
836    "BOATRAMP_CLUSTER_JOIN_TOKEN",
837    "BOATRAMP_CLUSTER_STORE_DIR",
838    "BOATRAMP_CLUSTER_MESH_KEY_FILE",
839    "BOATRAMP_CLUSTER_MESH_KEY_ROTATION",
840    "BOATRAMP_CLUSTER_MESH_JOIN_TOKEN_TTL",
841    "BOATRAMP_CLUSTER_MESH_GATE_CLIENT_WRITES",
842];
843
844/// The `BOATRAMP_*` variables that populate the nested `[cluster.mesh]` sub-config.
845const CLUSTER_MESH_ENV_VARS: &[&str] = &[
846    "BOATRAMP_CLUSTER_MESH_KEY_FILE",
847    "BOATRAMP_CLUSTER_MESH_KEY_ROTATION",
848    "BOATRAMP_CLUSTER_MESH_JOIN_TOKEN_TTL",
849    "BOATRAMP_CLUSTER_MESH_GATE_CLIENT_WRITES",
850];
851
852/// Where env-override values come from: the real process environment, or an
853/// explicit map for a deterministic unit test. Keeping the lookup behind this enum
854/// lets [`ServerConfig::apply_env_overrides`] be tested without touching (racy,
855/// process-global) `std::env`.
856enum EnvSource {
857    /// The live process environment (`std::env::var`).
858    Process,
859    /// A fixed name→value map (tests only).
860    #[cfg(test)]
861    Map(BTreeMap<String, String>),
862}
863
864impl EnvSource {
865    /// The value of `var`, if set to a non-empty string. An empty value is treated
866    /// as unset so an accidental `VAR=` doesn't clobber a file value with `""`.
867    fn get(&self, var: &str) -> Option<String> {
868        let raw = match self {
869            Self::Process => std::env::var(var).ok(),
870            #[cfg(test)]
871            Self::Map(m) => m.get(var).cloned(),
872        };
873        raw.filter(|v| !v.is_empty())
874    }
875
876    /// Whether any of `vars` is set (to a non-empty value).
877    fn any(&self, vars: &[&str]) -> bool {
878        vars.iter().any(|v| self.get(v).is_some())
879    }
880
881    /// Whether any variable whose name starts with `prefix` is set (to a
882    /// non-empty value). Used to decide whether to materialise a keyed map (the
883    /// `databases` env scheme) whose member names aren't known ahead of time.
884    fn any_with_prefix(&self, prefix: &str) -> bool {
885        self.names()
886            .any(|name| name.starts_with(prefix) && self.get(&name).is_some())
887    }
888
889    /// The full set of variable names visible to this source. Used to discover the
890    /// keyed-map member names from the environment (there is no config file to
891    /// enumerate them). Returned owned so it doesn't borrow the process env.
892    fn names(&self) -> Box<dyn Iterator<Item = String> + '_> {
893        match self {
894            Self::Process => Box::new(std::env::vars().map(|(k, _)| k)),
895            #[cfg(test)]
896            Self::Map(m) => Box::new(m.keys().cloned()),
897        }
898    }
899
900    /// Parse `var` as one of a fixed set of string-mapped variants, mapping an
901    /// unknown value to a clear [`ConfigError::Env`] that names the variable and
902    /// the accepted values. Used for the config enums that have no `FromStr`
903    /// (their only string mapping is a serde `rename_all`). `Ok(None)` when unset.
904    fn parse_enum<T: Copy>(
905        &self,
906        var: &str,
907        variants: &[(&str, T)],
908    ) -> Result<Option<T>, ConfigError> {
909        match self.get(var) {
910            Some(raw) => {
911                let lower = raw.trim().to_ascii_lowercase();
912                variants
913                    .iter()
914                    .find(|(name, _)| *name == lower)
915                    .map(|(_, v)| Some(*v))
916                    .ok_or_else(|| ConfigError::Env {
917                        var: var.to_string(),
918                        reason: format!(
919                            "expected one of {}, got {raw:?}",
920                            variants
921                                .iter()
922                                .map(|(n, _)| *n)
923                                .collect::<Vec<_>>()
924                                .join("/")
925                        ),
926                    })
927            }
928            None => Ok(None),
929        }
930    }
931
932    /// The distinct `<NAME>` tokens of every `BOATRAMP_HANDLERS_SQL_DB_<NAME>_<FIELD>`
933    /// variable that is set. The name is everything between the fixed prefix and the
934    /// *last* `_<FIELD>` segment, so a database name may itself contain underscores
935    /// (the field suffix is one of a known set). Returned sorted + de-duplicated so
936    /// the map is built deterministically.
937    fn sql_database_names(&self) -> Vec<String> {
938        let mut names: Vec<String> = self
939            .names()
940            .filter(|n| n.starts_with(SQL_DB_ENV_PREFIX) && self.get(n).is_some())
941            .filter_map(|n| {
942                let rest = n.strip_prefix(SQL_DB_ENV_PREFIX)?;
943                // Strip the recognised field suffix to isolate `<NAME>`. The suffixes
944                // are matched longest-first so `READ_URL_ENV` wins over `URL_ENV`.
945                SQL_DB_FIELD_SUFFIXES
946                    .iter()
947                    .find_map(|suffix| rest.strip_suffix(suffix))
948                    .filter(|name| !name.is_empty())
949                    .map(str::to_string)
950            })
951            .collect();
952        names.sort();
953        names.dedup();
954        names
955    }
956
957    /// Parse `var` as a **comma-separated** list of non-empty trimmed items, e.g.
958    /// the kernel trust anchors. A single value (no comma) yields a one-element
959    /// list. Empty items are dropped so a trailing comma or doubled separator is
960    /// tolerated. `Ok(None)` when unset; `Some(Vec::new())` never happens (an
961    /// all-empty value is treated as unset by [`Self::get`]).
962    fn parse_list(&self, var: &str) -> Option<Vec<String>> {
963        self.get(var).map(|raw| {
964            raw.split(',')
965                .map(str::trim)
966                .filter(|s| !s.is_empty())
967                .map(str::to_string)
968                .collect()
969        })
970    }
971
972    /// Parse `var` as any [`FromStr`](std::str::FromStr) type (numbers), mapping a
973    /// parse failure to a clear [`ConfigError::Env`]. `Ok(None)` when the variable
974    /// is unset.
975    fn parse<T>(&self, var: &str) -> Result<Option<T>, ConfigError>
976    where
977        T: std::str::FromStr,
978        T::Err: std::fmt::Display,
979    {
980        match self.get(var) {
981            Some(raw) => raw.parse::<T>().map(Some).map_err(|e| ConfigError::Env {
982                var: var.to_string(),
983                reason: e.to_string(),
984            }),
985            None => Ok(None),
986        }
987    }
988
989    /// Parse `var` as a boolean, accepting the common truthy/falsey spellings
990    /// (`true`/`false`, `1`/`0`, `yes`/`no`, `on`/`off`) case-insensitively so an
991    /// operator isn't surprised by a strict `true`-only parse. `Ok(None)` when
992    /// unset.
993    fn parse_bool(&self, var: &str) -> Result<Option<bool>, ConfigError> {
994        match self.get(var) {
995            Some(raw) => match raw.trim().to_ascii_lowercase().as_str() {
996                "true" | "1" | "yes" | "on" => Ok(Some(true)),
997                "false" | "0" | "no" | "off" => Ok(Some(false)),
998                other => Err(ConfigError::Env {
999                    var: var.to_string(),
1000                    reason: format!("expected a boolean (true/false), got {other:?}"),
1001                }),
1002            },
1003            None => Ok(None),
1004        }
1005    }
1006}
1007
1008/// How a **managed database** (PLAN-managed-compute-sql) runs its stock image on a
1009/// shared-kernel backend, whose entrypoint would otherwise fail under the dropped-`ALL`
1010/// hardening. `rootless` (the default) needs no capabilities and works under any
1011/// posture; `caps` is the fallback for an image that won't run rootless.
1012#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Deserialize)]
1013#[serde(rename_all = "lowercase")]
1014pub enum ManagedDbPrivilege {
1015    /// Run the DB as its image's user (`999:999` for the official postgres/mysql
1016    /// images) against a pre-owned volume — no added capabilities, any posture.
1017    #[default]
1018    Rootless,
1019    /// Add the minimal capability set the entrypoint needs (`CHOWN`, `DAC_OVERRIDE`,
1020    /// `FOWNER`, `SETUID`, `SETGID`). Honored only under the single-tenant posture.
1021    Caps,
1022}
1023
1024/// `compute` section — opt-in compute backends. Present
1025/// ⇒ `serve` registers the backends this node can offer and advertises them to
1026/// the scheduler; backends are capability-detected (container on Linux, remote
1027/// docker when a daemon is reachable, VMM when `/dev/kvm` exists).
1028#[derive(Debug, Clone, Deserialize)]
1029#[serde(default, deny_unknown_fields)]
1030pub struct ComputeConfig {
1031    /// Bridge the container veths / VM taps attach to (default `br-boatramp`).
1032    pub bridge: String,
1033    /// Guest IP subnet (default `10.0.0.0/24`).
1034    pub subnet: String,
1035    /// vCPUs this node advertises as schedulable (`0` ⇒ detect from the host).
1036    pub vcpus: u32,
1037    /// Memory (MiB) this node advertises as schedulable (`0` ⇒ a 1 GiB default).
1038    pub mem_mib: u32,
1039    /// **Static** kernel-signing public keys (`"<alg>:<hex>"`) — the trust anchor
1040    /// for the posture-scaled kernel bar. Under `multi-tenant`, a dynamically-
1041    /// selected default kernel must carry a signature verifying against one of
1042    /// these. Host-access-gated (never in the KV tier); changing it needs a
1043    /// restart. Empty ⇒ no kernel may be signed-verified (strict posture then
1044    /// accepts none).
1045    pub kernel_signing_pubkeys: Vec<String>,
1046    /// **Static** allow-list of kernel content hashes (sha256 hex) a dynamic
1047    /// default may select under `multi-tenant`. Host-access-gated. Empty ⇒ no
1048    /// kernel is allow-listed.
1049    pub kernel_allowed_hashes: Vec<String>,
1050    /// This node's **region** tag (FA-8). Advertised on the compute `Node` so a
1051    /// gateway routing to a `compute:`-backed workload with `--lb nearest` sends
1052    /// each request to the nearest replica by its node's region — no manual
1053    /// `--region` map. `None` ⇒ region-agnostic.
1054    pub region: Option<String>,
1055    /// How the remote-Docker backend reports a workload's reachable endpoint.
1056    /// `published` (default) publishes the container port on `127.0.0.1:<ephemeral>`
1057    /// so a host-native `serve` reaches it on any daemon (incl. Docker Desktop /
1058    /// macOS, where the bridge IP is not host-routable); `bridge` routes to the
1059    /// container bridge IP directly (only when `serve` shares the daemon's network).
1060    pub docker_endpoint: boatramp_docker::DockerEndpoint,
1061    /// How the remote-Docker backend backs a workload's persistent volumes.
1062    /// `named` (default) attaches a daemon-managed `docker volume` by name (portable
1063    /// across daemons + Docker Desktop / macOS); `bind` bind-mounts a host directory
1064    /// under `<data_dir>/compute/volumes/<name>` (local daemon only).
1065    pub docker_volume_mode: boatramp_docker::DockerVolumeMode,
1066    /// Guest-reachable base URL of the compute **sql-shim** (PLAN-compute-bindings) —
1067    /// e.g. `http://10.0.0.1:8081` (the compute bridge gateway) or the docker bridge
1068    /// gateway. Set ⇒ a workload's `--bind sql` reaches the managed database through a
1069    /// listener bound on `0.0.0.0:<port>`. `None` (default) ⇒ compute sql bindings off.
1070    #[serde(default, skip_serializing_if = "Option::is_none")]
1071    #[cfg_attr(not(feature = "handlers"), allow(dead_code))]
1072    pub sql_shim_url: Option<String>,
1073    /// Privilege strategy for a managed database's stock image on a shared-kernel
1074    /// backend (see [`ManagedDbPrivilege`]). `rootless` by default.
1075    #[serde(default)]
1076    #[cfg_attr(not(feature = "handlers"), allow(dead_code))]
1077    pub managed_db_privilege: ManagedDbPrivilege,
1078    /// Per-project **internal DNS** (service discovery): run a lightweight resolver
1079    /// on the bridge gateway so a guest can reach peers by name (`<workload>` /
1080    /// `<workload>.<project>.<dns_domain>`) instead of a numeric IP, scoped to its
1081    /// own project. Default **on** — it activates only when the container backend +
1082    /// bridge come up, so a node without them is unaffected. `false` disables it and
1083    /// leaves each image's own `/etc/resolv.conf`.
1084    #[serde(default = "default_internal_dns")]
1085    pub internal_dns: bool,
1086    /// The upstream resolver the internal DNS forwards non-internal queries to
1087    /// (external names + non-`A`/`AAAA` types), so the resolver is the guest's single
1088    /// nameserver. `"host:port"`; default `1.1.1.1:53`.
1089    #[serde(default = "default_dns_upstream")]
1090    pub dns_upstream: String,
1091    /// The internal DNS suffix names live under (`<workload>.<project>.<dns_domain>`);
1092    /// also the `search` domain written into each container's resolv.conf. Default
1093    /// `boatramp.internal`.
1094    #[serde(default = "default_dns_domain")]
1095    pub dns_domain: String,
1096}
1097
1098/// Default for [`ComputeConfig::internal_dns`] — on (activates only with the
1099/// container backend + bridge).
1100fn default_internal_dns() -> bool {
1101    true
1102}
1103
1104/// Default upstream resolver for [`ComputeConfig::dns_upstream`].
1105fn default_dns_upstream() -> String {
1106    "1.1.1.1:53".to_string()
1107}
1108
1109/// Default internal DNS suffix for [`ComputeConfig::dns_domain`].
1110fn default_dns_domain() -> String {
1111    boatramp_container::dns::DEFAULT_INTERNAL_DOMAIN.to_string()
1112}
1113
1114/// The built-in **boatramp kernel-signing public key** (`es256:…`), whose private
1115/// half lives as the `KERNEL_SIGNING_KEY` Actions secret in
1116/// [`BoatRamp/boatramp-vmlinux`](https://github.com/BoatRamp/boatramp-vmlinux).
1117/// Shipped as a default trust anchor so the first-party signed `boatramp-vmlinux`
1118/// verifies out of the box under the strict posture. An operator can replace
1119/// `kernel_signing_pubkeys` to trust only their own keys.
1120pub const BOATRAMP_KERNEL_SIGNING_PUBKEY: &str =
1121    "es256:02c4e4af2e9cba6ba6745c513f193622e6674a8b2d0187ebea5612f5b46a7eade4";
1122
1123/// The first-party signed-kernel content hashes trusted under the **strict**
1124/// posture, for this build's **guest arch**. The guest arch mirrors the host: an
1125/// x86_64 host boots x86_64 KVM guests (the embedded VMM); an Apple-silicon host
1126/// boots aarch64 guests (the Virtualization.framework `vmm-vz` backend). An x86_64
1127/// kernel can't boot an aarch64 VM (and vice versa), so each arch trusts only its
1128/// own signed `boatramp-vmlinux-<arch>` releases. Bump on each new signed release.
1129///
1130/// The **relaxed** (single-tenant) posture ignores this list — it verifies only the
1131/// content-hash pin — so an operator-supplied kernel boots there regardless of arch.
1132fn default_allowed_kernel_hashes() -> Vec<String> {
1133    #[cfg(target_arch = "x86_64")]
1134    {
1135        vec![
1136            // v0.2.0 minimal Firecracker 6.1-config kernel: boots under the
1137            // firecracker-*binary* backend (ACPI device discovery) but NOT the
1138            // in-process embedded VMM. Kept trusted so operators on the currently
1139            // published release don't fail strict verification.
1140            "cf1e590a9e642be3667131ca35fbf390378a457d8908169d2a169608e299d974".to_string(),
1141            // Same kernel + CONFIG_VIRTIO_MMIO_CMDLINE_DEVICES=y (flake `#vmlinux`),
1142            // so the embedded VMM binds its virtio-block root over the cmdline
1143            // transport. Reproducible build output (deterministic nix build,
1144            // verified on KVM); the next signed boatramp-vmlinux release — which
1145            // reuses this flake — publishes + signs it, gated by
1146            // `vmlinux-release-boot.yml`.
1147            "d0dc2098ab2a2a3c1bc72ab61dc85d9e464d798d7e55b6b80525db5ca2f00c5a".to_string(),
1148        ]
1149    }
1150    #[cfg(target_arch = "aarch64")]
1151    {
1152        vec![
1153            // `boatramp-vmlinux-aarch64` v0.2.3 (the Virtualization.framework guest
1154            // kernel, flake `#vmlinux` on aarch64-linux — a raw arm64 `Image`). This
1155            // release enables the generic PCIe host + virtio-pci so the guest actually
1156            // discovers VZ's virtio disk/net/console (the earlier v0.2.2 `be95fb0d…`
1157            // built with `CONFIG_PCI` off never booted under VZ and is dropped). This
1158            // is the hash of the **published, ES256-signed** release asset (signed by
1159            // BOATRAMP_KERNEL_SIGNING_PUBKEY), so a selected `compute.default_kernel`
1160            // clears the strict bar out of the box; the boot + scale-to-zero round-trip
1161            // was validated against this exact published kernel. NOTE: unlike x86_64,
1162            // the aarch64 build is not currently bit-reproducible across build hosts
1163            // (same config + size, different build metadata), so pin/verify against the
1164            // published `.sha256`/`.sig`, not a local rebuild. Bump on each new release.
1165            "d785a48d754e65a4630443301f1fb84cb69cf882336d3cf37055e437b3d8e21f".to_string(),
1166        ]
1167    }
1168    #[cfg(not(any(target_arch = "x86_64", target_arch = "aarch64")))]
1169    {
1170        Vec::new()
1171    }
1172}
1173
1174impl Default for ComputeConfig {
1175    fn default() -> Self {
1176        Self {
1177            bridge: "br-boatramp".to_string(),
1178            subnet: "10.0.0.0/24".to_string(),
1179            vcpus: 0,
1180            mem_mib: 0,
1181            kernel_signing_pubkeys: vec![BOATRAMP_KERNEL_SIGNING_PUBKEY.to_string()],
1182            kernel_allowed_hashes: default_allowed_kernel_hashes(),
1183            region: None,
1184            docker_endpoint: boatramp_docker::DockerEndpoint::default(),
1185            docker_volume_mode: boatramp_docker::DockerVolumeMode::default(),
1186            sql_shim_url: None,
1187            managed_db_privilege: ManagedDbPrivilege::default(),
1188            internal_dns: default_internal_dns(),
1189            dns_upstream: default_dns_upstream(),
1190            dns_domain: default_dns_domain(),
1191        }
1192    }
1193}
1194
1195/// `cluster` section — self-hosted **cluster mode**. Parsed in
1196/// every build so config files stay portable; only *consumed* when the `cluster`
1197/// feature is compiled in (`boatramp serve --mode cluster`).
1198#[cfg_attr(not(feature = "cluster"), allow(dead_code))]
1199#[derive(Debug, Clone, Deserialize)]
1200pub struct ClusterConfig {
1201    /// Address to bind this node's Raft **peer mesh** on (the `/raft/*` +
1202    /// `/stream/*` endpoints) — distinct from the public `serve.addr`.
1203    pub listen: SocketAddr,
1204    /// The cluster **root anchor set** — the `es256:`/`ed25519:`-tagged public
1205    /// keys that define this cluster's identity (a cluster *is* its root key).
1206    /// Every join/trust decision verifies against this set. Empty ⇒ falls back to
1207    /// `serve.auth_root_public_key` (the single-anchor default). A *set* enables
1208    /// make-before-break root rotation.
1209    #[serde(default)]
1210    pub root_pubkeys: Vec<String>,
1211    /// **Seeds** — control-plane addresses of existing cluster members
1212    /// (`host:port`), any of which can admit this node. Present ⇒ this node
1213    /// **joins** (redeems its `join_token`); absent + no durable state + explicit
1214    /// `--cluster-init` ⇒ it **founds**. There is no peer map: members are learned
1215    /// from the root-signed join response.
1216    #[serde(default)]
1217    pub seeds: Vec<String>,
1218    /// The single-use bearer **join token** used when `seeds` are set. Keeps the
1219    /// secret out of the file via a prefix: `env:VAR`, `path:/file`, or an inline
1220    /// literal. Usually supplied via `serve --cluster-join <ticket>` instead.
1221    #[serde(default)]
1222    pub join_token: Option<String>,
1223    /// Directory for this node's **durable** Raft log/state store (node-local;
1224    /// distinct from the replicated control plane). Default
1225    /// `<data-dir>/raft`.
1226    #[serde(default)]
1227    pub store_dir: Option<PathBuf>,
1228    /// Mesh identity + TLS settings. Absent ⇒ defaults (identity key
1229    /// auto-generated under `<data-dir>/mesh/identity.key`).
1230    #[serde(default)]
1231    pub mesh: Option<MeshConfig>,
1232}
1233
1234/// `[cluster.mesh]` — mesh identity + TLS knobs.
1235#[cfg_attr(not(feature = "cluster"), allow(dead_code))]
1236#[derive(Debug, Clone, Default, Deserialize)]
1237#[serde(default, deny_unknown_fields)]
1238pub struct MeshConfig {
1239    /// Path to this node's Ed25519 identity key (PKCS#8 DER, `0600`,
1240    /// auto-generated). Default `<data-dir>/mesh/identity.key`.
1241    pub key_file: Option<PathBuf>,
1242    /// Automatic key-rotation cadence (e.g. `"30d"`); `None` = manual only.
1243    /// Consumed by the rotation loop.
1244    pub key_rotation: Option<String>,
1245    /// TTL for a single-use join token (e.g. `"1h"`).
1246    pub join_token_ttl: Option<String>,
1247    /// Gate mesh `client-write`s behind a control-plane **cluster-write
1248    /// capability**, so a trusted peer can't inject arbitrary
1249    /// control-plane writes on mesh trust alone. Requires the token root
1250    /// **private** key on every node (each mints + presents its own capability);
1251    /// default `false`.
1252    pub gate_client_writes: Option<bool>,
1253}
1254
1255/// `handlers` section — server-side handler runtime config (read by `serve`).
1256/// Parsed in every build (so config files stay portable), but only *consumed*
1257/// when the `handlers` feature is compiled in.
1258#[cfg_attr(not(feature = "handlers"), allow(dead_code))]
1259#[derive(Debug, Clone, Default, Deserialize)]
1260#[serde(default)]
1261pub struct HandlersConfig {
1262    /// `handlers.bindings` — which backend serves each handler binding.
1263    pub bindings: BindingsConfig,
1264    /// Use the wasmtime **pooling** instance allocator: faster
1265    /// instantiation at the cost of a large up-front virtual-memory reservation.
1266    /// Off by default — opt in and benchmark for your workload.
1267    pub pooling: bool,
1268    /// Engine-wide **safety max** on a *connection-bearing* invocation (a site
1269    /// handler or a synchronous function/webhook invoke), milliseconds. A route
1270    /// or function may declare a *lower* timeout, never a higher one. Kept tight
1271    /// on purpose: a client, proxy, and the shared request pool are all blocked
1272    /// while a sync handler runs. Absent ⇒ 10s (the historical default). This is
1273    /// a node safety ceiling, not a per-invocation budget, and is distinct from
1274    /// a per-site `max_timeout_ms`.
1275    pub sync_max_timeout_ms: Option<u64>,
1276    /// Engine-wide safety max on a *durable async* invocation — the drain that
1277    /// runs `?mode=async` calls, workflow steps, cron/queue/blob triggers, and
1278    /// `wasi:messaging` consumers, milliseconds. No client is connected and the
1279    /// work is retried + dead-lettered, so this can be far larger than the sync
1280    /// ceiling: it is what lets a legitimately long background job (e.g. an LLM
1281    /// generation) declare and actually get minutes of runtime. Absent ⇒ 15
1282    /// minutes. Runs on its own concurrency budget (`async_max_concurrency`), so
1283    /// a long job never starves live traffic.
1284    pub async_max_timeout_ms: Option<u64>,
1285    /// Max concurrent in-flight *async-lane* invocations, kept separate from the
1286    /// (larger) request pool so a burst of long background jobs can't exhaust the
1287    /// slots live site traffic needs. Absent ⇒ 8.
1288    pub async_max_concurrency: Option<usize>,
1289    /// Optional CPU **fuel** ceiling for an async-lane invocation. A large async
1290    /// timeout bounds only wall-clock; without a fuel bound a CPU-bound guest can
1291    /// spin for the whole window. Absent ⇒ unmetered (same as the sync default).
1292    pub async_max_fuel: Option<u64>,
1293    /// **Relaxed messaging-publish durability** — the max number of published
1294    /// messages that may be acknowledged from the in-memory buffer BEFORE a durable
1295    /// checkpoint is forced. **Absent / `0` ⇒ strong durability (the default):**
1296    /// every `publish()` returns only after the message is crash-durable — a
1297    /// *stronger* guarantee than NATS JetStream's default sync publish. Set `N > 0`
1298    /// to opt a node into fast-ack (publish returns on the buffer insert, ~10µs
1299    /// instead of ~one flush interval), at the cost of a **bounded loss window: up
1300    /// to `N` acknowledged-but-unflushed messages are lost on a process crash / OOM
1301    /// / SIGKILL / power loss** before the next flush. Affects ONLY the messaging
1302    /// bus publish path — control-plane, auth, and consumer ack/redelivery
1303    /// durability are unaffected. Single-node only (cluster durability is
1304    /// replication). A node with `N > 0` logs a warning at startup.
1305    pub messaging_max_unflushed_msgs: Option<usize>,
1306    /// **Event-driven delivery — safety-net reconcile cadence** (ms). The coarse timer the delivery
1307    /// drainer falls back to when no fast-path wake fires: it drains the durable ready-set and fires
1308    /// lease-expiry redelivery via the per-message due-heap, so a dropped wake or a time-based
1309    /// visibility never stalls delivery beyond this interval. It never scans idle topics (an idle
1310    /// fleet costs ~0). Absent ⇒ ~2 s. Lower for tighter redelivery latency at more wakeups; raise to
1311    /// quiet a large idle fleet further.
1312    pub messaging_safetynet_interval_ms: Option<u64>,
1313    /// **Event-driven delivery — ready-set rebuild cadence** (ms). The long-cadence self-heal that
1314    /// re-derives the ready-set from the authoritative message index — recovering a marker lost to a
1315    /// crash between the index write and the ready write, pruning a stale marker, and self-populating
1316    /// a fresh/upgraded node's ready-set. This is the one full-ish scan, so it runs rarely. Absent ⇒
1317    /// ~30 s. The correctness backstop for the ready-set (a lost marker costs at most one rebuild
1318    /// interval of latency, never a lost message).
1319    pub messaging_readyset_rebuild_interval_ms: Option<u64>,
1320    /// Max wall-clock for a *streaming-lane* response (a `#[handler(stream)]`
1321    /// route — SSE, chunked, agent token streaming), milliseconds. A client is
1322    /// connected but the body is written incrementally over seconds-to-minutes,
1323    /// so this is far larger than the sync ceiling. Runs on its own concurrency
1324    /// budget (`streaming_max_concurrency`), isolated from both the fast request
1325    /// pool and the async drain. Absent ⇒ 15 minutes.
1326    pub streaming_max_timeout_ms: Option<u64>,
1327    /// Max concurrent in-flight *streaming-lane* responses, kept separate from the
1328    /// request pool and the async drain so a burst of long-lived streams starves
1329    /// neither. Absent ⇒ 64.
1330    pub streaming_max_concurrency: Option<usize>,
1331    /// Optional CPU **fuel** ceiling for a streaming-lane response. Absent ⇒
1332    /// unmetered (a stream is I/O-bound on the client, not CPU-bound).
1333    pub streaming_max_fuel: Option<u64>,
1334    /// Optional ceiling on a guest's **outbound** `wasi:http` call — the connect
1335    /// and time-to-first-byte wait — milliseconds, independent of the invocation
1336    /// timeout, so a hung upstream is bounded on its own terms. The streaming
1337    /// (between-bytes) timeout is left at wasmtime's default so a slow token
1338    /// stream is not cut mid-flight. Absent ⇒ wasmtime's default.
1339    pub outbound_timeout_ms: Option<u64>,
1340}
1341
1342/// `handlers.bindings` — per-binding backend configuration. kv/blob reuse the
1343/// server's own KV/Storage backends (per-site prefixed); `sql` is the single
1344/// libsql backend, whose single-node-vs-cluster split is the only choice.
1345#[cfg_attr(not(feature = "handlers"), allow(dead_code))]
1346#[derive(Debug, Clone, Default, Deserialize)]
1347#[serde(default)]
1348pub struct BindingsConfig {
1349    /// `handlers.bindings.sql` — libsql settings. Absent ⇒ single-node,
1350    /// per-site embedded files under `<data-dir>/handlers-sql`.
1351    pub sql: Option<SqlBindingConfig>,
1352}
1353
1354/// libsql settings for the handler `sql` binding — the single SQL backend. Each
1355/// site gets a real database boundary (an embedded file per site, or a sqld
1356/// namespace per site), never schema separation (which arbitrary guest SQL
1357/// escapes). Setting `url` switches from single-node to a shared sqld cluster;
1358/// everything else stays identical.
1359#[cfg_attr(not(feature = "handlers"), allow(dead_code))]
1360#[derive(Debug, Clone, Default, Deserialize)]
1361#[serde(default)]
1362pub struct SqlBindingConfig {
1363    /// Single-node: root directory for the per-site embedded database files
1364    /// (default `<data-dir>/handlers-sql`). Ignored when `url` is set.
1365    pub dir: Option<PathBuf>,
1366    /// Cluster: base sqld data URL (e.g. `http://sqld:8080`). When set, each
1367    /// site is a sqld namespace addressed as a subdomain of this URL; `admin_url`
1368    /// is then required.
1369    pub url: Option<String>,
1370    /// Cluster: sqld admin API base URL (e.g. `http://sqld:9090`) for creating
1371    /// per-site namespaces. Required when `url` is set.
1372    pub admin_url: Option<String>,
1373    /// Cluster: optional sqld **read-replica** data URL. When set, handlers'
1374    /// read-only `sql` transactions (`open-read-only`) route to this endpoint
1375    /// while writes stay on `url` (reads → replicas, writes → primary).
1376    /// Reads may lag (eventually consistent). Ignored in
1377    /// single-node mode (no `url`).
1378    pub replica_url: Option<String>,
1379    /// Name of the env var holding the sqld data auth token (optional; never
1380    /// the token itself in-file).
1381    pub token_env: Option<String>,
1382    /// Name of the env var holding the sqld admin API auth key (optional).
1383    pub admin_token_env: Option<String>,
1384    /// How preview deployments get their SQL database: `empty` (default — a
1385    /// fresh isolated db), `branch` (a consistent copy of the site's live db;
1386    /// single-node only), or `shared` (the site's live db). See
1387    /// `boatramp_core::sql::PreviewSqlMode`.
1388    pub preview_mode: Option<String>,
1389    /// Path to an idempotent SQL script run when an `empty` preview database is
1390    /// first opened (e.g. schema/seed). Ignored in `branch`/`shared` modes.
1391    pub preview_init: Option<PathBuf>,
1392    /// `handlers.bindings.sql.databases` — external **bring-your-own** databases,
1393    /// each opened by name via `sql.open("<name>")`. An operator-configured
1394    /// Postgres/MySQL whose *isolation is the operator's* (it's their database),
1395    /// so these bypass the per-site libsql boundary and are reachable by any
1396    /// handler/function granted the `sql` binding. Needs the `sql-postgres` /
1397    /// `sql-mysql` build feature for the engine. A name here shadows the same
1398    /// name on the managed libsql default.
1399    pub databases: BTreeMap<String, ExternalDatabaseConfig>,
1400    /// **Soft-delete grace window** for a per-tenant managed database, in seconds
1401    /// (env `BOATRAMP_HANDLERS_SQL_DEPROVISION_GRACE_SECS`). When a project/site is
1402    /// deleted, a **Shared + Postgres** tenant is *soft*-deleted (its database is
1403    /// renamed aside and its role disabled) and stays recoverable for this long
1404    /// before a reaper hard-drops it — see
1405    /// [`tenant_sql`](crate::tenant_sql). `None` ⇒ the 7-day default
1406    /// (`DEFAULT_DEPROVISION_GRACE_SECS`); `0` ⇒ disable the soft path (immediate,
1407    /// irreversible hard drop everywhere). MySQL and all `Single` tenants always
1408    /// hard-drop immediately (the engine/cell can't be renamed aside safely), so this
1409    /// knob only affects the Shared-Postgres cell.
1410    pub deprovision_grace_secs: Option<u64>,
1411    /// **Trusted-extension allowlist** for the owner-gated schema-migration surface — the ONLY
1412    /// Postgres extensions a migration `Extension` step may enable (a name not here is refused
1413    /// fail-closed). A raw `sql` migration step may not `CREATE EXTENSION` at all, so this list is
1414    /// the single, operator-controlled gate on which extensions a project can install via
1415    /// migrations. Empty / `None` ⇒ no extension may be enabled through a migration (the safest
1416    /// default). Keep it tight (e.g. `["pgcrypto", "uuid-ossp", "citext"]`); an entry like
1417    /// `dblink`/`postgres_fdw` deliberately widens cross-database reach, so add those only knowingly.
1418    pub migrate_trusted_extensions: Option<Vec<String>>,
1419}
1420
1421/// One external SQL database for the handler `sql` binding. Its **source** is one
1422/// of two mutually-exclusive forms:
1423///  - `url_env` — a **bring-your-own** database: the connection URL is a secret,
1424///    named indirectly by an env var (never written in the config file).
1425///  - `compute` — a database **boatramp runs** as a compute workload: boatramp
1426///    derives the connection from the workload's live endpoint (host\:port) plus
1427///    the `database`/`user`/`password_env` here, so there is no URL to hand-map and
1428///    it follows the workload across restarts (PLAN-managed-compute-sql).
1429#[cfg_attr(not(feature = "handlers"), allow(dead_code))]
1430#[derive(Debug, Clone, Default, Deserialize)]
1431#[serde(default)]
1432pub struct ExternalDatabaseConfig {
1433    /// Engine: `postgres` (aliases `postgresql`/`pg`), `mysql` (alias
1434    /// `mariadb`), or `libsql` (aliases `sqlite`/`sqlite3`) — the embedded
1435    /// SQLite-compatible engine (single-node file, or a remote sqld primary via
1436    /// `url_env`). A `libsql` entry needs neither `compute` nor an external URL for
1437    /// the single-node case: it names an on-disk file via [`path`](Self::path).
1438    pub kind: String,
1439    /// Name of the env var holding the connection URL (e.g.
1440    /// `postgres://user:pw@host/db`). Required unless `compute` is set — or, for a
1441    /// single-node `libsql` database, unless `path` is set (an embedded file needs
1442    /// no URL/secret).
1443    pub url_env: String,
1444    /// Optional env var holding a **read-replica** connection URL. When set,
1445    /// `open-read-only` transactions route there; writes stay on `url_env`.
1446    pub read_url_env: Option<String>,
1447    /// Optional env var holding a **DDL/migration** connection URL for the
1448    /// **owner-role analog** of the schema-migration surface — a login that is
1449    /// DDL-capable *and distinct from the runtime binding user* (`user` /
1450    /// `url_env`). Its whole purpose is to keep migration DDL off the runtime
1451    /// tenant identity, mirroring the Postgres owner-role split (Postgres mints a
1452    /// per-tenant non-superuser owner role automatically; MySQL has no such role
1453    /// model, so the DDL identity must be supplied explicitly).
1454    ///
1455    /// **MySQL:** required to run schema migrations. Point it at an admin/DDL
1456    /// login (e.g. `mysql://root:…@host/db` or a purpose-made `_migrate` grant
1457    /// with `CREATE, ALTER, DROP, INDEX, REFERENCES` on the schema) that is **not**
1458    /// the runtime `user`. If it is unset (or resolves to the same identity as the
1459    /// runtime binding), migrate **refuses** fail-closed rather than run owner-DDL
1460    /// as the runtime tenant user — there is no owner/runtime split to fall back
1461    /// on. Ignored by the normal handler `sql` path; read only by the migration
1462    /// runner.
1463    ///
1464    /// **Postgres:** ignored — the per-project non-superuser owner role +
1465    /// its sealed credential are minted automatically at provision, so no
1466    /// operator-supplied DDL URL is needed (a set value is harmless and unused).
1467    pub migration_url_env: Option<String>,
1468    /// The name of a **compute workload** (a Postgres/MySQL server boatramp runs)
1469    /// to source this database from, instead of `url_env`. boatramp resolves the
1470    /// workload's live endpoint and builds the connection. Mutually exclusive with
1471    /// `url_env`.
1472    pub compute: Option<String>,
1473    /// The database name inside the compute-backed server (non-secret).
1474    pub database: Option<String>,
1475    /// The connecting user for the compute-backed server (non-secret).
1476    pub user: Option<String>,
1477    /// Env var holding the password for `user` on the compute-backed server.
1478    /// **Omit to let boatramp fully manage the credential** (PLAN-managed-compute-sql
1479    /// Phase 2): it generates a strong password once, seals it with the `[secrets]`
1480    /// envelope, injects it into the DB workload's server-init env at launch, and
1481    /// connects the handler with it — the operator sets no DB secret at all. Set it
1482    /// only to bring your own password for the compute-backed server.
1483    pub password_env: Option<String>,
1484    /// Maximum pooled connections (default 8).
1485    pub pool_max: Option<u32>,
1486    /// Open every transaction `READ ONLY` (the engine rejects writes) — for a
1487    /// database functions should only read.
1488    pub read_only: bool,
1489    /// Permit **preview** deployments to reach this database. Default `false`: a
1490    /// preview is refused, so it can never touch the operator's live external DB.
1491    pub allow_preview: bool,
1492    /// Connection/acquire timeout in seconds (default 10).
1493    pub connect_timeout_secs: Option<u64>,
1494    /// The stock OCI image for a **managed co-located** database (`compute` set, no
1495    /// `password_env`). When omitted, boatramp auto-registers the workload from the
1496    /// engine's default image (`pgvector/pgvector:pg16` for postgres, `mysql:8.0`
1497    /// for mysql). Ignored for a bring-your-own (`url_env`) database.
1498    pub image: Option<String>,
1499    /// The persistent data-volume size in MiB for a **managed co-located** database
1500    /// (default 10240 = 10 GiB). Ignored for a bring-your-own database.
1501    pub volume_size_mib: Option<u32>,
1502    /// Startup grace (seconds) for a **managed co-located** database: how long a
1503    /// freshly launched server has to finish its first `initdb` before the reconcile
1504    /// loop treats a still-unhealthy replica as a broken launch to stop + relaunch.
1505    /// When set it overrides the engine default the synthesizer picks (Postgres 60,
1506    /// MySQL 120). Omit to use that default. Ignored for a bring-your-own database.
1507    pub startup_grace_secs: Option<u32>,
1508    /// **Isolation mechanism** for a compute-backed managed database (2×2 axis 1).
1509    /// `single` (default) — a *dedicated* database server (its own container) per
1510    /// tenant; `shared` — *one* server hosting a permission-separated database + role
1511    /// per tenant. Ignored for a bring-your-own (`url_env`) database.
1512    pub tenant: TenantIsolation,
1513    /// **Tenant grain** for a compute-backed managed database (2×2 axis 2). `project`
1514    /// (default) — a tenant is a project; `site` — a tenant is a site. A tenant may
1515    /// hold several databases (one per binding that names it); it gets one login role
1516    /// and sealed credential per (tenant, server), granted on all its own databases
1517    /// and none of another tenant's. The reserved `default` project uses the plain
1518    /// configured name, so a single-tenant install is just one ordinary database.
1519    pub tenant_scope: TenantScope,
1520    /// **Opt-in** (default `false`): inject the request's `boatramp.project` /
1521    /// `boatramp.site` into the SQL session at each transaction start (Postgres
1522    /// `set_config` GUC, MySQL session var), so hand-written **native RLS** policies
1523    /// can key on them per-request. The GraphQL data connector's row-level policy is
1524    /// claim-sourced and needs nothing here; this is for hand-rolled RLS on the plain
1525    /// `sql.open` path (Postgres — the engine with native row-level security).
1526    ///
1527    /// # Trust model — read before relying on this for isolation
1528    ///
1529    /// `rls_session` **provides** the request's tenant to the SQL session for an app's
1530    /// RLS to key on. It is **not** a general hostile-guest boundary:
1531    ///
1532    /// - The reserved keys (`boatramp.*` / `@boatramp_*`) are **protected** from guest
1533    ///   override — a handler statement that tries to `set_config('boatramp.…', …)` /
1534    ///   `SET boatramp.… ` / `SET @boatramp_… ` (or `RESET`/`DISCARD` them) is refused,
1535    ///   so a guest cannot spoof its injected tenant.
1536    /// - But the **real tenant-isolation boundary** is the **per-tenant database +
1537    ///   role** (`tenant = single` / `shared`), which a compromised handler cannot
1538    ///   cross regardless of what it does in-session. `rls_session` is a convenience
1539    ///   for app-authored RLS *within* a tenant's own database, layered on top of that
1540    ///   boundary — not a substitute for it.
1541    /// - For untrusted data, prefer **claim-sourced** enforcement (the GraphQL data
1542    ///   connector's row-level policy), which derives the tenant from the verified
1543    ///   request, not from anything the handler's SQL can influence.
1544    pub rls_session: bool,
1545    /// The Postgres session GUC name an app's RLS policies read for the host-resolved **tenant**
1546    /// (e.g. `app.tenant_id`), set per request/write on the `rls_session` path so RLS mirrors
1547    /// boatramp's injected predicate as a defense-in-depth backstop (v0.4.20). Only honored when
1548    /// `rls_session` is on and the backend is Postgres. `None` ⇒ not exposed (today's behavior).
1549    /// The guest can never set this GUC itself (its namespace becomes reserved).
1550    #[serde(default)]
1551    pub tenant_guc: Option<String>,
1552    /// The session GUC name for the anonymous **session** axis (e.g. `app.session_id`), the
1553    /// disjoint-column sibling of `tenant_guc` for `TenantOrSession` tables. `None` ⇒ not exposed.
1554    #[serde(default)]
1555    pub session_guc: Option<String>,
1556    /// A reserved sentinel value written to `tenant_guc` on an **`all`-scoped READ** (v0.4.21), so a
1557    /// table that opts in with `USING (… OR current_setting(tenant_guc, true) = '<marker>')` opens
1558    /// cross-tenant for the audited `all` twins. Pick a value that can **never** be a real tenant id
1559    /// (e.g. `*` or `__all__`). Only honored with `tenant_guc` set + `rls_session` on + Postgres.
1560    /// `None`/empty ⇒ `all` reads leave the GUC untouched (v0.4.20 fail-closed behavior). The guest
1561    /// can never set it — the `tenant_guc` namespace is already reserved against guest writes.
1562    #[serde(default)]
1563    pub tenant_all_marker: Option<String>,
1564    /// The on-disk file path for a single-node **`libsql`** database (`kind: "libsql"`), e.g.
1565    /// `/data/app.db`. The parent directory is created if absent. Used only by the embedded engine;
1566    /// ignored for `postgres`/`mysql` and for a remote-sqld `libsql` binding (which uses `url_env`).
1567    /// A `libsql` entry sets exactly one of `path` (single-node file) or `url_env` (remote sqld).
1568    #[serde(default)]
1569    pub path: Option<PathBuf>,
1570}
1571
1572/// How a managed compute-backed database is physically isolated per tenant (2×2 axis
1573/// 1). `Single` = a dedicated server (container) per tenant (isolation by separate
1574/// process); `Shared` = one server with a per-tenant database + login role (isolation
1575/// by grants — Postgres `REVOKE CONNECT FROM PUBLIC` + owner grant; MySQL per-schema
1576/// grant), so a tenant's role cannot connect to another tenant's database.
1577#[cfg_attr(not(feature = "handlers"), allow(dead_code))]
1578#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Deserialize)]
1579#[serde(rename_all = "lowercase")]
1580pub enum TenantIsolation {
1581    /// A dedicated database server (its own container) per tenant. The default.
1582    #[default]
1583    Single,
1584    /// One shared server hosting a per-tenant database + role (grant-isolated).
1585    Shared,
1586}
1587
1588/// The grain of a tenant for a managed compute-backed database (2×2 axis 2) —
1589/// `Project` (default) or `Site`. The two grains are parallel; the isolation
1590/// mechanism is [`TenantIsolation`].
1591#[cfg_attr(not(feature = "handlers"), allow(dead_code))]
1592#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Deserialize)]
1593#[serde(rename_all = "lowercase")]
1594pub enum TenantScope {
1595    /// A tenant is a **project** (the default).
1596    #[default]
1597    Project,
1598    /// A tenant is a **site** (finer than project).
1599    Site,
1600}
1601
1602impl ExternalDatabaseConfig {
1603    /// Validate the source is well-formed: **exactly one** of `url_env` /
1604    /// `compute`, and a `compute`-backed database has the connection details
1605    /// boatramp can't infer (`database` + `user`). `password_env` is **optional** —
1606    /// omit it to let boatramp manage the credential (Phase 2). `name` is the
1607    /// binding name, for the error message.
1608    #[cfg_attr(not(feature = "handlers"), allow(dead_code))]
1609    pub fn validate(&self, name: &str) -> Result<(), String> {
1610        let has_url = !self.url_env.is_empty();
1611        let has_compute = self.compute.as_deref().is_some_and(|c| !c.is_empty());
1612        let has_path = self
1613            .path
1614            .as_deref()
1615            .is_some_and(|p| !p.as_os_str().is_empty());
1616
1617        // A `libsql`/`sqlite` entry is the embedded engine: single-node via `path`, or remote sqld
1618        // via `url_env` — never `compute` (boatramp doesn't run a libsql server workload). Validate
1619        // it on its own axis (exactly one of `path` / `url_env`), and reject `path` on the external
1620        // engines (a Postgres/MySQL binding has no on-disk file).
1621        let is_libsql = matches!(
1622            self.kind.trim().to_ascii_lowercase().as_str(),
1623            "libsql" | "sqlite" | "sqlite3"
1624        );
1625        if is_libsql {
1626            if has_compute {
1627                return Err(format!(
1628                    "sql database {name:?}: a `libsql` database is the embedded engine — set `path` \
1629                     (single-node file) or `url_env` (remote sqld), not `compute`"
1630                ));
1631            }
1632            return match (has_path, has_url) {
1633                (true, true) => Err(format!(
1634                    "sql database {name:?}: a `libsql` database sets exactly one of `path` \
1635                     (single-node file) or `url_env` (remote sqld), not both"
1636                )),
1637                (false, false) => Err(format!(
1638                    "sql database {name:?}: a `libsql` database needs a source — set `path` \
1639                     (single-node file) or `url_env` (remote sqld)"
1640                )),
1641                _ => Ok(()),
1642            };
1643        }
1644        if has_path {
1645            return Err(format!(
1646                "sql database {name:?}: `path` is only valid for a `libsql` database (the embedded \
1647                 engine); a {} binding uses `url_env` or `compute`",
1648                self.kind
1649            ));
1650        }
1651
1652        match (has_url, has_compute) {
1653            (true, true) => Err(format!(
1654                "sql database {name:?}: set exactly one of `url_env` or `compute`, not both"
1655            )),
1656            (false, false) => Err(format!(
1657                "sql database {name:?}: needs a source — set `url_env` (bring-your-own) or \
1658                 `compute` (a database boatramp runs)"
1659            )),
1660            (false, true) => {
1661                // `database` + `user` are non-secret and can't be inferred; a missing
1662                // `password_env` is *not* an error — it selects the managed credential.
1663                for (field, val) in [("database", &self.database), ("user", &self.user)] {
1664                    if val.as_deref().is_none_or(str::is_empty) {
1665                        return Err(format!(
1666                            "sql database {name:?}: a `compute`-backed database requires `{field}`"
1667                        ));
1668                    }
1669                }
1670                Ok(())
1671            }
1672            (true, false) => Ok(()),
1673        }
1674    }
1675
1676    /// Whether this compute-backed database uses a **boatramp-managed** credential
1677    /// (Phase 2): `compute` is set and no `password_env` was supplied.
1678    #[cfg_attr(not(feature = "handlers"), allow(dead_code))]
1679    pub fn is_managed_credential(&self) -> bool {
1680        self.compute.as_deref().is_some_and(|c| !c.is_empty())
1681            && self.password_env.as_deref().is_none_or(str::is_empty)
1682    }
1683}
1684
1685/// The signing algorithm for a signer that can choose one (`Local`, `Vault`,
1686/// `Pkcs11`). ES256 is the portable default; the cloud KMS backends are ES256-only
1687/// and ignore this. Written as a RON enum: `alg: Es256` / `alg: Ed25519`.
1688#[derive(Debug, Clone, Copy, Default, Deserialize)]
1689pub enum SignerAlg {
1690    /// ECDSA P-256 (COSE ES256) — the default.
1691    #[default]
1692    Es256,
1693    /// Ed25519 (COSE EdDSA).
1694    Ed25519,
1695}
1696
1697impl SignerAlg {
1698    fn to_token_alg(self) -> boatramp_core::cose::TokenAlg {
1699        match self {
1700            Self::Es256 => boatramp_core::cose::TokenAlg::Es256,
1701            Self::Ed25519 => boatramp_core::cose::TokenAlg::Ed25519,
1702        }
1703    }
1704}
1705
1706/// External token signer selector (`serve.signer`). Maps to
1707/// [`boatramp_server::signer::SignerConfig`]; secrets (tokens/PINs) are resolved
1708/// from the named env vars at startup, never stored in config. Written as a RON
1709/// enum — `signer: Vault(...)`, `signer: AwsKms(...)`, `signer: Pkcs11(...)`, ….
1710#[derive(Debug, Clone, Deserialize)]
1711#[serde(deny_unknown_fields)]
1712pub enum AuthSignerConfig {
1713    /// In-process key (`"<alg>:<hex>"`).
1714    Local {
1715        /// The private key spec, `"<alg>:<hex>"`.
1716        private_key: String,
1717    },
1718    /// HashiCorp Vault Transit key.
1719    Vault {
1720        /// Vault base address.
1721        address: String,
1722        /// The Transit key name.
1723        key: String,
1724        /// Env var holding the Vault token.
1725        token_env: String,
1726        /// The key algorithm.
1727        #[serde(default)]
1728        alg: SignerAlg,
1729    },
1730    /// AWS KMS asymmetric key (ES256).
1731    AwsKms {
1732        /// The KMS key id or ARN.
1733        key_id: String,
1734        /// Optional region override.
1735        #[serde(default)]
1736        region: Option<String>,
1737    },
1738    /// GCP Cloud KMS key version (ES256).
1739    GcpKms {
1740        /// The key-version resource name.
1741        key_version: String,
1742        /// Env var holding a GCP OAuth2 access token.
1743        access_token_env: String,
1744    },
1745    /// Azure Key Vault key (ES256).
1746    AzureKv {
1747        /// The vault base URL.
1748        vault_url: String,
1749        /// The key name.
1750        key: String,
1751        /// The key version.
1752        key_version: String,
1753        /// Env var holding an Azure AD access token.
1754        access_token_env: String,
1755    },
1756    /// PKCS#11 HSM key.
1757    Pkcs11 {
1758        /// Path to the PKCS#11 module.
1759        module: String,
1760        /// The token label.
1761        token_label: String,
1762        /// The key's `CKA_LABEL`.
1763        key_label: String,
1764        /// Env var holding the user PIN.
1765        pin_env: String,
1766        /// The key algorithm.
1767        #[serde(default)]
1768        alg: SignerAlg,
1769    },
1770}
1771
1772impl AuthSignerConfig {
1773    /// Map the config-file form to the server's runtime [`SignerConfig`].
1774    pub fn to_signer_config(&self) -> boatramp_server::signer::SignerConfig {
1775        use boatramp_server::signer::SignerConfig;
1776        match self {
1777            Self::Local { private_key } => SignerConfig::Local {
1778                private_key: private_key.clone(),
1779            },
1780            Self::Vault {
1781                address,
1782                key,
1783                token_env,
1784                alg,
1785            } => SignerConfig::Vault {
1786                address: address.clone(),
1787                key: key.clone(),
1788                token_env: token_env.clone(),
1789                alg: alg.to_token_alg(),
1790            },
1791            Self::AwsKms { key_id, region } => SignerConfig::AwsKms {
1792                key_id: key_id.clone(),
1793                region: region.clone(),
1794            },
1795            Self::GcpKms {
1796                key_version,
1797                access_token_env,
1798            } => SignerConfig::GcpKms {
1799                key_version: key_version.clone(),
1800                access_token_env: access_token_env.clone(),
1801            },
1802            Self::AzureKv {
1803                vault_url,
1804                key,
1805                key_version,
1806                access_token_env,
1807            } => SignerConfig::AzureKv {
1808                vault_url: vault_url.clone(),
1809                key: key.clone(),
1810                key_version: key_version.clone(),
1811                access_token_env: access_token_env.clone(),
1812            },
1813            Self::Pkcs11 {
1814                module,
1815                token_label,
1816                key_label,
1817                pin_env,
1818                alg,
1819            } => SignerConfig::Pkcs11 {
1820                module: module.clone(),
1821                token_label: token_label.clone(),
1822                key_label: key_label.clone(),
1823                pin_env: pin_env.clone(),
1824                alg: alg.to_token_alg(),
1825            },
1826        }
1827    }
1828}
1829
1830/// `serve` section — server defaults, overridden by flags/env.
1831#[derive(Debug, Clone, Default, Deserialize)]
1832#[serde(default)]
1833pub struct ServeConfig {
1834    /// Bind address (e.g. `0.0.0.0:8080`).
1835    pub addr: Option<SocketAddr>,
1836    /// Data directory for filesystem backends.
1837    pub data_dir: Option<PathBuf>,
1838    /// Token root **private** key (hex) — issuing node: verifies *and* mints
1839    /// tokens / OIDC exchanges.
1840    pub auth_root_private_key: Option<String>,
1841    /// Token root **public** key (hex) — verify-only node.
1842    pub auth_root_public_key: Option<String>,
1843    /// Single-use bootstrap secret enabling `POST /api/tokens/bootstrap` (mint the
1844    /// first token without an admin bearer). Prefer the `BOATRAMP_BOOTSTRAP_SECRET`
1845    /// env / `--bootstrap-secret` flag so it isn't persisted in the config file.
1846    pub bootstrap_secret: Option<String>,
1847    /// External token signer (`[serve.signer]`): mint with a
1848    /// KMS/HSM/Vault-held root key instead of an in-process `auth_root_private_key`.
1849    /// Absent ⇒ the in-process key. When set, its public half is the trust anchor.
1850    pub signer: Option<AuthSignerConfig>,
1851    /// Reject blob uploads larger than this many bytes.
1852    pub max_upload_bytes: Option<u64>,
1853    /// Abort an upload that stalls for longer than this many seconds.
1854    pub upload_idle_timeout_secs: Option<u64>,
1855    /// Cap on simultaneous blob uploads.
1856    pub max_concurrent_uploads: Option<usize>,
1857    /// In a TLS mode, bind this plain-HTTP address on a second listener that
1858    /// redirects to HTTPS (dual-listener). Only read in `tls` builds.
1859    #[cfg_attr(not(feature = "tls"), allow(dead_code))]
1860    pub http_redirect_addr: Option<SocketAddr>,
1861    /// Site to serve for a `Host` matching no domain, instead of 404.
1862    pub default_site: Option<String>,
1863    /// The fleet's canonical public origin (e.g. `https://cp.example.com`) that a
1864    /// per-request proof-of-possession must bind to (`aud`). Required for
1865    /// holder-bound (`cnf`/PoP) tokens to be usable — a proof's origin is compared
1866    /// against this value, never against a `Host`/`X-Forwarded-*` header.
1867    pub pop_origin: Option<String>,
1868    /// Require a valid control-plane token to view deployment previews.
1869    pub protect_previews: bool,
1870    /// Rate-limit cluster-wide via the control-plane KV instead of per node.
1871    pub cluster_rate_limit: bool,
1872    /// Keep the config cache coherent across processes sharing one KV via the
1873    /// changelog.
1874    pub shared_cache_coherence: bool,
1875    /// Cloud blob-change notification provisioning tier (FA-5b2): how boatramp
1876    /// obtains the native event pipeline (S3→SQS) that backs a `blob` trigger —
1877    /// `dry-run` (print the recipe), `provision` (create + retract), `verify-only`
1878    /// (operator pre-wired), or `refuse` (fail closed). Absent ⇒ no provisioning:
1879    /// `blob` triggers then work only on a self-watching backend (fs). Only wired
1880    /// for the S3 backend (`--features s3`).
1881    pub blob_notify_tier: Option<boatramp_core::blob_notify::ProvisionTier>,
1882    /// The AWS account id used to scope the provisioned SQS queue's `SendMessage`
1883    /// policy (`aws:SourceAccount`). Required when `blob_notify_tier` provisions.
1884    pub blob_notify_account_id: Option<String>,
1885    /// `[serve.console]` — the embedded web management console. Absent (or
1886    /// `enabled: false`) ⇒ not served. This is the **baseline** for the dynamic
1887    /// `console.*` daemon-config override, which can enable/move it at runtime
1888    /// (`boatramp config set console.enabled true`) without a restart.
1889    pub console: Option<ConsoleConfig>,
1890}
1891
1892/// `[serve.console]` — the embedded web console (a Wasm SPA baked into the
1893/// binary with the `console` build feature). Opt-in: the static shell holds no
1894/// secrets and the `/api` it drives is token-gated, so it is served
1895/// **unauthenticated** at a deliberately obscure path (a bearer token can't gate
1896/// a top-level browser navigation anyway — the path is the obscurity, the token
1897/// is the real gate).
1898#[cfg_attr(not(feature = "console"), allow(dead_code))]
1899#[derive(Debug, Clone, Default, Deserialize)]
1900#[serde(default, deny_unknown_fields)]
1901pub struct ConsoleConfig {
1902    /// Serve the embedded console (default `false`). Requires the `console` build
1903    /// feature; enabling it in a build without that feature is a logged no-op.
1904    pub enabled: bool,
1905    /// Host(s) the console answers on: `*` (any host, the default), an exact host
1906    /// (`console.example.com`), or a leading-wildcard (`*.example.com`).
1907    pub host: Option<String>,
1908    /// URL path prefix the console mounts at (default `/_console`). Kept under the
1909    /// reserved `/_` namespace so it never collides with a published site path.
1910    pub path: Option<String>,
1911}
1912
1913/// `publish` section — where and what to deploy (the `sync` target).
1914#[derive(Debug, Default, Deserialize)]
1915#[serde(default)]
1916pub struct PublishConfig {
1917    /// Base URL of the boatramp server (e.g. `https://pad.example.com`).
1918    pub server: Option<String>,
1919    /// Site name to publish to.
1920    pub site: Option<String>,
1921    /// API token for the control plane (or set `BOATRAMP_TOKEN`).
1922    pub token: Option<String>,
1923    /// Project this site belongs to (overrides with `--project` / `BOATRAMP_PROJECT`).
1924    pub project: Option<String>,
1925}
1926
1927/// `build` section.
1928#[derive(Debug, Clone, Deserialize)]
1929pub struct BuildConfig {
1930    /// Shell command to run (e.g. `npm run build`).
1931    pub command: String,
1932    /// Directory the build emits, published by `sync` (e.g. `dist`).
1933    #[serde(default)]
1934    pub output: Option<String>,
1935}
1936
1937/// `bundle` section — the in-process Rust bundler (`bundler` feature).
1938#[derive(Debug, Clone, Default, Deserialize)]
1939#[serde(default)]
1940pub struct BundleConfig {
1941    /// Output directory for bundled assets (e.g. `dist`).
1942    #[serde(default = "default_bundle_outdir")]
1943    pub outdir: String,
1944    /// JS/TS entry points bundled by Rolldown (tree-shaken, code-split).
1945    pub js: Vec<String>,
1946    /// CSS entry points bundled by lightningcss (`@import` inlined).
1947    pub css: Vec<String>,
1948    /// Minify output (default true).
1949    #[serde(default = "default_true")]
1950    pub minify: bool,
1951}
1952
1953fn default_bundle_outdir() -> String {
1954    "dist".to_string()
1955}
1956
1957fn default_true() -> bool {
1958    true
1959}
1960
1961#[cfg(test)]
1962mod tests {
1963    use super::*;
1964
1965    fn project(text: &str) -> ProjectConfig {
1966        ron_options().from_str(text).unwrap()
1967    }
1968
1969    fn server(text: &str) -> ServerConfig {
1970        ron_options().from_str(text).unwrap()
1971    }
1972
1973    /// Build an [`EnvSource::Map`] from `(name, value)` pairs for deterministic
1974    /// override tests (no process-global `std::env` mutation).
1975    fn env(pairs: &[(&str, &str)]) -> EnvSource {
1976        EnvSource::Map(
1977            pairs
1978                .iter()
1979                .map(|(k, v)| (k.to_string(), v.to_string()))
1980                .collect(),
1981        )
1982    }
1983
1984    #[test]
1985    fn env_overrides_configure_all_three_sections_with_no_file() {
1986        // The crux of the ask: with NO `boatramp.cfg` at all (the default config),
1987        // env vars alone materialise + populate the compute, security, and handler
1988        // `sql` sections. `ServerConfig::default()` has all three absent.
1989        let mut cfg = ServerConfig::default();
1990        assert!(cfg.compute.is_none() && cfg.security.is_none() && cfg.handlers.is_none());
1991
1992        cfg.apply_env_overrides(&env(&[
1993            ("BOATRAMP_COMPUTE_VCPUS", "8"),
1994            ("BOATRAMP_COMPUTE_MEM_MIB", "4096"),
1995            ("BOATRAMP_COMPUTE_REGION", "eu-central"),
1996            ("BOATRAMP_SECURITY_PROFILE", "single-tenant"),
1997            ("BOATRAMP_SECURITY_ALLOW_SITE_PRIVATE_UPSTREAMS", "true"),
1998            ("BOATRAMP_SECURITY_MAX_UPLOAD_BYTES", "1048576"),
1999            ("BOATRAMP_HANDLERS_SQL_URL", "http://sqld:8080"),
2000            ("BOATRAMP_HANDLERS_SQL_ADMIN_URL", "http://sqld:9090"),
2001        ]))
2002        .expect("valid env overrides apply");
2003
2004        // compute: the section now exists with the env values (and defaults elsewhere).
2005        let compute = cfg.compute.expect("compute materialised from env");
2006        assert_eq!(compute.vcpus, 8);
2007        assert_eq!(compute.mem_mib, 4096);
2008        assert_eq!(compute.region.as_deref(), Some("eu-central"));
2009        assert_eq!(compute.bridge, "br-boatramp"); // untouched default
2010
2011        // security: profile + an override both took, and the posture resolves.
2012        let security = cfg.security.expect("security materialised from env");
2013        assert_eq!(security.profile.as_deref(), Some("single-tenant"));
2014        let posture = security.resolve().expect("resolves");
2015        assert!(posture.allow_site_private_upstreams);
2016        assert_eq!(posture.max_upload_bytes, 1_048_576);
2017
2018        // handler sql: the nested handlers.bindings.sql chain was created.
2019        let sql = cfg
2020            .handlers
2021            .expect("handlers materialised from env")
2022            .bindings
2023            .sql
2024            .expect("sql binding materialised from env");
2025        assert_eq!(sql.url.as_deref(), Some("http://sqld:8080"));
2026        assert_eq!(sql.admin_url.as_deref(), Some("http://sqld:9090"));
2027    }
2028
2029    #[test]
2030    fn internal_dns_defaults_on_with_the_standard_upstream_and_domain() {
2031        // The `[compute]` defaults: internal DNS on, forwarding to 1.1.1.1:53, names
2032        // under `boatramp.internal`.
2033        let compute = ComputeConfig::default();
2034        assert!(compute.internal_dns, "internal DNS is on by default");
2035        assert_eq!(compute.dns_upstream, "1.1.1.1:53");
2036        assert_eq!(compute.dns_domain, "boatramp.internal");
2037    }
2038
2039    #[test]
2040    fn internal_dns_knobs_parse_from_a_file() {
2041        // A file can turn it off and override the upstream + domain.
2042        let cfg = server(
2043            r#"(
2044                compute: ( internal_dns: false, dns_upstream: "10.0.0.53:53", dns_domain: "svc.internal" ),
2045            )"#,
2046        );
2047        let compute = cfg.compute.expect("compute section");
2048        assert!(!compute.internal_dns);
2049        assert_eq!(compute.dns_upstream, "10.0.0.53:53");
2050        assert_eq!(compute.dns_domain, "svc.internal");
2051    }
2052
2053    #[test]
2054    fn internal_dns_knobs_are_env_settable() {
2055        // Env alone materialises `[compute]` and sets each internal-DNS knob (and an
2056        // unrecognised bool spelling is a clear error, exercised by parse_bool).
2057        let mut cfg = ServerConfig::default();
2058        cfg.apply_env_overrides(&env(&[
2059            ("BOATRAMP_COMPUTE_INTERNAL_DNS", "off"),
2060            ("BOATRAMP_COMPUTE_DNS_UPSTREAM", "9.9.9.9:53"),
2061            ("BOATRAMP_COMPUTE_DNS_DOMAIN", "corp.internal"),
2062        ]))
2063        .expect("valid env overrides apply");
2064        let compute = cfg.compute.expect("compute materialised from env");
2065        assert!(!compute.internal_dns, "env `off` disables internal DNS");
2066        assert_eq!(compute.dns_upstream, "9.9.9.9:53");
2067        assert_eq!(compute.dns_domain, "corp.internal");
2068    }
2069
2070    #[test]
2071    fn env_override_wins_over_file_value_but_unset_defers() {
2072        // A file that set each section; env then overrides one field per section
2073        // and leaves the rest of the file value in place (precedence: env > file).
2074        let mut cfg = server(
2075            r#"(
2076                compute: ( vcpus: 2, mem_mib: 512, region: "us-east" ),
2077                security: ( profile: "multi-tenant" ),
2078                handlers: ( bindings: ( sql: ( url: "http://file:8080", admin_url: "http://file:9090" ) ) ),
2079            )"#,
2080        );
2081
2082        cfg.apply_env_overrides(&env(&[
2083            ("BOATRAMP_COMPUTE_VCPUS", "16"),
2084            ("BOATRAMP_SECURITY_PROFILE", "dev"),
2085            ("BOATRAMP_HANDLERS_SQL_URL", "http://env:8080"),
2086        ]))
2087        .expect("valid env overrides apply");
2088
2089        let compute = cfg.compute.unwrap();
2090        assert_eq!(compute.vcpus, 16, "env wins over the file vcpus");
2091        assert_eq!(compute.mem_mib, 512, "unset env defers to the file mem_mib");
2092        assert_eq!(
2093            compute.region.as_deref(),
2094            Some("us-east"),
2095            "unset env defers to the file region"
2096        );
2097
2098        assert_eq!(
2099            cfg.security.unwrap().profile.as_deref(),
2100            Some("dev"),
2101            "env profile wins over the file profile"
2102        );
2103
2104        let sql = cfg.handlers.unwrap().bindings.sql.unwrap();
2105        assert_eq!(
2106            sql.url.as_deref(),
2107            Some("http://env:8080"),
2108            "env wins over the file sql url"
2109        );
2110        assert_eq!(
2111            sql.admin_url.as_deref(),
2112            Some("http://file:9090"),
2113            "unset env defers to the file sql admin_url"
2114        );
2115    }
2116
2117    #[test]
2118    fn env_overrides_leave_unmentioned_sections_absent() {
2119        // With no relevant env vars set, an empty config stays empty — the sections
2120        // are materialised only on demand, so an unset environment adds nothing.
2121        let mut cfg = ServerConfig::default();
2122        cfg.apply_env_overrides(&env(&[("SOME_UNRELATED_VAR", "x")]))
2123            .expect("no-op env applies");
2124        assert!(cfg.compute.is_none());
2125        assert!(cfg.security.is_none());
2126        assert!(cfg.handlers.is_none());
2127        assert!(cfg.secrets.is_none());
2128        assert!(cfg.cluster.is_none());
2129    }
2130
2131    #[test]
2132    fn env_bool_accepts_common_spellings_and_rejects_garbage() {
2133        // Truthy/falsey spellings all parse.
2134        for (raw, want) in [
2135            ("true", true),
2136            ("1", true),
2137            ("YES", true),
2138            ("On", true),
2139            ("false", false),
2140            ("0", false),
2141            ("no", false),
2142            ("OFF", false),
2143        ] {
2144            let mut cfg = ServerConfig::default();
2145            cfg.apply_env_overrides(&env(&[("BOATRAMP_SECURITY_REQUIRE_POP", raw)]))
2146                .expect("boolean parses");
2147            assert_eq!(
2148                cfg.security.unwrap().overrides.require_pop,
2149                Some(want),
2150                "{raw:?} ⇒ {want}"
2151            );
2152        }
2153        // A non-boolean value is a clear error, not a silent default.
2154        let mut cfg = ServerConfig::default();
2155        let err = cfg
2156            .apply_env_overrides(&env(&[("BOATRAMP_SECURITY_REQUIRE_POP", "maybe")]))
2157            .expect_err("garbage boolean is rejected");
2158        match err {
2159            ConfigError::Env { var, .. } => assert_eq!(var, "BOATRAMP_SECURITY_REQUIRE_POP"),
2160            other => panic!("expected ConfigError::Env, got {other:?}"),
2161        }
2162    }
2163
2164    #[test]
2165    fn env_number_parse_error_names_the_variable() {
2166        // A non-numeric numeric var is rejected with the variable named.
2167        let mut cfg = ServerConfig::default();
2168        let err = cfg
2169            .apply_env_overrides(&env(&[("BOATRAMP_COMPUTE_VCPUS", "lots")]))
2170            .expect_err("garbage number is rejected");
2171        match err {
2172            ConfigError::Env { var, .. } => assert_eq!(var, "BOATRAMP_COMPUTE_VCPUS"),
2173            other => panic!("expected ConfigError::Env, got {other:?}"),
2174        }
2175    }
2176
2177    #[test]
2178    fn empty_env_value_is_treated_as_unset() {
2179        // `VAR=` (empty) must not clobber a file value with an empty string.
2180        let mut cfg = server(r#"( compute: ( region: "us-east" ) )"#);
2181        cfg.apply_env_overrides(&env(&[("BOATRAMP_COMPUTE_REGION", "")]))
2182            .expect("empty env applies as a no-op");
2183        assert_eq!(
2184            cfg.compute.unwrap().region.as_deref(),
2185            Some("us-east"),
2186            "an empty env value leaves the file value in place"
2187        );
2188    }
2189
2190    #[test]
2191    fn env_configures_managed_postgres_secrets_and_privilege_with_no_file() {
2192        // The construens acceptance case: with NO `boatramp.cfg` at all, the
2193        // environment alone stands up a managed co-located Postgres. It configures
2194        // the default (`"default"`-named, v0.5.0) database in
2195        // `handlers.bindings.sql.databases` (kind=postgres, compute=pg, database+user
2196        // set), the `[secrets]` envelope (local + a kek path so the managed credential
2197        // can be sealed), and `compute.managed_db_privilege = rootless`. All three
2198        // sections start absent.
2199        let mut cfg = ServerConfig::default();
2200        assert!(cfg.handlers.is_none() && cfg.secrets.is_none() && cfg.compute.is_none());
2201
2202        cfg.apply_env_overrides(&env(&[
2203            // The default database is addressed by the reserved `DEFAULT` token,
2204            // which maps to the reserved real name `"default"` (v0.5.0).
2205            ("BOATRAMP_HANDLERS_SQL_DB_DEFAULT_KIND", "postgres"),
2206            ("BOATRAMP_HANDLERS_SQL_DB_DEFAULT_COMPUTE", "pg"),
2207            ("BOATRAMP_HANDLERS_SQL_DB_DEFAULT_DATABASE", "appdb"),
2208            ("BOATRAMP_HANDLERS_SQL_DB_DEFAULT_USER", "app"),
2209            // Secrets: the local envelope + a KEK path (never key material).
2210            ("BOATRAMP_SECRETS_ENVELOPE", "local"),
2211            ("BOATRAMP_SECRETS_KEK_FILE", "/var/lib/boatramp/secrets/kek"),
2212            // The shared-kernel DB privilege strategy.
2213            ("BOATRAMP_COMPUTE_MANAGED_DB_PRIVILEGE", "rootless"),
2214        ]))
2215        .expect("valid env overrides apply");
2216
2217        // The default (`"default"`-keyed) managed database exists with the right source.
2218        let sql = cfg
2219            .handlers
2220            .expect("handlers materialised from env")
2221            .bindings
2222            .sql
2223            .expect("sql binding materialised from env");
2224        let db = sql
2225            .databases
2226            .get(boatramp_core::project::DEFAULT_DB_NAME)
2227            .expect("the default `default`-named database was created from DEFAULT");
2228        assert!(
2229            !sql.databases.contains_key(""),
2230            "the empty-string key is never produced (v0.5.0)"
2231        );
2232        assert_eq!(db.kind, "postgres");
2233        assert_eq!(db.compute.as_deref(), Some("pg"));
2234        assert_eq!(db.database.as_deref(), Some("appdb"));
2235        assert_eq!(db.user.as_deref(), Some("app"));
2236        // No `password_env` ⇒ boatramp manages the credential (Phase 2), and the
2237        // compute-backed source validates.
2238        assert!(db.password_env.is_none());
2239        assert!(db.is_managed_credential());
2240        assert!(db.validate("").is_ok());
2241
2242        // The secrets envelope + KEK path took (the path is a location, not a key).
2243        let secrets = cfg.secrets.expect("secrets materialised from env");
2244        assert_eq!(secrets.envelope, "local");
2245        assert_eq!(
2246            secrets.kek_file.as_deref(),
2247            Some(Path::new("/var/lib/boatramp/secrets/kek"))
2248        );
2249        assert!(
2250            secrets.vault.is_none(),
2251            "no vault vars ⇒ no vault sub-config"
2252        );
2253
2254        // The managed-DB privilege strategy resolved from its lowercase variant.
2255        let compute = cfg.compute.expect("compute materialised from env");
2256        assert_eq!(compute.managed_db_privilege, ManagedDbPrivilege::Rootless);
2257    }
2258
2259    #[test]
2260    fn env_declares_named_databases_and_merges_over_the_file() {
2261        // A file declares one database; the env overrides one of its fields and
2262        // ADDS a second, discovering both member names from the environment.
2263        let mut cfg = server(
2264            r#"(
2265                handlers: ( bindings: ( sql: (
2266                    databases: {
2267                        "analytics": ( kind: "postgres", url_env: "FILE_PG_URL", pool_max: 4 ),
2268                    },
2269                ) ) ),
2270            )"#,
2271        );
2272        cfg.apply_env_overrides(&env(&[
2273            // Override the file database's pool size (merge by key, per field).
2274            ("BOATRAMP_HANDLERS_SQL_DB_analytics_POOL_MAX", "32"),
2275            // Add a brand-new database whose name has an underscore, exercising the
2276            // longest-suffix name isolation (`_READ_URL_ENV`, not `_URL_ENV`).
2277            ("BOATRAMP_HANDLERS_SQL_DB_events_log_KIND", "mysql"),
2278            ("BOATRAMP_HANDLERS_SQL_DB_events_log_URL_ENV", "EVENTS_URL"),
2279            (
2280                "BOATRAMP_HANDLERS_SQL_DB_events_log_READ_URL_ENV",
2281                "EVENTS_RO_URL",
2282            ),
2283            ("BOATRAMP_HANDLERS_SQL_DB_events_log_READ_ONLY", "true"),
2284        ]))
2285        .expect("valid env overrides apply");
2286
2287        let sql = cfg.handlers.unwrap().bindings.sql.unwrap();
2288        assert_eq!(sql.databases.len(), 2);
2289
2290        let analytics = &sql.databases["analytics"];
2291        assert_eq!(
2292            analytics.pool_max,
2293            Some(32),
2294            "env pool_max wins over the file"
2295        );
2296        assert_eq!(
2297            analytics.url_env, "FILE_PG_URL",
2298            "the file's url_env survives (env didn't touch it)"
2299        );
2300
2301        let events = &sql.databases["events_log"];
2302        assert_eq!(events.kind, "mysql");
2303        assert_eq!(events.url_env, "EVENTS_URL");
2304        assert_eq!(events.read_url_env.as_deref(), Some("EVENTS_RO_URL"));
2305        assert!(events.read_only);
2306    }
2307
2308    #[test]
2309    fn default_token_maps_to_the_reserved_default_name_not_empty() {
2310        // v0.5.0 breaking change: the reserved `DEFAULT` env token maps to the real
2311        // name `"default"` (a valid URL path segment), never the empty string. This is
2312        // what makes the default binding addressable as `--db default` and keeps every
2313        // db-name ingress path-segment-safe.
2314        let mut cfg = ServerConfig::default();
2315        cfg.apply_env_overrides(&env(&[
2316            ("BOATRAMP_HANDLERS_SQL_DB_DEFAULT_KIND", "postgres"),
2317            ("BOATRAMP_HANDLERS_SQL_DB_DEFAULT_URL_ENV", "PG_URL"),
2318        ]))
2319        .expect("valid env overrides apply");
2320        let databases = cfg.handlers.unwrap().bindings.sql.unwrap().databases;
2321        assert!(
2322            databases.contains_key(boatramp_core::project::DEFAULT_DB_NAME),
2323            "DEFAULT → the reserved `default` key"
2324        );
2325        assert!(
2326            !databases.contains_key(""),
2327            "the empty-string key is never produced"
2328        );
2329    }
2330
2331    #[test]
2332    fn empty_string_db_binding_name_is_rejected_with_a_cure() {
2333        // A `boatramp.cfg` that literally writes the legacy empty-string default key
2334        // fails closed on load (it would emit a `//` control-plane path), and the
2335        // error points at the cure (`default`).
2336        let err = ServerConfig::parse(
2337            r#"(
2338                handlers: ( bindings: ( sql: (
2339                    databases: {
2340                        "": ( kind: "postgres", url_env: "PG_URL" ),
2341                    },
2342                ) ) ),
2343            )"#,
2344        )
2345        .expect_err("an empty-string db binding name is refused");
2346        match err {
2347            ConfigError::InvalidDbName { name, reason, cure } => {
2348                assert_eq!(name, "");
2349                assert!(reason.contains("empty"), "reason names the emptiness");
2350                assert!(
2351                    cure.contains("default") && cure.contains("CHANGELOG"),
2352                    "the cure points at `default` + the CHANGELOG"
2353                );
2354            }
2355            other => panic!("expected ConfigError::InvalidDbName, got {other:?}"),
2356        }
2357    }
2358
2359    #[test]
2360    fn path_separator_db_binding_name_is_rejected() {
2361        // A non-path-segment name (contains `/`) is refused with no default-cure (the
2362        // fix is to rename it, not adopt `default`).
2363        let err = ServerConfig::parse(
2364            r#"(
2365                handlers: ( bindings: ( sql: (
2366                    databases: {
2367                        "a/b": ( kind: "postgres", url_env: "PG_URL" ),
2368                    },
2369                ) ) ),
2370            )"#,
2371        )
2372        .expect_err("a `/`-bearing db binding name is refused");
2373        match err {
2374            ConfigError::InvalidDbName { name, reason, cure } => {
2375                assert_eq!(name, "a/b");
2376                assert!(reason.contains("path separator"));
2377                assert!(cure.is_empty(), "no default-cure for a non-default name");
2378            }
2379            other => panic!("expected ConfigError::InvalidDbName, got {other:?}"),
2380        }
2381    }
2382
2383    #[test]
2384    fn env_sets_managed_db_startup_grace() {
2385        // The per-binding startup-grace override is env-settable like the other
2386        // managed scalars, discovered by the `_STARTUP_GRACE_SECS` suffix.
2387        let mut cfg = ServerConfig::default();
2388        cfg.apply_env_overrides(&env(&[
2389            ("BOATRAMP_HANDLERS_SQL_DB_DEFAULT_KIND", "postgres"),
2390            ("BOATRAMP_HANDLERS_SQL_DB_DEFAULT_COMPUTE", "pg"),
2391            ("BOATRAMP_HANDLERS_SQL_DB_DEFAULT_DATABASE", "appdb"),
2392            ("BOATRAMP_HANDLERS_SQL_DB_DEFAULT_USER", "app"),
2393            ("BOATRAMP_HANDLERS_SQL_DB_DEFAULT_STARTUP_GRACE_SECS", "90"),
2394        ]))
2395        .expect("valid env overrides apply");
2396        let db = &cfg.handlers.unwrap().bindings.sql.unwrap().databases
2397            [boatramp_core::project::DEFAULT_DB_NAME];
2398        assert_eq!(db.startup_grace_secs, Some(90));
2399    }
2400
2401    #[test]
2402    fn env_sets_rls_gucs_and_all_marker_without_suffix_collision() {
2403        // The RLS GUC names + the v0.4.21 all-read marker are env-settable. `_TENANT_ALL_MARKER`
2404        // and `_TENANT_GUC` must NOT be shadowed by the shorter `_TENANT` suffix (longest-first
2405        // isolation) — a `_TENANT` value would otherwise swallow the DB-name split.
2406        let mut cfg = ServerConfig::default();
2407        cfg.apply_env_overrides(&env(&[
2408            ("BOATRAMP_HANDLERS_SQL_DB_DEFAULT_KIND", "postgres"),
2409            ("BOATRAMP_HANDLERS_SQL_DB_DEFAULT_DATABASE", "appdb"),
2410            (
2411                "BOATRAMP_HANDLERS_SQL_DB_DEFAULT_TENANT_GUC",
2412                "app.tenant_id",
2413            ),
2414            (
2415                "BOATRAMP_HANDLERS_SQL_DB_DEFAULT_SESSION_GUC",
2416                "app.session_id",
2417            ),
2418            ("BOATRAMP_HANDLERS_SQL_DB_DEFAULT_TENANT_ALL_MARKER", "*"),
2419        ]))
2420        .expect("valid env overrides apply");
2421        let db = &cfg.handlers.unwrap().bindings.sql.unwrap().databases
2422            [boatramp_core::project::DEFAULT_DB_NAME];
2423        assert_eq!(db.tenant_guc.as_deref(), Some("app.tenant_id"));
2424        assert_eq!(db.session_guc.as_deref(), Some("app.session_id"));
2425        assert_eq!(db.tenant_all_marker.as_deref(), Some("*"));
2426    }
2427
2428    #[test]
2429    fn env_enum_parse_error_names_the_variable_and_variants() {
2430        // An unknown enum value is a clear error that names the offending variable.
2431        let mut cfg = ServerConfig::default();
2432        let err = cfg
2433            .apply_env_overrides(&env(&[(
2434                "BOATRAMP_COMPUTE_MANAGED_DB_PRIVILEGE",
2435                "superuser",
2436            )]))
2437            .expect_err("unknown enum variant is rejected");
2438        match err {
2439            ConfigError::Env { var, reason } => {
2440                assert_eq!(var, "BOATRAMP_COMPUTE_MANAGED_DB_PRIVILEGE");
2441                assert!(reason.contains("rootless") && reason.contains("caps"));
2442            }
2443            other => panic!("expected ConfigError::Env, got {other:?}"),
2444        }
2445        // The docker enums map their lowercase serde variants too.
2446        let mut cfg = ServerConfig::default();
2447        cfg.apply_env_overrides(&env(&[
2448            ("BOATRAMP_COMPUTE_DOCKER_ENDPOINT", "bridge"),
2449            ("BOATRAMP_COMPUTE_DOCKER_VOLUME_MODE", "bind"),
2450        ]))
2451        .expect("known enum variants parse");
2452        let compute = cfg.compute.unwrap();
2453        assert_eq!(
2454            compute.docker_endpoint,
2455            boatramp_docker::DockerEndpoint::Bridge
2456        );
2457        assert_eq!(
2458            compute.docker_volume_mode,
2459            boatramp_docker::DockerVolumeMode::Bind
2460        );
2461    }
2462
2463    #[test]
2464    fn env_trust_anchors_parse_as_a_comma_separated_list() {
2465        // The kernel trust anchors are comma-separated (whitespace trimmed, empty
2466        // items dropped so a trailing comma is tolerated). A file default is
2467        // fully replaced, not appended to.
2468        let mut cfg = ServerConfig::default();
2469        cfg.apply_env_overrides(&env(&[
2470            (
2471                "BOATRAMP_COMPUTE_KERNEL_SIGNING_PUBKEYS",
2472                " es256:aa , es256:bb ,",
2473            ),
2474            ("BOATRAMP_COMPUTE_KERNEL_ALLOWED_HASHES", "deadbeef"),
2475        ]))
2476        .expect("valid list env applies");
2477        let compute = cfg.compute.unwrap();
2478        assert_eq!(
2479            compute.kernel_signing_pubkeys,
2480            vec!["es256:aa".to_string(), "es256:bb".to_string()],
2481            "trimmed, comma-split, trailing-empty dropped, defaults replaced"
2482        );
2483        assert_eq!(
2484            compute.kernel_allowed_hashes,
2485            vec!["deadbeef".to_string()],
2486            "a single value is a one-element list"
2487        );
2488    }
2489
2490    #[test]
2491    fn env_configures_secrets_vault_subconfig() {
2492        // The vault sub-config materialises only when a vault var is set, and the
2493        // token stays indirected via a variable NAME (`token_env`), never inline.
2494        let mut cfg = ServerConfig::default();
2495        cfg.apply_env_overrides(&env(&[
2496            ("BOATRAMP_SECRETS_ENVELOPE", "vault"),
2497            ("BOATRAMP_SECRETS_VAULT_ADDR", "https://vault:8200"),
2498            ("BOATRAMP_SECRETS_VAULT_KEY", "certs"),
2499        ]))
2500        .expect("valid env overrides apply");
2501        let secrets = cfg.secrets.unwrap();
2502        assert_eq!(secrets.envelope, "vault");
2503        let vault = secrets.vault.expect("vault sub-config materialised");
2504        assert_eq!(vault.addr, "https://vault:8200");
2505        assert_eq!(vault.key, "certs");
2506        // token_env defaults to VAULT_TOKEN when not overridden.
2507        assert_eq!(vault.token_env, "VAULT_TOKEN");
2508    }
2509
2510    #[test]
2511    fn env_materialises_and_overrides_the_cluster_section() {
2512        // With no file, a `BOATRAMP_CLUSTER_LISTEN` materialises the section; the
2513        // remaining fields (lists, join token, mesh) layer on. The founding/joining
2514        // action flags (`BOATRAMP_CLUSTER_INIT`/`_JOIN`) are separate `serve` args
2515        // and are not part of this section.
2516        let mut cfg = ServerConfig::default();
2517        cfg.apply_env_overrides(&env(&[
2518            ("BOATRAMP_CLUSTER_LISTEN", "10.0.0.2:7000"),
2519            ("BOATRAMP_CLUSTER_ROOT_PUBKEYS", "es256:aa,es256:bb"),
2520            ("BOATRAMP_CLUSTER_SEEDS", "https://10.0.0.1:8080"),
2521            ("BOATRAMP_CLUSTER_JOIN_TOKEN", "env:BOATRAMP_JOIN_TOKEN"),
2522            ("BOATRAMP_CLUSTER_STORE_DIR", "/var/lib/boatramp/raft"),
2523            ("BOATRAMP_CLUSTER_MESH_GATE_CLIENT_WRITES", "true"),
2524        ]))
2525        .expect("valid env overrides apply");
2526        let cluster = cfg.cluster.expect("cluster materialised from env");
2527        assert_eq!(
2528            cluster.listen,
2529            "10.0.0.2:7000".parse::<std::net::SocketAddr>().unwrap()
2530        );
2531        assert_eq!(
2532            cluster.root_pubkeys,
2533            vec!["es256:aa".to_string(), "es256:bb".to_string()]
2534        );
2535        assert_eq!(cluster.seeds, vec!["https://10.0.0.1:8080".to_string()]);
2536        assert_eq!(
2537            cluster.join_token.as_deref(),
2538            Some("env:BOATRAMP_JOIN_TOKEN")
2539        );
2540        assert_eq!(
2541            cluster.store_dir.as_deref(),
2542            Some(Path::new("/var/lib/boatramp/raft"))
2543        );
2544        assert_eq!(
2545            cluster.mesh.expect("mesh sub-config").gate_client_writes,
2546            Some(true)
2547        );
2548
2549        // Without a listen (and no file section) there is nothing to materialise:
2550        // a non-listen cluster var alone leaves the section absent.
2551        let mut cfg = ServerConfig::default();
2552        cfg.apply_env_overrides(&env(&[("BOATRAMP_CLUSTER_SEEDS", "https://10.0.0.1:8080")]))
2553            .expect("applies");
2554        assert!(
2555            cfg.cluster.is_none(),
2556            "no listen + no file section ⇒ no cluster"
2557        );
2558    }
2559
2560    #[test]
2561    fn env_cluster_listen_overrides_a_file_section() {
2562        // A file `[cluster]` section: env overrides `listen` and adds seeds.
2563        let mut cfg = server(r#"( cluster: ( listen: "0.0.0.0:7000" ) )"#);
2564        cfg.apply_env_overrides(&env(&[
2565            ("BOATRAMP_CLUSTER_LISTEN", "10.0.0.9:7000"),
2566            ("BOATRAMP_CLUSTER_SEEDS", "https://seed:8080"),
2567        ]))
2568        .expect("applies");
2569        let cluster = cfg.cluster.unwrap();
2570        assert_eq!(
2571            cluster.listen,
2572            "10.0.0.9:7000".parse::<std::net::SocketAddr>().unwrap(),
2573            "env listen wins over the file"
2574        );
2575        assert_eq!(cluster.seeds, vec!["https://seed:8080".to_string()]);
2576    }
2577
2578    #[test]
2579    fn empty_project_config_is_default() {
2580        let cfg = project("()");
2581        assert!(cfg.publish.server.is_none());
2582        assert!(cfg.publish.site.is_none());
2583        assert!(cfg.build.is_none());
2584        assert!(cfg.bundle.is_none());
2585        // Routing defaults: schema v1, the single default index candidate.
2586        assert_eq!(cfg.routing.version, 1);
2587        assert_eq!(cfg.routing.index, vec!["index.html".to_string()]);
2588    }
2589
2590    #[test]
2591    fn serve_signer_config_parses_and_maps_each_backend() {
2592        use boatramp_core::cose::TokenAlg;
2593        use boatramp_server::signer::SignerConfig;
2594
2595        // RON-native enum tagging (`Vault(...)`); `IMPLICIT_SOME` lets the optional
2596        // fields (region) take a bare value or be omitted (→ None). This is the
2597        // exact RON documented in the Authentication guide.
2598        let vault = server(
2599            r#"( serve: ( signer: Vault(
2600                address: "https://vault.example:8200",
2601                key: "boatramp-root",
2602                token_env: "VAULT_TOKEN",
2603                alg: Ed25519,
2604            ) ) )"#,
2605        );
2606        match vault.serve.unwrap().signer.unwrap().to_signer_config() {
2607            SignerConfig::Vault {
2608                address,
2609                key,
2610                token_env,
2611                alg,
2612            } => {
2613                assert_eq!(address, "https://vault.example:8200");
2614                assert_eq!(key, "boatramp-root");
2615                assert_eq!(token_env, "VAULT_TOKEN");
2616                assert_eq!(alg, TokenAlg::Ed25519);
2617            }
2618            other => panic!("expected Vault, got {other:?}"),
2619        }
2620
2621        // AWS KMS: region omitted → None; PKCS#11: alg omitted → the ES256 default.
2622        let aws =
2623            server(r#"( serve: ( signer: AwsKms(key_id: "arn:aws:kms:eu-west-1:1:key/abc") ) )"#);
2624        assert!(matches!(
2625            aws.serve.unwrap().signer.unwrap().to_signer_config(),
2626            SignerConfig::AwsKms { region: None, .. }
2627        ));
2628
2629        let hsm = server(
2630            r#"( serve: ( signer: Pkcs11(
2631                module: "/usr/lib/softhsm/libsofthsm2.so",
2632                token_label: "boatramp",
2633                key_label: "root",
2634                pin_env: "HSM_PIN",
2635            ) ) )"#,
2636        );
2637        match hsm.serve.unwrap().signer.unwrap().to_signer_config() {
2638            SignerConfig::Pkcs11 { alg, .. } => assert_eq!(alg, TokenAlg::Es256),
2639            other => panic!("expected Pkcs11, got {other:?}"),
2640        }
2641    }
2642
2643    #[test]
2644    fn project_config_parses_publish_build_and_routing() {
2645        let cfg = project(
2646            r#"(
2647                publish: ( server: "http://127.0.0.1:8080", site: "demo" ),
2648                build: ( command: "npm run build", output: "dist" ),
2649                routing: (
2650                    clean_urls: true,
2651                    redirects: [ (from: "/old/:slug", to: "/new/:slug", status: 301) ],
2652                ),
2653            )"#,
2654        );
2655        assert_eq!(cfg.publish.server.as_deref(), Some("http://127.0.0.1:8080"));
2656        assert_eq!(cfg.publish.site.as_deref(), Some("demo"));
2657        let build = cfg.build.unwrap();
2658        assert_eq!(build.command, "npm run build");
2659        assert_eq!(build.output.as_deref(), Some("dist"));
2660        assert!(cfg.routing.clean_urls);
2661        assert_eq!(cfg.routing.redirects.len(), 1);
2662        assert_eq!(cfg.routing.redirects[0].status, 301);
2663    }
2664
2665    #[test]
2666    fn project_config_rejects_bad_routing_pattern() {
2667        // The same compile-check `load` runs: a bad route pattern is an error.
2668        let cfg = project(r#"( routing: ( redirects: [ (from: "/a/**/b/**", to: "/x") ] ) )"#);
2669        assert!(cfg.routing.compile_check().is_err());
2670    }
2671
2672    #[test]
2673    fn empty_server_config_has_no_sections() {
2674        let cfg = server("()");
2675        assert!(cfg.serve.is_none());
2676        assert!(cfg.handlers.is_none());
2677        assert!(cfg.cluster.is_none());
2678        assert!(cfg.security.is_none());
2679    }
2680
2681    #[test]
2682    fn security_section_parses_and_resolves() {
2683        // A profile plus an override that wins over it.
2684        let cfg = server(
2685            r#"(
2686                security: (
2687                    profile: "dev",
2688                    overrides: (
2689                        oidc_require_audience: true,
2690                        max_upload_bytes: 0,
2691                    ),
2692                )
2693            )"#,
2694        );
2695        let posture = cfg.security.unwrap().resolve().expect("resolves");
2696        // `dev` is loose...
2697        assert!(posture.allow_unauthenticated_public_bind);
2698        // ...but the explicit override wins over the profile.
2699        assert!(posture.oidc_require_audience);
2700        assert_eq!(posture.max_upload_bytes, 0); // unlimited
2701    }
2702
2703    #[test]
2704    fn env_wires_allow_env_secret_refs_over_the_multi_tenant_default() {
2705        // With no file, the multi-tenant default leaves host-env secret refs off;
2706        // the env knob re-enables them (env > default), same as the other posture bools.
2707        let mut cfg = ServerConfig::default();
2708        cfg.apply_env_overrides(&env(&[("BOATRAMP_SECURITY_ALLOW_ENV_SECRET_REFS", "true")]))
2709            .expect("valid env override applies");
2710        let posture = cfg
2711            .security
2712            .expect("security materialised from env")
2713            .resolve()
2714            .expect("resolves");
2715        assert!(posture.allow_env_secret_refs);
2716    }
2717
2718    #[test]
2719    fn env_wires_the_multi_tenant_subknobs_over_the_default() {
2720        // Gap 4b: the four multi-tenant sub-knobs were file-only; env now sets them (env > the
2721        // multi-tenant preset default), so a 12-factor deploy can tune tenancy isolation + guest
2722        // capability minting with no `boatramp.cfg`. Verified: strict declaration stays on while
2723        // cross-tenant `all` twins + guest cap-mint are permitted (they compose — Gap 4.3).
2724        let mut cfg = ServerConfig::default();
2725        cfg.apply_env_overrides(&env(&[
2726            ("BOATRAMP_SECURITY_PROFILE", "multi-tenant"),
2727            ("BOATRAMP_SECURITY_REQUIRE_TENANCY_DECLARATION", "true"),
2728            ("BOATRAMP_SECURITY_ALLOW_CROSS_TENANT_DB", "true"),
2729            ("BOATRAMP_SECURITY_ALLOW_GUEST_MINT_CAPABILITY", "true"),
2730            ("BOATRAMP_SECURITY_MAX_GUEST_CAPABILITY_TTL_SECS", "1800"),
2731        ]))
2732        .expect("valid env overrides apply");
2733        let posture = cfg
2734            .security
2735            .expect("security materialised from env")
2736            .resolve()
2737            .expect("resolves");
2738        assert!(posture.require_tenancy_declaration);
2739        assert!(posture.allow_cross_tenant_db);
2740        assert!(posture.allow_guest_mint_capability);
2741        assert_eq!(posture.max_guest_capability_ttl_secs, 1800);
2742    }
2743
2744    #[test]
2745    fn env_wires_the_remaining_guest_feature_knobs_over_the_multi_tenant_default() {
2746        // v0.4.18 env parity: `allow_guest_email` (which regressed prod SMTP on the P48 cutover —
2747        // multi-tenant defaults it OFF and there was no env lever), its egress sibling
2748        // `allow_guest_egress_extra_ca` (shipped config-only in v0.4.17), and the four
2749        // `allow_guest_admin_*` self-config knobs were all missing from the env map. Each preset
2750        // defaults them OFF under `multi-tenant`; the env knob must now flip each back on for a
2751        // 12-factor env-only fleet, exactly like `allow_guest_mint_capability`.
2752        let mut cfg = ServerConfig::default();
2753        cfg.apply_env_overrides(&env(&[
2754            ("BOATRAMP_SECURITY_PROFILE", "multi-tenant"),
2755            ("BOATRAMP_SECURITY_ALLOW_GUEST_EMAIL", "true"),
2756            ("BOATRAMP_SECURITY_ALLOW_GUEST_EGRESS_EXTRA_CA", "true"),
2757            ("BOATRAMP_SECURITY_ALLOW_GUEST_ADMIN_DOMAINS", "true"),
2758            ("BOATRAMP_SECURITY_ALLOW_GUEST_ADMIN_EMAIL", "true"),
2759            ("BOATRAMP_SECURITY_ALLOW_GUEST_ADMIN_SITE", "true"),
2760            ("BOATRAMP_SECURITY_ALLOW_GUEST_ADMIN_SECRETS", "true"),
2761        ]))
2762        .expect("valid env overrides apply");
2763        let security = cfg.security.expect("security materialised from env");
2764        let posture = security.resolve().expect("resolves");
2765        // Every one flips on over the multi-tenant preset default (which is `false` for all six).
2766        assert!(posture.allow_guest_email, "guest email re-enabled via env");
2767        assert!(posture.allow_guest_egress_extra_ca);
2768        assert!(posture.allow_guest_admin_domains);
2769        assert!(posture.allow_guest_admin_email);
2770        assert!(posture.allow_guest_admin_site);
2771        assert!(posture.allow_guest_admin_secrets);
2772        // `security explain` attributes each to the override/env source (not the profile preset).
2773        let explained = security.explain().expect("explains");
2774        for knob in [
2775            "allow_guest_email",
2776            "allow_guest_egress_extra_ca",
2777            "allow_guest_admin_domains",
2778            "allow_guest_admin_email",
2779            "allow_guest_admin_site",
2780            "allow_guest_admin_secrets",
2781        ] {
2782            assert!(
2783                explained
2784                    .lines()
2785                    .any(|l| l.contains(knob) && l.contains("true") && l.contains("(override)")),
2786                "explain shows {knob} = true (override): \n{explained}"
2787            );
2788        }
2789    }
2790
2791    #[test]
2792    fn each_guest_feature_env_var_moves_its_own_posture_field() {
2793        // Cross-wiring guard: set each of the six guest-feature vars ALONE over the multi-tenant
2794        // default and assert THAT var's own resolved field flips — so a copy-paste arm mapping a var
2795        // to the wrong field (or an unregistered var that never materialises the section) fails here.
2796        // Complements `every_posture_override_field_has_an_env_mapping` below (which proves coverage
2797        // by field name but not that each arm targets the right field).
2798        for (var, check) in [
2799            (
2800                "BOATRAMP_SECURITY_ALLOW_GUEST_EMAIL",
2801                (|p: &boatramp_core::security::SecurityPosture| p.allow_guest_email)
2802                    as fn(&boatramp_core::security::SecurityPosture) -> bool,
2803            ),
2804            ("BOATRAMP_SECURITY_ALLOW_GUEST_EGRESS_EXTRA_CA", |p| {
2805                p.allow_guest_egress_extra_ca
2806            }),
2807            ("BOATRAMP_SECURITY_ALLOW_GUEST_ADMIN_DOMAINS", |p| {
2808                p.allow_guest_admin_domains
2809            }),
2810            ("BOATRAMP_SECURITY_ALLOW_GUEST_ADMIN_EMAIL", |p| {
2811                p.allow_guest_admin_email
2812            }),
2813            ("BOATRAMP_SECURITY_ALLOW_GUEST_ADMIN_SITE", |p| {
2814                p.allow_guest_admin_site
2815            }),
2816            ("BOATRAMP_SECURITY_ALLOW_GUEST_ADMIN_SECRETS", |p| {
2817                p.allow_guest_admin_secrets
2818            }),
2819        ] {
2820            let mut cfg = ServerConfig::default();
2821            cfg.apply_env_overrides(&env(&[
2822                ("BOATRAMP_SECURITY_PROFILE", "multi-tenant"),
2823                (var, "true"),
2824            ]))
2825            .unwrap_or_else(|e| panic!("{var} applies: {e}"));
2826            let posture = cfg
2827                .security
2828                .unwrap_or_else(|| panic!("{var} materialises the security section"))
2829                .resolve()
2830                .expect("resolves");
2831            assert!(check(&posture), "{var} did not flip the resolved posture");
2832        }
2833    }
2834
2835    #[test]
2836    fn every_posture_override_field_has_an_env_mapping() {
2837        // Exhaustive guard against the EXACT class of gap v0.4.18 closes — a `PostureOverrides`
2838        // field a 12-factor fleet can set in `[security.overrides]` but NOT via env — for EVERY
2839        // field, now and in the future. Enumerate the struct's fields structurally (serialize a
2840        // default instance; every field renders as a key) and assert each maps to a registered
2841        // `BOATRAMP_SECURITY_<UPPER(field)>` in `SECURITY_ENV_VARS`. A new override field added
2842        // without an env var (or a var left out of the registry) fails here — so the omission that
2843        // regressed `allow_guest_email` can't silently recur. The registry entry is load-bearing:
2844        // `apply_env_overrides` only materialises the section when `source.any(SECURITY_ENV_VARS)`.
2845        let all = serde_json::to_value(boatramp_core::security::PostureOverrides::default())
2846            .expect("PostureOverrides serializes");
2847        let fields = all.as_object().expect("a struct is a JSON object");
2848        assert!(!fields.is_empty(), "expected some override fields");
2849        for field in fields.keys() {
2850            let var = format!("BOATRAMP_SECURITY_{}", field.to_uppercase());
2851            assert!(
2852                SECURITY_ENV_VARS.contains(&var.as_str()),
2853                "PostureOverrides field `{field}` has no env mapping — add `{var}` to \
2854                 SECURITY_ENV_VARS + an arm in apply_env_overrides (the v0.4.18 forgot-a-knob guard)"
2855            );
2856        }
2857    }
2858
2859    #[test]
2860    fn cluster_section_parses_the_dynamic_join_shape() {
2861        let cfg = server(
2862            r#"(
2863                cluster: (
2864                    listen: "10.0.0.2:7000",
2865                    root_pubkeys: ["es256:03a1"],
2866                    seeds: ["https://10.0.0.1:8080"],
2867                    join_token: "env:BOATRAMP_JOIN_TOKEN",
2868                ),
2869            )"#,
2870        );
2871        let cluster = cfg.cluster.unwrap();
2872        assert_eq!(
2873            cluster.listen,
2874            "10.0.0.2:7000".parse::<std::net::SocketAddr>().unwrap()
2875        );
2876        assert_eq!(cluster.root_pubkeys, vec!["es256:03a1".to_string()]);
2877        assert_eq!(cluster.seeds, vec!["https://10.0.0.1:8080".to_string()]);
2878        assert_eq!(
2879            cluster.join_token.as_deref(),
2880            Some("env:BOATRAMP_JOIN_TOKEN")
2881        );
2882        // store_dir defaults to None (→ <data-dir>/raft at serve time).
2883        assert!(cluster.store_dir.is_none());
2884    }
2885
2886    #[test]
2887    fn cluster_section_founds_with_just_a_listen_addr() {
2888        // A founder needs no seeds/token — just where to bind the mesh.
2889        let cfg = server(r#"( cluster: ( listen: "0.0.0.0:7000" ) )"#);
2890        let cluster = cfg.cluster.unwrap();
2891        assert!(cluster.seeds.is_empty());
2892        assert!(cluster.root_pubkeys.is_empty());
2893        assert!(cluster.join_token.is_none());
2894    }
2895
2896    #[test]
2897    fn sql_binding_single_node_defaults() {
2898        // A bare section (or none) means single-node: no url, default dir.
2899        let cfg = server(r#"( handlers: ( bindings: ( sql: () ) ) )"#);
2900        let sql = cfg.handlers.unwrap().bindings.sql.unwrap();
2901        assert!(sql.url.is_none());
2902        assert!(sql.dir.is_none());
2903    }
2904
2905    #[test]
2906    fn sql_binding_single_node_custom_dir() {
2907        let cfg =
2908            server(r#"( handlers: ( bindings: ( sql: ( dir: "/var/lib/boatramp/sql" ) ) ) )"#);
2909        let sql = cfg.handlers.unwrap().bindings.sql.unwrap();
2910        assert_eq!(sql.dir.as_deref(), Some(Path::new("/var/lib/boatramp/sql")));
2911        assert!(sql.url.is_none());
2912    }
2913
2914    #[test]
2915    fn sql_binding_cluster() {
2916        let cfg = server(
2917            r#"(
2918                handlers: ( bindings: ( sql: (
2919                    url: "http://sqld:8080",
2920                    admin_url: "http://sqld:9090",
2921                    token_env: "BOATRAMP_SQL_TOKEN",
2922                ) ) ),
2923            )"#,
2924        );
2925        let sql = cfg.handlers.unwrap().bindings.sql.unwrap();
2926        assert_eq!(sql.url.as_deref(), Some("http://sqld:8080"));
2927        assert_eq!(sql.admin_url.as_deref(), Some("http://sqld:9090"));
2928        assert_eq!(sql.token_env.as_deref(), Some("BOATRAMP_SQL_TOKEN"));
2929        assert_eq!(sql.admin_token_env, None);
2930    }
2931
2932    #[test]
2933    fn sql_binding_preview_policy() {
2934        let cfg = server(
2935            r#"(
2936                handlers: ( bindings: ( sql: (
2937                    preview_mode: "branch",
2938                    preview_init: "/etc/boatramp/seed.sql",
2939                ) ) ),
2940            )"#,
2941        );
2942        let sql = cfg.handlers.unwrap().bindings.sql.unwrap();
2943        assert_eq!(sql.preview_mode.as_deref(), Some("branch"));
2944        assert_eq!(
2945            sql.preview_init.as_deref(),
2946            Some(Path::new("/etc/boatramp/seed.sql"))
2947        );
2948    }
2949
2950    #[test]
2951    fn sql_binding_external_databases() {
2952        let cfg = server(
2953            r#"(
2954                handlers: ( bindings: ( sql: (
2955                    databases: {
2956                        "analytics": (
2957                            kind: "postgres",
2958                            url_env: "ANALYTICS_PG_URL",
2959                            pool_max: 16,
2960                            read_only: true,
2961                        ),
2962                        "events": (
2963                            kind: "mysql",
2964                            url_env: "EVENTS_MYSQL_URL",
2965                            read_url_env: "EVENTS_MYSQL_REPLICA_URL",
2966                            allow_preview: true,
2967                        ),
2968                    },
2969                ) ) ),
2970            )"#,
2971        );
2972        let sql = cfg.handlers.unwrap().bindings.sql.unwrap();
2973        assert_eq!(sql.databases.len(), 2);
2974
2975        let analytics = &sql.databases["analytics"];
2976        assert_eq!(analytics.kind, "postgres");
2977        assert_eq!(analytics.url_env, "ANALYTICS_PG_URL");
2978        assert_eq!(analytics.pool_max, Some(16));
2979        assert!(analytics.read_only);
2980        assert!(!analytics.allow_preview);
2981        assert!(analytics.read_url_env.is_none());
2982
2983        let events = &sql.databases["events"];
2984        assert_eq!(events.kind, "mysql");
2985        assert_eq!(
2986            events.read_url_env.as_deref(),
2987            Some("EVENTS_MYSQL_REPLICA_URL")
2988        );
2989        assert!(events.allow_preview);
2990        assert!(!events.read_only);
2991    }
2992
2993    #[test]
2994    fn sql_binding_compute_backed_database() {
2995        let cfg = server(
2996            r#"(
2997                handlers: ( bindings: ( sql: (
2998                    databases: {
2999                        "analytics": (
3000                            kind: "postgres",
3001                            compute: "pg",
3002                            database: "analytics",
3003                            user: "app",
3004                            password_env: "PG_APP_PW",
3005                        ),
3006                    },
3007                ) ) ),
3008            )"#,
3009        );
3010        let db = &cfg.handlers.unwrap().bindings.sql.unwrap().databases["analytics"];
3011        assert_eq!(db.kind, "postgres");
3012        assert_eq!(db.compute.as_deref(), Some("pg"));
3013        assert_eq!(db.database.as_deref(), Some("analytics"));
3014        assert_eq!(db.user.as_deref(), Some("app"));
3015        assert_eq!(db.password_env.as_deref(), Some("PG_APP_PW"));
3016        assert!(db.url_env.is_empty(), "compute-backed has no url_env");
3017        assert!(db.validate("analytics").is_ok());
3018    }
3019
3020    #[test]
3021    fn sql_binding_source_is_exactly_one_of_url_or_compute() {
3022        // Neither source → error.
3023        assert!(ExternalDatabaseConfig::default().validate("db").is_err());
3024        // Both sources → error.
3025        let both = ExternalDatabaseConfig {
3026            kind: "postgres".into(),
3027            url_env: "PG_URL".into(),
3028            compute: Some("pg".into()),
3029            ..Default::default()
3030        };
3031        assert!(both.validate("db").is_err());
3032        // `url_env` only → ok.
3033        let url = ExternalDatabaseConfig {
3034            kind: "postgres".into(),
3035            url_env: "PG_URL".into(),
3036            ..Default::default()
3037        };
3038        assert!(url.validate("db").is_ok());
3039        // `compute` without the connection details boatramp can't infer → error.
3040        let bare = ExternalDatabaseConfig {
3041            kind: "postgres".into(),
3042            compute: Some("pg".into()),
3043            ..Default::default()
3044        };
3045        assert!(bare.validate("db").is_err());
3046        // `compute` with database/user + a bring-your-own `password_env` → ok, and
3047        // is *not* a managed credential.
3048        let byo = ExternalDatabaseConfig {
3049            kind: "postgres".into(),
3050            compute: Some("pg".into()),
3051            database: Some("analytics".into()),
3052            user: Some("app".into()),
3053            password_env: Some("PG_APP_PW".into()),
3054            ..Default::default()
3055        };
3056        assert!(byo.validate("db").is_ok());
3057        assert!(!byo.is_managed_credential());
3058        // `compute` with database/user but NO `password_env` → ok, and boatramp
3059        // manages the credential (Phase 2).
3060        let managed = ExternalDatabaseConfig {
3061            kind: "postgres".into(),
3062            compute: Some("pg".into()),
3063            database: Some("analytics".into()),
3064            user: Some("app".into()),
3065            ..Default::default()
3066        };
3067        assert!(managed.validate("db").is_ok());
3068        assert!(managed.is_managed_credential());
3069    }
3070
3071    #[test]
3072    fn libsql_source_is_exactly_one_of_path_or_url() {
3073        // A single-node `libsql` file (path only) → ok.
3074        let file = ExternalDatabaseConfig {
3075            kind: "libsql".into(),
3076            path: Some("/data/app.db".into()),
3077            ..Default::default()
3078        };
3079        assert!(file.validate("app").is_ok());
3080        // `sqlite` alias works the same.
3081        let sqlite = ExternalDatabaseConfig {
3082            kind: "sqlite".into(),
3083            path: Some("/data/app.db".into()),
3084            ..Default::default()
3085        };
3086        assert!(sqlite.validate("app").is_ok());
3087        // A remote-sqld `libsql` (url_env only) → ok.
3088        let remote = ExternalDatabaseConfig {
3089            kind: "libsql".into(),
3090            url_env: "LIBSQL_URL".into(),
3091            ..Default::default()
3092        };
3093        assert!(remote.validate("app").is_ok());
3094        // Neither `path` nor `url_env` → error.
3095        let neither = ExternalDatabaseConfig {
3096            kind: "libsql".into(),
3097            ..Default::default()
3098        };
3099        assert!(neither.validate("app").is_err());
3100        // Both `path` and `url_env` → error (exactly one).
3101        let both = ExternalDatabaseConfig {
3102            kind: "libsql".into(),
3103            path: Some("/data/app.db".into()),
3104            url_env: "LIBSQL_URL".into(),
3105            ..Default::default()
3106        };
3107        assert!(both.validate("app").is_err());
3108        // `compute` on a `libsql` binding → error (boatramp doesn't run a libsql server workload).
3109        let compute = ExternalDatabaseConfig {
3110            kind: "libsql".into(),
3111            compute: Some("x".into()),
3112            path: Some("/data/app.db".into()),
3113            ..Default::default()
3114        };
3115        assert!(compute.validate("app").is_err());
3116        // `path` on a NON-libsql (postgres) binding → error (only libsql has an on-disk file).
3117        let pg_path = ExternalDatabaseConfig {
3118            kind: "postgres".into(),
3119            url_env: "PG_URL".into(),
3120            path: Some("/data/app.db".into()),
3121            ..Default::default()
3122        };
3123        assert!(pg_path.validate("db").is_err());
3124    }
3125
3126    /// Path to a file at the repo root (two levels up from this crate).
3127    fn repo_root_file(name: &str) -> PathBuf {
3128        Path::new(env!("CARGO_MANIFEST_DIR"))
3129            .join("../..")
3130            .join(name)
3131    }
3132
3133    #[test]
3134    fn shipped_project_example_parses() {
3135        // The example we ship must always parse + compile-check, so it can't drift
3136        // from the schema.
3137        let text = std::fs::read_to_string(repo_root_file("examples/site/project.cfg.example"))
3138            .expect("example project config is present");
3139        let cfg = ProjectConfig::parse(&text).expect("example project config parses");
3140        assert_eq!(cfg.publish.server.as_deref(), Some("http://127.0.0.1:8080"));
3141        assert_eq!(cfg.build.as_ref().unwrap().command, "npm run build");
3142        assert_eq!(
3143            cfg.routing.error_documents.get(&404).map(String::as_str),
3144            Some("/404.html")
3145        );
3146    }
3147
3148    #[test]
3149    fn shipped_server_example_parses() {
3150        let text = std::fs::read_to_string(repo_root_file("boatramp.cfg.example"))
3151            .expect("example server config is present");
3152        let cfg = ServerConfig::parse(&text).expect("example server config parses");
3153        let serve = cfg.serve.expect("example sets a serve section");
3154        assert_eq!(
3155            serve.addr,
3156            Some("0.0.0.0:8080".parse::<std::net::SocketAddr>().unwrap())
3157        );
3158    }
3159
3160    #[test]
3161    fn secrets_section_parses_local_and_vault() {
3162        let local = server(r#"( secrets: ( envelope: "local", kek_file: "/k/kek" ) )"#)
3163            .secrets
3164            .expect("secrets section");
3165        assert_eq!(local.envelope, "local");
3166        assert_eq!(
3167            local.kek_file.as_deref(),
3168            Some(std::path::Path::new("/k/kek"))
3169        );
3170
3171        let vault = server(
3172            r#"( secrets: ( envelope: "vault", vault: ( addr: "https://vault:8200", key: "certs" ) ) )"#,
3173        )
3174        .secrets
3175        .expect("secrets section");
3176        let v = vault.vault.expect("vault subsection");
3177        assert_eq!(v.addr, "https://vault:8200");
3178        assert_eq!(v.key, "certs");
3179        // The token env defaults to VAULT_TOKEN and is never in the file.
3180        assert_eq!(v.token_env, "VAULT_TOKEN");
3181    }
3182
3183    #[test]
3184    fn serve_section_partial_parses() {
3185        // A partial `serve` section parses — unset fields take their defaults.
3186        let cfg = server(r#"( serve: ( addr: "0.0.0.0:8080", protect_previews: true ) )"#);
3187        let serve = cfg.serve.unwrap();
3188        assert_eq!(
3189            serve.addr,
3190            Some("0.0.0.0:8080".parse::<std::net::SocketAddr>().unwrap())
3191        );
3192        assert!(serve.protect_previews);
3193        assert!(!serve.cluster_rate_limit);
3194        assert!(serve.data_dir.is_none());
3195    }
3196
3197    #[test]
3198    fn serve_console_config_parses() {
3199        // Absent ⇒ no console.
3200        let cfg = server(r#"( serve: ( addr: "0.0.0.0:8080" ) )"#);
3201        assert!(cfg.serve.unwrap().console.is_none());
3202        // Explicit console block with host + path.
3203        let cfg = server(
3204            r#"( serve: ( console: (
3205                enabled: true,
3206                host: "console.example.com",
3207                path: "/_console",
3208            ) ) )"#,
3209        );
3210        let console = cfg.serve.unwrap().console.unwrap();
3211        assert!(console.enabled);
3212        assert_eq!(console.host.as_deref(), Some("console.example.com"));
3213        assert_eq!(console.path.as_deref(), Some("/_console"));
3214        // Bare `enabled` ⇒ host/path take their (server-side) defaults.
3215        let cfg = server(r#"( serve: ( console: ( enabled: true ) ) )"#);
3216        let console = cfg.serve.unwrap().console.unwrap();
3217        assert!(console.enabled);
3218        assert!(console.host.is_none() && console.path.is_none());
3219    }
3220}