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