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.
52        var: &'static str,
53        /// Why the value was rejected.
54        reason: String,
55    },
56}
57
58/// Project configuration, loaded from `project.cfg` (RON) in the project folder.
59///
60/// Read by the client commands (`sync`, `build`, `bundle`, `validate`).
61/// Everything is optional; a missing file is the default.
62#[derive(Debug, Default, Deserialize)]
63#[serde(default)]
64pub struct ProjectConfig {
65    /// Where and how to publish this project.
66    pub publish: PublishConfig,
67    /// Optional build step run before `sync`.
68    pub build: Option<BuildConfig>,
69    /// Optional embedded-bundler step (`bundler` feature).
70    pub bundle: Option<BundleConfig>,
71    /// Deploy-scoped routing/handlers config. Folded into the deployment
72    /// manifest at `sync` (so it is atomic with the content and rolls back with
73    /// it). The bulk of a project's config — redirects, rewrites, headers,
74    /// handlers, consumers, crons, streams.
75    pub routing: DeployConfig,
76}
77
78impl ProjectConfig {
79    /// Parse a `project.cfg` document (RON). The `routing` section is
80    /// compile-checked (route patterns, cron schedules, imports) so a bad config
81    /// fails fast.
82    pub fn parse(text: &str) -> Result<Self, ConfigError> {
83        let config: Self = ron_options().from_str(text)?;
84        config.routing.compile_check()?;
85        Ok(config)
86    }
87
88    /// Load from `path` (RON). A missing file yields the default config.
89    pub fn load(path: &Path) -> Result<Self, ConfigError> {
90        match std::fs::read_to_string(path) {
91            Ok(contents) => Self::parse(&contents).map_err(|err| ConfigError::File {
92                path: path.display().to_string(),
93                source: Box::new(err),
94            }),
95            Err(err) if err.kind() == std::io::ErrorKind::NotFound => Ok(Self::default()),
96            Err(err) => Err(err.into()),
97        }
98    }
99}
100
101/// Server daemon configuration, loaded from `boatramp.cfg` (RON). Read by
102/// `boatramp serve`; flags/env override the `serve` values.
103#[derive(Debug, Default, Deserialize)]
104#[serde(default)]
105pub struct ServerConfig {
106    /// Server defaults for `serve` (flag/env override these).
107    pub serve: Option<ServeConfig>,
108    /// Server-side handler runtime config (which backend serves each binding),
109    /// consumed only with the `handlers` feature.
110    pub handlers: Option<HandlersConfig>,
111    /// Self-hosted cluster mode (consumed only with the `cluster` feature).
112    pub cluster: Option<ClusterConfig>,
113    /// Opt-in **compute** backends. Present ⇒ this node
114    /// runs compute workloads via the backends it can offer; absent ⇒ no compute
115    /// (the reconcile loop stays a no-op).
116    pub compute: Option<ComputeConfig>,
117    /// Operator security posture (the hardening knobs): a profile
118    /// preset + overrides, resolved at startup. Absent ⇒ the strict
119    /// `multi-tenant` default. Operator-only — never part of site config.
120    pub security: Option<boatramp_core::security::SecurityConfig>,
121    /// Secrets-at-rest envelope. Absent ⇒ private
122    /// keys stored cleartext in the (replicated) control plane.
123    pub secrets: Option<SecretsConfig>,
124}
125
126/// `secrets` section — envelope encryption for private keys at rest.
127#[cfg_attr(not(feature = "cluster"), allow(dead_code))]
128#[derive(Debug, Clone, Default, Deserialize)]
129#[serde(default, deny_unknown_fields)]
130pub struct SecretsConfig {
131    /// Backend: `"local"` (machine-local AES-256-GCM KEK) or `"vault"` (Vault
132    /// Transit). Empty/other ⇒ no wrapping. In a cluster a local KEK must be the
133    /// **same file on every node** (wrapped certs replicate); Vault avoids that.
134    pub envelope: String,
135    /// Local-KEK key file (`envelope = "local"`). Default
136    /// `<data-dir>/secrets/kek`. Auto-generated `0600` if absent.
137    pub kek_file: Option<PathBuf>,
138    /// Vault Transit config (`envelope = "vault"`).
139    pub vault: Option<VaultSecretsConfig>,
140}
141
142/// Vault Transit settings for `envelope = "vault"`. The token is read from the
143/// environment (`token_env`), never stored in the config file.
144#[cfg_attr(not(all(feature = "cluster", feature = "acme-dns")), allow(dead_code))]
145#[derive(Debug, Clone, Deserialize)]
146#[serde(deny_unknown_fields)]
147pub struct VaultSecretsConfig {
148    /// Vault address, e.g. `https://vault:8200`.
149    pub addr: String,
150    /// Transit key name to wrap under.
151    pub key: String,
152    /// Environment variable holding the Vault token (default `VAULT_TOKEN`).
153    #[serde(default = "default_vault_token_env")]
154    pub token_env: String,
155}
156
157fn default_vault_token_env() -> String {
158    "VAULT_TOKEN".to_string()
159}
160
161impl ServerConfig {
162    /// Parse a `boatramp.cfg` document (RON).
163    pub fn parse(text: &str) -> Result<Self, ConfigError> {
164        Ok(ron_options().from_str(text)?)
165    }
166
167    /// Load from `path` (RON), then layer `BOATRAMP_*` environment overrides on
168    /// top. A missing file yields the default config, so `serve` can be configured
169    /// entirely from the environment (12-factor deployments where dropping a
170    /// `boatramp.cfg` is awkward — fly.io / Cloudflare / containers).
171    pub fn load(path: &Path) -> Result<Self, ConfigError> {
172        let mut config = match std::fs::read_to_string(path) {
173            Ok(contents) => Self::parse(&contents).map_err(|err| ConfigError::File {
174                path: path.display().to_string(),
175                source: Box::new(err),
176            })?,
177            Err(err) if err.kind() == std::io::ErrorKind::NotFound => Self::default(),
178            Err(err) => return Err(err.into()),
179        };
180        config.apply_env_overrides(&EnvSource::Process)?;
181        Ok(config)
182    }
183
184    /// Layer `BOATRAMP_*` environment overrides onto the loaded config for the
185    /// `compute`, `security`, and handler-`sql` sections — the operational knobs
186    /// that were previously reachable only through the `boatramp.cfg` file.
187    ///
188    /// **Precedence: env overrides file.** This matches the existing `serve`
189    /// section (its `#[arg(long, env = …)]` flags already let an env var win over
190    /// the file value), keeping the resolution rule uniform. A set variable
191    /// updates the field even when the file also set it; an unset variable leaves
192    /// the file (or built-in default) untouched. When a section is absent from the
193    /// file but any of its variables are set, the section is materialised from its
194    /// defaults first — so no config file is required to configure it.
195    ///
196    /// `source` supplies the variables (the process environment in production; an
197    /// explicit map in tests), so this stays a pure function of its inputs.
198    fn apply_env_overrides(&mut self, source: &EnvSource) -> Result<(), ConfigError> {
199        // --- compute ---------------------------------------------------------
200        // Materialise `[compute]` only if at least one of its variables is set, so
201        // an unset environment leaves an absent section absent (⇒ no compute).
202        if source.any(COMPUTE_ENV_VARS) {
203            let compute = self.compute.get_or_insert_with(ComputeConfig::default);
204            if let Some(v) = source.get("BOATRAMP_COMPUTE_BRIDGE") {
205                compute.bridge = v;
206            }
207            if let Some(v) = source.get("BOATRAMP_COMPUTE_SUBNET") {
208                compute.subnet = v;
209            }
210            if let Some(v) = source.parse("BOATRAMP_COMPUTE_VCPUS")? {
211                compute.vcpus = v;
212            }
213            if let Some(v) = source.parse("BOATRAMP_COMPUTE_MEM_MIB")? {
214                compute.mem_mib = v;
215            }
216            if let Some(v) = source.get("BOATRAMP_COMPUTE_REGION") {
217                compute.region = Some(v);
218            }
219            if let Some(v) = source.get("BOATRAMP_COMPUTE_SQL_SHIM_URL") {
220                compute.sql_shim_url = Some(v);
221            }
222        }
223
224        // --- security --------------------------------------------------------
225        // Always materialise `[security]` when any knob is set: an absent section
226        // resolves to the strict `multi-tenant` default, and an env override then
227        // layers over that exactly as a file `overrides` block would.
228        if source.any(SECURITY_ENV_VARS) {
229            let security = self
230                .security
231                .get_or_insert_with(boatramp_core::security::SecurityConfig::default);
232            if let Some(v) = source.get("BOATRAMP_SECURITY_PROFILE") {
233                security.profile = Some(v);
234            }
235            let o = &mut security.overrides;
236            if let Some(v) =
237                source.parse_bool("BOATRAMP_SECURITY_ALLOW_UNAUTHENTICATED_PUBLIC_BIND")?
238            {
239                o.allow_unauthenticated_public_bind = Some(v);
240            }
241            if let Some(v) = source.parse("BOATRAMP_SECURITY_MAX_UPLOAD_BYTES")? {
242                o.max_upload_bytes = Some(v);
243            }
244            if let Some(v) = source.parse_bool("BOATRAMP_SECURITY_ALLOW_SITE_UNIX_UPSTREAMS")? {
245                o.allow_site_unix_upstreams = Some(v);
246            }
247            if let Some(v) = source.parse_bool("BOATRAMP_SECURITY_ALLOW_SITE_PRIVATE_UPSTREAMS")? {
248                o.allow_site_private_upstreams = Some(v);
249            }
250            if let Some(v) = source.parse_bool("BOATRAMP_SECURITY_ALLOW_GUEST_PRIVATE_EGRESS")? {
251                o.allow_guest_private_egress = Some(v);
252            }
253            if let Some(v) = source.parse_bool("BOATRAMP_SECURITY_ALLOW_GUEST_SELF_EGRESS")? {
254                o.allow_guest_self_egress = Some(v);
255            }
256            if let Some(v) = source.parse("BOATRAMP_SECURITY_MAX_HANDLER_BLOB_BYTES")? {
257                o.max_handler_blob_bytes = Some(v);
258            }
259            if let Some(v) = source.parse("BOATRAMP_SECURITY_MAX_COMPONENT_BYTES")? {
260                o.max_component_bytes = Some(v);
261            }
262            if let Some(v) = source.parse_bool("BOATRAMP_SECURITY_OIDC_REQUIRE_AUDIENCE")? {
263                o.oidc_require_audience = Some(v);
264            }
265            if let Some(v) = source.parse_bool("BOATRAMP_SECURITY_DOMAIN_VERIFY_ALLOW_PRIVATE")? {
266                o.domain_verify_allow_private = Some(v);
267            }
268            if let Some(v) = source.parse_bool("BOATRAMP_SECURITY_DOMAIN_VERIFY_SELF_SERVE")? {
269                o.domain_verify_self_serve = Some(v);
270            }
271            if let Some(v) = source.parse_bool("BOATRAMP_SECURITY_ALLOW_SHARED_KERNEL_COMPUTE")? {
272                o.allow_shared_kernel_compute = Some(v);
273            }
274            if let Some(v) = source.parse_bool("BOATRAMP_SECURITY_RATELIMIT_FAIL_OPEN")? {
275                o.ratelimit_fail_open = Some(v);
276            }
277            if let Some(v) = source.parse_bool("BOATRAMP_SECURITY_ALLOW_IMPLICIT_ROUTING")? {
278                o.allow_implicit_routing = Some(v);
279            }
280            if let Some(v) = source.parse_bool("BOATRAMP_SECURITY_REQUIRE_POP")? {
281                o.require_pop = Some(v);
282            }
283            if let Some(v) = source.parse_bool("BOATRAMP_SECURITY_REQUIRE_DOMAIN_VERIFICATION")? {
284                o.require_domain_verification = Some(v);
285            }
286        }
287
288        // --- handler sql (`handlers.bindings.sql`) ---------------------------
289        // Materialise the nested `handlers.bindings.sql` chain only when a `sql`
290        // variable is set, so an unset environment doesn't conjure an empty
291        // handlers section. The variables mirror the config path
292        // (`BOATRAMP_HANDLERS_SQL_*`) and cover the cluster-vs-single-node knobs;
293        // secrets stay indirected via `*_TOKEN_ENV` names, never the token itself.
294        if source.any(SQL_ENV_VARS) {
295            let handlers = self.handlers.get_or_insert_with(HandlersConfig::default);
296            let sql = handlers
297                .bindings
298                .sql
299                .get_or_insert_with(SqlBindingConfig::default);
300            if let Some(v) = source.get("BOATRAMP_HANDLERS_SQL_DIR") {
301                sql.dir = Some(PathBuf::from(v));
302            }
303            if let Some(v) = source.get("BOATRAMP_HANDLERS_SQL_URL") {
304                sql.url = Some(v);
305            }
306            if let Some(v) = source.get("BOATRAMP_HANDLERS_SQL_ADMIN_URL") {
307                sql.admin_url = Some(v);
308            }
309            if let Some(v) = source.get("BOATRAMP_HANDLERS_SQL_REPLICA_URL") {
310                sql.replica_url = Some(v);
311            }
312            if let Some(v) = source.get("BOATRAMP_HANDLERS_SQL_TOKEN_ENV") {
313                sql.token_env = Some(v);
314            }
315            if let Some(v) = source.get("BOATRAMP_HANDLERS_SQL_ADMIN_TOKEN_ENV") {
316                sql.admin_token_env = Some(v);
317            }
318            if let Some(v) = source.get("BOATRAMP_HANDLERS_SQL_PREVIEW_MODE") {
319                sql.preview_mode = Some(v);
320            }
321            if let Some(v) = source.get("BOATRAMP_HANDLERS_SQL_PREVIEW_INIT") {
322                sql.preview_init = Some(PathBuf::from(v));
323            }
324        }
325
326        Ok(())
327    }
328}
329
330/// The `BOATRAMP_*` variables that populate the `[compute]` section. Kept as one
331/// list so [`ServerConfig::apply_env_overrides`] can decide whether to materialise
332/// an absent section without repeating the names.
333const COMPUTE_ENV_VARS: &[&str] = &[
334    "BOATRAMP_COMPUTE_BRIDGE",
335    "BOATRAMP_COMPUTE_SUBNET",
336    "BOATRAMP_COMPUTE_VCPUS",
337    "BOATRAMP_COMPUTE_MEM_MIB",
338    "BOATRAMP_COMPUTE_REGION",
339    "BOATRAMP_COMPUTE_SQL_SHIM_URL",
340];
341
342/// The `BOATRAMP_*` variables that populate the `[security]` section.
343const SECURITY_ENV_VARS: &[&str] = &[
344    "BOATRAMP_SECURITY_PROFILE",
345    "BOATRAMP_SECURITY_ALLOW_UNAUTHENTICATED_PUBLIC_BIND",
346    "BOATRAMP_SECURITY_MAX_UPLOAD_BYTES",
347    "BOATRAMP_SECURITY_ALLOW_SITE_UNIX_UPSTREAMS",
348    "BOATRAMP_SECURITY_ALLOW_SITE_PRIVATE_UPSTREAMS",
349    "BOATRAMP_SECURITY_ALLOW_GUEST_PRIVATE_EGRESS",
350    "BOATRAMP_SECURITY_ALLOW_GUEST_SELF_EGRESS",
351    "BOATRAMP_SECURITY_MAX_HANDLER_BLOB_BYTES",
352    "BOATRAMP_SECURITY_MAX_COMPONENT_BYTES",
353    "BOATRAMP_SECURITY_OIDC_REQUIRE_AUDIENCE",
354    "BOATRAMP_SECURITY_DOMAIN_VERIFY_ALLOW_PRIVATE",
355    "BOATRAMP_SECURITY_DOMAIN_VERIFY_SELF_SERVE",
356    "BOATRAMP_SECURITY_ALLOW_SHARED_KERNEL_COMPUTE",
357    "BOATRAMP_SECURITY_RATELIMIT_FAIL_OPEN",
358    "BOATRAMP_SECURITY_ALLOW_IMPLICIT_ROUTING",
359    "BOATRAMP_SECURITY_REQUIRE_POP",
360    "BOATRAMP_SECURITY_REQUIRE_DOMAIN_VERIFICATION",
361];
362
363/// The `BOATRAMP_*` variables that populate `handlers.bindings.sql`.
364const SQL_ENV_VARS: &[&str] = &[
365    "BOATRAMP_HANDLERS_SQL_DIR",
366    "BOATRAMP_HANDLERS_SQL_URL",
367    "BOATRAMP_HANDLERS_SQL_ADMIN_URL",
368    "BOATRAMP_HANDLERS_SQL_REPLICA_URL",
369    "BOATRAMP_HANDLERS_SQL_TOKEN_ENV",
370    "BOATRAMP_HANDLERS_SQL_ADMIN_TOKEN_ENV",
371    "BOATRAMP_HANDLERS_SQL_PREVIEW_MODE",
372    "BOATRAMP_HANDLERS_SQL_PREVIEW_INIT",
373];
374
375/// Where env-override values come from: the real process environment, or an
376/// explicit map for a deterministic unit test. Keeping the lookup behind this enum
377/// lets [`ServerConfig::apply_env_overrides`] be tested without touching (racy,
378/// process-global) `std::env`.
379enum EnvSource {
380    /// The live process environment (`std::env::var`).
381    Process,
382    /// A fixed name→value map (tests only).
383    #[cfg(test)]
384    Map(BTreeMap<String, String>),
385}
386
387impl EnvSource {
388    /// The value of `var`, if set to a non-empty string. An empty value is treated
389    /// as unset so an accidental `VAR=` doesn't clobber a file value with `""`.
390    fn get(&self, var: &str) -> Option<String> {
391        let raw = match self {
392            Self::Process => std::env::var(var).ok(),
393            #[cfg(test)]
394            Self::Map(m) => m.get(var).cloned(),
395        };
396        raw.filter(|v| !v.is_empty())
397    }
398
399    /// Whether any of `vars` is set (to a non-empty value).
400    fn any(&self, vars: &[&str]) -> bool {
401        vars.iter().any(|v| self.get(v).is_some())
402    }
403
404    /// Parse `var` as any [`FromStr`](std::str::FromStr) type (numbers), mapping a
405    /// parse failure to a clear [`ConfigError::Env`]. `Ok(None)` when the variable
406    /// is unset.
407    fn parse<T>(&self, var: &'static str) -> Result<Option<T>, ConfigError>
408    where
409        T: std::str::FromStr,
410        T::Err: std::fmt::Display,
411    {
412        match self.get(var) {
413            Some(raw) => raw.parse::<T>().map(Some).map_err(|e| ConfigError::Env {
414                var,
415                reason: e.to_string(),
416            }),
417            None => Ok(None),
418        }
419    }
420
421    /// Parse `var` as a boolean, accepting the common truthy/falsey spellings
422    /// (`true`/`false`, `1`/`0`, `yes`/`no`, `on`/`off`) case-insensitively so an
423    /// operator isn't surprised by a strict `true`-only parse. `Ok(None)` when
424    /// unset.
425    fn parse_bool(&self, var: &'static str) -> Result<Option<bool>, ConfigError> {
426        match self.get(var) {
427            Some(raw) => match raw.trim().to_ascii_lowercase().as_str() {
428                "true" | "1" | "yes" | "on" => Ok(Some(true)),
429                "false" | "0" | "no" | "off" => Ok(Some(false)),
430                other => Err(ConfigError::Env {
431                    var,
432                    reason: format!("expected a boolean (true/false), got {other:?}"),
433                }),
434            },
435            None => Ok(None),
436        }
437    }
438}
439
440/// How a **managed database** (PLAN-managed-compute-sql) runs its stock image on a
441/// shared-kernel backend, whose entrypoint would otherwise fail under the dropped-`ALL`
442/// hardening. `rootless` (the default) needs no capabilities and works under any
443/// posture; `caps` is the fallback for an image that won't run rootless.
444#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Deserialize)]
445#[serde(rename_all = "lowercase")]
446pub enum ManagedDbPrivilege {
447    /// Run the DB as its image's user (`999:999` for the official postgres/mysql
448    /// images) against a pre-owned volume — no added capabilities, any posture.
449    #[default]
450    Rootless,
451    /// Add the minimal capability set the entrypoint needs (`CHOWN`, `DAC_OVERRIDE`,
452    /// `FOWNER`, `SETUID`, `SETGID`). Honored only under the single-tenant posture.
453    Caps,
454}
455
456/// `compute` section — opt-in compute backends. Present
457/// ⇒ `serve` registers the backends this node can offer and advertises them to
458/// the scheduler; backends are capability-detected (container on Linux, remote
459/// docker when a daemon is reachable, VMM when `/dev/kvm` exists).
460#[derive(Debug, Clone, Deserialize)]
461#[serde(default, deny_unknown_fields)]
462pub struct ComputeConfig {
463    /// Bridge the container veths / VM taps attach to (default `br-boatramp`).
464    pub bridge: String,
465    /// Guest IP subnet (default `10.0.0.0/24`).
466    pub subnet: String,
467    /// vCPUs this node advertises as schedulable (`0` ⇒ detect from the host).
468    pub vcpus: u32,
469    /// Memory (MiB) this node advertises as schedulable (`0` ⇒ a 1 GiB default).
470    pub mem_mib: u32,
471    /// **Static** kernel-signing public keys (`"<alg>:<hex>"`) — the trust anchor
472    /// for the posture-scaled kernel bar. Under `multi-tenant`, a dynamically-
473    /// selected default kernel must carry a signature verifying against one of
474    /// these. Host-access-gated (never in the KV tier); changing it needs a
475    /// restart. Empty ⇒ no kernel may be signed-verified (strict posture then
476    /// accepts none).
477    pub kernel_signing_pubkeys: Vec<String>,
478    /// **Static** allow-list of kernel content hashes (sha256 hex) a dynamic
479    /// default may select under `multi-tenant`. Host-access-gated. Empty ⇒ no
480    /// kernel is allow-listed.
481    pub kernel_allowed_hashes: Vec<String>,
482    /// This node's **region** tag (FA-8). Advertised on the compute `Node` so a
483    /// gateway routing to a `compute:`-backed workload with `--lb nearest` sends
484    /// each request to the nearest replica by its node's region — no manual
485    /// `--region` map. `None` ⇒ region-agnostic.
486    pub region: Option<String>,
487    /// How the remote-Docker backend reports a workload's reachable endpoint.
488    /// `published` (default) publishes the container port on `127.0.0.1:<ephemeral>`
489    /// so a host-native `serve` reaches it on any daemon (incl. Docker Desktop /
490    /// macOS, where the bridge IP is not host-routable); `bridge` routes to the
491    /// container bridge IP directly (only when `serve` shares the daemon's network).
492    pub docker_endpoint: boatramp_docker::DockerEndpoint,
493    /// How the remote-Docker backend backs a workload's persistent volumes.
494    /// `named` (default) attaches a daemon-managed `docker volume` by name (portable
495    /// across daemons + Docker Desktop / macOS); `bind` bind-mounts a host directory
496    /// under `<data_dir>/compute/volumes/<name>` (local daemon only).
497    pub docker_volume_mode: boatramp_docker::DockerVolumeMode,
498    /// Guest-reachable base URL of the compute **sql-shim** (PLAN-compute-bindings) —
499    /// e.g. `http://10.0.0.1:8081` (the compute bridge gateway) or the docker bridge
500    /// gateway. Set ⇒ a workload's `--bind sql` reaches the managed database through a
501    /// listener bound on `0.0.0.0:<port>`. `None` (default) ⇒ compute sql bindings off.
502    #[serde(default, skip_serializing_if = "Option::is_none")]
503    #[cfg_attr(not(feature = "handlers"), allow(dead_code))]
504    pub sql_shim_url: Option<String>,
505    /// Privilege strategy for a managed database's stock image on a shared-kernel
506    /// backend (see [`ManagedDbPrivilege`]). `rootless` by default.
507    #[serde(default)]
508    #[cfg_attr(not(feature = "handlers"), allow(dead_code))]
509    pub managed_db_privilege: ManagedDbPrivilege,
510}
511
512/// The built-in **boatramp kernel-signing public key** (`es256:…`), whose private
513/// half lives as the `KERNEL_SIGNING_KEY` Actions secret in
514/// [`BoatRamp/boatramp-vmlinux`](https://github.com/BoatRamp/boatramp-vmlinux).
515/// Shipped as a default trust anchor so the first-party signed `boatramp-vmlinux`
516/// verifies out of the box under the strict posture. An operator can replace
517/// `kernel_signing_pubkeys` to trust only their own keys.
518pub const BOATRAMP_KERNEL_SIGNING_PUBKEY: &str =
519    "es256:02c4e4af2e9cba6ba6745c513f193622e6674a8b2d0187ebea5612f5b46a7eade4";
520
521/// The first-party signed-kernel content hashes trusted under the **strict**
522/// posture, for this build's **guest arch**. The guest arch mirrors the host: an
523/// x86_64 host boots x86_64 KVM guests (the embedded VMM); an Apple-silicon host
524/// boots aarch64 guests (the Virtualization.framework `vmm-vz` backend). An x86_64
525/// kernel can't boot an aarch64 VM (and vice versa), so each arch trusts only its
526/// own signed `boatramp-vmlinux-<arch>` releases. Bump on each new signed release.
527///
528/// The **relaxed** (single-tenant) posture ignores this list — it verifies only the
529/// content-hash pin — so an operator-supplied kernel boots there regardless of arch.
530fn default_allowed_kernel_hashes() -> Vec<String> {
531    #[cfg(target_arch = "x86_64")]
532    {
533        vec![
534            // v0.2.0 minimal Firecracker 6.1-config kernel: boots under the
535            // firecracker-*binary* backend (ACPI device discovery) but NOT the
536            // in-process embedded VMM. Kept trusted so operators on the currently
537            // published release don't fail strict verification.
538            "cf1e590a9e642be3667131ca35fbf390378a457d8908169d2a169608e299d974".to_string(),
539            // Same kernel + CONFIG_VIRTIO_MMIO_CMDLINE_DEVICES=y (flake `#vmlinux`),
540            // so the embedded VMM binds its virtio-block root over the cmdline
541            // transport. Reproducible build output (deterministic nix build,
542            // verified on KVM); the next signed boatramp-vmlinux release — which
543            // reuses this flake — publishes + signs it, gated by
544            // `vmlinux-release-boot.yml`.
545            "d0dc2098ab2a2a3c1bc72ab61dc85d9e464d798d7e55b6b80525db5ca2f00c5a".to_string(),
546        ]
547    }
548    #[cfg(target_arch = "aarch64")]
549    {
550        vec![
551            // `boatramp-vmlinux-aarch64` v0.2.3 (the Virtualization.framework guest
552            // kernel, flake `#vmlinux` on aarch64-linux — a raw arm64 `Image`). This
553            // release enables the generic PCIe host + virtio-pci so the guest actually
554            // discovers VZ's virtio disk/net/console (the earlier v0.2.2 `be95fb0d…`
555            // built with `CONFIG_PCI` off never booted under VZ and is dropped). This
556            // is the hash of the **published, ES256-signed** release asset (signed by
557            // BOATRAMP_KERNEL_SIGNING_PUBKEY), so a selected `compute.default_kernel`
558            // clears the strict bar out of the box; the boot + scale-to-zero round-trip
559            // was validated against this exact published kernel. NOTE: unlike x86_64,
560            // the aarch64 build is not currently bit-reproducible across build hosts
561            // (same config + size, different build metadata), so pin/verify against the
562            // published `.sha256`/`.sig`, not a local rebuild. Bump on each new release.
563            "d785a48d754e65a4630443301f1fb84cb69cf882336d3cf37055e437b3d8e21f".to_string(),
564        ]
565    }
566    #[cfg(not(any(target_arch = "x86_64", target_arch = "aarch64")))]
567    {
568        Vec::new()
569    }
570}
571
572impl Default for ComputeConfig {
573    fn default() -> Self {
574        Self {
575            bridge: "br-boatramp".to_string(),
576            subnet: "10.0.0.0/24".to_string(),
577            vcpus: 0,
578            mem_mib: 0,
579            kernel_signing_pubkeys: vec![BOATRAMP_KERNEL_SIGNING_PUBKEY.to_string()],
580            kernel_allowed_hashes: default_allowed_kernel_hashes(),
581            region: None,
582            docker_endpoint: boatramp_docker::DockerEndpoint::default(),
583            docker_volume_mode: boatramp_docker::DockerVolumeMode::default(),
584            sql_shim_url: None,
585            managed_db_privilege: ManagedDbPrivilege::default(),
586        }
587    }
588}
589
590/// `cluster` section — self-hosted **cluster mode**. Parsed in
591/// every build so config files stay portable; only *consumed* when the `cluster`
592/// feature is compiled in (`boatramp serve --mode cluster`).
593#[cfg_attr(not(feature = "cluster"), allow(dead_code))]
594#[derive(Debug, Clone, Deserialize)]
595pub struct ClusterConfig {
596    /// Address to bind this node's Raft **peer mesh** on (the `/raft/*` +
597    /// `/stream/*` endpoints) — distinct from the public `serve.addr`.
598    pub listen: SocketAddr,
599    /// The cluster **root anchor set** — the `es256:`/`ed25519:`-tagged public
600    /// keys that define this cluster's identity (a cluster *is* its root key).
601    /// Every join/trust decision verifies against this set. Empty ⇒ falls back to
602    /// `serve.auth_root_public_key` (the single-anchor default). A *set* enables
603    /// make-before-break root rotation.
604    #[serde(default)]
605    pub root_pubkeys: Vec<String>,
606    /// **Seeds** — control-plane addresses of existing cluster members
607    /// (`host:port`), any of which can admit this node. Present ⇒ this node
608    /// **joins** (redeems its `join_token`); absent + no durable state + explicit
609    /// `--cluster-init` ⇒ it **founds**. There is no peer map: members are learned
610    /// from the root-signed join response.
611    #[serde(default)]
612    pub seeds: Vec<String>,
613    /// The single-use bearer **join token** used when `seeds` are set. Keeps the
614    /// secret out of the file via a prefix: `env:VAR`, `path:/file`, or an inline
615    /// literal. Usually supplied via `serve --cluster-join <ticket>` instead.
616    #[serde(default)]
617    pub join_token: Option<String>,
618    /// Directory for this node's **durable** Raft log/state store (node-local;
619    /// distinct from the replicated control plane). Default
620    /// `<data-dir>/raft`.
621    #[serde(default)]
622    pub store_dir: Option<PathBuf>,
623    /// Mesh identity + TLS settings. Absent ⇒ defaults (identity key
624    /// auto-generated under `<data-dir>/mesh/identity.key`).
625    #[serde(default)]
626    pub mesh: Option<MeshConfig>,
627}
628
629/// `[cluster.mesh]` — mesh identity + TLS knobs.
630#[cfg_attr(not(feature = "cluster"), allow(dead_code))]
631#[derive(Debug, Clone, Default, Deserialize)]
632#[serde(default, deny_unknown_fields)]
633pub struct MeshConfig {
634    /// Path to this node's Ed25519 identity key (PKCS#8 DER, `0600`,
635    /// auto-generated). Default `<data-dir>/mesh/identity.key`.
636    pub key_file: Option<PathBuf>,
637    /// Automatic key-rotation cadence (e.g. `"30d"`); `None` = manual only.
638    /// Consumed by the rotation loop.
639    pub key_rotation: Option<String>,
640    /// TTL for a single-use join token (e.g. `"1h"`).
641    pub join_token_ttl: Option<String>,
642    /// Gate mesh `client-write`s behind a control-plane **cluster-write
643    /// capability**, so a trusted peer can't inject arbitrary
644    /// control-plane writes on mesh trust alone. Requires the token root
645    /// **private** key on every node (each mints + presents its own capability);
646    /// default `false`.
647    pub gate_client_writes: Option<bool>,
648}
649
650/// `handlers` section — server-side handler runtime config (read by `serve`).
651/// Parsed in every build (so config files stay portable), but only *consumed*
652/// when the `handlers` feature is compiled in.
653#[cfg_attr(not(feature = "handlers"), allow(dead_code))]
654#[derive(Debug, Clone, Default, Deserialize)]
655#[serde(default)]
656pub struct HandlersConfig {
657    /// `handlers.bindings` — which backend serves each handler binding.
658    pub bindings: BindingsConfig,
659    /// Use the wasmtime **pooling** instance allocator: faster
660    /// instantiation at the cost of a large up-front virtual-memory reservation.
661    /// Off by default — opt in and benchmark for your workload.
662    pub pooling: bool,
663    /// Engine-wide **safety max** on a *connection-bearing* invocation (a site
664    /// handler or a synchronous function/webhook invoke), milliseconds. A route
665    /// or function may declare a *lower* timeout, never a higher one. Kept tight
666    /// on purpose: a client, proxy, and the shared request pool are all blocked
667    /// while a sync handler runs. Absent ⇒ 10s (the historical default). This is
668    /// a node safety ceiling, not a per-invocation budget, and is distinct from
669    /// a per-site `max_timeout_ms`.
670    pub sync_max_timeout_ms: Option<u64>,
671    /// Engine-wide safety max on a *durable async* invocation — the drain that
672    /// runs `?mode=async` calls, workflow steps, cron/queue/blob triggers, and
673    /// `wasi:messaging` consumers, milliseconds. No client is connected and the
674    /// work is retried + dead-lettered, so this can be far larger than the sync
675    /// ceiling: it is what lets a legitimately long background job (e.g. an LLM
676    /// generation) declare and actually get minutes of runtime. Absent ⇒ 15
677    /// minutes. Runs on its own concurrency budget (`async_max_concurrency`), so
678    /// a long job never starves live traffic.
679    pub async_max_timeout_ms: Option<u64>,
680    /// Max concurrent in-flight *async-lane* invocations, kept separate from the
681    /// (larger) request pool so a burst of long background jobs can't exhaust the
682    /// slots live site traffic needs. Absent ⇒ 8.
683    pub async_max_concurrency: Option<usize>,
684    /// Optional CPU **fuel** ceiling for an async-lane invocation. A large async
685    /// timeout bounds only wall-clock; without a fuel bound a CPU-bound guest can
686    /// spin for the whole window. Absent ⇒ unmetered (same as the sync default).
687    pub async_max_fuel: Option<u64>,
688    /// Max wall-clock for a *streaming-lane* response (a `#[handler(stream)]`
689    /// route — SSE, chunked, agent token streaming), milliseconds. A client is
690    /// connected but the body is written incrementally over seconds-to-minutes,
691    /// so this is far larger than the sync ceiling. Runs on its own concurrency
692    /// budget (`streaming_max_concurrency`), isolated from both the fast request
693    /// pool and the async drain. Absent ⇒ 15 minutes.
694    pub streaming_max_timeout_ms: Option<u64>,
695    /// Max concurrent in-flight *streaming-lane* responses, kept separate from the
696    /// request pool and the async drain so a burst of long-lived streams starves
697    /// neither. Absent ⇒ 64.
698    pub streaming_max_concurrency: Option<usize>,
699    /// Optional CPU **fuel** ceiling for a streaming-lane response. Absent ⇒
700    /// unmetered (a stream is I/O-bound on the client, not CPU-bound).
701    pub streaming_max_fuel: Option<u64>,
702    /// Optional ceiling on a guest's **outbound** `wasi:http` call — the connect
703    /// and time-to-first-byte wait — milliseconds, independent of the invocation
704    /// timeout, so a hung upstream is bounded on its own terms. The streaming
705    /// (between-bytes) timeout is left at wasmtime's default so a slow token
706    /// stream is not cut mid-flight. Absent ⇒ wasmtime's default.
707    pub outbound_timeout_ms: Option<u64>,
708}
709
710/// `handlers.bindings` — per-binding backend configuration. kv/blob reuse the
711/// server's own KV/Storage backends (per-site prefixed); `sql` is the single
712/// libsql backend, whose single-node-vs-cluster split is the only choice.
713#[cfg_attr(not(feature = "handlers"), allow(dead_code))]
714#[derive(Debug, Clone, Default, Deserialize)]
715#[serde(default)]
716pub struct BindingsConfig {
717    /// `handlers.bindings.sql` — libsql settings. Absent ⇒ single-node,
718    /// per-site embedded files under `<data-dir>/handlers-sql`.
719    pub sql: Option<SqlBindingConfig>,
720}
721
722/// libsql settings for the handler `sql` binding — the single SQL backend. Each
723/// site gets a real database boundary (an embedded file per site, or a sqld
724/// namespace per site), never schema separation (which arbitrary guest SQL
725/// escapes). Setting `url` switches from single-node to a shared sqld cluster;
726/// everything else stays identical.
727#[cfg_attr(not(feature = "handlers"), allow(dead_code))]
728#[derive(Debug, Clone, Default, Deserialize)]
729#[serde(default)]
730pub struct SqlBindingConfig {
731    /// Single-node: root directory for the per-site embedded database files
732    /// (default `<data-dir>/handlers-sql`). Ignored when `url` is set.
733    pub dir: Option<PathBuf>,
734    /// Cluster: base sqld data URL (e.g. `http://sqld:8080`). When set, each
735    /// site is a sqld namespace addressed as a subdomain of this URL; `admin_url`
736    /// is then required.
737    pub url: Option<String>,
738    /// Cluster: sqld admin API base URL (e.g. `http://sqld:9090`) for creating
739    /// per-site namespaces. Required when `url` is set.
740    pub admin_url: Option<String>,
741    /// Cluster: optional sqld **read-replica** data URL. When set, handlers'
742    /// read-only `sql` transactions (`open-read-only`) route to this endpoint
743    /// while writes stay on `url` (reads → replicas, writes → primary).
744    /// Reads may lag (eventually consistent). Ignored in
745    /// single-node mode (no `url`).
746    pub replica_url: Option<String>,
747    /// Name of the env var holding the sqld data auth token (optional; never
748    /// the token itself in-file).
749    pub token_env: Option<String>,
750    /// Name of the env var holding the sqld admin API auth key (optional).
751    pub admin_token_env: Option<String>,
752    /// How preview deployments get their SQL database: `empty` (default — a
753    /// fresh isolated db), `branch` (a consistent copy of the site's live db;
754    /// single-node only), or `shared` (the site's live db). See
755    /// `boatramp_core::sql::PreviewSqlMode`.
756    pub preview_mode: Option<String>,
757    /// Path to an idempotent SQL script run when an `empty` preview database is
758    /// first opened (e.g. schema/seed). Ignored in `branch`/`shared` modes.
759    pub preview_init: Option<PathBuf>,
760    /// `handlers.bindings.sql.databases` — external **bring-your-own** databases,
761    /// each opened by name via `sql.open("<name>")`. An operator-configured
762    /// Postgres/MySQL whose *isolation is the operator's* (it's their database),
763    /// so these bypass the per-site libsql boundary and are reachable by any
764    /// handler/function granted the `sql` binding. Needs the `sql-postgres` /
765    /// `sql-mysql` build feature for the engine. A name here shadows the same
766    /// name on the managed libsql default.
767    pub databases: BTreeMap<String, ExternalDatabaseConfig>,
768}
769
770/// One external SQL database for the handler `sql` binding. Its **source** is one
771/// of two mutually-exclusive forms:
772///  - `url_env` — a **bring-your-own** database: the connection URL is a secret,
773///    named indirectly by an env var (never written in the config file).
774///  - `compute` — a database **boatramp runs** as a compute workload: boatramp
775///    derives the connection from the workload's live endpoint (host\:port) plus
776///    the `database`/`user`/`password_env` here, so there is no URL to hand-map and
777///    it follows the workload across restarts (PLAN-managed-compute-sql).
778#[cfg_attr(not(feature = "handlers"), allow(dead_code))]
779#[derive(Debug, Clone, Default, Deserialize)]
780#[serde(default)]
781pub struct ExternalDatabaseConfig {
782    /// Engine: `postgres` (aliases `postgresql`/`pg`) or `mysql` (alias
783    /// `mariadb`).
784    pub kind: String,
785    /// Name of the env var holding the connection URL (e.g.
786    /// `postgres://user:pw@host/db`). Required unless `compute` is set.
787    pub url_env: String,
788    /// Optional env var holding a **read-replica** connection URL. When set,
789    /// `open-read-only` transactions route there; writes stay on `url_env`.
790    pub read_url_env: Option<String>,
791    /// The name of a **compute workload** (a Postgres/MySQL server boatramp runs)
792    /// to source this database from, instead of `url_env`. boatramp resolves the
793    /// workload's live endpoint and builds the connection. Mutually exclusive with
794    /// `url_env`.
795    pub compute: Option<String>,
796    /// The database name inside the compute-backed server (non-secret).
797    pub database: Option<String>,
798    /// The connecting user for the compute-backed server (non-secret).
799    pub user: Option<String>,
800    /// Env var holding the password for `user` on the compute-backed server.
801    /// **Omit to let boatramp fully manage the credential** (PLAN-managed-compute-sql
802    /// Phase 2): it generates a strong password once, seals it with the `[secrets]`
803    /// envelope, injects it into the DB workload's server-init env at launch, and
804    /// connects the handler with it — the operator sets no DB secret at all. Set it
805    /// only to bring your own password for the compute-backed server.
806    pub password_env: Option<String>,
807    /// Maximum pooled connections (default 8).
808    pub pool_max: Option<u32>,
809    /// Open every transaction `READ ONLY` (the engine rejects writes) — for a
810    /// database functions should only read.
811    pub read_only: bool,
812    /// Permit **preview** deployments to reach this database. Default `false`: a
813    /// preview is refused, so it can never touch the operator's live external DB.
814    pub allow_preview: bool,
815    /// Connection/acquire timeout in seconds (default 10).
816    pub connect_timeout_secs: Option<u64>,
817}
818
819impl ExternalDatabaseConfig {
820    /// Validate the source is well-formed: **exactly one** of `url_env` /
821    /// `compute`, and a `compute`-backed database has the connection details
822    /// boatramp can't infer (`database` + `user`). `password_env` is **optional** —
823    /// omit it to let boatramp manage the credential (Phase 2). `name` is the
824    /// binding name, for the error message.
825    #[cfg_attr(not(feature = "handlers"), allow(dead_code))]
826    pub fn validate(&self, name: &str) -> Result<(), String> {
827        let has_url = !self.url_env.is_empty();
828        let has_compute = self.compute.as_deref().is_some_and(|c| !c.is_empty());
829        match (has_url, has_compute) {
830            (true, true) => Err(format!(
831                "sql database {name:?}: set exactly one of `url_env` or `compute`, not both"
832            )),
833            (false, false) => Err(format!(
834                "sql database {name:?}: needs a source — set `url_env` (bring-your-own) or \
835                 `compute` (a database boatramp runs)"
836            )),
837            (false, true) => {
838                // `database` + `user` are non-secret and can't be inferred; a missing
839                // `password_env` is *not* an error — it selects the managed credential.
840                for (field, val) in [("database", &self.database), ("user", &self.user)] {
841                    if val.as_deref().is_none_or(str::is_empty) {
842                        return Err(format!(
843                            "sql database {name:?}: a `compute`-backed database requires `{field}`"
844                        ));
845                    }
846                }
847                Ok(())
848            }
849            (true, false) => Ok(()),
850        }
851    }
852
853    /// Whether this compute-backed database uses a **boatramp-managed** credential
854    /// (Phase 2): `compute` is set and no `password_env` was supplied.
855    #[cfg_attr(not(feature = "handlers"), allow(dead_code))]
856    pub fn is_managed_credential(&self) -> bool {
857        self.compute.as_deref().is_some_and(|c| !c.is_empty())
858            && self.password_env.as_deref().is_none_or(str::is_empty)
859    }
860}
861
862/// The signing algorithm for a signer that can choose one (`Local`, `Vault`,
863/// `Pkcs11`). ES256 is the portable default; the cloud KMS backends are ES256-only
864/// and ignore this. Written as a RON enum: `alg: Es256` / `alg: Ed25519`.
865#[derive(Debug, Clone, Copy, Default, Deserialize)]
866pub enum SignerAlg {
867    /// ECDSA P-256 (COSE ES256) — the default.
868    #[default]
869    Es256,
870    /// Ed25519 (COSE EdDSA).
871    Ed25519,
872}
873
874impl SignerAlg {
875    fn to_token_alg(self) -> boatramp_core::cose::TokenAlg {
876        match self {
877            Self::Es256 => boatramp_core::cose::TokenAlg::Es256,
878            Self::Ed25519 => boatramp_core::cose::TokenAlg::Ed25519,
879        }
880    }
881}
882
883/// External token signer selector (`serve.signer`). Maps to
884/// [`boatramp_server::signer::SignerConfig`]; secrets (tokens/PINs) are resolved
885/// from the named env vars at startup, never stored in config. Written as a RON
886/// enum — `signer: Vault(...)`, `signer: AwsKms(...)`, `signer: Pkcs11(...)`, ….
887#[derive(Debug, Clone, Deserialize)]
888#[serde(deny_unknown_fields)]
889pub enum AuthSignerConfig {
890    /// In-process key (`"<alg>:<hex>"`).
891    Local {
892        /// The private key spec, `"<alg>:<hex>"`.
893        private_key: String,
894    },
895    /// HashiCorp Vault Transit key.
896    Vault {
897        /// Vault base address.
898        address: String,
899        /// The Transit key name.
900        key: String,
901        /// Env var holding the Vault token.
902        token_env: String,
903        /// The key algorithm.
904        #[serde(default)]
905        alg: SignerAlg,
906    },
907    /// AWS KMS asymmetric key (ES256).
908    AwsKms {
909        /// The KMS key id or ARN.
910        key_id: String,
911        /// Optional region override.
912        #[serde(default)]
913        region: Option<String>,
914    },
915    /// GCP Cloud KMS key version (ES256).
916    GcpKms {
917        /// The key-version resource name.
918        key_version: String,
919        /// Env var holding a GCP OAuth2 access token.
920        access_token_env: String,
921    },
922    /// Azure Key Vault key (ES256).
923    AzureKv {
924        /// The vault base URL.
925        vault_url: String,
926        /// The key name.
927        key: String,
928        /// The key version.
929        key_version: String,
930        /// Env var holding an Azure AD access token.
931        access_token_env: String,
932    },
933    /// PKCS#11 HSM key.
934    Pkcs11 {
935        /// Path to the PKCS#11 module.
936        module: String,
937        /// The token label.
938        token_label: String,
939        /// The key's `CKA_LABEL`.
940        key_label: String,
941        /// Env var holding the user PIN.
942        pin_env: String,
943        /// The key algorithm.
944        #[serde(default)]
945        alg: SignerAlg,
946    },
947}
948
949impl AuthSignerConfig {
950    /// Map the config-file form to the server's runtime [`SignerConfig`].
951    pub fn to_signer_config(&self) -> boatramp_server::signer::SignerConfig {
952        use boatramp_server::signer::SignerConfig;
953        match self {
954            Self::Local { private_key } => SignerConfig::Local {
955                private_key: private_key.clone(),
956            },
957            Self::Vault {
958                address,
959                key,
960                token_env,
961                alg,
962            } => SignerConfig::Vault {
963                address: address.clone(),
964                key: key.clone(),
965                token_env: token_env.clone(),
966                alg: alg.to_token_alg(),
967            },
968            Self::AwsKms { key_id, region } => SignerConfig::AwsKms {
969                key_id: key_id.clone(),
970                region: region.clone(),
971            },
972            Self::GcpKms {
973                key_version,
974                access_token_env,
975            } => SignerConfig::GcpKms {
976                key_version: key_version.clone(),
977                access_token_env: access_token_env.clone(),
978            },
979            Self::AzureKv {
980                vault_url,
981                key,
982                key_version,
983                access_token_env,
984            } => SignerConfig::AzureKv {
985                vault_url: vault_url.clone(),
986                key: key.clone(),
987                key_version: key_version.clone(),
988                access_token_env: access_token_env.clone(),
989            },
990            Self::Pkcs11 {
991                module,
992                token_label,
993                key_label,
994                pin_env,
995                alg,
996            } => SignerConfig::Pkcs11 {
997                module: module.clone(),
998                token_label: token_label.clone(),
999                key_label: key_label.clone(),
1000                pin_env: pin_env.clone(),
1001                alg: alg.to_token_alg(),
1002            },
1003        }
1004    }
1005}
1006
1007/// `serve` section — server defaults, overridden by flags/env.
1008#[derive(Debug, Clone, Default, Deserialize)]
1009#[serde(default)]
1010pub struct ServeConfig {
1011    /// Bind address (e.g. `0.0.0.0:8080`).
1012    pub addr: Option<SocketAddr>,
1013    /// Data directory for filesystem backends.
1014    pub data_dir: Option<PathBuf>,
1015    /// Token root **private** key (hex) — issuing node: verifies *and* mints
1016    /// tokens / OIDC exchanges.
1017    pub auth_root_private_key: Option<String>,
1018    /// Token root **public** key (hex) — verify-only node.
1019    pub auth_root_public_key: Option<String>,
1020    /// Single-use bootstrap secret enabling `POST /api/tokens/bootstrap` (mint the
1021    /// first token without an admin bearer). Prefer the `BOATRAMP_BOOTSTRAP_SECRET`
1022    /// env / `--bootstrap-secret` flag so it isn't persisted in the config file.
1023    pub bootstrap_secret: Option<String>,
1024    /// External token signer (`[serve.signer]`): mint with a
1025    /// KMS/HSM/Vault-held root key instead of an in-process `auth_root_private_key`.
1026    /// Absent ⇒ the in-process key. When set, its public half is the trust anchor.
1027    pub signer: Option<AuthSignerConfig>,
1028    /// Reject blob uploads larger than this many bytes.
1029    pub max_upload_bytes: Option<u64>,
1030    /// Abort an upload that stalls for longer than this many seconds.
1031    pub upload_idle_timeout_secs: Option<u64>,
1032    /// Cap on simultaneous blob uploads.
1033    pub max_concurrent_uploads: Option<usize>,
1034    /// In a TLS mode, bind this plain-HTTP address on a second listener that
1035    /// redirects to HTTPS (dual-listener). Only read in `tls` builds.
1036    #[cfg_attr(not(feature = "tls"), allow(dead_code))]
1037    pub http_redirect_addr: Option<SocketAddr>,
1038    /// Site to serve for a `Host` matching no domain, instead of 404.
1039    pub default_site: Option<String>,
1040    /// The fleet's canonical public origin (e.g. `https://cp.example.com`) that a
1041    /// per-request proof-of-possession must bind to (`aud`). Required for
1042    /// holder-bound (`cnf`/PoP) tokens to be usable — a proof's origin is compared
1043    /// against this value, never against a `Host`/`X-Forwarded-*` header.
1044    pub pop_origin: Option<String>,
1045    /// Require a valid control-plane token to view deployment previews.
1046    pub protect_previews: bool,
1047    /// Rate-limit cluster-wide via the control-plane KV instead of per node.
1048    pub cluster_rate_limit: bool,
1049    /// Keep the config cache coherent across processes sharing one KV via the
1050    /// changelog.
1051    pub shared_cache_coherence: bool,
1052    /// Cloud blob-change notification provisioning tier (FA-5b2): how boatramp
1053    /// obtains the native event pipeline (S3→SQS) that backs a `blob` trigger —
1054    /// `dry-run` (print the recipe), `provision` (create + retract), `verify-only`
1055    /// (operator pre-wired), or `refuse` (fail closed). Absent ⇒ no provisioning:
1056    /// `blob` triggers then work only on a self-watching backend (fs). Only wired
1057    /// for the S3 backend (`--features s3`).
1058    pub blob_notify_tier: Option<boatramp_core::blob_notify::ProvisionTier>,
1059    /// The AWS account id used to scope the provisioned SQS queue's `SendMessage`
1060    /// policy (`aws:SourceAccount`). Required when `blob_notify_tier` provisions.
1061    pub blob_notify_account_id: Option<String>,
1062    /// `[serve.console]` — the embedded web management console. Absent (or
1063    /// `enabled: false`) ⇒ not served. This is the **baseline** for the dynamic
1064    /// `console.*` daemon-config override, which can enable/move it at runtime
1065    /// (`boatramp config set console.enabled true`) without a restart.
1066    pub console: Option<ConsoleConfig>,
1067}
1068
1069/// `[serve.console]` — the embedded web console (a Wasm SPA baked into the
1070/// binary with the `console` build feature). Opt-in: the static shell holds no
1071/// secrets and the `/api` it drives is token-gated, so it is served
1072/// **unauthenticated** at a deliberately obscure path (a bearer token can't gate
1073/// a top-level browser navigation anyway — the path is the obscurity, the token
1074/// is the real gate).
1075#[cfg_attr(not(feature = "console"), allow(dead_code))]
1076#[derive(Debug, Clone, Default, Deserialize)]
1077#[serde(default, deny_unknown_fields)]
1078pub struct ConsoleConfig {
1079    /// Serve the embedded console (default `false`). Requires the `console` build
1080    /// feature; enabling it in a build without that feature is a logged no-op.
1081    pub enabled: bool,
1082    /// Host(s) the console answers on: `*` (any host, the default), an exact host
1083    /// (`console.example.com`), or a leading-wildcard (`*.example.com`).
1084    pub host: Option<String>,
1085    /// URL path prefix the console mounts at (default `/_console`). Kept under the
1086    /// reserved `/_` namespace so it never collides with a published site path.
1087    pub path: Option<String>,
1088}
1089
1090/// `publish` section — where and what to deploy (the `sync` target).
1091#[derive(Debug, Default, Deserialize)]
1092#[serde(default)]
1093pub struct PublishConfig {
1094    /// Base URL of the boatramp server (e.g. `https://pad.example.com`).
1095    pub server: Option<String>,
1096    /// Site name to publish to.
1097    pub site: Option<String>,
1098    /// API token for the control plane (or set `BOATRAMP_TOKEN`).
1099    pub token: Option<String>,
1100    /// Project this site belongs to (overrides with `--project` / `BOATRAMP_PROJECT`).
1101    pub project: Option<String>,
1102}
1103
1104/// `build` section.
1105#[derive(Debug, Clone, Deserialize)]
1106pub struct BuildConfig {
1107    /// Shell command to run (e.g. `npm run build`).
1108    pub command: String,
1109    /// Directory the build emits, published by `sync` (e.g. `dist`).
1110    #[serde(default)]
1111    pub output: Option<String>,
1112}
1113
1114/// `bundle` section — the in-process Rust bundler (`bundler` feature).
1115#[derive(Debug, Clone, Default, Deserialize)]
1116#[serde(default)]
1117pub struct BundleConfig {
1118    /// Output directory for bundled assets (e.g. `dist`).
1119    #[serde(default = "default_bundle_outdir")]
1120    pub outdir: String,
1121    /// JS/TS entry points bundled by Rolldown (tree-shaken, code-split).
1122    pub js: Vec<String>,
1123    /// CSS entry points bundled by lightningcss (`@import` inlined).
1124    pub css: Vec<String>,
1125    /// Minify output (default true).
1126    #[serde(default = "default_true")]
1127    pub minify: bool,
1128}
1129
1130fn default_bundle_outdir() -> String {
1131    "dist".to_string()
1132}
1133
1134fn default_true() -> bool {
1135    true
1136}
1137
1138#[cfg(test)]
1139mod tests {
1140    use super::*;
1141
1142    fn project(text: &str) -> ProjectConfig {
1143        ron_options().from_str(text).unwrap()
1144    }
1145
1146    fn server(text: &str) -> ServerConfig {
1147        ron_options().from_str(text).unwrap()
1148    }
1149
1150    /// Build an [`EnvSource::Map`] from `(name, value)` pairs for deterministic
1151    /// override tests (no process-global `std::env` mutation).
1152    fn env(pairs: &[(&str, &str)]) -> EnvSource {
1153        EnvSource::Map(
1154            pairs
1155                .iter()
1156                .map(|(k, v)| (k.to_string(), v.to_string()))
1157                .collect(),
1158        )
1159    }
1160
1161    #[test]
1162    fn env_overrides_configure_all_three_sections_with_no_file() {
1163        // The crux of the ask: with NO `boatramp.cfg` at all (the default config),
1164        // env vars alone materialise + populate the compute, security, and handler
1165        // `sql` sections. `ServerConfig::default()` has all three absent.
1166        let mut cfg = ServerConfig::default();
1167        assert!(cfg.compute.is_none() && cfg.security.is_none() && cfg.handlers.is_none());
1168
1169        cfg.apply_env_overrides(&env(&[
1170            ("BOATRAMP_COMPUTE_VCPUS", "8"),
1171            ("BOATRAMP_COMPUTE_MEM_MIB", "4096"),
1172            ("BOATRAMP_COMPUTE_REGION", "eu-central"),
1173            ("BOATRAMP_SECURITY_PROFILE", "single-tenant"),
1174            ("BOATRAMP_SECURITY_ALLOW_SITE_PRIVATE_UPSTREAMS", "true"),
1175            ("BOATRAMP_SECURITY_MAX_UPLOAD_BYTES", "1048576"),
1176            ("BOATRAMP_HANDLERS_SQL_URL", "http://sqld:8080"),
1177            ("BOATRAMP_HANDLERS_SQL_ADMIN_URL", "http://sqld:9090"),
1178        ]))
1179        .expect("valid env overrides apply");
1180
1181        // compute: the section now exists with the env values (and defaults elsewhere).
1182        let compute = cfg.compute.expect("compute materialised from env");
1183        assert_eq!(compute.vcpus, 8);
1184        assert_eq!(compute.mem_mib, 4096);
1185        assert_eq!(compute.region.as_deref(), Some("eu-central"));
1186        assert_eq!(compute.bridge, "br-boatramp"); // untouched default
1187
1188        // security: profile + an override both took, and the posture resolves.
1189        let security = cfg.security.expect("security materialised from env");
1190        assert_eq!(security.profile.as_deref(), Some("single-tenant"));
1191        let posture = security.resolve().expect("resolves");
1192        assert!(posture.allow_site_private_upstreams);
1193        assert_eq!(posture.max_upload_bytes, 1_048_576);
1194
1195        // handler sql: the nested handlers.bindings.sql chain was created.
1196        let sql = cfg
1197            .handlers
1198            .expect("handlers materialised from env")
1199            .bindings
1200            .sql
1201            .expect("sql binding materialised from env");
1202        assert_eq!(sql.url.as_deref(), Some("http://sqld:8080"));
1203        assert_eq!(sql.admin_url.as_deref(), Some("http://sqld:9090"));
1204    }
1205
1206    #[test]
1207    fn env_override_wins_over_file_value_but_unset_defers() {
1208        // A file that set each section; env then overrides one field per section
1209        // and leaves the rest of the file value in place (precedence: env > file).
1210        let mut cfg = server(
1211            r#"(
1212                compute: ( vcpus: 2, mem_mib: 512, region: "us-east" ),
1213                security: ( profile: "multi-tenant" ),
1214                handlers: ( bindings: ( sql: ( url: "http://file:8080", admin_url: "http://file:9090" ) ) ),
1215            )"#,
1216        );
1217
1218        cfg.apply_env_overrides(&env(&[
1219            ("BOATRAMP_COMPUTE_VCPUS", "16"),
1220            ("BOATRAMP_SECURITY_PROFILE", "dev"),
1221            ("BOATRAMP_HANDLERS_SQL_URL", "http://env:8080"),
1222        ]))
1223        .expect("valid env overrides apply");
1224
1225        let compute = cfg.compute.unwrap();
1226        assert_eq!(compute.vcpus, 16, "env wins over the file vcpus");
1227        assert_eq!(compute.mem_mib, 512, "unset env defers to the file mem_mib");
1228        assert_eq!(
1229            compute.region.as_deref(),
1230            Some("us-east"),
1231            "unset env defers to the file region"
1232        );
1233
1234        assert_eq!(
1235            cfg.security.unwrap().profile.as_deref(),
1236            Some("dev"),
1237            "env profile wins over the file profile"
1238        );
1239
1240        let sql = cfg.handlers.unwrap().bindings.sql.unwrap();
1241        assert_eq!(
1242            sql.url.as_deref(),
1243            Some("http://env:8080"),
1244            "env wins over the file sql url"
1245        );
1246        assert_eq!(
1247            sql.admin_url.as_deref(),
1248            Some("http://file:9090"),
1249            "unset env defers to the file sql admin_url"
1250        );
1251    }
1252
1253    #[test]
1254    fn env_overrides_leave_unmentioned_sections_absent() {
1255        // With no relevant env vars set, an empty config stays empty — the sections
1256        // are materialised only on demand, so an unset environment adds nothing.
1257        let mut cfg = ServerConfig::default();
1258        cfg.apply_env_overrides(&env(&[("SOME_UNRELATED_VAR", "x")]))
1259            .expect("no-op env applies");
1260        assert!(cfg.compute.is_none());
1261        assert!(cfg.security.is_none());
1262        assert!(cfg.handlers.is_none());
1263    }
1264
1265    #[test]
1266    fn env_bool_accepts_common_spellings_and_rejects_garbage() {
1267        // Truthy/falsey spellings all parse.
1268        for (raw, want) in [
1269            ("true", true),
1270            ("1", true),
1271            ("YES", true),
1272            ("On", true),
1273            ("false", false),
1274            ("0", false),
1275            ("no", false),
1276            ("OFF", false),
1277        ] {
1278            let mut cfg = ServerConfig::default();
1279            cfg.apply_env_overrides(&env(&[("BOATRAMP_SECURITY_REQUIRE_POP", raw)]))
1280                .expect("boolean parses");
1281            assert_eq!(
1282                cfg.security.unwrap().overrides.require_pop,
1283                Some(want),
1284                "{raw:?} ⇒ {want}"
1285            );
1286        }
1287        // A non-boolean value is a clear error, not a silent default.
1288        let mut cfg = ServerConfig::default();
1289        let err = cfg
1290            .apply_env_overrides(&env(&[("BOATRAMP_SECURITY_REQUIRE_POP", "maybe")]))
1291            .expect_err("garbage boolean is rejected");
1292        assert!(matches!(
1293            err,
1294            ConfigError::Env {
1295                var: "BOATRAMP_SECURITY_REQUIRE_POP",
1296                ..
1297            }
1298        ));
1299    }
1300
1301    #[test]
1302    fn env_number_parse_error_names_the_variable() {
1303        // A non-numeric numeric var is rejected with the variable named.
1304        let mut cfg = ServerConfig::default();
1305        let err = cfg
1306            .apply_env_overrides(&env(&[("BOATRAMP_COMPUTE_VCPUS", "lots")]))
1307            .expect_err("garbage number is rejected");
1308        match err {
1309            ConfigError::Env { var, .. } => assert_eq!(var, "BOATRAMP_COMPUTE_VCPUS"),
1310            other => panic!("expected ConfigError::Env, got {other:?}"),
1311        }
1312    }
1313
1314    #[test]
1315    fn empty_env_value_is_treated_as_unset() {
1316        // `VAR=` (empty) must not clobber a file value with an empty string.
1317        let mut cfg = server(r#"( compute: ( region: "us-east" ) )"#);
1318        cfg.apply_env_overrides(&env(&[("BOATRAMP_COMPUTE_REGION", "")]))
1319            .expect("empty env applies as a no-op");
1320        assert_eq!(
1321            cfg.compute.unwrap().region.as_deref(),
1322            Some("us-east"),
1323            "an empty env value leaves the file value in place"
1324        );
1325    }
1326
1327    #[test]
1328    fn empty_project_config_is_default() {
1329        let cfg = project("()");
1330        assert!(cfg.publish.server.is_none());
1331        assert!(cfg.publish.site.is_none());
1332        assert!(cfg.build.is_none());
1333        assert!(cfg.bundle.is_none());
1334        // Routing defaults: schema v1, the single default index candidate.
1335        assert_eq!(cfg.routing.version, 1);
1336        assert_eq!(cfg.routing.index, vec!["index.html".to_string()]);
1337    }
1338
1339    #[test]
1340    fn serve_signer_config_parses_and_maps_each_backend() {
1341        use boatramp_core::cose::TokenAlg;
1342        use boatramp_server::signer::SignerConfig;
1343
1344        // RON-native enum tagging (`Vault(...)`); `IMPLICIT_SOME` lets the optional
1345        // fields (region) take a bare value or be omitted (→ None). This is the
1346        // exact RON documented in the Authentication guide.
1347        let vault = server(
1348            r#"( serve: ( signer: Vault(
1349                address: "https://vault.example:8200",
1350                key: "boatramp-root",
1351                token_env: "VAULT_TOKEN",
1352                alg: Ed25519,
1353            ) ) )"#,
1354        );
1355        match vault.serve.unwrap().signer.unwrap().to_signer_config() {
1356            SignerConfig::Vault {
1357                address,
1358                key,
1359                token_env,
1360                alg,
1361            } => {
1362                assert_eq!(address, "https://vault.example:8200");
1363                assert_eq!(key, "boatramp-root");
1364                assert_eq!(token_env, "VAULT_TOKEN");
1365                assert_eq!(alg, TokenAlg::Ed25519);
1366            }
1367            other => panic!("expected Vault, got {other:?}"),
1368        }
1369
1370        // AWS KMS: region omitted → None; PKCS#11: alg omitted → the ES256 default.
1371        let aws =
1372            server(r#"( serve: ( signer: AwsKms(key_id: "arn:aws:kms:eu-west-1:1:key/abc") ) )"#);
1373        assert!(matches!(
1374            aws.serve.unwrap().signer.unwrap().to_signer_config(),
1375            SignerConfig::AwsKms { region: None, .. }
1376        ));
1377
1378        let hsm = server(
1379            r#"( serve: ( signer: Pkcs11(
1380                module: "/usr/lib/softhsm/libsofthsm2.so",
1381                token_label: "boatramp",
1382                key_label: "root",
1383                pin_env: "HSM_PIN",
1384            ) ) )"#,
1385        );
1386        match hsm.serve.unwrap().signer.unwrap().to_signer_config() {
1387            SignerConfig::Pkcs11 { alg, .. } => assert_eq!(alg, TokenAlg::Es256),
1388            other => panic!("expected Pkcs11, got {other:?}"),
1389        }
1390    }
1391
1392    #[test]
1393    fn project_config_parses_publish_build_and_routing() {
1394        let cfg = project(
1395            r#"(
1396                publish: ( server: "http://127.0.0.1:8080", site: "demo" ),
1397                build: ( command: "npm run build", output: "dist" ),
1398                routing: (
1399                    clean_urls: true,
1400                    redirects: [ (from: "/old/:slug", to: "/new/:slug", status: 301) ],
1401                ),
1402            )"#,
1403        );
1404        assert_eq!(cfg.publish.server.as_deref(), Some("http://127.0.0.1:8080"));
1405        assert_eq!(cfg.publish.site.as_deref(), Some("demo"));
1406        let build = cfg.build.unwrap();
1407        assert_eq!(build.command, "npm run build");
1408        assert_eq!(build.output.as_deref(), Some("dist"));
1409        assert!(cfg.routing.clean_urls);
1410        assert_eq!(cfg.routing.redirects.len(), 1);
1411        assert_eq!(cfg.routing.redirects[0].status, 301);
1412    }
1413
1414    #[test]
1415    fn project_config_rejects_bad_routing_pattern() {
1416        // The same compile-check `load` runs: a bad route pattern is an error.
1417        let cfg = project(r#"( routing: ( redirects: [ (from: "/a/**/b/**", to: "/x") ] ) )"#);
1418        assert!(cfg.routing.compile_check().is_err());
1419    }
1420
1421    #[test]
1422    fn empty_server_config_has_no_sections() {
1423        let cfg = server("()");
1424        assert!(cfg.serve.is_none());
1425        assert!(cfg.handlers.is_none());
1426        assert!(cfg.cluster.is_none());
1427        assert!(cfg.security.is_none());
1428    }
1429
1430    #[test]
1431    fn security_section_parses_and_resolves() {
1432        // A profile plus an override that wins over it.
1433        let cfg = server(
1434            r#"(
1435                security: (
1436                    profile: "dev",
1437                    overrides: (
1438                        oidc_require_audience: true,
1439                        max_upload_bytes: 0,
1440                    ),
1441                )
1442            )"#,
1443        );
1444        let posture = cfg.security.unwrap().resolve().expect("resolves");
1445        // `dev` is loose...
1446        assert!(posture.allow_unauthenticated_public_bind);
1447        // ...but the explicit override wins over the profile.
1448        assert!(posture.oidc_require_audience);
1449        assert_eq!(posture.max_upload_bytes, 0); // unlimited
1450    }
1451
1452    #[test]
1453    fn cluster_section_parses_the_dynamic_join_shape() {
1454        let cfg = server(
1455            r#"(
1456                cluster: (
1457                    listen: "10.0.0.2:7000",
1458                    root_pubkeys: ["es256:03a1"],
1459                    seeds: ["https://10.0.0.1:8080"],
1460                    join_token: "env:BOATRAMP_JOIN_TOKEN",
1461                ),
1462            )"#,
1463        );
1464        let cluster = cfg.cluster.unwrap();
1465        assert_eq!(
1466            cluster.listen,
1467            "10.0.0.2:7000".parse::<std::net::SocketAddr>().unwrap()
1468        );
1469        assert_eq!(cluster.root_pubkeys, vec!["es256:03a1".to_string()]);
1470        assert_eq!(cluster.seeds, vec!["https://10.0.0.1:8080".to_string()]);
1471        assert_eq!(
1472            cluster.join_token.as_deref(),
1473            Some("env:BOATRAMP_JOIN_TOKEN")
1474        );
1475        // store_dir defaults to None (→ <data-dir>/raft at serve time).
1476        assert!(cluster.store_dir.is_none());
1477    }
1478
1479    #[test]
1480    fn cluster_section_founds_with_just_a_listen_addr() {
1481        // A founder needs no seeds/token — just where to bind the mesh.
1482        let cfg = server(r#"( cluster: ( listen: "0.0.0.0:7000" ) )"#);
1483        let cluster = cfg.cluster.unwrap();
1484        assert!(cluster.seeds.is_empty());
1485        assert!(cluster.root_pubkeys.is_empty());
1486        assert!(cluster.join_token.is_none());
1487    }
1488
1489    #[test]
1490    fn sql_binding_single_node_defaults() {
1491        // A bare section (or none) means single-node: no url, default dir.
1492        let cfg = server(r#"( handlers: ( bindings: ( sql: () ) ) )"#);
1493        let sql = cfg.handlers.unwrap().bindings.sql.unwrap();
1494        assert!(sql.url.is_none());
1495        assert!(sql.dir.is_none());
1496    }
1497
1498    #[test]
1499    fn sql_binding_single_node_custom_dir() {
1500        let cfg =
1501            server(r#"( handlers: ( bindings: ( sql: ( dir: "/var/lib/boatramp/sql" ) ) ) )"#);
1502        let sql = cfg.handlers.unwrap().bindings.sql.unwrap();
1503        assert_eq!(sql.dir.as_deref(), Some(Path::new("/var/lib/boatramp/sql")));
1504        assert!(sql.url.is_none());
1505    }
1506
1507    #[test]
1508    fn sql_binding_cluster() {
1509        let cfg = server(
1510            r#"(
1511                handlers: ( bindings: ( sql: (
1512                    url: "http://sqld:8080",
1513                    admin_url: "http://sqld:9090",
1514                    token_env: "BOATRAMP_SQL_TOKEN",
1515                ) ) ),
1516            )"#,
1517        );
1518        let sql = cfg.handlers.unwrap().bindings.sql.unwrap();
1519        assert_eq!(sql.url.as_deref(), Some("http://sqld:8080"));
1520        assert_eq!(sql.admin_url.as_deref(), Some("http://sqld:9090"));
1521        assert_eq!(sql.token_env.as_deref(), Some("BOATRAMP_SQL_TOKEN"));
1522        assert_eq!(sql.admin_token_env, None);
1523    }
1524
1525    #[test]
1526    fn sql_binding_preview_policy() {
1527        let cfg = server(
1528            r#"(
1529                handlers: ( bindings: ( sql: (
1530                    preview_mode: "branch",
1531                    preview_init: "/etc/boatramp/seed.sql",
1532                ) ) ),
1533            )"#,
1534        );
1535        let sql = cfg.handlers.unwrap().bindings.sql.unwrap();
1536        assert_eq!(sql.preview_mode.as_deref(), Some("branch"));
1537        assert_eq!(
1538            sql.preview_init.as_deref(),
1539            Some(Path::new("/etc/boatramp/seed.sql"))
1540        );
1541    }
1542
1543    #[test]
1544    fn sql_binding_external_databases() {
1545        let cfg = server(
1546            r#"(
1547                handlers: ( bindings: ( sql: (
1548                    databases: {
1549                        "analytics": (
1550                            kind: "postgres",
1551                            url_env: "ANALYTICS_PG_URL",
1552                            pool_max: 16,
1553                            read_only: true,
1554                        ),
1555                        "events": (
1556                            kind: "mysql",
1557                            url_env: "EVENTS_MYSQL_URL",
1558                            read_url_env: "EVENTS_MYSQL_REPLICA_URL",
1559                            allow_preview: true,
1560                        ),
1561                    },
1562                ) ) ),
1563            )"#,
1564        );
1565        let sql = cfg.handlers.unwrap().bindings.sql.unwrap();
1566        assert_eq!(sql.databases.len(), 2);
1567
1568        let analytics = &sql.databases["analytics"];
1569        assert_eq!(analytics.kind, "postgres");
1570        assert_eq!(analytics.url_env, "ANALYTICS_PG_URL");
1571        assert_eq!(analytics.pool_max, Some(16));
1572        assert!(analytics.read_only);
1573        assert!(!analytics.allow_preview);
1574        assert!(analytics.read_url_env.is_none());
1575
1576        let events = &sql.databases["events"];
1577        assert_eq!(events.kind, "mysql");
1578        assert_eq!(
1579            events.read_url_env.as_deref(),
1580            Some("EVENTS_MYSQL_REPLICA_URL")
1581        );
1582        assert!(events.allow_preview);
1583        assert!(!events.read_only);
1584    }
1585
1586    #[test]
1587    fn sql_binding_compute_backed_database() {
1588        let cfg = server(
1589            r#"(
1590                handlers: ( bindings: ( sql: (
1591                    databases: {
1592                        "analytics": (
1593                            kind: "postgres",
1594                            compute: "pg",
1595                            database: "analytics",
1596                            user: "app",
1597                            password_env: "PG_APP_PW",
1598                        ),
1599                    },
1600                ) ) ),
1601            )"#,
1602        );
1603        let db = &cfg.handlers.unwrap().bindings.sql.unwrap().databases["analytics"];
1604        assert_eq!(db.kind, "postgres");
1605        assert_eq!(db.compute.as_deref(), Some("pg"));
1606        assert_eq!(db.database.as_deref(), Some("analytics"));
1607        assert_eq!(db.user.as_deref(), Some("app"));
1608        assert_eq!(db.password_env.as_deref(), Some("PG_APP_PW"));
1609        assert!(db.url_env.is_empty(), "compute-backed has no url_env");
1610        assert!(db.validate("analytics").is_ok());
1611    }
1612
1613    #[test]
1614    fn sql_binding_source_is_exactly_one_of_url_or_compute() {
1615        // Neither source → error.
1616        assert!(ExternalDatabaseConfig::default().validate("db").is_err());
1617        // Both sources → error.
1618        let both = ExternalDatabaseConfig {
1619            kind: "postgres".into(),
1620            url_env: "PG_URL".into(),
1621            compute: Some("pg".into()),
1622            ..Default::default()
1623        };
1624        assert!(both.validate("db").is_err());
1625        // `url_env` only → ok.
1626        let url = ExternalDatabaseConfig {
1627            kind: "postgres".into(),
1628            url_env: "PG_URL".into(),
1629            ..Default::default()
1630        };
1631        assert!(url.validate("db").is_ok());
1632        // `compute` without the connection details boatramp can't infer → error.
1633        let bare = ExternalDatabaseConfig {
1634            kind: "postgres".into(),
1635            compute: Some("pg".into()),
1636            ..Default::default()
1637        };
1638        assert!(bare.validate("db").is_err());
1639        // `compute` with database/user + a bring-your-own `password_env` → ok, and
1640        // is *not* a managed credential.
1641        let byo = ExternalDatabaseConfig {
1642            kind: "postgres".into(),
1643            compute: Some("pg".into()),
1644            database: Some("analytics".into()),
1645            user: Some("app".into()),
1646            password_env: Some("PG_APP_PW".into()),
1647            ..Default::default()
1648        };
1649        assert!(byo.validate("db").is_ok());
1650        assert!(!byo.is_managed_credential());
1651        // `compute` with database/user but NO `password_env` → ok, and boatramp
1652        // manages the credential (Phase 2).
1653        let managed = ExternalDatabaseConfig {
1654            kind: "postgres".into(),
1655            compute: Some("pg".into()),
1656            database: Some("analytics".into()),
1657            user: Some("app".into()),
1658            ..Default::default()
1659        };
1660        assert!(managed.validate("db").is_ok());
1661        assert!(managed.is_managed_credential());
1662    }
1663
1664    /// Path to a file at the repo root (two levels up from this crate).
1665    fn repo_root_file(name: &str) -> PathBuf {
1666        Path::new(env!("CARGO_MANIFEST_DIR"))
1667            .join("../..")
1668            .join(name)
1669    }
1670
1671    #[test]
1672    fn shipped_project_example_parses() {
1673        // The example we ship must always parse + compile-check, so it can't drift
1674        // from the schema.
1675        let text = std::fs::read_to_string(repo_root_file("examples/site/project.cfg.example"))
1676            .expect("example project config is present");
1677        let cfg = ProjectConfig::parse(&text).expect("example project config parses");
1678        assert_eq!(cfg.publish.server.as_deref(), Some("http://127.0.0.1:8080"));
1679        assert_eq!(cfg.build.as_ref().unwrap().command, "npm run build");
1680        assert_eq!(
1681            cfg.routing.error_documents.get(&404).map(String::as_str),
1682            Some("/404.html")
1683        );
1684    }
1685
1686    #[test]
1687    fn shipped_server_example_parses() {
1688        let text = std::fs::read_to_string(repo_root_file("boatramp.cfg.example"))
1689            .expect("example server config is present");
1690        let cfg = ServerConfig::parse(&text).expect("example server config parses");
1691        let serve = cfg.serve.expect("example sets a serve section");
1692        assert_eq!(
1693            serve.addr,
1694            Some("0.0.0.0:8080".parse::<std::net::SocketAddr>().unwrap())
1695        );
1696    }
1697
1698    #[test]
1699    fn secrets_section_parses_local_and_vault() {
1700        let local = server(r#"( secrets: ( envelope: "local", kek_file: "/k/kek" ) )"#)
1701            .secrets
1702            .expect("secrets section");
1703        assert_eq!(local.envelope, "local");
1704        assert_eq!(
1705            local.kek_file.as_deref(),
1706            Some(std::path::Path::new("/k/kek"))
1707        );
1708
1709        let vault = server(
1710            r#"( secrets: ( envelope: "vault", vault: ( addr: "https://vault:8200", key: "certs" ) ) )"#,
1711        )
1712        .secrets
1713        .expect("secrets section");
1714        let v = vault.vault.expect("vault subsection");
1715        assert_eq!(v.addr, "https://vault:8200");
1716        assert_eq!(v.key, "certs");
1717        // The token env defaults to VAULT_TOKEN and is never in the file.
1718        assert_eq!(v.token_env, "VAULT_TOKEN");
1719    }
1720
1721    #[test]
1722    fn serve_section_partial_parses() {
1723        // A partial `serve` section parses — unset fields take their defaults.
1724        let cfg = server(r#"( serve: ( addr: "0.0.0.0:8080", protect_previews: true ) )"#);
1725        let serve = cfg.serve.unwrap();
1726        assert_eq!(
1727            serve.addr,
1728            Some("0.0.0.0:8080".parse::<std::net::SocketAddr>().unwrap())
1729        );
1730        assert!(serve.protect_previews);
1731        assert!(!serve.cluster_rate_limit);
1732        assert!(serve.data_dir.is_none());
1733    }
1734
1735    #[test]
1736    fn serve_console_config_parses() {
1737        // Absent ⇒ no console.
1738        let cfg = server(r#"( serve: ( addr: "0.0.0.0:8080" ) )"#);
1739        assert!(cfg.serve.unwrap().console.is_none());
1740        // Explicit console block with host + path.
1741        let cfg = server(
1742            r#"( serve: ( console: (
1743                enabled: true,
1744                host: "console.example.com",
1745                path: "/_console",
1746            ) ) )"#,
1747        );
1748        let console = cfg.serve.unwrap().console.unwrap();
1749        assert!(console.enabled);
1750        assert_eq!(console.host.as_deref(), Some("console.example.com"));
1751        assert_eq!(console.path.as_deref(), Some("/_console"));
1752        // Bare `enabled` ⇒ host/path take their (server-side) defaults.
1753        let cfg = server(r#"( serve: ( console: ( enabled: true ) ) )"#);
1754        let console = cfg.serve.unwrap().console.unwrap();
1755        assert!(console.enabled);
1756        assert!(console.host.is_none() && console.path.is_none());
1757    }
1758}