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}
59
60/// Project configuration, loaded from `project.cfg` (RON) in the project folder.
61///
62/// Read by the client commands (`sync`, `build`, `bundle`, `validate`).
63/// Everything is optional; a missing file is the default.
64#[derive(Debug, Default, Deserialize)]
65#[serde(default)]
66pub struct ProjectConfig {
67    /// Where and how to publish this project.
68    pub publish: PublishConfig,
69    /// Optional build step run before `sync`.
70    pub build: Option<BuildConfig>,
71    /// Optional embedded-bundler step (`bundler` feature).
72    pub bundle: Option<BundleConfig>,
73    /// Deploy-scoped routing/handlers config. Folded into the deployment
74    /// manifest at `sync` (so it is atomic with the content and rolls back with
75    /// it). The bulk of a project's config — redirects, rewrites, headers,
76    /// handlers, consumers, crons, streams.
77    pub routing: DeployConfig,
78}
79
80impl ProjectConfig {
81    /// Parse a `project.cfg` document (RON). The `routing` section is
82    /// compile-checked (route patterns, cron schedules, imports) so a bad config
83    /// fails fast.
84    pub fn parse(text: &str) -> Result<Self, ConfigError> {
85        let config: Self = ron_options().from_str(text)?;
86        config.routing.compile_check()?;
87        Ok(config)
88    }
89
90    /// Load from `path` (RON). A missing file yields the default config.
91    pub fn load(path: &Path) -> Result<Self, ConfigError> {
92        match std::fs::read_to_string(path) {
93            Ok(contents) => Self::parse(&contents).map_err(|err| ConfigError::File {
94                path: path.display().to_string(),
95                source: Box::new(err),
96            }),
97            Err(err) if err.kind() == std::io::ErrorKind::NotFound => Ok(Self::default()),
98            Err(err) => Err(err.into()),
99        }
100    }
101}
102
103/// Server daemon configuration, loaded from `boatramp.cfg` (RON). Read by
104/// `boatramp serve`; flags/env override the `serve` values.
105#[derive(Debug, Default, Deserialize)]
106#[serde(default)]
107pub struct ServerConfig {
108    /// Server defaults for `serve` (flag/env override these).
109    pub serve: Option<ServeConfig>,
110    /// Server-side handler runtime config (which backend serves each binding),
111    /// consumed only with the `handlers` feature.
112    pub handlers: Option<HandlersConfig>,
113    /// Self-hosted cluster mode (consumed only with the `cluster` feature).
114    pub cluster: Option<ClusterConfig>,
115    /// Opt-in **compute** backends. Present ⇒ this node
116    /// runs compute workloads via the backends it can offer; absent ⇒ no compute
117    /// (the reconcile loop stays a no-op).
118    pub compute: Option<ComputeConfig>,
119    /// Operator security posture (the hardening knobs): a profile
120    /// preset + overrides, resolved at startup. Absent ⇒ the strict
121    /// `multi-tenant` default. Operator-only — never part of site config.
122    pub security: Option<boatramp_core::security::SecurityConfig>,
123    /// Secrets-at-rest envelope. Absent ⇒ private
124    /// keys stored cleartext in the (replicated) control plane.
125    pub secrets: Option<SecretsConfig>,
126}
127
128/// `secrets` section — envelope encryption for private keys at rest.
129#[cfg_attr(not(feature = "cluster"), allow(dead_code))]
130#[derive(Debug, Clone, Default, Deserialize)]
131#[serde(default, deny_unknown_fields)]
132pub struct SecretsConfig {
133    /// Backend: `"local"` (machine-local AES-256-GCM KEK) or `"vault"` (Vault
134    /// Transit). Empty/other ⇒ no wrapping. In a cluster a local KEK must be the
135    /// **same file on every node** (wrapped certs replicate); Vault avoids that.
136    pub envelope: String,
137    /// Local-KEK key file (`envelope = "local"`). Default
138    /// `<data-dir>/secrets/kek`. Auto-generated `0600` if absent.
139    pub kek_file: Option<PathBuf>,
140    /// Vault Transit config (`envelope = "vault"`).
141    pub vault: Option<VaultSecretsConfig>,
142}
143
144/// Vault Transit settings for `envelope = "vault"`. The token is read from the
145/// environment (`token_env`), never stored in the config file.
146#[cfg_attr(not(all(feature = "cluster", feature = "acme-dns")), allow(dead_code))]
147#[derive(Debug, Clone, Deserialize)]
148#[serde(deny_unknown_fields)]
149pub struct VaultSecretsConfig {
150    /// Vault address, e.g. `https://vault:8200`.
151    pub addr: String,
152    /// Transit key name to wrap under.
153    pub key: String,
154    /// Environment variable holding the Vault token (default `VAULT_TOKEN`).
155    #[serde(default = "default_vault_token_env")]
156    pub token_env: String,
157}
158
159fn default_vault_token_env() -> String {
160    "VAULT_TOKEN".to_string()
161}
162
163impl Default for VaultSecretsConfig {
164    fn default() -> Self {
165        Self {
166            addr: String::new(),
167            key: String::new(),
168            token_env: default_vault_token_env(),
169        }
170    }
171}
172
173impl ServerConfig {
174    /// Parse a `boatramp.cfg` document (RON).
175    pub fn parse(text: &str) -> Result<Self, ConfigError> {
176        Ok(ron_options().from_str(text)?)
177    }
178
179    /// Load from `path` (RON), then layer `BOATRAMP_*` environment overrides on
180    /// top. A missing file yields the default config, so `serve` can be configured
181    /// entirely from the environment (12-factor deployments where dropping a
182    /// `boatramp.cfg` is awkward — fly.io / Cloudflare / containers).
183    pub fn load(path: &Path) -> Result<Self, ConfigError> {
184        let mut config = match std::fs::read_to_string(path) {
185            Ok(contents) => Self::parse(&contents).map_err(|err| ConfigError::File {
186                path: path.display().to_string(),
187                source: Box::new(err),
188            })?,
189            Err(err) if err.kind() == std::io::ErrorKind::NotFound => Self::default(),
190            Err(err) => return Err(err.into()),
191        };
192        config.apply_env_overrides(&EnvSource::Process)?;
193        Ok(config)
194    }
195
196    /// Layer `BOATRAMP_*` environment overrides onto the loaded config for the
197    /// `compute`, `security`, and handler-`sql` sections — the operational knobs
198    /// that were previously reachable only through the `boatramp.cfg` file.
199    ///
200    /// **Precedence: env overrides file.** This matches the existing `serve`
201    /// section (its `#[arg(long, env = …)]` flags already let an env var win over
202    /// the file value), keeping the resolution rule uniform. A set variable
203    /// updates the field even when the file also set it; an unset variable leaves
204    /// the file (or built-in default) untouched. When a section is absent from the
205    /// file but any of its variables are set, the section is materialised from its
206    /// defaults first — so no config file is required to configure it.
207    ///
208    /// `source` supplies the variables (the process environment in production; an
209    /// explicit map in tests), so this stays a pure function of its inputs.
210    fn apply_env_overrides(&mut self, source: &EnvSource) -> Result<(), ConfigError> {
211        // --- compute ---------------------------------------------------------
212        // Materialise `[compute]` only if at least one of its variables is set, so
213        // an unset environment leaves an absent section absent (⇒ no compute).
214        if source.any(COMPUTE_ENV_VARS) {
215            let compute = self.compute.get_or_insert_with(ComputeConfig::default);
216            if let Some(v) = source.get("BOATRAMP_COMPUTE_BRIDGE") {
217                compute.bridge = v;
218            }
219            if let Some(v) = source.get("BOATRAMP_COMPUTE_SUBNET") {
220                compute.subnet = v;
221            }
222            if let Some(v) = source.parse("BOATRAMP_COMPUTE_VCPUS")? {
223                compute.vcpus = v;
224            }
225            if let Some(v) = source.parse("BOATRAMP_COMPUTE_MEM_MIB")? {
226                compute.mem_mib = v;
227            }
228            if let Some(v) = source.get("BOATRAMP_COMPUTE_REGION") {
229                compute.region = Some(v);
230            }
231            if let Some(v) = source.get("BOATRAMP_COMPUTE_SQL_SHIM_URL") {
232                compute.sql_shim_url = Some(v);
233            }
234            // The two shared-kernel enums have no `FromStr`, only a serde
235            // `rename_all = "lowercase"`; map their variants by that same spelling.
236            if let Some(v) = source.parse_enum(
237                "BOATRAMP_COMPUTE_MANAGED_DB_PRIVILEGE",
238                &[
239                    ("rootless", ManagedDbPrivilege::Rootless),
240                    ("caps", ManagedDbPrivilege::Caps),
241                ],
242            )? {
243                compute.managed_db_privilege = v;
244            }
245            if let Some(v) = source.parse_enum(
246                "BOATRAMP_COMPUTE_DOCKER_ENDPOINT",
247                &[
248                    ("published", boatramp_docker::DockerEndpoint::Published),
249                    ("bridge", boatramp_docker::DockerEndpoint::Bridge),
250                ],
251            )? {
252                compute.docker_endpoint = v;
253            }
254            if let Some(v) = source.parse_enum(
255                "BOATRAMP_COMPUTE_DOCKER_VOLUME_MODE",
256                &[
257                    ("named", boatramp_docker::DockerVolumeMode::Named),
258                    ("bind", boatramp_docker::DockerVolumeMode::Bind),
259                ],
260            )? {
261                compute.docker_volume_mode = v;
262            }
263            // Kernel trust anchors — comma-separated lists. These are
264            // security-critical: they are the trust anchor for the posture-scaled
265            // kernel bar, so a value here decides which kernels a `multi-tenant`
266            // node will boot. In a 12-factor deployment the environment IS the
267            // operator's trusted config source (a fly.toml `[env]` is committed the
268            // same as a file), so they are exposed here — but an operator should
269            // know the environment is *more* visible than a file (it leaks through
270            // `/proc/<pid>/environ` and is inherited by every subprocess), so a
271            // file remains the better home for them when one is available.
272            if let Some(v) = source.parse_list("BOATRAMP_COMPUTE_KERNEL_SIGNING_PUBKEYS") {
273                compute.kernel_signing_pubkeys = v;
274            }
275            if let Some(v) = source.parse_list("BOATRAMP_COMPUTE_KERNEL_ALLOWED_HASHES") {
276                compute.kernel_allowed_hashes = v;
277            }
278        }
279
280        // --- security --------------------------------------------------------
281        // Always materialise `[security]` when any knob is set: an absent section
282        // resolves to the strict `multi-tenant` default, and an env override then
283        // layers over that exactly as a file `overrides` block would.
284        if source.any(SECURITY_ENV_VARS) {
285            let security = self
286                .security
287                .get_or_insert_with(boatramp_core::security::SecurityConfig::default);
288            if let Some(v) = source.get("BOATRAMP_SECURITY_PROFILE") {
289                security.profile = Some(v);
290            }
291            let o = &mut security.overrides;
292            if let Some(v) =
293                source.parse_bool("BOATRAMP_SECURITY_ALLOW_UNAUTHENTICATED_PUBLIC_BIND")?
294            {
295                o.allow_unauthenticated_public_bind = Some(v);
296            }
297            if let Some(v) = source.parse("BOATRAMP_SECURITY_MAX_UPLOAD_BYTES")? {
298                o.max_upload_bytes = Some(v);
299            }
300            if let Some(v) = source.parse_bool("BOATRAMP_SECURITY_ALLOW_SITE_UNIX_UPSTREAMS")? {
301                o.allow_site_unix_upstreams = Some(v);
302            }
303            if let Some(v) = source.parse_bool("BOATRAMP_SECURITY_ALLOW_SITE_PRIVATE_UPSTREAMS")? {
304                o.allow_site_private_upstreams = Some(v);
305            }
306            if let Some(v) = source.parse_bool("BOATRAMP_SECURITY_ALLOW_GUEST_PRIVATE_EGRESS")? {
307                o.allow_guest_private_egress = Some(v);
308            }
309            if let Some(v) = source.parse_bool("BOATRAMP_SECURITY_ALLOW_GUEST_SELF_EGRESS")? {
310                o.allow_guest_self_egress = Some(v);
311            }
312            if let Some(v) = source.parse("BOATRAMP_SECURITY_MAX_HANDLER_BLOB_BYTES")? {
313                o.max_handler_blob_bytes = Some(v);
314            }
315            if let Some(v) = source.parse("BOATRAMP_SECURITY_MAX_COMPONENT_BYTES")? {
316                o.max_component_bytes = Some(v);
317            }
318            if let Some(v) = source.parse_bool("BOATRAMP_SECURITY_OIDC_REQUIRE_AUDIENCE")? {
319                o.oidc_require_audience = Some(v);
320            }
321            if let Some(v) = source.parse_bool("BOATRAMP_SECURITY_DOMAIN_VERIFY_ALLOW_PRIVATE")? {
322                o.domain_verify_allow_private = Some(v);
323            }
324            if let Some(v) = source.parse_bool("BOATRAMP_SECURITY_DOMAIN_VERIFY_SELF_SERVE")? {
325                o.domain_verify_self_serve = Some(v);
326            }
327            if let Some(v) = source.parse_bool("BOATRAMP_SECURITY_ALLOW_SHARED_KERNEL_COMPUTE")? {
328                o.allow_shared_kernel_compute = Some(v);
329            }
330            if let Some(v) = source.parse_bool("BOATRAMP_SECURITY_ALLOW_COMPUTE_EXEC")? {
331                o.allow_compute_exec = Some(v);
332            }
333            if let Some(v) = source.parse_bool("BOATRAMP_SECURITY_RATELIMIT_FAIL_OPEN")? {
334                o.ratelimit_fail_open = Some(v);
335            }
336            if let Some(v) = source.parse_bool("BOATRAMP_SECURITY_ALLOW_IMPLICIT_ROUTING")? {
337                o.allow_implicit_routing = Some(v);
338            }
339            if let Some(v) = source.parse_bool("BOATRAMP_SECURITY_REQUIRE_POP")? {
340                o.require_pop = Some(v);
341            }
342            if let Some(v) = source.parse_bool("BOATRAMP_SECURITY_REQUIRE_DOMAIN_VERIFICATION")? {
343                o.require_domain_verification = Some(v);
344            }
345            if let Some(v) = source.parse_bool("BOATRAMP_SECURITY_ALLOW_ENV_SECRET_REFS")? {
346                o.allow_env_secret_refs = Some(v);
347            }
348        }
349
350        // --- handler sql (`handlers.bindings.sql`) ---------------------------
351        // Materialise the nested `handlers.bindings.sql` chain only when a `sql`
352        // variable is set, so an unset environment doesn't conjure an empty
353        // handlers section. The variables mirror the config path
354        // (`BOATRAMP_HANDLERS_SQL_*`) and cover the cluster-vs-single-node knobs;
355        // secrets stay indirected via `*_TOKEN_ENV` names, never the token itself.
356        if source.any(SQL_ENV_VARS) {
357            let handlers = self.handlers.get_or_insert_with(HandlersConfig::default);
358            let sql = handlers
359                .bindings
360                .sql
361                .get_or_insert_with(SqlBindingConfig::default);
362            if let Some(v) = source.get("BOATRAMP_HANDLERS_SQL_DIR") {
363                sql.dir = Some(PathBuf::from(v));
364            }
365            if let Some(v) = source.get("BOATRAMP_HANDLERS_SQL_URL") {
366                sql.url = Some(v);
367            }
368            if let Some(v) = source.get("BOATRAMP_HANDLERS_SQL_ADMIN_URL") {
369                sql.admin_url = Some(v);
370            }
371            if let Some(v) = source.get("BOATRAMP_HANDLERS_SQL_REPLICA_URL") {
372                sql.replica_url = Some(v);
373            }
374            if let Some(v) = source.get("BOATRAMP_HANDLERS_SQL_TOKEN_ENV") {
375                sql.token_env = Some(v);
376            }
377            if let Some(v) = source.get("BOATRAMP_HANDLERS_SQL_ADMIN_TOKEN_ENV") {
378                sql.admin_token_env = Some(v);
379            }
380            if let Some(v) = source.get("BOATRAMP_HANDLERS_SQL_PREVIEW_MODE") {
381                sql.preview_mode = Some(v);
382            }
383            if let Some(v) = source.get("BOATRAMP_HANDLERS_SQL_PREVIEW_INIT") {
384                sql.preview_init = Some(PathBuf::from(v));
385            }
386            if let Some(v) = source.parse("BOATRAMP_HANDLERS_SQL_DEPROVISION_GRACE_SECS")? {
387                sql.deprovision_grace_secs = Some(v);
388            }
389        }
390
391        // --- handler sql external databases (`handlers.bindings.sql.databases`) ---
392        // The bring-your-own / managed-compute DB map, keyed by name. There is no
393        // config file to enumerate the members, so the member names are discovered
394        // from the environment: any `BOATRAMP_HANDLERS_SQL_DB_<NAME>_<FIELD>`
395        // variable declares database `<NAME>`. Each env-declared DB is merged into
396        // (overriding, per field, by key) whatever the file already declared under
397        // that name — the same env-over-file precedence as the scalars.
398        //
399        // The map key may be the **empty string** (the default database that a
400        // handler opens as `sql.open("")`); it can't appear in a variable name, so
401        // the reserved name token `DEFAULT` addresses it:
402        // `BOATRAMP_HANDLERS_SQL_DB_DEFAULT_KIND` populates the `""` key.
403        if source.any_with_prefix(SQL_DB_ENV_PREFIX) {
404            let handlers = self.handlers.get_or_insert_with(HandlersConfig::default);
405            let sql = handlers
406                .bindings
407                .sql
408                .get_or_insert_with(SqlBindingConfig::default);
409            for name in source.sql_database_names() {
410                // `DEFAULT` is the reserved token for the `""` (default) database.
411                let key = if name == "DEFAULT" {
412                    String::new()
413                } else {
414                    name.clone()
415                };
416                let db = sql.databases.entry(key).or_default();
417                let prefix = format!("{SQL_DB_ENV_PREFIX}{name}_");
418                if let Some(v) = source.get(&format!("{prefix}KIND")) {
419                    db.kind = v;
420                }
421                if let Some(v) = source.get(&format!("{prefix}URL_ENV")) {
422                    db.url_env = v;
423                }
424                if let Some(v) = source.get(&format!("{prefix}READ_URL_ENV")) {
425                    db.read_url_env = Some(v);
426                }
427                if let Some(v) = source.get(&format!("{prefix}COMPUTE")) {
428                    db.compute = Some(v);
429                }
430                if let Some(v) = source.get(&format!("{prefix}DATABASE")) {
431                    db.database = Some(v);
432                }
433                if let Some(v) = source.get(&format!("{prefix}USER")) {
434                    db.user = Some(v);
435                }
436                if let Some(v) = source.get(&format!("{prefix}PASSWORD_ENV")) {
437                    db.password_env = Some(v);
438                }
439                if let Some(v) = source.parse(&format!("{prefix}POOL_MAX"))? {
440                    db.pool_max = Some(v);
441                }
442                if let Some(v) = source.parse_bool(&format!("{prefix}READ_ONLY"))? {
443                    db.read_only = v;
444                }
445                if let Some(v) = source.parse_bool(&format!("{prefix}ALLOW_PREVIEW"))? {
446                    db.allow_preview = v;
447                }
448                if let Some(v) = source.parse(&format!("{prefix}CONNECT_TIMEOUT_SECS"))? {
449                    db.connect_timeout_secs = Some(v);
450                }
451                if let Some(v) = source.get(&format!("{prefix}IMAGE")) {
452                    db.image = Some(v);
453                }
454                if let Some(v) = source.parse(&format!("{prefix}VOLUME_SIZE_MIB"))? {
455                    db.volume_size_mib = Some(v);
456                }
457                if let Some(v) = source.parse_enum(
458                    &format!("{prefix}TENANT"),
459                    &[
460                        ("single", TenantIsolation::Single),
461                        ("shared", TenantIsolation::Shared),
462                    ],
463                )? {
464                    db.tenant = v;
465                }
466                if let Some(v) = source.parse_enum(
467                    &format!("{prefix}TENANT_SCOPE"),
468                    &[
469                        ("project", TenantScope::Project),
470                        ("site", TenantScope::Site),
471                    ],
472                )? {
473                    db.tenant_scope = v;
474                }
475                if let Some(v) = source.parse_bool(&format!("{prefix}RLS_SESSION"))? {
476                    db.rls_session = v;
477                }
478            }
479        }
480
481        // --- secrets (`[secrets]`) -------------------------------------------
482        // Envelope encryption for private keys at rest. `kek_file` holds a *path*
483        // (never key material) and the Vault token stays indirected via
484        // `token_env` (a variable name, not the token). Materialise the nested
485        // `vault` sub-config only when a vault variable is set.
486        if source.any(SECRETS_ENV_VARS) {
487            let secrets = self.secrets.get_or_insert_with(SecretsConfig::default);
488            if let Some(v) = source.get("BOATRAMP_SECRETS_ENVELOPE") {
489                secrets.envelope = v;
490            }
491            if let Some(v) = source.get("BOATRAMP_SECRETS_KEK_FILE") {
492                secrets.kek_file = Some(PathBuf::from(v));
493            }
494            if source.any(SECRETS_VAULT_ENV_VARS) {
495                let vault = secrets
496                    .vault
497                    .get_or_insert_with(VaultSecretsConfig::default);
498                if let Some(v) = source.get("BOATRAMP_SECRETS_VAULT_ADDR") {
499                    vault.addr = v;
500                }
501                if let Some(v) = source.get("BOATRAMP_SECRETS_VAULT_KEY") {
502                    vault.key = v;
503                }
504                if let Some(v) = source.get("BOATRAMP_SECRETS_VAULT_TOKEN_ENV") {
505                    vault.token_env = v;
506                }
507            }
508        }
509
510        // --- cluster (`[cluster]`) -------------------------------------------
511        // The self-hosted cluster section's own fields. The founding/joining
512        // *actions* already have their own `serve` flags with env
513        // (`BOATRAMP_CLUSTER_INIT` / `_JOIN` / `_ADVERTISE_ADDR`); those are
514        // distinct from — and not duplicated by — the `[cluster]` section fields
515        // exposed here. `join_token` keeps a secret out of plain sight via the
516        // usual `env:VAR` / `path:/file` prefix, so the env holds the *reference*,
517        // not the token. `ClusterConfig` has no `Default` (a founder needs at least
518        // a `listen`), so a `BOATRAMP_CLUSTER_LISTEN` is required to materialise an
519        // absent section from the environment.
520        if source.any(CLUSTER_ENV_VARS) {
521            // Materialise an absent section only if a bind address is supplied;
522            // otherwise there is no valid `ClusterConfig` to build (it has no
523            // `Default` — a node must know where to bind its mesh). When the file
524            // already declared `[cluster]`, its `listen` stands and the other env
525            // fields layer over it even without `BOATRAMP_CLUSTER_LISTEN`.
526            let listen = source.parse::<SocketAddr>("BOATRAMP_CLUSTER_LISTEN")?;
527            if self.cluster.is_none() {
528                if let Some(listen) = listen {
529                    self.cluster = Some(ClusterConfig {
530                        listen,
531                        root_pubkeys: Vec::new(),
532                        seeds: Vec::new(),
533                        join_token: None,
534                        store_dir: None,
535                        mesh: None,
536                    });
537                }
538            }
539            if let Some(cluster) = self.cluster.as_mut() {
540                // A `listen` override applies to an already-present section too (a
541                // freshly materialised one already carries it).
542                if let Some(v) = listen {
543                    cluster.listen = v;
544                }
545                if let Some(v) = source.parse_list("BOATRAMP_CLUSTER_ROOT_PUBKEYS") {
546                    cluster.root_pubkeys = v;
547                }
548                if let Some(v) = source.parse_list("BOATRAMP_CLUSTER_SEEDS") {
549                    cluster.seeds = v;
550                }
551                if let Some(v) = source.get("BOATRAMP_CLUSTER_JOIN_TOKEN") {
552                    cluster.join_token = Some(v);
553                }
554                if let Some(v) = source.get("BOATRAMP_CLUSTER_STORE_DIR") {
555                    cluster.store_dir = Some(PathBuf::from(v));
556                }
557                if source.any(CLUSTER_MESH_ENV_VARS) {
558                    let mesh = cluster.mesh.get_or_insert_with(MeshConfig::default);
559                    if let Some(v) = source.get("BOATRAMP_CLUSTER_MESH_KEY_FILE") {
560                        mesh.key_file = Some(PathBuf::from(v));
561                    }
562                    if let Some(v) = source.get("BOATRAMP_CLUSTER_MESH_KEY_ROTATION") {
563                        mesh.key_rotation = Some(v);
564                    }
565                    if let Some(v) = source.get("BOATRAMP_CLUSTER_MESH_JOIN_TOKEN_TTL") {
566                        mesh.join_token_ttl = Some(v);
567                    }
568                    if let Some(v) =
569                        source.parse_bool("BOATRAMP_CLUSTER_MESH_GATE_CLIENT_WRITES")?
570                    {
571                        mesh.gate_client_writes = Some(v);
572                    }
573                }
574            }
575        }
576
577        Ok(())
578    }
579}
580
581/// The `BOATRAMP_*` variables that populate the `[compute]` section. Kept as one
582/// list so [`ServerConfig::apply_env_overrides`] can decide whether to materialise
583/// an absent section without repeating the names.
584const COMPUTE_ENV_VARS: &[&str] = &[
585    "BOATRAMP_COMPUTE_BRIDGE",
586    "BOATRAMP_COMPUTE_SUBNET",
587    "BOATRAMP_COMPUTE_VCPUS",
588    "BOATRAMP_COMPUTE_MEM_MIB",
589    "BOATRAMP_COMPUTE_REGION",
590    "BOATRAMP_COMPUTE_SQL_SHIM_URL",
591    "BOATRAMP_COMPUTE_MANAGED_DB_PRIVILEGE",
592    "BOATRAMP_COMPUTE_DOCKER_ENDPOINT",
593    "BOATRAMP_COMPUTE_DOCKER_VOLUME_MODE",
594    "BOATRAMP_COMPUTE_KERNEL_SIGNING_PUBKEYS",
595    "BOATRAMP_COMPUTE_KERNEL_ALLOWED_HASHES",
596];
597
598/// The `BOATRAMP_*` variables that populate the `[security]` section.
599const SECURITY_ENV_VARS: &[&str] = &[
600    "BOATRAMP_SECURITY_PROFILE",
601    "BOATRAMP_SECURITY_ALLOW_UNAUTHENTICATED_PUBLIC_BIND",
602    "BOATRAMP_SECURITY_MAX_UPLOAD_BYTES",
603    "BOATRAMP_SECURITY_ALLOW_SITE_UNIX_UPSTREAMS",
604    "BOATRAMP_SECURITY_ALLOW_SITE_PRIVATE_UPSTREAMS",
605    "BOATRAMP_SECURITY_ALLOW_GUEST_PRIVATE_EGRESS",
606    "BOATRAMP_SECURITY_ALLOW_GUEST_SELF_EGRESS",
607    "BOATRAMP_SECURITY_MAX_HANDLER_BLOB_BYTES",
608    "BOATRAMP_SECURITY_MAX_COMPONENT_BYTES",
609    "BOATRAMP_SECURITY_OIDC_REQUIRE_AUDIENCE",
610    "BOATRAMP_SECURITY_DOMAIN_VERIFY_ALLOW_PRIVATE",
611    "BOATRAMP_SECURITY_DOMAIN_VERIFY_SELF_SERVE",
612    "BOATRAMP_SECURITY_ALLOW_SHARED_KERNEL_COMPUTE",
613    "BOATRAMP_SECURITY_ALLOW_COMPUTE_EXEC",
614    "BOATRAMP_SECURITY_RATELIMIT_FAIL_OPEN",
615    "BOATRAMP_SECURITY_ALLOW_IMPLICIT_ROUTING",
616    "BOATRAMP_SECURITY_REQUIRE_POP",
617    "BOATRAMP_SECURITY_REQUIRE_DOMAIN_VERIFICATION",
618    "BOATRAMP_SECURITY_ALLOW_ENV_SECRET_REFS",
619];
620
621/// The `BOATRAMP_*` variables that populate `handlers.bindings.sql`.
622const SQL_ENV_VARS: &[&str] = &[
623    "BOATRAMP_HANDLERS_SQL_DIR",
624    "BOATRAMP_HANDLERS_SQL_URL",
625    "BOATRAMP_HANDLERS_SQL_ADMIN_URL",
626    "BOATRAMP_HANDLERS_SQL_REPLICA_URL",
627    "BOATRAMP_HANDLERS_SQL_TOKEN_ENV",
628    "BOATRAMP_HANDLERS_SQL_ADMIN_TOKEN_ENV",
629    "BOATRAMP_HANDLERS_SQL_PREVIEW_MODE",
630    "BOATRAMP_HANDLERS_SQL_PREVIEW_INIT",
631    "BOATRAMP_HANDLERS_SQL_DEPROVISION_GRACE_SECS",
632];
633
634/// The fixed prefix of a keyed `handlers.bindings.sql.databases` variable —
635/// `BOATRAMP_HANDLERS_SQL_DB_<NAME>_<FIELD>`. Member names aren't known ahead of
636/// time (there is no config file to enumerate them), so they are discovered by
637/// scanning the environment for this prefix.
638const SQL_DB_ENV_PREFIX: &str = "BOATRAMP_HANDLERS_SQL_DB_";
639
640/// The recognised `_<FIELD>` suffixes of a `databases` variable, ordered so a
641/// name-isolating strip matches the **longest** suffix first (`_READ_URL_ENV`
642/// before `_URL_ENV`). Each mirrors a field of [`ExternalDatabaseConfig`].
643const SQL_DB_FIELD_SUFFIXES: &[&str] = &[
644    "_CONNECT_TIMEOUT_SECS",
645    "_VOLUME_SIZE_MIB",
646    "_READ_URL_ENV",
647    "_PASSWORD_ENV",
648    "_ALLOW_PREVIEW",
649    "_URL_ENV",
650    "_DATABASE",
651    "_READ_ONLY",
652    "_POOL_MAX",
653    "_RLS_SESSION",
654    "_TENANT_SCOPE",
655    "_COMPUTE",
656    "_TENANT",
657    "_IMAGE",
658    "_KIND",
659    "_USER",
660];
661
662/// The `BOATRAMP_*` variables that populate the `[secrets]` section (excluding the
663/// nested `vault` sub-config, gated separately by [`SECRETS_VAULT_ENV_VARS`]).
664const SECRETS_ENV_VARS: &[&str] = &[
665    "BOATRAMP_SECRETS_ENVELOPE",
666    "BOATRAMP_SECRETS_KEK_FILE",
667    "BOATRAMP_SECRETS_VAULT_ADDR",
668    "BOATRAMP_SECRETS_VAULT_KEY",
669    "BOATRAMP_SECRETS_VAULT_TOKEN_ENV",
670];
671
672/// The `BOATRAMP_*` variables that populate the nested `[secrets.vault]` sub-config.
673const SECRETS_VAULT_ENV_VARS: &[&str] = &[
674    "BOATRAMP_SECRETS_VAULT_ADDR",
675    "BOATRAMP_SECRETS_VAULT_KEY",
676    "BOATRAMP_SECRETS_VAULT_TOKEN_ENV",
677];
678
679/// The `BOATRAMP_*` variables that populate the `[cluster]` section fields (the
680/// section's own config, distinct from the founding/joining *action* flags
681/// `BOATRAMP_CLUSTER_INIT` / `_JOIN` / `_ADVERTISE_ADDR`, which are `serve` clap
682/// args and are deliberately not listed here).
683const CLUSTER_ENV_VARS: &[&str] = &[
684    "BOATRAMP_CLUSTER_LISTEN",
685    "BOATRAMP_CLUSTER_ROOT_PUBKEYS",
686    "BOATRAMP_CLUSTER_SEEDS",
687    "BOATRAMP_CLUSTER_JOIN_TOKEN",
688    "BOATRAMP_CLUSTER_STORE_DIR",
689    "BOATRAMP_CLUSTER_MESH_KEY_FILE",
690    "BOATRAMP_CLUSTER_MESH_KEY_ROTATION",
691    "BOATRAMP_CLUSTER_MESH_JOIN_TOKEN_TTL",
692    "BOATRAMP_CLUSTER_MESH_GATE_CLIENT_WRITES",
693];
694
695/// The `BOATRAMP_*` variables that populate the nested `[cluster.mesh]` sub-config.
696const CLUSTER_MESH_ENV_VARS: &[&str] = &[
697    "BOATRAMP_CLUSTER_MESH_KEY_FILE",
698    "BOATRAMP_CLUSTER_MESH_KEY_ROTATION",
699    "BOATRAMP_CLUSTER_MESH_JOIN_TOKEN_TTL",
700    "BOATRAMP_CLUSTER_MESH_GATE_CLIENT_WRITES",
701];
702
703/// Where env-override values come from: the real process environment, or an
704/// explicit map for a deterministic unit test. Keeping the lookup behind this enum
705/// lets [`ServerConfig::apply_env_overrides`] be tested without touching (racy,
706/// process-global) `std::env`.
707enum EnvSource {
708    /// The live process environment (`std::env::var`).
709    Process,
710    /// A fixed name→value map (tests only).
711    #[cfg(test)]
712    Map(BTreeMap<String, String>),
713}
714
715impl EnvSource {
716    /// The value of `var`, if set to a non-empty string. An empty value is treated
717    /// as unset so an accidental `VAR=` doesn't clobber a file value with `""`.
718    fn get(&self, var: &str) -> Option<String> {
719        let raw = match self {
720            Self::Process => std::env::var(var).ok(),
721            #[cfg(test)]
722            Self::Map(m) => m.get(var).cloned(),
723        };
724        raw.filter(|v| !v.is_empty())
725    }
726
727    /// Whether any of `vars` is set (to a non-empty value).
728    fn any(&self, vars: &[&str]) -> bool {
729        vars.iter().any(|v| self.get(v).is_some())
730    }
731
732    /// Whether any variable whose name starts with `prefix` is set (to a
733    /// non-empty value). Used to decide whether to materialise a keyed map (the
734    /// `databases` env scheme) whose member names aren't known ahead of time.
735    fn any_with_prefix(&self, prefix: &str) -> bool {
736        self.names()
737            .any(|name| name.starts_with(prefix) && self.get(&name).is_some())
738    }
739
740    /// The full set of variable names visible to this source. Used to discover the
741    /// keyed-map member names from the environment (there is no config file to
742    /// enumerate them). Returned owned so it doesn't borrow the process env.
743    fn names(&self) -> Box<dyn Iterator<Item = String> + '_> {
744        match self {
745            Self::Process => Box::new(std::env::vars().map(|(k, _)| k)),
746            #[cfg(test)]
747            Self::Map(m) => Box::new(m.keys().cloned()),
748        }
749    }
750
751    /// Parse `var` as one of a fixed set of string-mapped variants, mapping an
752    /// unknown value to a clear [`ConfigError::Env`] that names the variable and
753    /// the accepted values. Used for the config enums that have no `FromStr`
754    /// (their only string mapping is a serde `rename_all`). `Ok(None)` when unset.
755    fn parse_enum<T: Copy>(
756        &self,
757        var: &str,
758        variants: &[(&str, T)],
759    ) -> Result<Option<T>, ConfigError> {
760        match self.get(var) {
761            Some(raw) => {
762                let lower = raw.trim().to_ascii_lowercase();
763                variants
764                    .iter()
765                    .find(|(name, _)| *name == lower)
766                    .map(|(_, v)| Some(*v))
767                    .ok_or_else(|| ConfigError::Env {
768                        var: var.to_string(),
769                        reason: format!(
770                            "expected one of {}, got {raw:?}",
771                            variants
772                                .iter()
773                                .map(|(n, _)| *n)
774                                .collect::<Vec<_>>()
775                                .join("/")
776                        ),
777                    })
778            }
779            None => Ok(None),
780        }
781    }
782
783    /// The distinct `<NAME>` tokens of every `BOATRAMP_HANDLERS_SQL_DB_<NAME>_<FIELD>`
784    /// variable that is set. The name is everything between the fixed prefix and the
785    /// *last* `_<FIELD>` segment, so a database name may itself contain underscores
786    /// (the field suffix is one of a known set). Returned sorted + de-duplicated so
787    /// the map is built deterministically.
788    fn sql_database_names(&self) -> Vec<String> {
789        let mut names: Vec<String> = self
790            .names()
791            .filter(|n| n.starts_with(SQL_DB_ENV_PREFIX) && self.get(n).is_some())
792            .filter_map(|n| {
793                let rest = n.strip_prefix(SQL_DB_ENV_PREFIX)?;
794                // Strip the recognised field suffix to isolate `<NAME>`. The suffixes
795                // are matched longest-first so `READ_URL_ENV` wins over `URL_ENV`.
796                SQL_DB_FIELD_SUFFIXES
797                    .iter()
798                    .find_map(|suffix| rest.strip_suffix(suffix))
799                    .filter(|name| !name.is_empty())
800                    .map(str::to_string)
801            })
802            .collect();
803        names.sort();
804        names.dedup();
805        names
806    }
807
808    /// Parse `var` as a **comma-separated** list of non-empty trimmed items, e.g.
809    /// the kernel trust anchors. A single value (no comma) yields a one-element
810    /// list. Empty items are dropped so a trailing comma or doubled separator is
811    /// tolerated. `Ok(None)` when unset; `Some(Vec::new())` never happens (an
812    /// all-empty value is treated as unset by [`Self::get`]).
813    fn parse_list(&self, var: &str) -> Option<Vec<String>> {
814        self.get(var).map(|raw| {
815            raw.split(',')
816                .map(str::trim)
817                .filter(|s| !s.is_empty())
818                .map(str::to_string)
819                .collect()
820        })
821    }
822
823    /// Parse `var` as any [`FromStr`](std::str::FromStr) type (numbers), mapping a
824    /// parse failure to a clear [`ConfigError::Env`]. `Ok(None)` when the variable
825    /// is unset.
826    fn parse<T>(&self, var: &str) -> Result<Option<T>, ConfigError>
827    where
828        T: std::str::FromStr,
829        T::Err: std::fmt::Display,
830    {
831        match self.get(var) {
832            Some(raw) => raw.parse::<T>().map(Some).map_err(|e| ConfigError::Env {
833                var: var.to_string(),
834                reason: e.to_string(),
835            }),
836            None => Ok(None),
837        }
838    }
839
840    /// Parse `var` as a boolean, accepting the common truthy/falsey spellings
841    /// (`true`/`false`, `1`/`0`, `yes`/`no`, `on`/`off`) case-insensitively so an
842    /// operator isn't surprised by a strict `true`-only parse. `Ok(None)` when
843    /// unset.
844    fn parse_bool(&self, var: &str) -> Result<Option<bool>, ConfigError> {
845        match self.get(var) {
846            Some(raw) => match raw.trim().to_ascii_lowercase().as_str() {
847                "true" | "1" | "yes" | "on" => Ok(Some(true)),
848                "false" | "0" | "no" | "off" => Ok(Some(false)),
849                other => Err(ConfigError::Env {
850                    var: var.to_string(),
851                    reason: format!("expected a boolean (true/false), got {other:?}"),
852                }),
853            },
854            None => Ok(None),
855        }
856    }
857}
858
859/// How a **managed database** (PLAN-managed-compute-sql) runs its stock image on a
860/// shared-kernel backend, whose entrypoint would otherwise fail under the dropped-`ALL`
861/// hardening. `rootless` (the default) needs no capabilities and works under any
862/// posture; `caps` is the fallback for an image that won't run rootless.
863#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Deserialize)]
864#[serde(rename_all = "lowercase")]
865pub enum ManagedDbPrivilege {
866    /// Run the DB as its image's user (`999:999` for the official postgres/mysql
867    /// images) against a pre-owned volume — no added capabilities, any posture.
868    #[default]
869    Rootless,
870    /// Add the minimal capability set the entrypoint needs (`CHOWN`, `DAC_OVERRIDE`,
871    /// `FOWNER`, `SETUID`, `SETGID`). Honored only under the single-tenant posture.
872    Caps,
873}
874
875/// `compute` section — opt-in compute backends. Present
876/// ⇒ `serve` registers the backends this node can offer and advertises them to
877/// the scheduler; backends are capability-detected (container on Linux, remote
878/// docker when a daemon is reachable, VMM when `/dev/kvm` exists).
879#[derive(Debug, Clone, Deserialize)]
880#[serde(default, deny_unknown_fields)]
881pub struct ComputeConfig {
882    /// Bridge the container veths / VM taps attach to (default `br-boatramp`).
883    pub bridge: String,
884    /// Guest IP subnet (default `10.0.0.0/24`).
885    pub subnet: String,
886    /// vCPUs this node advertises as schedulable (`0` ⇒ detect from the host).
887    pub vcpus: u32,
888    /// Memory (MiB) this node advertises as schedulable (`0` ⇒ a 1 GiB default).
889    pub mem_mib: u32,
890    /// **Static** kernel-signing public keys (`"<alg>:<hex>"`) — the trust anchor
891    /// for the posture-scaled kernel bar. Under `multi-tenant`, a dynamically-
892    /// selected default kernel must carry a signature verifying against one of
893    /// these. Host-access-gated (never in the KV tier); changing it needs a
894    /// restart. Empty ⇒ no kernel may be signed-verified (strict posture then
895    /// accepts none).
896    pub kernel_signing_pubkeys: Vec<String>,
897    /// **Static** allow-list of kernel content hashes (sha256 hex) a dynamic
898    /// default may select under `multi-tenant`. Host-access-gated. Empty ⇒ no
899    /// kernel is allow-listed.
900    pub kernel_allowed_hashes: Vec<String>,
901    /// This node's **region** tag (FA-8). Advertised on the compute `Node` so a
902    /// gateway routing to a `compute:`-backed workload with `--lb nearest` sends
903    /// each request to the nearest replica by its node's region — no manual
904    /// `--region` map. `None` ⇒ region-agnostic.
905    pub region: Option<String>,
906    /// How the remote-Docker backend reports a workload's reachable endpoint.
907    /// `published` (default) publishes the container port on `127.0.0.1:<ephemeral>`
908    /// so a host-native `serve` reaches it on any daemon (incl. Docker Desktop /
909    /// macOS, where the bridge IP is not host-routable); `bridge` routes to the
910    /// container bridge IP directly (only when `serve` shares the daemon's network).
911    pub docker_endpoint: boatramp_docker::DockerEndpoint,
912    /// How the remote-Docker backend backs a workload's persistent volumes.
913    /// `named` (default) attaches a daemon-managed `docker volume` by name (portable
914    /// across daemons + Docker Desktop / macOS); `bind` bind-mounts a host directory
915    /// under `<data_dir>/compute/volumes/<name>` (local daemon only).
916    pub docker_volume_mode: boatramp_docker::DockerVolumeMode,
917    /// Guest-reachable base URL of the compute **sql-shim** (PLAN-compute-bindings) —
918    /// e.g. `http://10.0.0.1:8081` (the compute bridge gateway) or the docker bridge
919    /// gateway. Set ⇒ a workload's `--bind sql` reaches the managed database through a
920    /// listener bound on `0.0.0.0:<port>`. `None` (default) ⇒ compute sql bindings off.
921    #[serde(default, skip_serializing_if = "Option::is_none")]
922    #[cfg_attr(not(feature = "handlers"), allow(dead_code))]
923    pub sql_shim_url: Option<String>,
924    /// Privilege strategy for a managed database's stock image on a shared-kernel
925    /// backend (see [`ManagedDbPrivilege`]). `rootless` by default.
926    #[serde(default)]
927    #[cfg_attr(not(feature = "handlers"), allow(dead_code))]
928    pub managed_db_privilege: ManagedDbPrivilege,
929}
930
931/// The built-in **boatramp kernel-signing public key** (`es256:…`), whose private
932/// half lives as the `KERNEL_SIGNING_KEY` Actions secret in
933/// [`BoatRamp/boatramp-vmlinux`](https://github.com/BoatRamp/boatramp-vmlinux).
934/// Shipped as a default trust anchor so the first-party signed `boatramp-vmlinux`
935/// verifies out of the box under the strict posture. An operator can replace
936/// `kernel_signing_pubkeys` to trust only their own keys.
937pub const BOATRAMP_KERNEL_SIGNING_PUBKEY: &str =
938    "es256:02c4e4af2e9cba6ba6745c513f193622e6674a8b2d0187ebea5612f5b46a7eade4";
939
940/// The first-party signed-kernel content hashes trusted under the **strict**
941/// posture, for this build's **guest arch**. The guest arch mirrors the host: an
942/// x86_64 host boots x86_64 KVM guests (the embedded VMM); an Apple-silicon host
943/// boots aarch64 guests (the Virtualization.framework `vmm-vz` backend). An x86_64
944/// kernel can't boot an aarch64 VM (and vice versa), so each arch trusts only its
945/// own signed `boatramp-vmlinux-<arch>` releases. Bump on each new signed release.
946///
947/// The **relaxed** (single-tenant) posture ignores this list — it verifies only the
948/// content-hash pin — so an operator-supplied kernel boots there regardless of arch.
949fn default_allowed_kernel_hashes() -> Vec<String> {
950    #[cfg(target_arch = "x86_64")]
951    {
952        vec![
953            // v0.2.0 minimal Firecracker 6.1-config kernel: boots under the
954            // firecracker-*binary* backend (ACPI device discovery) but NOT the
955            // in-process embedded VMM. Kept trusted so operators on the currently
956            // published release don't fail strict verification.
957            "cf1e590a9e642be3667131ca35fbf390378a457d8908169d2a169608e299d974".to_string(),
958            // Same kernel + CONFIG_VIRTIO_MMIO_CMDLINE_DEVICES=y (flake `#vmlinux`),
959            // so the embedded VMM binds its virtio-block root over the cmdline
960            // transport. Reproducible build output (deterministic nix build,
961            // verified on KVM); the next signed boatramp-vmlinux release — which
962            // reuses this flake — publishes + signs it, gated by
963            // `vmlinux-release-boot.yml`.
964            "d0dc2098ab2a2a3c1bc72ab61dc85d9e464d798d7e55b6b80525db5ca2f00c5a".to_string(),
965        ]
966    }
967    #[cfg(target_arch = "aarch64")]
968    {
969        vec![
970            // `boatramp-vmlinux-aarch64` v0.2.3 (the Virtualization.framework guest
971            // kernel, flake `#vmlinux` on aarch64-linux — a raw arm64 `Image`). This
972            // release enables the generic PCIe host + virtio-pci so the guest actually
973            // discovers VZ's virtio disk/net/console (the earlier v0.2.2 `be95fb0d…`
974            // built with `CONFIG_PCI` off never booted under VZ and is dropped). This
975            // is the hash of the **published, ES256-signed** release asset (signed by
976            // BOATRAMP_KERNEL_SIGNING_PUBKEY), so a selected `compute.default_kernel`
977            // clears the strict bar out of the box; the boot + scale-to-zero round-trip
978            // was validated against this exact published kernel. NOTE: unlike x86_64,
979            // the aarch64 build is not currently bit-reproducible across build hosts
980            // (same config + size, different build metadata), so pin/verify against the
981            // published `.sha256`/`.sig`, not a local rebuild. Bump on each new release.
982            "d785a48d754e65a4630443301f1fb84cb69cf882336d3cf37055e437b3d8e21f".to_string(),
983        ]
984    }
985    #[cfg(not(any(target_arch = "x86_64", target_arch = "aarch64")))]
986    {
987        Vec::new()
988    }
989}
990
991impl Default for ComputeConfig {
992    fn default() -> Self {
993        Self {
994            bridge: "br-boatramp".to_string(),
995            subnet: "10.0.0.0/24".to_string(),
996            vcpus: 0,
997            mem_mib: 0,
998            kernel_signing_pubkeys: vec![BOATRAMP_KERNEL_SIGNING_PUBKEY.to_string()],
999            kernel_allowed_hashes: default_allowed_kernel_hashes(),
1000            region: None,
1001            docker_endpoint: boatramp_docker::DockerEndpoint::default(),
1002            docker_volume_mode: boatramp_docker::DockerVolumeMode::default(),
1003            sql_shim_url: None,
1004            managed_db_privilege: ManagedDbPrivilege::default(),
1005        }
1006    }
1007}
1008
1009/// `cluster` section — self-hosted **cluster mode**. Parsed in
1010/// every build so config files stay portable; only *consumed* when the `cluster`
1011/// feature is compiled in (`boatramp serve --mode cluster`).
1012#[cfg_attr(not(feature = "cluster"), allow(dead_code))]
1013#[derive(Debug, Clone, Deserialize)]
1014pub struct ClusterConfig {
1015    /// Address to bind this node's Raft **peer mesh** on (the `/raft/*` +
1016    /// `/stream/*` endpoints) — distinct from the public `serve.addr`.
1017    pub listen: SocketAddr,
1018    /// The cluster **root anchor set** — the `es256:`/`ed25519:`-tagged public
1019    /// keys that define this cluster's identity (a cluster *is* its root key).
1020    /// Every join/trust decision verifies against this set. Empty ⇒ falls back to
1021    /// `serve.auth_root_public_key` (the single-anchor default). A *set* enables
1022    /// make-before-break root rotation.
1023    #[serde(default)]
1024    pub root_pubkeys: Vec<String>,
1025    /// **Seeds** — control-plane addresses of existing cluster members
1026    /// (`host:port`), any of which can admit this node. Present ⇒ this node
1027    /// **joins** (redeems its `join_token`); absent + no durable state + explicit
1028    /// `--cluster-init` ⇒ it **founds**. There is no peer map: members are learned
1029    /// from the root-signed join response.
1030    #[serde(default)]
1031    pub seeds: Vec<String>,
1032    /// The single-use bearer **join token** used when `seeds` are set. Keeps the
1033    /// secret out of the file via a prefix: `env:VAR`, `path:/file`, or an inline
1034    /// literal. Usually supplied via `serve --cluster-join <ticket>` instead.
1035    #[serde(default)]
1036    pub join_token: Option<String>,
1037    /// Directory for this node's **durable** Raft log/state store (node-local;
1038    /// distinct from the replicated control plane). Default
1039    /// `<data-dir>/raft`.
1040    #[serde(default)]
1041    pub store_dir: Option<PathBuf>,
1042    /// Mesh identity + TLS settings. Absent ⇒ defaults (identity key
1043    /// auto-generated under `<data-dir>/mesh/identity.key`).
1044    #[serde(default)]
1045    pub mesh: Option<MeshConfig>,
1046}
1047
1048/// `[cluster.mesh]` — mesh identity + TLS knobs.
1049#[cfg_attr(not(feature = "cluster"), allow(dead_code))]
1050#[derive(Debug, Clone, Default, Deserialize)]
1051#[serde(default, deny_unknown_fields)]
1052pub struct MeshConfig {
1053    /// Path to this node's Ed25519 identity key (PKCS#8 DER, `0600`,
1054    /// auto-generated). Default `<data-dir>/mesh/identity.key`.
1055    pub key_file: Option<PathBuf>,
1056    /// Automatic key-rotation cadence (e.g. `"30d"`); `None` = manual only.
1057    /// Consumed by the rotation loop.
1058    pub key_rotation: Option<String>,
1059    /// TTL for a single-use join token (e.g. `"1h"`).
1060    pub join_token_ttl: Option<String>,
1061    /// Gate mesh `client-write`s behind a control-plane **cluster-write
1062    /// capability**, so a trusted peer can't inject arbitrary
1063    /// control-plane writes on mesh trust alone. Requires the token root
1064    /// **private** key on every node (each mints + presents its own capability);
1065    /// default `false`.
1066    pub gate_client_writes: Option<bool>,
1067}
1068
1069/// `handlers` section — server-side handler runtime config (read by `serve`).
1070/// Parsed in every build (so config files stay portable), but only *consumed*
1071/// when the `handlers` feature is compiled in.
1072#[cfg_attr(not(feature = "handlers"), allow(dead_code))]
1073#[derive(Debug, Clone, Default, Deserialize)]
1074#[serde(default)]
1075pub struct HandlersConfig {
1076    /// `handlers.bindings` — which backend serves each handler binding.
1077    pub bindings: BindingsConfig,
1078    /// Use the wasmtime **pooling** instance allocator: faster
1079    /// instantiation at the cost of a large up-front virtual-memory reservation.
1080    /// Off by default — opt in and benchmark for your workload.
1081    pub pooling: bool,
1082    /// Engine-wide **safety max** on a *connection-bearing* invocation (a site
1083    /// handler or a synchronous function/webhook invoke), milliseconds. A route
1084    /// or function may declare a *lower* timeout, never a higher one. Kept tight
1085    /// on purpose: a client, proxy, and the shared request pool are all blocked
1086    /// while a sync handler runs. Absent ⇒ 10s (the historical default). This is
1087    /// a node safety ceiling, not a per-invocation budget, and is distinct from
1088    /// a per-site `max_timeout_ms`.
1089    pub sync_max_timeout_ms: Option<u64>,
1090    /// Engine-wide safety max on a *durable async* invocation — the drain that
1091    /// runs `?mode=async` calls, workflow steps, cron/queue/blob triggers, and
1092    /// `wasi:messaging` consumers, milliseconds. No client is connected and the
1093    /// work is retried + dead-lettered, so this can be far larger than the sync
1094    /// ceiling: it is what lets a legitimately long background job (e.g. an LLM
1095    /// generation) declare and actually get minutes of runtime. Absent ⇒ 15
1096    /// minutes. Runs on its own concurrency budget (`async_max_concurrency`), so
1097    /// a long job never starves live traffic.
1098    pub async_max_timeout_ms: Option<u64>,
1099    /// Max concurrent in-flight *async-lane* invocations, kept separate from the
1100    /// (larger) request pool so a burst of long background jobs can't exhaust the
1101    /// slots live site traffic needs. Absent ⇒ 8.
1102    pub async_max_concurrency: Option<usize>,
1103    /// Optional CPU **fuel** ceiling for an async-lane invocation. A large async
1104    /// timeout bounds only wall-clock; without a fuel bound a CPU-bound guest can
1105    /// spin for the whole window. Absent ⇒ unmetered (same as the sync default).
1106    pub async_max_fuel: Option<u64>,
1107    /// Max wall-clock for a *streaming-lane* response (a `#[handler(stream)]`
1108    /// route — SSE, chunked, agent token streaming), milliseconds. A client is
1109    /// connected but the body is written incrementally over seconds-to-minutes,
1110    /// so this is far larger than the sync ceiling. Runs on its own concurrency
1111    /// budget (`streaming_max_concurrency`), isolated from both the fast request
1112    /// pool and the async drain. Absent ⇒ 15 minutes.
1113    pub streaming_max_timeout_ms: Option<u64>,
1114    /// Max concurrent in-flight *streaming-lane* responses, kept separate from the
1115    /// request pool and the async drain so a burst of long-lived streams starves
1116    /// neither. Absent ⇒ 64.
1117    pub streaming_max_concurrency: Option<usize>,
1118    /// Optional CPU **fuel** ceiling for a streaming-lane response. Absent ⇒
1119    /// unmetered (a stream is I/O-bound on the client, not CPU-bound).
1120    pub streaming_max_fuel: Option<u64>,
1121    /// Optional ceiling on a guest's **outbound** `wasi:http` call — the connect
1122    /// and time-to-first-byte wait — milliseconds, independent of the invocation
1123    /// timeout, so a hung upstream is bounded on its own terms. The streaming
1124    /// (between-bytes) timeout is left at wasmtime's default so a slow token
1125    /// stream is not cut mid-flight. Absent ⇒ wasmtime's default.
1126    pub outbound_timeout_ms: Option<u64>,
1127}
1128
1129/// `handlers.bindings` — per-binding backend configuration. kv/blob reuse the
1130/// server's own KV/Storage backends (per-site prefixed); `sql` is the single
1131/// libsql backend, whose single-node-vs-cluster split is the only choice.
1132#[cfg_attr(not(feature = "handlers"), allow(dead_code))]
1133#[derive(Debug, Clone, Default, Deserialize)]
1134#[serde(default)]
1135pub struct BindingsConfig {
1136    /// `handlers.bindings.sql` — libsql settings. Absent ⇒ single-node,
1137    /// per-site embedded files under `<data-dir>/handlers-sql`.
1138    pub sql: Option<SqlBindingConfig>,
1139}
1140
1141/// libsql settings for the handler `sql` binding — the single SQL backend. Each
1142/// site gets a real database boundary (an embedded file per site, or a sqld
1143/// namespace per site), never schema separation (which arbitrary guest SQL
1144/// escapes). Setting `url` switches from single-node to a shared sqld cluster;
1145/// everything else stays identical.
1146#[cfg_attr(not(feature = "handlers"), allow(dead_code))]
1147#[derive(Debug, Clone, Default, Deserialize)]
1148#[serde(default)]
1149pub struct SqlBindingConfig {
1150    /// Single-node: root directory for the per-site embedded database files
1151    /// (default `<data-dir>/handlers-sql`). Ignored when `url` is set.
1152    pub dir: Option<PathBuf>,
1153    /// Cluster: base sqld data URL (e.g. `http://sqld:8080`). When set, each
1154    /// site is a sqld namespace addressed as a subdomain of this URL; `admin_url`
1155    /// is then required.
1156    pub url: Option<String>,
1157    /// Cluster: sqld admin API base URL (e.g. `http://sqld:9090`) for creating
1158    /// per-site namespaces. Required when `url` is set.
1159    pub admin_url: Option<String>,
1160    /// Cluster: optional sqld **read-replica** data URL. When set, handlers'
1161    /// read-only `sql` transactions (`open-read-only`) route to this endpoint
1162    /// while writes stay on `url` (reads → replicas, writes → primary).
1163    /// Reads may lag (eventually consistent). Ignored in
1164    /// single-node mode (no `url`).
1165    pub replica_url: Option<String>,
1166    /// Name of the env var holding the sqld data auth token (optional; never
1167    /// the token itself in-file).
1168    pub token_env: Option<String>,
1169    /// Name of the env var holding the sqld admin API auth key (optional).
1170    pub admin_token_env: Option<String>,
1171    /// How preview deployments get their SQL database: `empty` (default — a
1172    /// fresh isolated db), `branch` (a consistent copy of the site's live db;
1173    /// single-node only), or `shared` (the site's live db). See
1174    /// `boatramp_core::sql::PreviewSqlMode`.
1175    pub preview_mode: Option<String>,
1176    /// Path to an idempotent SQL script run when an `empty` preview database is
1177    /// first opened (e.g. schema/seed). Ignored in `branch`/`shared` modes.
1178    pub preview_init: Option<PathBuf>,
1179    /// `handlers.bindings.sql.databases` — external **bring-your-own** databases,
1180    /// each opened by name via `sql.open("<name>")`. An operator-configured
1181    /// Postgres/MySQL whose *isolation is the operator's* (it's their database),
1182    /// so these bypass the per-site libsql boundary and are reachable by any
1183    /// handler/function granted the `sql` binding. Needs the `sql-postgres` /
1184    /// `sql-mysql` build feature for the engine. A name here shadows the same
1185    /// name on the managed libsql default.
1186    pub databases: BTreeMap<String, ExternalDatabaseConfig>,
1187    /// **Soft-delete grace window** for a per-tenant managed database, in seconds
1188    /// (env `BOATRAMP_HANDLERS_SQL_DEPROVISION_GRACE_SECS`). When a project/site is
1189    /// deleted, a **Shared + Postgres** tenant is *soft*-deleted (its database is
1190    /// renamed aside and its role disabled) and stays recoverable for this long
1191    /// before a reaper hard-drops it — see
1192    /// [`tenant_sql`](crate::tenant_sql). `None` ⇒ the 7-day default
1193    /// (`DEFAULT_DEPROVISION_GRACE_SECS`); `0` ⇒ disable the soft path (immediate,
1194    /// irreversible hard drop everywhere). MySQL and all `Single` tenants always
1195    /// hard-drop immediately (the engine/cell can't be renamed aside safely), so this
1196    /// knob only affects the Shared-Postgres cell.
1197    pub deprovision_grace_secs: Option<u64>,
1198}
1199
1200/// One external SQL database for the handler `sql` binding. Its **source** is one
1201/// of two mutually-exclusive forms:
1202///  - `url_env` — a **bring-your-own** database: the connection URL is a secret,
1203///    named indirectly by an env var (never written in the config file).
1204///  - `compute` — a database **boatramp runs** as a compute workload: boatramp
1205///    derives the connection from the workload's live endpoint (host\:port) plus
1206///    the `database`/`user`/`password_env` here, so there is no URL to hand-map and
1207///    it follows the workload across restarts (PLAN-managed-compute-sql).
1208#[cfg_attr(not(feature = "handlers"), allow(dead_code))]
1209#[derive(Debug, Clone, Default, Deserialize)]
1210#[serde(default)]
1211pub struct ExternalDatabaseConfig {
1212    /// Engine: `postgres` (aliases `postgresql`/`pg`) or `mysql` (alias
1213    /// `mariadb`).
1214    pub kind: String,
1215    /// Name of the env var holding the connection URL (e.g.
1216    /// `postgres://user:pw@host/db`). Required unless `compute` is set.
1217    pub url_env: String,
1218    /// Optional env var holding a **read-replica** connection URL. When set,
1219    /// `open-read-only` transactions route there; writes stay on `url_env`.
1220    pub read_url_env: Option<String>,
1221    /// The name of a **compute workload** (a Postgres/MySQL server boatramp runs)
1222    /// to source this database from, instead of `url_env`. boatramp resolves the
1223    /// workload's live endpoint and builds the connection. Mutually exclusive with
1224    /// `url_env`.
1225    pub compute: Option<String>,
1226    /// The database name inside the compute-backed server (non-secret).
1227    pub database: Option<String>,
1228    /// The connecting user for the compute-backed server (non-secret).
1229    pub user: Option<String>,
1230    /// Env var holding the password for `user` on the compute-backed server.
1231    /// **Omit to let boatramp fully manage the credential** (PLAN-managed-compute-sql
1232    /// Phase 2): it generates a strong password once, seals it with the `[secrets]`
1233    /// envelope, injects it into the DB workload's server-init env at launch, and
1234    /// connects the handler with it — the operator sets no DB secret at all. Set it
1235    /// only to bring your own password for the compute-backed server.
1236    pub password_env: Option<String>,
1237    /// Maximum pooled connections (default 8).
1238    pub pool_max: Option<u32>,
1239    /// Open every transaction `READ ONLY` (the engine rejects writes) — for a
1240    /// database functions should only read.
1241    pub read_only: bool,
1242    /// Permit **preview** deployments to reach this database. Default `false`: a
1243    /// preview is refused, so it can never touch the operator's live external DB.
1244    pub allow_preview: bool,
1245    /// Connection/acquire timeout in seconds (default 10).
1246    pub connect_timeout_secs: Option<u64>,
1247    /// The stock OCI image for a **managed co-located** database (`compute` set, no
1248    /// `password_env`). When omitted, boatramp auto-registers the workload from the
1249    /// engine's default image (`pgvector/pgvector:pg16` for postgres, `mysql:8.0`
1250    /// for mysql). Ignored for a bring-your-own (`url_env`) database.
1251    pub image: Option<String>,
1252    /// The persistent data-volume size in MiB for a **managed co-located** database
1253    /// (default 10240 = 10 GiB). Ignored for a bring-your-own database.
1254    pub volume_size_mib: Option<u32>,
1255    /// **Isolation mechanism** for a compute-backed managed database (2×2 axis 1).
1256    /// `single` (default) — a *dedicated* database server (its own container) per
1257    /// tenant; `shared` — *one* server hosting a permission-separated database + role
1258    /// per tenant. Ignored for a bring-your-own (`url_env`) database.
1259    pub tenant: TenantIsolation,
1260    /// **Tenant grain** for a compute-backed managed database (2×2 axis 2). `project`
1261    /// (default) — a tenant is a project; `site` — a tenant is a site. A tenant may
1262    /// hold several databases (one per binding that names it); it gets one login role
1263    /// and sealed credential per (tenant, server), granted on all its own databases
1264    /// and none of another tenant's. The reserved `default` project uses the plain
1265    /// configured name, so a single-tenant install is just one ordinary database.
1266    pub tenant_scope: TenantScope,
1267    /// **Opt-in** (default `false`): inject the request's `boatramp.project` /
1268    /// `boatramp.site` into the SQL session at each transaction start (Postgres
1269    /// `set_config` GUC, MySQL session var), so hand-written **native RLS** policies
1270    /// can key on them per-request. The GraphQL data connector's row-level policy is
1271    /// claim-sourced and needs nothing here; this is for hand-rolled RLS on the plain
1272    /// `sql.open` path (Postgres — the engine with native row-level security).
1273    ///
1274    /// # Trust model — read before relying on this for isolation
1275    ///
1276    /// `rls_session` **provides** the request's tenant to the SQL session for an app's
1277    /// RLS to key on. It is **not** a general hostile-guest boundary:
1278    ///
1279    /// - The reserved keys (`boatramp.*` / `@boatramp_*`) are **protected** from guest
1280    ///   override — a handler statement that tries to `set_config('boatramp.…', …)` /
1281    ///   `SET boatramp.… ` / `SET @boatramp_… ` (or `RESET`/`DISCARD` them) is refused,
1282    ///   so a guest cannot spoof its injected tenant.
1283    /// - But the **real tenant-isolation boundary** is the **per-tenant database +
1284    ///   role** (`tenant = single` / `shared`), which a compromised handler cannot
1285    ///   cross regardless of what it does in-session. `rls_session` is a convenience
1286    ///   for app-authored RLS *within* a tenant's own database, layered on top of that
1287    ///   boundary — not a substitute for it.
1288    /// - For untrusted data, prefer **claim-sourced** enforcement (the GraphQL data
1289    ///   connector's row-level policy), which derives the tenant from the verified
1290    ///   request, not from anything the handler's SQL can influence.
1291    pub rls_session: bool,
1292}
1293
1294/// How a managed compute-backed database is physically isolated per tenant (2×2 axis
1295/// 1). `Single` = a dedicated server (container) per tenant (isolation by separate
1296/// process); `Shared` = one server with a per-tenant database + login role (isolation
1297/// by grants — Postgres `REVOKE CONNECT FROM PUBLIC` + owner grant; MySQL per-schema
1298/// grant), so a tenant's role cannot connect to another tenant's database.
1299#[cfg_attr(not(feature = "handlers"), allow(dead_code))]
1300#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Deserialize)]
1301#[serde(rename_all = "lowercase")]
1302pub enum TenantIsolation {
1303    /// A dedicated database server (its own container) per tenant. The default.
1304    #[default]
1305    Single,
1306    /// One shared server hosting a per-tenant database + role (grant-isolated).
1307    Shared,
1308}
1309
1310/// The grain of a tenant for a managed compute-backed database (2×2 axis 2) —
1311/// `Project` (default) or `Site`. The two grains are parallel; the isolation
1312/// mechanism is [`TenantIsolation`].
1313#[cfg_attr(not(feature = "handlers"), allow(dead_code))]
1314#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Deserialize)]
1315#[serde(rename_all = "lowercase")]
1316pub enum TenantScope {
1317    /// A tenant is a **project** (the default).
1318    #[default]
1319    Project,
1320    /// A tenant is a **site** (finer than project).
1321    Site,
1322}
1323
1324impl ExternalDatabaseConfig {
1325    /// Validate the source is well-formed: **exactly one** of `url_env` /
1326    /// `compute`, and a `compute`-backed database has the connection details
1327    /// boatramp can't infer (`database` + `user`). `password_env` is **optional** —
1328    /// omit it to let boatramp manage the credential (Phase 2). `name` is the
1329    /// binding name, for the error message.
1330    #[cfg_attr(not(feature = "handlers"), allow(dead_code))]
1331    pub fn validate(&self, name: &str) -> Result<(), String> {
1332        let has_url = !self.url_env.is_empty();
1333        let has_compute = self.compute.as_deref().is_some_and(|c| !c.is_empty());
1334        match (has_url, has_compute) {
1335            (true, true) => Err(format!(
1336                "sql database {name:?}: set exactly one of `url_env` or `compute`, not both"
1337            )),
1338            (false, false) => Err(format!(
1339                "sql database {name:?}: needs a source — set `url_env` (bring-your-own) or \
1340                 `compute` (a database boatramp runs)"
1341            )),
1342            (false, true) => {
1343                // `database` + `user` are non-secret and can't be inferred; a missing
1344                // `password_env` is *not* an error — it selects the managed credential.
1345                for (field, val) in [("database", &self.database), ("user", &self.user)] {
1346                    if val.as_deref().is_none_or(str::is_empty) {
1347                        return Err(format!(
1348                            "sql database {name:?}: a `compute`-backed database requires `{field}`"
1349                        ));
1350                    }
1351                }
1352                Ok(())
1353            }
1354            (true, false) => Ok(()),
1355        }
1356    }
1357
1358    /// Whether this compute-backed database uses a **boatramp-managed** credential
1359    /// (Phase 2): `compute` is set and no `password_env` was supplied.
1360    #[cfg_attr(not(feature = "handlers"), allow(dead_code))]
1361    pub fn is_managed_credential(&self) -> bool {
1362        self.compute.as_deref().is_some_and(|c| !c.is_empty())
1363            && self.password_env.as_deref().is_none_or(str::is_empty)
1364    }
1365}
1366
1367/// The signing algorithm for a signer that can choose one (`Local`, `Vault`,
1368/// `Pkcs11`). ES256 is the portable default; the cloud KMS backends are ES256-only
1369/// and ignore this. Written as a RON enum: `alg: Es256` / `alg: Ed25519`.
1370#[derive(Debug, Clone, Copy, Default, Deserialize)]
1371pub enum SignerAlg {
1372    /// ECDSA P-256 (COSE ES256) — the default.
1373    #[default]
1374    Es256,
1375    /// Ed25519 (COSE EdDSA).
1376    Ed25519,
1377}
1378
1379impl SignerAlg {
1380    fn to_token_alg(self) -> boatramp_core::cose::TokenAlg {
1381        match self {
1382            Self::Es256 => boatramp_core::cose::TokenAlg::Es256,
1383            Self::Ed25519 => boatramp_core::cose::TokenAlg::Ed25519,
1384        }
1385    }
1386}
1387
1388/// External token signer selector (`serve.signer`). Maps to
1389/// [`boatramp_server::signer::SignerConfig`]; secrets (tokens/PINs) are resolved
1390/// from the named env vars at startup, never stored in config. Written as a RON
1391/// enum — `signer: Vault(...)`, `signer: AwsKms(...)`, `signer: Pkcs11(...)`, ….
1392#[derive(Debug, Clone, Deserialize)]
1393#[serde(deny_unknown_fields)]
1394pub enum AuthSignerConfig {
1395    /// In-process key (`"<alg>:<hex>"`).
1396    Local {
1397        /// The private key spec, `"<alg>:<hex>"`.
1398        private_key: String,
1399    },
1400    /// HashiCorp Vault Transit key.
1401    Vault {
1402        /// Vault base address.
1403        address: String,
1404        /// The Transit key name.
1405        key: String,
1406        /// Env var holding the Vault token.
1407        token_env: String,
1408        /// The key algorithm.
1409        #[serde(default)]
1410        alg: SignerAlg,
1411    },
1412    /// AWS KMS asymmetric key (ES256).
1413    AwsKms {
1414        /// The KMS key id or ARN.
1415        key_id: String,
1416        /// Optional region override.
1417        #[serde(default)]
1418        region: Option<String>,
1419    },
1420    /// GCP Cloud KMS key version (ES256).
1421    GcpKms {
1422        /// The key-version resource name.
1423        key_version: String,
1424        /// Env var holding a GCP OAuth2 access token.
1425        access_token_env: String,
1426    },
1427    /// Azure Key Vault key (ES256).
1428    AzureKv {
1429        /// The vault base URL.
1430        vault_url: String,
1431        /// The key name.
1432        key: String,
1433        /// The key version.
1434        key_version: String,
1435        /// Env var holding an Azure AD access token.
1436        access_token_env: String,
1437    },
1438    /// PKCS#11 HSM key.
1439    Pkcs11 {
1440        /// Path to the PKCS#11 module.
1441        module: String,
1442        /// The token label.
1443        token_label: String,
1444        /// The key's `CKA_LABEL`.
1445        key_label: String,
1446        /// Env var holding the user PIN.
1447        pin_env: String,
1448        /// The key algorithm.
1449        #[serde(default)]
1450        alg: SignerAlg,
1451    },
1452}
1453
1454impl AuthSignerConfig {
1455    /// Map the config-file form to the server's runtime [`SignerConfig`].
1456    pub fn to_signer_config(&self) -> boatramp_server::signer::SignerConfig {
1457        use boatramp_server::signer::SignerConfig;
1458        match self {
1459            Self::Local { private_key } => SignerConfig::Local {
1460                private_key: private_key.clone(),
1461            },
1462            Self::Vault {
1463                address,
1464                key,
1465                token_env,
1466                alg,
1467            } => SignerConfig::Vault {
1468                address: address.clone(),
1469                key: key.clone(),
1470                token_env: token_env.clone(),
1471                alg: alg.to_token_alg(),
1472            },
1473            Self::AwsKms { key_id, region } => SignerConfig::AwsKms {
1474                key_id: key_id.clone(),
1475                region: region.clone(),
1476            },
1477            Self::GcpKms {
1478                key_version,
1479                access_token_env,
1480            } => SignerConfig::GcpKms {
1481                key_version: key_version.clone(),
1482                access_token_env: access_token_env.clone(),
1483            },
1484            Self::AzureKv {
1485                vault_url,
1486                key,
1487                key_version,
1488                access_token_env,
1489            } => SignerConfig::AzureKv {
1490                vault_url: vault_url.clone(),
1491                key: key.clone(),
1492                key_version: key_version.clone(),
1493                access_token_env: access_token_env.clone(),
1494            },
1495            Self::Pkcs11 {
1496                module,
1497                token_label,
1498                key_label,
1499                pin_env,
1500                alg,
1501            } => SignerConfig::Pkcs11 {
1502                module: module.clone(),
1503                token_label: token_label.clone(),
1504                key_label: key_label.clone(),
1505                pin_env: pin_env.clone(),
1506                alg: alg.to_token_alg(),
1507            },
1508        }
1509    }
1510}
1511
1512/// `serve` section — server defaults, overridden by flags/env.
1513#[derive(Debug, Clone, Default, Deserialize)]
1514#[serde(default)]
1515pub struct ServeConfig {
1516    /// Bind address (e.g. `0.0.0.0:8080`).
1517    pub addr: Option<SocketAddr>,
1518    /// Data directory for filesystem backends.
1519    pub data_dir: Option<PathBuf>,
1520    /// Token root **private** key (hex) — issuing node: verifies *and* mints
1521    /// tokens / OIDC exchanges.
1522    pub auth_root_private_key: Option<String>,
1523    /// Token root **public** key (hex) — verify-only node.
1524    pub auth_root_public_key: Option<String>,
1525    /// Single-use bootstrap secret enabling `POST /api/tokens/bootstrap` (mint the
1526    /// first token without an admin bearer). Prefer the `BOATRAMP_BOOTSTRAP_SECRET`
1527    /// env / `--bootstrap-secret` flag so it isn't persisted in the config file.
1528    pub bootstrap_secret: Option<String>,
1529    /// External token signer (`[serve.signer]`): mint with a
1530    /// KMS/HSM/Vault-held root key instead of an in-process `auth_root_private_key`.
1531    /// Absent ⇒ the in-process key. When set, its public half is the trust anchor.
1532    pub signer: Option<AuthSignerConfig>,
1533    /// Reject blob uploads larger than this many bytes.
1534    pub max_upload_bytes: Option<u64>,
1535    /// Abort an upload that stalls for longer than this many seconds.
1536    pub upload_idle_timeout_secs: Option<u64>,
1537    /// Cap on simultaneous blob uploads.
1538    pub max_concurrent_uploads: Option<usize>,
1539    /// In a TLS mode, bind this plain-HTTP address on a second listener that
1540    /// redirects to HTTPS (dual-listener). Only read in `tls` builds.
1541    #[cfg_attr(not(feature = "tls"), allow(dead_code))]
1542    pub http_redirect_addr: Option<SocketAddr>,
1543    /// Site to serve for a `Host` matching no domain, instead of 404.
1544    pub default_site: Option<String>,
1545    /// The fleet's canonical public origin (e.g. `https://cp.example.com`) that a
1546    /// per-request proof-of-possession must bind to (`aud`). Required for
1547    /// holder-bound (`cnf`/PoP) tokens to be usable — a proof's origin is compared
1548    /// against this value, never against a `Host`/`X-Forwarded-*` header.
1549    pub pop_origin: Option<String>,
1550    /// Require a valid control-plane token to view deployment previews.
1551    pub protect_previews: bool,
1552    /// Rate-limit cluster-wide via the control-plane KV instead of per node.
1553    pub cluster_rate_limit: bool,
1554    /// Keep the config cache coherent across processes sharing one KV via the
1555    /// changelog.
1556    pub shared_cache_coherence: bool,
1557    /// Cloud blob-change notification provisioning tier (FA-5b2): how boatramp
1558    /// obtains the native event pipeline (S3→SQS) that backs a `blob` trigger —
1559    /// `dry-run` (print the recipe), `provision` (create + retract), `verify-only`
1560    /// (operator pre-wired), or `refuse` (fail closed). Absent ⇒ no provisioning:
1561    /// `blob` triggers then work only on a self-watching backend (fs). Only wired
1562    /// for the S3 backend (`--features s3`).
1563    pub blob_notify_tier: Option<boatramp_core::blob_notify::ProvisionTier>,
1564    /// The AWS account id used to scope the provisioned SQS queue's `SendMessage`
1565    /// policy (`aws:SourceAccount`). Required when `blob_notify_tier` provisions.
1566    pub blob_notify_account_id: Option<String>,
1567    /// `[serve.console]` — the embedded web management console. Absent (or
1568    /// `enabled: false`) ⇒ not served. This is the **baseline** for the dynamic
1569    /// `console.*` daemon-config override, which can enable/move it at runtime
1570    /// (`boatramp config set console.enabled true`) without a restart.
1571    pub console: Option<ConsoleConfig>,
1572}
1573
1574/// `[serve.console]` — the embedded web console (a Wasm SPA baked into the
1575/// binary with the `console` build feature). Opt-in: the static shell holds no
1576/// secrets and the `/api` it drives is token-gated, so it is served
1577/// **unauthenticated** at a deliberately obscure path (a bearer token can't gate
1578/// a top-level browser navigation anyway — the path is the obscurity, the token
1579/// is the real gate).
1580#[cfg_attr(not(feature = "console"), allow(dead_code))]
1581#[derive(Debug, Clone, Default, Deserialize)]
1582#[serde(default, deny_unknown_fields)]
1583pub struct ConsoleConfig {
1584    /// Serve the embedded console (default `false`). Requires the `console` build
1585    /// feature; enabling it in a build without that feature is a logged no-op.
1586    pub enabled: bool,
1587    /// Host(s) the console answers on: `*` (any host, the default), an exact host
1588    /// (`console.example.com`), or a leading-wildcard (`*.example.com`).
1589    pub host: Option<String>,
1590    /// URL path prefix the console mounts at (default `/_console`). Kept under the
1591    /// reserved `/_` namespace so it never collides with a published site path.
1592    pub path: Option<String>,
1593}
1594
1595/// `publish` section — where and what to deploy (the `sync` target).
1596#[derive(Debug, Default, Deserialize)]
1597#[serde(default)]
1598pub struct PublishConfig {
1599    /// Base URL of the boatramp server (e.g. `https://pad.example.com`).
1600    pub server: Option<String>,
1601    /// Site name to publish to.
1602    pub site: Option<String>,
1603    /// API token for the control plane (or set `BOATRAMP_TOKEN`).
1604    pub token: Option<String>,
1605    /// Project this site belongs to (overrides with `--project` / `BOATRAMP_PROJECT`).
1606    pub project: Option<String>,
1607}
1608
1609/// `build` section.
1610#[derive(Debug, Clone, Deserialize)]
1611pub struct BuildConfig {
1612    /// Shell command to run (e.g. `npm run build`).
1613    pub command: String,
1614    /// Directory the build emits, published by `sync` (e.g. `dist`).
1615    #[serde(default)]
1616    pub output: Option<String>,
1617}
1618
1619/// `bundle` section — the in-process Rust bundler (`bundler` feature).
1620#[derive(Debug, Clone, Default, Deserialize)]
1621#[serde(default)]
1622pub struct BundleConfig {
1623    /// Output directory for bundled assets (e.g. `dist`).
1624    #[serde(default = "default_bundle_outdir")]
1625    pub outdir: String,
1626    /// JS/TS entry points bundled by Rolldown (tree-shaken, code-split).
1627    pub js: Vec<String>,
1628    /// CSS entry points bundled by lightningcss (`@import` inlined).
1629    pub css: Vec<String>,
1630    /// Minify output (default true).
1631    #[serde(default = "default_true")]
1632    pub minify: bool,
1633}
1634
1635fn default_bundle_outdir() -> String {
1636    "dist".to_string()
1637}
1638
1639fn default_true() -> bool {
1640    true
1641}
1642
1643#[cfg(test)]
1644mod tests {
1645    use super::*;
1646
1647    fn project(text: &str) -> ProjectConfig {
1648        ron_options().from_str(text).unwrap()
1649    }
1650
1651    fn server(text: &str) -> ServerConfig {
1652        ron_options().from_str(text).unwrap()
1653    }
1654
1655    /// Build an [`EnvSource::Map`] from `(name, value)` pairs for deterministic
1656    /// override tests (no process-global `std::env` mutation).
1657    fn env(pairs: &[(&str, &str)]) -> EnvSource {
1658        EnvSource::Map(
1659            pairs
1660                .iter()
1661                .map(|(k, v)| (k.to_string(), v.to_string()))
1662                .collect(),
1663        )
1664    }
1665
1666    #[test]
1667    fn env_overrides_configure_all_three_sections_with_no_file() {
1668        // The crux of the ask: with NO `boatramp.cfg` at all (the default config),
1669        // env vars alone materialise + populate the compute, security, and handler
1670        // `sql` sections. `ServerConfig::default()` has all three absent.
1671        let mut cfg = ServerConfig::default();
1672        assert!(cfg.compute.is_none() && cfg.security.is_none() && cfg.handlers.is_none());
1673
1674        cfg.apply_env_overrides(&env(&[
1675            ("BOATRAMP_COMPUTE_VCPUS", "8"),
1676            ("BOATRAMP_COMPUTE_MEM_MIB", "4096"),
1677            ("BOATRAMP_COMPUTE_REGION", "eu-central"),
1678            ("BOATRAMP_SECURITY_PROFILE", "single-tenant"),
1679            ("BOATRAMP_SECURITY_ALLOW_SITE_PRIVATE_UPSTREAMS", "true"),
1680            ("BOATRAMP_SECURITY_MAX_UPLOAD_BYTES", "1048576"),
1681            ("BOATRAMP_HANDLERS_SQL_URL", "http://sqld:8080"),
1682            ("BOATRAMP_HANDLERS_SQL_ADMIN_URL", "http://sqld:9090"),
1683        ]))
1684        .expect("valid env overrides apply");
1685
1686        // compute: the section now exists with the env values (and defaults elsewhere).
1687        let compute = cfg.compute.expect("compute materialised from env");
1688        assert_eq!(compute.vcpus, 8);
1689        assert_eq!(compute.mem_mib, 4096);
1690        assert_eq!(compute.region.as_deref(), Some("eu-central"));
1691        assert_eq!(compute.bridge, "br-boatramp"); // untouched default
1692
1693        // security: profile + an override both took, and the posture resolves.
1694        let security = cfg.security.expect("security materialised from env");
1695        assert_eq!(security.profile.as_deref(), Some("single-tenant"));
1696        let posture = security.resolve().expect("resolves");
1697        assert!(posture.allow_site_private_upstreams);
1698        assert_eq!(posture.max_upload_bytes, 1_048_576);
1699
1700        // handler sql: the nested handlers.bindings.sql chain was created.
1701        let sql = cfg
1702            .handlers
1703            .expect("handlers materialised from env")
1704            .bindings
1705            .sql
1706            .expect("sql binding materialised from env");
1707        assert_eq!(sql.url.as_deref(), Some("http://sqld:8080"));
1708        assert_eq!(sql.admin_url.as_deref(), Some("http://sqld:9090"));
1709    }
1710
1711    #[test]
1712    fn env_override_wins_over_file_value_but_unset_defers() {
1713        // A file that set each section; env then overrides one field per section
1714        // and leaves the rest of the file value in place (precedence: env > file).
1715        let mut cfg = server(
1716            r#"(
1717                compute: ( vcpus: 2, mem_mib: 512, region: "us-east" ),
1718                security: ( profile: "multi-tenant" ),
1719                handlers: ( bindings: ( sql: ( url: "http://file:8080", admin_url: "http://file:9090" ) ) ),
1720            )"#,
1721        );
1722
1723        cfg.apply_env_overrides(&env(&[
1724            ("BOATRAMP_COMPUTE_VCPUS", "16"),
1725            ("BOATRAMP_SECURITY_PROFILE", "dev"),
1726            ("BOATRAMP_HANDLERS_SQL_URL", "http://env:8080"),
1727        ]))
1728        .expect("valid env overrides apply");
1729
1730        let compute = cfg.compute.unwrap();
1731        assert_eq!(compute.vcpus, 16, "env wins over the file vcpus");
1732        assert_eq!(compute.mem_mib, 512, "unset env defers to the file mem_mib");
1733        assert_eq!(
1734            compute.region.as_deref(),
1735            Some("us-east"),
1736            "unset env defers to the file region"
1737        );
1738
1739        assert_eq!(
1740            cfg.security.unwrap().profile.as_deref(),
1741            Some("dev"),
1742            "env profile wins over the file profile"
1743        );
1744
1745        let sql = cfg.handlers.unwrap().bindings.sql.unwrap();
1746        assert_eq!(
1747            sql.url.as_deref(),
1748            Some("http://env:8080"),
1749            "env wins over the file sql url"
1750        );
1751        assert_eq!(
1752            sql.admin_url.as_deref(),
1753            Some("http://file:9090"),
1754            "unset env defers to the file sql admin_url"
1755        );
1756    }
1757
1758    #[test]
1759    fn env_overrides_leave_unmentioned_sections_absent() {
1760        // With no relevant env vars set, an empty config stays empty — the sections
1761        // are materialised only on demand, so an unset environment adds nothing.
1762        let mut cfg = ServerConfig::default();
1763        cfg.apply_env_overrides(&env(&[("SOME_UNRELATED_VAR", "x")]))
1764            .expect("no-op env applies");
1765        assert!(cfg.compute.is_none());
1766        assert!(cfg.security.is_none());
1767        assert!(cfg.handlers.is_none());
1768        assert!(cfg.secrets.is_none());
1769        assert!(cfg.cluster.is_none());
1770    }
1771
1772    #[test]
1773    fn env_bool_accepts_common_spellings_and_rejects_garbage() {
1774        // Truthy/falsey spellings all parse.
1775        for (raw, want) in [
1776            ("true", true),
1777            ("1", true),
1778            ("YES", true),
1779            ("On", true),
1780            ("false", false),
1781            ("0", false),
1782            ("no", false),
1783            ("OFF", false),
1784        ] {
1785            let mut cfg = ServerConfig::default();
1786            cfg.apply_env_overrides(&env(&[("BOATRAMP_SECURITY_REQUIRE_POP", raw)]))
1787                .expect("boolean parses");
1788            assert_eq!(
1789                cfg.security.unwrap().overrides.require_pop,
1790                Some(want),
1791                "{raw:?} ⇒ {want}"
1792            );
1793        }
1794        // A non-boolean value is a clear error, not a silent default.
1795        let mut cfg = ServerConfig::default();
1796        let err = cfg
1797            .apply_env_overrides(&env(&[("BOATRAMP_SECURITY_REQUIRE_POP", "maybe")]))
1798            .expect_err("garbage boolean is rejected");
1799        match err {
1800            ConfigError::Env { var, .. } => assert_eq!(var, "BOATRAMP_SECURITY_REQUIRE_POP"),
1801            other => panic!("expected ConfigError::Env, got {other:?}"),
1802        }
1803    }
1804
1805    #[test]
1806    fn env_number_parse_error_names_the_variable() {
1807        // A non-numeric numeric var is rejected with the variable named.
1808        let mut cfg = ServerConfig::default();
1809        let err = cfg
1810            .apply_env_overrides(&env(&[("BOATRAMP_COMPUTE_VCPUS", "lots")]))
1811            .expect_err("garbage number is rejected");
1812        match err {
1813            ConfigError::Env { var, .. } => assert_eq!(var, "BOATRAMP_COMPUTE_VCPUS"),
1814            other => panic!("expected ConfigError::Env, got {other:?}"),
1815        }
1816    }
1817
1818    #[test]
1819    fn empty_env_value_is_treated_as_unset() {
1820        // `VAR=` (empty) must not clobber a file value with an empty string.
1821        let mut cfg = server(r#"( compute: ( region: "us-east" ) )"#);
1822        cfg.apply_env_overrides(&env(&[("BOATRAMP_COMPUTE_REGION", "")]))
1823            .expect("empty env applies as a no-op");
1824        assert_eq!(
1825            cfg.compute.unwrap().region.as_deref(),
1826            Some("us-east"),
1827            "an empty env value leaves the file value in place"
1828        );
1829    }
1830
1831    #[test]
1832    fn env_configures_managed_postgres_secrets_and_privilege_with_no_file() {
1833        // The construens acceptance case: with NO `boatramp.cfg` at all, the
1834        // environment alone stands up a managed co-located Postgres. It configures
1835        // the default (`""`-named) database in `handlers.bindings.sql.databases`
1836        // (kind=postgres, compute=pg, database+user set), the `[secrets]` envelope
1837        // (local + a kek path so the managed credential can be sealed), and
1838        // `compute.managed_db_privilege = rootless`. All three sections start absent.
1839        let mut cfg = ServerConfig::default();
1840        assert!(cfg.handlers.is_none() && cfg.secrets.is_none() && cfg.compute.is_none());
1841
1842        cfg.apply_env_overrides(&env(&[
1843            // The default database is addressed by the reserved `DEFAULT` token,
1844            // which maps to the empty-string map key.
1845            ("BOATRAMP_HANDLERS_SQL_DB_DEFAULT_KIND", "postgres"),
1846            ("BOATRAMP_HANDLERS_SQL_DB_DEFAULT_COMPUTE", "pg"),
1847            ("BOATRAMP_HANDLERS_SQL_DB_DEFAULT_DATABASE", "appdb"),
1848            ("BOATRAMP_HANDLERS_SQL_DB_DEFAULT_USER", "app"),
1849            // Secrets: the local envelope + a KEK path (never key material).
1850            ("BOATRAMP_SECRETS_ENVELOPE", "local"),
1851            ("BOATRAMP_SECRETS_KEK_FILE", "/var/lib/boatramp/secrets/kek"),
1852            // The shared-kernel DB privilege strategy.
1853            ("BOATRAMP_COMPUTE_MANAGED_DB_PRIVILEGE", "rootless"),
1854        ]))
1855        .expect("valid env overrides apply");
1856
1857        // The default (`""`-keyed) managed database exists with the right source.
1858        let sql = cfg
1859            .handlers
1860            .expect("handlers materialised from env")
1861            .bindings
1862            .sql
1863            .expect("sql binding materialised from env");
1864        let db = sql
1865            .databases
1866            .get("")
1867            .expect("the default `\"\"`-named database was created from DEFAULT");
1868        assert_eq!(db.kind, "postgres");
1869        assert_eq!(db.compute.as_deref(), Some("pg"));
1870        assert_eq!(db.database.as_deref(), Some("appdb"));
1871        assert_eq!(db.user.as_deref(), Some("app"));
1872        // No `password_env` ⇒ boatramp manages the credential (Phase 2), and the
1873        // compute-backed source validates.
1874        assert!(db.password_env.is_none());
1875        assert!(db.is_managed_credential());
1876        assert!(db.validate("").is_ok());
1877
1878        // The secrets envelope + KEK path took (the path is a location, not a key).
1879        let secrets = cfg.secrets.expect("secrets materialised from env");
1880        assert_eq!(secrets.envelope, "local");
1881        assert_eq!(
1882            secrets.kek_file.as_deref(),
1883            Some(Path::new("/var/lib/boatramp/secrets/kek"))
1884        );
1885        assert!(
1886            secrets.vault.is_none(),
1887            "no vault vars ⇒ no vault sub-config"
1888        );
1889
1890        // The managed-DB privilege strategy resolved from its lowercase variant.
1891        let compute = cfg.compute.expect("compute materialised from env");
1892        assert_eq!(compute.managed_db_privilege, ManagedDbPrivilege::Rootless);
1893    }
1894
1895    #[test]
1896    fn env_declares_named_databases_and_merges_over_the_file() {
1897        // A file declares one database; the env overrides one of its fields and
1898        // ADDS a second, discovering both member names from the environment.
1899        let mut cfg = server(
1900            r#"(
1901                handlers: ( bindings: ( sql: (
1902                    databases: {
1903                        "analytics": ( kind: "postgres", url_env: "FILE_PG_URL", pool_max: 4 ),
1904                    },
1905                ) ) ),
1906            )"#,
1907        );
1908        cfg.apply_env_overrides(&env(&[
1909            // Override the file database's pool size (merge by key, per field).
1910            ("BOATRAMP_HANDLERS_SQL_DB_analytics_POOL_MAX", "32"),
1911            // Add a brand-new database whose name has an underscore, exercising the
1912            // longest-suffix name isolation (`_READ_URL_ENV`, not `_URL_ENV`).
1913            ("BOATRAMP_HANDLERS_SQL_DB_events_log_KIND", "mysql"),
1914            ("BOATRAMP_HANDLERS_SQL_DB_events_log_URL_ENV", "EVENTS_URL"),
1915            (
1916                "BOATRAMP_HANDLERS_SQL_DB_events_log_READ_URL_ENV",
1917                "EVENTS_RO_URL",
1918            ),
1919            ("BOATRAMP_HANDLERS_SQL_DB_events_log_READ_ONLY", "true"),
1920        ]))
1921        .expect("valid env overrides apply");
1922
1923        let sql = cfg.handlers.unwrap().bindings.sql.unwrap();
1924        assert_eq!(sql.databases.len(), 2);
1925
1926        let analytics = &sql.databases["analytics"];
1927        assert_eq!(
1928            analytics.pool_max,
1929            Some(32),
1930            "env pool_max wins over the file"
1931        );
1932        assert_eq!(
1933            analytics.url_env, "FILE_PG_URL",
1934            "the file's url_env survives (env didn't touch it)"
1935        );
1936
1937        let events = &sql.databases["events_log"];
1938        assert_eq!(events.kind, "mysql");
1939        assert_eq!(events.url_env, "EVENTS_URL");
1940        assert_eq!(events.read_url_env.as_deref(), Some("EVENTS_RO_URL"));
1941        assert!(events.read_only);
1942    }
1943
1944    #[test]
1945    fn env_enum_parse_error_names_the_variable_and_variants() {
1946        // An unknown enum value is a clear error that names the offending variable.
1947        let mut cfg = ServerConfig::default();
1948        let err = cfg
1949            .apply_env_overrides(&env(&[(
1950                "BOATRAMP_COMPUTE_MANAGED_DB_PRIVILEGE",
1951                "superuser",
1952            )]))
1953            .expect_err("unknown enum variant is rejected");
1954        match err {
1955            ConfigError::Env { var, reason } => {
1956                assert_eq!(var, "BOATRAMP_COMPUTE_MANAGED_DB_PRIVILEGE");
1957                assert!(reason.contains("rootless") && reason.contains("caps"));
1958            }
1959            other => panic!("expected ConfigError::Env, got {other:?}"),
1960        }
1961        // The docker enums map their lowercase serde variants too.
1962        let mut cfg = ServerConfig::default();
1963        cfg.apply_env_overrides(&env(&[
1964            ("BOATRAMP_COMPUTE_DOCKER_ENDPOINT", "bridge"),
1965            ("BOATRAMP_COMPUTE_DOCKER_VOLUME_MODE", "bind"),
1966        ]))
1967        .expect("known enum variants parse");
1968        let compute = cfg.compute.unwrap();
1969        assert_eq!(
1970            compute.docker_endpoint,
1971            boatramp_docker::DockerEndpoint::Bridge
1972        );
1973        assert_eq!(
1974            compute.docker_volume_mode,
1975            boatramp_docker::DockerVolumeMode::Bind
1976        );
1977    }
1978
1979    #[test]
1980    fn env_trust_anchors_parse_as_a_comma_separated_list() {
1981        // The kernel trust anchors are comma-separated (whitespace trimmed, empty
1982        // items dropped so a trailing comma is tolerated). A file default is
1983        // fully replaced, not appended to.
1984        let mut cfg = ServerConfig::default();
1985        cfg.apply_env_overrides(&env(&[
1986            (
1987                "BOATRAMP_COMPUTE_KERNEL_SIGNING_PUBKEYS",
1988                " es256:aa , es256:bb ,",
1989            ),
1990            ("BOATRAMP_COMPUTE_KERNEL_ALLOWED_HASHES", "deadbeef"),
1991        ]))
1992        .expect("valid list env applies");
1993        let compute = cfg.compute.unwrap();
1994        assert_eq!(
1995            compute.kernel_signing_pubkeys,
1996            vec!["es256:aa".to_string(), "es256:bb".to_string()],
1997            "trimmed, comma-split, trailing-empty dropped, defaults replaced"
1998        );
1999        assert_eq!(
2000            compute.kernel_allowed_hashes,
2001            vec!["deadbeef".to_string()],
2002            "a single value is a one-element list"
2003        );
2004    }
2005
2006    #[test]
2007    fn env_configures_secrets_vault_subconfig() {
2008        // The vault sub-config materialises only when a vault var is set, and the
2009        // token stays indirected via a variable NAME (`token_env`), never inline.
2010        let mut cfg = ServerConfig::default();
2011        cfg.apply_env_overrides(&env(&[
2012            ("BOATRAMP_SECRETS_ENVELOPE", "vault"),
2013            ("BOATRAMP_SECRETS_VAULT_ADDR", "https://vault:8200"),
2014            ("BOATRAMP_SECRETS_VAULT_KEY", "certs"),
2015        ]))
2016        .expect("valid env overrides apply");
2017        let secrets = cfg.secrets.unwrap();
2018        assert_eq!(secrets.envelope, "vault");
2019        let vault = secrets.vault.expect("vault sub-config materialised");
2020        assert_eq!(vault.addr, "https://vault:8200");
2021        assert_eq!(vault.key, "certs");
2022        // token_env defaults to VAULT_TOKEN when not overridden.
2023        assert_eq!(vault.token_env, "VAULT_TOKEN");
2024    }
2025
2026    #[test]
2027    fn env_materialises_and_overrides_the_cluster_section() {
2028        // With no file, a `BOATRAMP_CLUSTER_LISTEN` materialises the section; the
2029        // remaining fields (lists, join token, mesh) layer on. The founding/joining
2030        // action flags (`BOATRAMP_CLUSTER_INIT`/`_JOIN`) are separate `serve` args
2031        // and are not part of this section.
2032        let mut cfg = ServerConfig::default();
2033        cfg.apply_env_overrides(&env(&[
2034            ("BOATRAMP_CLUSTER_LISTEN", "10.0.0.2:7000"),
2035            ("BOATRAMP_CLUSTER_ROOT_PUBKEYS", "es256:aa,es256:bb"),
2036            ("BOATRAMP_CLUSTER_SEEDS", "https://10.0.0.1:8080"),
2037            ("BOATRAMP_CLUSTER_JOIN_TOKEN", "env:BOATRAMP_JOIN_TOKEN"),
2038            ("BOATRAMP_CLUSTER_STORE_DIR", "/var/lib/boatramp/raft"),
2039            ("BOATRAMP_CLUSTER_MESH_GATE_CLIENT_WRITES", "true"),
2040        ]))
2041        .expect("valid env overrides apply");
2042        let cluster = cfg.cluster.expect("cluster materialised from env");
2043        assert_eq!(
2044            cluster.listen,
2045            "10.0.0.2:7000".parse::<std::net::SocketAddr>().unwrap()
2046        );
2047        assert_eq!(
2048            cluster.root_pubkeys,
2049            vec!["es256:aa".to_string(), "es256:bb".to_string()]
2050        );
2051        assert_eq!(cluster.seeds, vec!["https://10.0.0.1:8080".to_string()]);
2052        assert_eq!(
2053            cluster.join_token.as_deref(),
2054            Some("env:BOATRAMP_JOIN_TOKEN")
2055        );
2056        assert_eq!(
2057            cluster.store_dir.as_deref(),
2058            Some(Path::new("/var/lib/boatramp/raft"))
2059        );
2060        assert_eq!(
2061            cluster.mesh.expect("mesh sub-config").gate_client_writes,
2062            Some(true)
2063        );
2064
2065        // Without a listen (and no file section) there is nothing to materialise:
2066        // a non-listen cluster var alone leaves the section absent.
2067        let mut cfg = ServerConfig::default();
2068        cfg.apply_env_overrides(&env(&[("BOATRAMP_CLUSTER_SEEDS", "https://10.0.0.1:8080")]))
2069            .expect("applies");
2070        assert!(
2071            cfg.cluster.is_none(),
2072            "no listen + no file section ⇒ no cluster"
2073        );
2074    }
2075
2076    #[test]
2077    fn env_cluster_listen_overrides_a_file_section() {
2078        // A file `[cluster]` section: env overrides `listen` and adds seeds.
2079        let mut cfg = server(r#"( cluster: ( listen: "0.0.0.0:7000" ) )"#);
2080        cfg.apply_env_overrides(&env(&[
2081            ("BOATRAMP_CLUSTER_LISTEN", "10.0.0.9:7000"),
2082            ("BOATRAMP_CLUSTER_SEEDS", "https://seed:8080"),
2083        ]))
2084        .expect("applies");
2085        let cluster = cfg.cluster.unwrap();
2086        assert_eq!(
2087            cluster.listen,
2088            "10.0.0.9:7000".parse::<std::net::SocketAddr>().unwrap(),
2089            "env listen wins over the file"
2090        );
2091        assert_eq!(cluster.seeds, vec!["https://seed:8080".to_string()]);
2092    }
2093
2094    #[test]
2095    fn empty_project_config_is_default() {
2096        let cfg = project("()");
2097        assert!(cfg.publish.server.is_none());
2098        assert!(cfg.publish.site.is_none());
2099        assert!(cfg.build.is_none());
2100        assert!(cfg.bundle.is_none());
2101        // Routing defaults: schema v1, the single default index candidate.
2102        assert_eq!(cfg.routing.version, 1);
2103        assert_eq!(cfg.routing.index, vec!["index.html".to_string()]);
2104    }
2105
2106    #[test]
2107    fn serve_signer_config_parses_and_maps_each_backend() {
2108        use boatramp_core::cose::TokenAlg;
2109        use boatramp_server::signer::SignerConfig;
2110
2111        // RON-native enum tagging (`Vault(...)`); `IMPLICIT_SOME` lets the optional
2112        // fields (region) take a bare value or be omitted (→ None). This is the
2113        // exact RON documented in the Authentication guide.
2114        let vault = server(
2115            r#"( serve: ( signer: Vault(
2116                address: "https://vault.example:8200",
2117                key: "boatramp-root",
2118                token_env: "VAULT_TOKEN",
2119                alg: Ed25519,
2120            ) ) )"#,
2121        );
2122        match vault.serve.unwrap().signer.unwrap().to_signer_config() {
2123            SignerConfig::Vault {
2124                address,
2125                key,
2126                token_env,
2127                alg,
2128            } => {
2129                assert_eq!(address, "https://vault.example:8200");
2130                assert_eq!(key, "boatramp-root");
2131                assert_eq!(token_env, "VAULT_TOKEN");
2132                assert_eq!(alg, TokenAlg::Ed25519);
2133            }
2134            other => panic!("expected Vault, got {other:?}"),
2135        }
2136
2137        // AWS KMS: region omitted → None; PKCS#11: alg omitted → the ES256 default.
2138        let aws =
2139            server(r#"( serve: ( signer: AwsKms(key_id: "arn:aws:kms:eu-west-1:1:key/abc") ) )"#);
2140        assert!(matches!(
2141            aws.serve.unwrap().signer.unwrap().to_signer_config(),
2142            SignerConfig::AwsKms { region: None, .. }
2143        ));
2144
2145        let hsm = server(
2146            r#"( serve: ( signer: Pkcs11(
2147                module: "/usr/lib/softhsm/libsofthsm2.so",
2148                token_label: "boatramp",
2149                key_label: "root",
2150                pin_env: "HSM_PIN",
2151            ) ) )"#,
2152        );
2153        match hsm.serve.unwrap().signer.unwrap().to_signer_config() {
2154            SignerConfig::Pkcs11 { alg, .. } => assert_eq!(alg, TokenAlg::Es256),
2155            other => panic!("expected Pkcs11, got {other:?}"),
2156        }
2157    }
2158
2159    #[test]
2160    fn project_config_parses_publish_build_and_routing() {
2161        let cfg = project(
2162            r#"(
2163                publish: ( server: "http://127.0.0.1:8080", site: "demo" ),
2164                build: ( command: "npm run build", output: "dist" ),
2165                routing: (
2166                    clean_urls: true,
2167                    redirects: [ (from: "/old/:slug", to: "/new/:slug", status: 301) ],
2168                ),
2169            )"#,
2170        );
2171        assert_eq!(cfg.publish.server.as_deref(), Some("http://127.0.0.1:8080"));
2172        assert_eq!(cfg.publish.site.as_deref(), Some("demo"));
2173        let build = cfg.build.unwrap();
2174        assert_eq!(build.command, "npm run build");
2175        assert_eq!(build.output.as_deref(), Some("dist"));
2176        assert!(cfg.routing.clean_urls);
2177        assert_eq!(cfg.routing.redirects.len(), 1);
2178        assert_eq!(cfg.routing.redirects[0].status, 301);
2179    }
2180
2181    #[test]
2182    fn project_config_rejects_bad_routing_pattern() {
2183        // The same compile-check `load` runs: a bad route pattern is an error.
2184        let cfg = project(r#"( routing: ( redirects: [ (from: "/a/**/b/**", to: "/x") ] ) )"#);
2185        assert!(cfg.routing.compile_check().is_err());
2186    }
2187
2188    #[test]
2189    fn empty_server_config_has_no_sections() {
2190        let cfg = server("()");
2191        assert!(cfg.serve.is_none());
2192        assert!(cfg.handlers.is_none());
2193        assert!(cfg.cluster.is_none());
2194        assert!(cfg.security.is_none());
2195    }
2196
2197    #[test]
2198    fn security_section_parses_and_resolves() {
2199        // A profile plus an override that wins over it.
2200        let cfg = server(
2201            r#"(
2202                security: (
2203                    profile: "dev",
2204                    overrides: (
2205                        oidc_require_audience: true,
2206                        max_upload_bytes: 0,
2207                    ),
2208                )
2209            )"#,
2210        );
2211        let posture = cfg.security.unwrap().resolve().expect("resolves");
2212        // `dev` is loose...
2213        assert!(posture.allow_unauthenticated_public_bind);
2214        // ...but the explicit override wins over the profile.
2215        assert!(posture.oidc_require_audience);
2216        assert_eq!(posture.max_upload_bytes, 0); // unlimited
2217    }
2218
2219    #[test]
2220    fn env_wires_allow_env_secret_refs_over_the_multi_tenant_default() {
2221        // With no file, the multi-tenant default leaves host-env secret refs off;
2222        // the env knob re-enables them (env > default), same as the other posture bools.
2223        let mut cfg = ServerConfig::default();
2224        cfg.apply_env_overrides(&env(&[("BOATRAMP_SECURITY_ALLOW_ENV_SECRET_REFS", "true")]))
2225            .expect("valid env override applies");
2226        let posture = cfg
2227            .security
2228            .expect("security materialised from env")
2229            .resolve()
2230            .expect("resolves");
2231        assert!(posture.allow_env_secret_refs);
2232    }
2233
2234    #[test]
2235    fn cluster_section_parses_the_dynamic_join_shape() {
2236        let cfg = server(
2237            r#"(
2238                cluster: (
2239                    listen: "10.0.0.2:7000",
2240                    root_pubkeys: ["es256:03a1"],
2241                    seeds: ["https://10.0.0.1:8080"],
2242                    join_token: "env:BOATRAMP_JOIN_TOKEN",
2243                ),
2244            )"#,
2245        );
2246        let cluster = cfg.cluster.unwrap();
2247        assert_eq!(
2248            cluster.listen,
2249            "10.0.0.2:7000".parse::<std::net::SocketAddr>().unwrap()
2250        );
2251        assert_eq!(cluster.root_pubkeys, vec!["es256:03a1".to_string()]);
2252        assert_eq!(cluster.seeds, vec!["https://10.0.0.1:8080".to_string()]);
2253        assert_eq!(
2254            cluster.join_token.as_deref(),
2255            Some("env:BOATRAMP_JOIN_TOKEN")
2256        );
2257        // store_dir defaults to None (→ <data-dir>/raft at serve time).
2258        assert!(cluster.store_dir.is_none());
2259    }
2260
2261    #[test]
2262    fn cluster_section_founds_with_just_a_listen_addr() {
2263        // A founder needs no seeds/token — just where to bind the mesh.
2264        let cfg = server(r#"( cluster: ( listen: "0.0.0.0:7000" ) )"#);
2265        let cluster = cfg.cluster.unwrap();
2266        assert!(cluster.seeds.is_empty());
2267        assert!(cluster.root_pubkeys.is_empty());
2268        assert!(cluster.join_token.is_none());
2269    }
2270
2271    #[test]
2272    fn sql_binding_single_node_defaults() {
2273        // A bare section (or none) means single-node: no url, default dir.
2274        let cfg = server(r#"( handlers: ( bindings: ( sql: () ) ) )"#);
2275        let sql = cfg.handlers.unwrap().bindings.sql.unwrap();
2276        assert!(sql.url.is_none());
2277        assert!(sql.dir.is_none());
2278    }
2279
2280    #[test]
2281    fn sql_binding_single_node_custom_dir() {
2282        let cfg =
2283            server(r#"( handlers: ( bindings: ( sql: ( dir: "/var/lib/boatramp/sql" ) ) ) )"#);
2284        let sql = cfg.handlers.unwrap().bindings.sql.unwrap();
2285        assert_eq!(sql.dir.as_deref(), Some(Path::new("/var/lib/boatramp/sql")));
2286        assert!(sql.url.is_none());
2287    }
2288
2289    #[test]
2290    fn sql_binding_cluster() {
2291        let cfg = server(
2292            r#"(
2293                handlers: ( bindings: ( sql: (
2294                    url: "http://sqld:8080",
2295                    admin_url: "http://sqld:9090",
2296                    token_env: "BOATRAMP_SQL_TOKEN",
2297                ) ) ),
2298            )"#,
2299        );
2300        let sql = cfg.handlers.unwrap().bindings.sql.unwrap();
2301        assert_eq!(sql.url.as_deref(), Some("http://sqld:8080"));
2302        assert_eq!(sql.admin_url.as_deref(), Some("http://sqld:9090"));
2303        assert_eq!(sql.token_env.as_deref(), Some("BOATRAMP_SQL_TOKEN"));
2304        assert_eq!(sql.admin_token_env, None);
2305    }
2306
2307    #[test]
2308    fn sql_binding_preview_policy() {
2309        let cfg = server(
2310            r#"(
2311                handlers: ( bindings: ( sql: (
2312                    preview_mode: "branch",
2313                    preview_init: "/etc/boatramp/seed.sql",
2314                ) ) ),
2315            )"#,
2316        );
2317        let sql = cfg.handlers.unwrap().bindings.sql.unwrap();
2318        assert_eq!(sql.preview_mode.as_deref(), Some("branch"));
2319        assert_eq!(
2320            sql.preview_init.as_deref(),
2321            Some(Path::new("/etc/boatramp/seed.sql"))
2322        );
2323    }
2324
2325    #[test]
2326    fn sql_binding_external_databases() {
2327        let cfg = server(
2328            r#"(
2329                handlers: ( bindings: ( sql: (
2330                    databases: {
2331                        "analytics": (
2332                            kind: "postgres",
2333                            url_env: "ANALYTICS_PG_URL",
2334                            pool_max: 16,
2335                            read_only: true,
2336                        ),
2337                        "events": (
2338                            kind: "mysql",
2339                            url_env: "EVENTS_MYSQL_URL",
2340                            read_url_env: "EVENTS_MYSQL_REPLICA_URL",
2341                            allow_preview: true,
2342                        ),
2343                    },
2344                ) ) ),
2345            )"#,
2346        );
2347        let sql = cfg.handlers.unwrap().bindings.sql.unwrap();
2348        assert_eq!(sql.databases.len(), 2);
2349
2350        let analytics = &sql.databases["analytics"];
2351        assert_eq!(analytics.kind, "postgres");
2352        assert_eq!(analytics.url_env, "ANALYTICS_PG_URL");
2353        assert_eq!(analytics.pool_max, Some(16));
2354        assert!(analytics.read_only);
2355        assert!(!analytics.allow_preview);
2356        assert!(analytics.read_url_env.is_none());
2357
2358        let events = &sql.databases["events"];
2359        assert_eq!(events.kind, "mysql");
2360        assert_eq!(
2361            events.read_url_env.as_deref(),
2362            Some("EVENTS_MYSQL_REPLICA_URL")
2363        );
2364        assert!(events.allow_preview);
2365        assert!(!events.read_only);
2366    }
2367
2368    #[test]
2369    fn sql_binding_compute_backed_database() {
2370        let cfg = server(
2371            r#"(
2372                handlers: ( bindings: ( sql: (
2373                    databases: {
2374                        "analytics": (
2375                            kind: "postgres",
2376                            compute: "pg",
2377                            database: "analytics",
2378                            user: "app",
2379                            password_env: "PG_APP_PW",
2380                        ),
2381                    },
2382                ) ) ),
2383            )"#,
2384        );
2385        let db = &cfg.handlers.unwrap().bindings.sql.unwrap().databases["analytics"];
2386        assert_eq!(db.kind, "postgres");
2387        assert_eq!(db.compute.as_deref(), Some("pg"));
2388        assert_eq!(db.database.as_deref(), Some("analytics"));
2389        assert_eq!(db.user.as_deref(), Some("app"));
2390        assert_eq!(db.password_env.as_deref(), Some("PG_APP_PW"));
2391        assert!(db.url_env.is_empty(), "compute-backed has no url_env");
2392        assert!(db.validate("analytics").is_ok());
2393    }
2394
2395    #[test]
2396    fn sql_binding_source_is_exactly_one_of_url_or_compute() {
2397        // Neither source → error.
2398        assert!(ExternalDatabaseConfig::default().validate("db").is_err());
2399        // Both sources → error.
2400        let both = ExternalDatabaseConfig {
2401            kind: "postgres".into(),
2402            url_env: "PG_URL".into(),
2403            compute: Some("pg".into()),
2404            ..Default::default()
2405        };
2406        assert!(both.validate("db").is_err());
2407        // `url_env` only → ok.
2408        let url = ExternalDatabaseConfig {
2409            kind: "postgres".into(),
2410            url_env: "PG_URL".into(),
2411            ..Default::default()
2412        };
2413        assert!(url.validate("db").is_ok());
2414        // `compute` without the connection details boatramp can't infer → error.
2415        let bare = ExternalDatabaseConfig {
2416            kind: "postgres".into(),
2417            compute: Some("pg".into()),
2418            ..Default::default()
2419        };
2420        assert!(bare.validate("db").is_err());
2421        // `compute` with database/user + a bring-your-own `password_env` → ok, and
2422        // is *not* a managed credential.
2423        let byo = ExternalDatabaseConfig {
2424            kind: "postgres".into(),
2425            compute: Some("pg".into()),
2426            database: Some("analytics".into()),
2427            user: Some("app".into()),
2428            password_env: Some("PG_APP_PW".into()),
2429            ..Default::default()
2430        };
2431        assert!(byo.validate("db").is_ok());
2432        assert!(!byo.is_managed_credential());
2433        // `compute` with database/user but NO `password_env` → ok, and boatramp
2434        // manages the credential (Phase 2).
2435        let managed = ExternalDatabaseConfig {
2436            kind: "postgres".into(),
2437            compute: Some("pg".into()),
2438            database: Some("analytics".into()),
2439            user: Some("app".into()),
2440            ..Default::default()
2441        };
2442        assert!(managed.validate("db").is_ok());
2443        assert!(managed.is_managed_credential());
2444    }
2445
2446    /// Path to a file at the repo root (two levels up from this crate).
2447    fn repo_root_file(name: &str) -> PathBuf {
2448        Path::new(env!("CARGO_MANIFEST_DIR"))
2449            .join("../..")
2450            .join(name)
2451    }
2452
2453    #[test]
2454    fn shipped_project_example_parses() {
2455        // The example we ship must always parse + compile-check, so it can't drift
2456        // from the schema.
2457        let text = std::fs::read_to_string(repo_root_file("examples/site/project.cfg.example"))
2458            .expect("example project config is present");
2459        let cfg = ProjectConfig::parse(&text).expect("example project config parses");
2460        assert_eq!(cfg.publish.server.as_deref(), Some("http://127.0.0.1:8080"));
2461        assert_eq!(cfg.build.as_ref().unwrap().command, "npm run build");
2462        assert_eq!(
2463            cfg.routing.error_documents.get(&404).map(String::as_str),
2464            Some("/404.html")
2465        );
2466    }
2467
2468    #[test]
2469    fn shipped_server_example_parses() {
2470        let text = std::fs::read_to_string(repo_root_file("boatramp.cfg.example"))
2471            .expect("example server config is present");
2472        let cfg = ServerConfig::parse(&text).expect("example server config parses");
2473        let serve = cfg.serve.expect("example sets a serve section");
2474        assert_eq!(
2475            serve.addr,
2476            Some("0.0.0.0:8080".parse::<std::net::SocketAddr>().unwrap())
2477        );
2478    }
2479
2480    #[test]
2481    fn secrets_section_parses_local_and_vault() {
2482        let local = server(r#"( secrets: ( envelope: "local", kek_file: "/k/kek" ) )"#)
2483            .secrets
2484            .expect("secrets section");
2485        assert_eq!(local.envelope, "local");
2486        assert_eq!(
2487            local.kek_file.as_deref(),
2488            Some(std::path::Path::new("/k/kek"))
2489        );
2490
2491        let vault = server(
2492            r#"( secrets: ( envelope: "vault", vault: ( addr: "https://vault:8200", key: "certs" ) ) )"#,
2493        )
2494        .secrets
2495        .expect("secrets section");
2496        let v = vault.vault.expect("vault subsection");
2497        assert_eq!(v.addr, "https://vault:8200");
2498        assert_eq!(v.key, "certs");
2499        // The token env defaults to VAULT_TOKEN and is never in the file.
2500        assert_eq!(v.token_env, "VAULT_TOKEN");
2501    }
2502
2503    #[test]
2504    fn serve_section_partial_parses() {
2505        // A partial `serve` section parses — unset fields take their defaults.
2506        let cfg = server(r#"( serve: ( addr: "0.0.0.0:8080", protect_previews: true ) )"#);
2507        let serve = cfg.serve.unwrap();
2508        assert_eq!(
2509            serve.addr,
2510            Some("0.0.0.0:8080".parse::<std::net::SocketAddr>().unwrap())
2511        );
2512        assert!(serve.protect_previews);
2513        assert!(!serve.cluster_rate_limit);
2514        assert!(serve.data_dir.is_none());
2515    }
2516
2517    #[test]
2518    fn serve_console_config_parses() {
2519        // Absent ⇒ no console.
2520        let cfg = server(r#"( serve: ( addr: "0.0.0.0:8080" ) )"#);
2521        assert!(cfg.serve.unwrap().console.is_none());
2522        // Explicit console block with host + path.
2523        let cfg = server(
2524            r#"( serve: ( console: (
2525                enabled: true,
2526                host: "console.example.com",
2527                path: "/_console",
2528            ) ) )"#,
2529        );
2530        let console = cfg.serve.unwrap().console.unwrap();
2531        assert!(console.enabled);
2532        assert_eq!(console.host.as_deref(), Some("console.example.com"));
2533        assert_eq!(console.path.as_deref(), Some("/_console"));
2534        // Bare `enabled` ⇒ host/path take their (server-side) defaults.
2535        let cfg = server(r#"( serve: ( console: ( enabled: true ) ) )"#);
2536        let console = cfg.serve.unwrap().console.unwrap();
2537        assert!(console.enabled);
2538        assert!(console.host.is_none() && console.path.is_none());
2539    }
2540}