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}
49
50/// Project configuration, loaded from `project.cfg` (RON) in the project folder.
51///
52/// Read by the client commands (`sync`, `build`, `bundle`, `validate`).
53/// Everything is optional; a missing file is the default.
54#[derive(Debug, Default, Deserialize)]
55#[serde(default)]
56pub struct ProjectConfig {
57    /// Where and how to publish this project.
58    pub publish: PublishConfig,
59    /// Optional build step run before `sync`.
60    pub build: Option<BuildConfig>,
61    /// Optional embedded-bundler step (`bundler` feature).
62    pub bundle: Option<BundleConfig>,
63    /// Deploy-scoped routing/handlers config. Folded into the deployment
64    /// manifest at `sync` (so it is atomic with the content and rolls back with
65    /// it). The bulk of a project's config — redirects, rewrites, headers,
66    /// handlers, consumers, crons, streams.
67    pub routing: DeployConfig,
68}
69
70impl ProjectConfig {
71    /// Parse a `project.cfg` document (RON). The `routing` section is
72    /// compile-checked (route patterns, cron schedules, imports) so a bad config
73    /// fails fast.
74    pub fn parse(text: &str) -> Result<Self, ConfigError> {
75        let config: Self = ron_options().from_str(text)?;
76        config.routing.compile_check()?;
77        Ok(config)
78    }
79
80    /// Load from `path` (RON). A missing file yields the default config.
81    pub fn load(path: &Path) -> Result<Self, ConfigError> {
82        match std::fs::read_to_string(path) {
83            Ok(contents) => Self::parse(&contents).map_err(|err| ConfigError::File {
84                path: path.display().to_string(),
85                source: Box::new(err),
86            }),
87            Err(err) if err.kind() == std::io::ErrorKind::NotFound => Ok(Self::default()),
88            Err(err) => Err(err.into()),
89        }
90    }
91}
92
93/// Server daemon configuration, loaded from `boatramp.cfg` (RON). Read by
94/// `boatramp serve`; flags/env override the `serve` values.
95#[derive(Debug, Default, Deserialize)]
96#[serde(default)]
97pub struct ServerConfig {
98    /// Server defaults for `serve` (flag/env override these).
99    pub serve: Option<ServeConfig>,
100    /// Server-side handler runtime config (which backend serves each binding),
101    /// consumed only with the `handlers` feature.
102    pub handlers: Option<HandlersConfig>,
103    /// Self-hosted cluster mode (consumed only with the `cluster` feature).
104    pub cluster: Option<ClusterConfig>,
105    /// Opt-in **compute** backends. Present ⇒ this node
106    /// runs compute workloads via the backends it can offer; absent ⇒ no compute
107    /// (the reconcile loop stays a no-op).
108    pub compute: Option<ComputeConfig>,
109    /// Operator security posture (the hardening knobs): a profile
110    /// preset + overrides, resolved at startup. Absent ⇒ the strict
111    /// `multi-tenant` default. Operator-only — never part of site config.
112    pub security: Option<boatramp_core::security::SecurityConfig>,
113    /// Secrets-at-rest envelope. Absent ⇒ private
114    /// keys stored cleartext in the (replicated) control plane.
115    pub secrets: Option<SecretsConfig>,
116}
117
118/// `secrets` section — envelope encryption for private keys at rest.
119#[cfg_attr(not(feature = "cluster"), allow(dead_code))]
120#[derive(Debug, Clone, Default, Deserialize)]
121#[serde(default, deny_unknown_fields)]
122pub struct SecretsConfig {
123    /// Backend: `"local"` (machine-local AES-256-GCM KEK) or `"vault"` (Vault
124    /// Transit). Empty/other ⇒ no wrapping. In a cluster a local KEK must be the
125    /// **same file on every node** (wrapped certs replicate); Vault avoids that.
126    pub envelope: String,
127    /// Local-KEK key file (`envelope = "local"`). Default
128    /// `<data-dir>/secrets/kek`. Auto-generated `0600` if absent.
129    pub kek_file: Option<PathBuf>,
130    /// Vault Transit config (`envelope = "vault"`).
131    pub vault: Option<VaultSecretsConfig>,
132}
133
134/// Vault Transit settings for `envelope = "vault"`. The token is read from the
135/// environment (`token_env`), never stored in the config file.
136#[cfg_attr(not(all(feature = "cluster", feature = "acme-dns")), allow(dead_code))]
137#[derive(Debug, Clone, Deserialize)]
138#[serde(deny_unknown_fields)]
139pub struct VaultSecretsConfig {
140    /// Vault address, e.g. `https://vault:8200`.
141    pub addr: String,
142    /// Transit key name to wrap under.
143    pub key: String,
144    /// Environment variable holding the Vault token (default `VAULT_TOKEN`).
145    #[serde(default = "default_vault_token_env")]
146    pub token_env: String,
147}
148
149fn default_vault_token_env() -> String {
150    "VAULT_TOKEN".to_string()
151}
152
153impl ServerConfig {
154    /// Parse a `boatramp.cfg` document (RON).
155    pub fn parse(text: &str) -> Result<Self, ConfigError> {
156        Ok(ron_options().from_str(text)?)
157    }
158
159    /// Load from `path` (RON). A missing file yields the default config.
160    pub fn load(path: &Path) -> Result<Self, ConfigError> {
161        match std::fs::read_to_string(path) {
162            Ok(contents) => Self::parse(&contents).map_err(|err| ConfigError::File {
163                path: path.display().to_string(),
164                source: Box::new(err),
165            }),
166            Err(err) if err.kind() == std::io::ErrorKind::NotFound => Ok(Self::default()),
167            Err(err) => Err(err.into()),
168        }
169    }
170}
171
172/// `compute` section — opt-in compute backends. Present
173/// ⇒ `serve` registers the backends this node can offer and advertises them to
174/// the scheduler; backends are capability-detected (container on Linux, remote
175/// docker when a daemon is reachable, VMM when `/dev/kvm` exists).
176#[derive(Debug, Clone, Deserialize)]
177#[serde(default, deny_unknown_fields)]
178pub struct ComputeConfig {
179    /// Bridge the container veths / VM taps attach to (default `br-boatramp`).
180    pub bridge: String,
181    /// Guest IP subnet (default `10.0.0.0/24`).
182    pub subnet: String,
183    /// vCPUs this node advertises as schedulable (`0` ⇒ detect from the host).
184    pub vcpus: u32,
185    /// Memory (MiB) this node advertises as schedulable (`0` ⇒ a 1 GiB default).
186    pub mem_mib: u32,
187    /// **Static** kernel-signing public keys (`"<alg>:<hex>"`) — the trust anchor
188    /// for the posture-scaled kernel bar. Under `multi-tenant`, a dynamically-
189    /// selected default kernel must carry a signature verifying against one of
190    /// these. Host-access-gated (never in the KV tier); changing it needs a
191    /// restart. Empty ⇒ no kernel may be signed-verified (strict posture then
192    /// accepts none).
193    pub kernel_signing_pubkeys: Vec<String>,
194    /// **Static** allow-list of kernel content hashes (sha256 hex) a dynamic
195    /// default may select under `multi-tenant`. Host-access-gated. Empty ⇒ no
196    /// kernel is allow-listed.
197    pub kernel_allowed_hashes: Vec<String>,
198    /// This node's **region** tag (FA-8). Advertised on the compute `Node` so a
199    /// gateway routing to a `compute:`-backed workload with `--lb nearest` sends
200    /// each request to the nearest replica by its node's region — no manual
201    /// `--region` map. `None` ⇒ region-agnostic.
202    pub region: Option<String>,
203    /// How the remote-Docker backend reports a workload's reachable endpoint.
204    /// `published` (default) publishes the container port on `127.0.0.1:<ephemeral>`
205    /// so a host-native `serve` reaches it on any daemon (incl. Docker Desktop /
206    /// macOS, where the bridge IP is not host-routable); `bridge` routes to the
207    /// container bridge IP directly (only when `serve` shares the daemon's network).
208    pub docker_endpoint: boatramp_docker::DockerEndpoint,
209    /// How the remote-Docker backend backs a workload's persistent volumes.
210    /// `named` (default) attaches a daemon-managed `docker volume` by name (portable
211    /// across daemons + Docker Desktop / macOS); `bind` bind-mounts a host directory
212    /// under `<data_dir>/compute/volumes/<name>` (local daemon only).
213    pub docker_volume_mode: boatramp_docker::DockerVolumeMode,
214    /// Guest-reachable base URL of the compute **sql-shim** (PLAN-compute-bindings) —
215    /// e.g. `http://10.0.0.1:8081` (the compute bridge gateway) or the docker bridge
216    /// gateway. Set ⇒ a workload's `--bind sql` reaches the managed database through a
217    /// listener bound on `0.0.0.0:<port>`. `None` (default) ⇒ compute sql bindings off.
218    #[serde(default, skip_serializing_if = "Option::is_none")]
219    #[cfg_attr(not(feature = "handlers"), allow(dead_code))]
220    pub sql_shim_url: Option<String>,
221}
222
223/// The built-in **boatramp kernel-signing public key** (`es256:…`), whose private
224/// half lives as the `KERNEL_SIGNING_KEY` Actions secret in
225/// [`BoatRamp/boatramp-vmlinux`](https://github.com/BoatRamp/boatramp-vmlinux).
226/// Shipped as a default trust anchor so the first-party signed `boatramp-vmlinux`
227/// verifies out of the box under the strict posture. An operator can replace
228/// `kernel_signing_pubkeys` to trust only their own keys.
229pub const BOATRAMP_KERNEL_SIGNING_PUBKEY: &str =
230    "es256:02c4e4af2e9cba6ba6745c513f193622e6674a8b2d0187ebea5612f5b46a7eade4";
231
232impl Default for ComputeConfig {
233    fn default() -> Self {
234        Self {
235            bridge: "br-boatramp".to_string(),
236            subnet: "10.0.0.0/24".to_string(),
237            vcpus: 0,
238            mem_mib: 0,
239            kernel_signing_pubkeys: vec![BOATRAMP_KERNEL_SIGNING_PUBKEY.to_string()],
240            // Signed `boatramp-vmlinux` release kernels trusted under the strict
241            // posture (content sha256), so a selected `compute.default_kernel`
242            // clears the bar out of the box. Bump on each new signed release.
243            kernel_allowed_hashes: vec![
244                // v0.2.0 minimal Firecracker 6.1-config kernel: boots under the
245                // firecracker-*binary* backend (ACPI device discovery) but NOT the
246                // in-process embedded VMM. Kept trusted so operators on the currently
247                // published release don't fail strict verification.
248                "cf1e590a9e642be3667131ca35fbf390378a457d8908169d2a169608e299d974".to_string(),
249                // Same kernel + CONFIG_VIRTIO_MMIO_CMDLINE_DEVICES=y (flake `#vmlinux`),
250                // so the embedded VMM binds its virtio-block root over the cmdline
251                // transport. Reproducible build output (deterministic nix build,
252                // verified on KVM); the next signed boatramp-vmlinux release — which
253                // reuses this flake — publishes + signs it, gated by
254                // `vmlinux-release-boot.yml`.
255                "d0dc2098ab2a2a3c1bc72ab61dc85d9e464d798d7e55b6b80525db5ca2f00c5a".to_string(),
256            ],
257            region: None,
258            docker_endpoint: boatramp_docker::DockerEndpoint::default(),
259            docker_volume_mode: boatramp_docker::DockerVolumeMode::default(),
260            sql_shim_url: None,
261        }
262    }
263}
264
265/// `cluster` section — self-hosted **cluster mode**. Parsed in
266/// every build so config files stay portable; only *consumed* when the `cluster`
267/// feature is compiled in (`boatramp serve --mode cluster`).
268#[cfg_attr(not(feature = "cluster"), allow(dead_code))]
269#[derive(Debug, Clone, Deserialize)]
270pub struct ClusterConfig {
271    /// Address to bind this node's Raft **peer mesh** on (the `/raft/*` +
272    /// `/stream/*` endpoints) — distinct from the public `serve.addr`.
273    pub listen: SocketAddr,
274    /// The cluster **root anchor set** — the `es256:`/`ed25519:`-tagged public
275    /// keys that define this cluster's identity (a cluster *is* its root key).
276    /// Every join/trust decision verifies against this set. Empty ⇒ falls back to
277    /// `serve.auth_root_public_key` (the single-anchor default). A *set* enables
278    /// make-before-break root rotation.
279    #[serde(default)]
280    pub root_pubkeys: Vec<String>,
281    /// **Seeds** — control-plane addresses of existing cluster members
282    /// (`host:port`), any of which can admit this node. Present ⇒ this node
283    /// **joins** (redeems its `join_token`); absent + no durable state + explicit
284    /// `--cluster-init` ⇒ it **founds**. There is no peer map: members are learned
285    /// from the root-signed join response.
286    #[serde(default)]
287    pub seeds: Vec<String>,
288    /// The single-use bearer **join token** used when `seeds` are set. Keeps the
289    /// secret out of the file via a prefix: `env:VAR`, `path:/file`, or an inline
290    /// literal. Usually supplied via `serve --cluster-join <ticket>` instead.
291    #[serde(default)]
292    pub join_token: Option<String>,
293    /// Directory for this node's **durable** Raft log/state store (node-local;
294    /// distinct from the replicated control plane). Default
295    /// `<data-dir>/raft`.
296    #[serde(default)]
297    pub store_dir: Option<PathBuf>,
298    /// Mesh identity + TLS settings. Absent ⇒ defaults (identity key
299    /// auto-generated under `<data-dir>/mesh/identity.key`).
300    #[serde(default)]
301    pub mesh: Option<MeshConfig>,
302}
303
304/// `[cluster.mesh]` — mesh identity + TLS knobs.
305#[cfg_attr(not(feature = "cluster"), allow(dead_code))]
306#[derive(Debug, Clone, Default, Deserialize)]
307#[serde(default, deny_unknown_fields)]
308pub struct MeshConfig {
309    /// Path to this node's Ed25519 identity key (PKCS#8 DER, `0600`,
310    /// auto-generated). Default `<data-dir>/mesh/identity.key`.
311    pub key_file: Option<PathBuf>,
312    /// Automatic key-rotation cadence (e.g. `"30d"`); `None` = manual only.
313    /// Consumed by the rotation loop.
314    pub key_rotation: Option<String>,
315    /// TTL for a single-use join token (e.g. `"1h"`).
316    pub join_token_ttl: Option<String>,
317    /// Gate mesh `client-write`s behind a control-plane **cluster-write
318    /// capability**, so a trusted peer can't inject arbitrary
319    /// control-plane writes on mesh trust alone. Requires the token root
320    /// **private** key on every node (each mints + presents its own capability);
321    /// default `false`.
322    pub gate_client_writes: Option<bool>,
323}
324
325/// `handlers` section — server-side handler runtime config (read by `serve`).
326/// Parsed in every build (so config files stay portable), but only *consumed*
327/// when the `handlers` feature is compiled in.
328#[cfg_attr(not(feature = "handlers"), allow(dead_code))]
329#[derive(Debug, Clone, Default, Deserialize)]
330#[serde(default)]
331pub struct HandlersConfig {
332    /// `handlers.bindings` — which backend serves each handler binding.
333    pub bindings: BindingsConfig,
334    /// Use the wasmtime **pooling** instance allocator: faster
335    /// instantiation at the cost of a large up-front virtual-memory reservation.
336    /// Off by default — opt in and benchmark for your workload.
337    pub pooling: bool,
338}
339
340/// `handlers.bindings` — per-binding backend configuration. kv/blob reuse the
341/// server's own KV/Storage backends (per-site prefixed); `sql` is the single
342/// libsql backend, whose single-node-vs-cluster split is the only choice.
343#[cfg_attr(not(feature = "handlers"), allow(dead_code))]
344#[derive(Debug, Clone, Default, Deserialize)]
345#[serde(default)]
346pub struct BindingsConfig {
347    /// `handlers.bindings.sql` — libsql settings. Absent ⇒ single-node,
348    /// per-site embedded files under `<data-dir>/handlers-sql`.
349    pub sql: Option<SqlBindingConfig>,
350}
351
352/// libsql settings for the handler `sql` binding — the single SQL backend. Each
353/// site gets a real database boundary (an embedded file per site, or a sqld
354/// namespace per site), never schema separation (which arbitrary guest SQL
355/// escapes). Setting `url` switches from single-node to a shared sqld cluster;
356/// everything else stays identical.
357#[cfg_attr(not(feature = "handlers"), allow(dead_code))]
358#[derive(Debug, Clone, Default, Deserialize)]
359#[serde(default)]
360pub struct SqlBindingConfig {
361    /// Single-node: root directory for the per-site embedded database files
362    /// (default `<data-dir>/handlers-sql`). Ignored when `url` is set.
363    pub dir: Option<PathBuf>,
364    /// Cluster: base sqld data URL (e.g. `http://sqld:8080`). When set, each
365    /// site is a sqld namespace addressed as a subdomain of this URL; `admin_url`
366    /// is then required.
367    pub url: Option<String>,
368    /// Cluster: sqld admin API base URL (e.g. `http://sqld:9090`) for creating
369    /// per-site namespaces. Required when `url` is set.
370    pub admin_url: Option<String>,
371    /// Cluster: optional sqld **read-replica** data URL. When set, handlers'
372    /// read-only `sql` transactions (`open-read-only`) route to this endpoint
373    /// while writes stay on `url` (reads → replicas, writes → primary).
374    /// Reads may lag (eventually consistent). Ignored in
375    /// single-node mode (no `url`).
376    pub replica_url: Option<String>,
377    /// Name of the env var holding the sqld data auth token (optional; never
378    /// the token itself in-file).
379    pub token_env: Option<String>,
380    /// Name of the env var holding the sqld admin API auth key (optional).
381    pub admin_token_env: Option<String>,
382    /// How preview deployments get their SQL database: `empty` (default — a
383    /// fresh isolated db), `branch` (a consistent copy of the site's live db;
384    /// single-node only), or `shared` (the site's live db). See
385    /// `boatramp_core::sql::PreviewSqlMode`.
386    pub preview_mode: Option<String>,
387    /// Path to an idempotent SQL script run when an `empty` preview database is
388    /// first opened (e.g. schema/seed). Ignored in `branch`/`shared` modes.
389    pub preview_init: Option<PathBuf>,
390    /// `handlers.bindings.sql.databases` — external **bring-your-own** databases,
391    /// each opened by name via `sql.open("<name>")`. An operator-configured
392    /// Postgres/MySQL whose *isolation is the operator's* (it's their database),
393    /// so these bypass the per-site libsql boundary and are reachable by any
394    /// handler/function granted the `sql` binding. Needs the `sql-postgres` /
395    /// `sql-mysql` build feature for the engine. A name here shadows the same
396    /// name on the managed libsql default.
397    pub databases: BTreeMap<String, ExternalDatabaseConfig>,
398}
399
400/// One external (bring-your-own) SQL database for the handler `sql` binding. The
401/// connection URL is a secret and is named indirectly (`url_env`), never written
402/// in the config file.
403#[cfg_attr(not(feature = "handlers"), allow(dead_code))]
404#[derive(Debug, Clone, Default, Deserialize)]
405#[serde(default)]
406pub struct ExternalDatabaseConfig {
407    /// Engine: `postgres` (aliases `postgresql`/`pg`) or `mysql` (alias
408    /// `mariadb`).
409    pub kind: String,
410    /// Name of the env var holding the connection URL (e.g.
411    /// `postgres://user:pw@host/db`). Required.
412    pub url_env: String,
413    /// Optional env var holding a **read-replica** connection URL. When set,
414    /// `open-read-only` transactions route there; writes stay on `url_env`.
415    pub read_url_env: Option<String>,
416    /// Maximum pooled connections (default 8).
417    pub pool_max: Option<u32>,
418    /// Open every transaction `READ ONLY` (the engine rejects writes) — for a
419    /// database functions should only read.
420    pub read_only: bool,
421    /// Permit **preview** deployments to reach this database. Default `false`: a
422    /// preview is refused, so it can never touch the operator's live external DB.
423    pub allow_preview: bool,
424    /// Connection/acquire timeout in seconds (default 10).
425    pub connect_timeout_secs: Option<u64>,
426}
427
428/// The signing algorithm for a signer that can choose one (`Local`, `Vault`,
429/// `Pkcs11`). ES256 is the portable default; the cloud KMS backends are ES256-only
430/// and ignore this. Written as a RON enum: `alg: Es256` / `alg: Ed25519`.
431#[derive(Debug, Clone, Copy, Default, Deserialize)]
432pub enum SignerAlg {
433    /// ECDSA P-256 (COSE ES256) — the default.
434    #[default]
435    Es256,
436    /// Ed25519 (COSE EdDSA).
437    Ed25519,
438}
439
440impl SignerAlg {
441    fn to_token_alg(self) -> boatramp_core::cose::TokenAlg {
442        match self {
443            Self::Es256 => boatramp_core::cose::TokenAlg::Es256,
444            Self::Ed25519 => boatramp_core::cose::TokenAlg::Ed25519,
445        }
446    }
447}
448
449/// External token signer selector (`serve.signer`). Maps to
450/// [`boatramp_server::signer::SignerConfig`]; secrets (tokens/PINs) are resolved
451/// from the named env vars at startup, never stored in config. Written as a RON
452/// enum — `signer: Vault(...)`, `signer: AwsKms(...)`, `signer: Pkcs11(...)`, ….
453#[derive(Debug, Clone, Deserialize)]
454#[serde(deny_unknown_fields)]
455pub enum AuthSignerConfig {
456    /// In-process key (`"<alg>:<hex>"`).
457    Local {
458        /// The private key spec, `"<alg>:<hex>"`.
459        private_key: String,
460    },
461    /// HashiCorp Vault Transit key.
462    Vault {
463        /// Vault base address.
464        address: String,
465        /// The Transit key name.
466        key: String,
467        /// Env var holding the Vault token.
468        token_env: String,
469        /// The key algorithm.
470        #[serde(default)]
471        alg: SignerAlg,
472    },
473    /// AWS KMS asymmetric key (ES256).
474    AwsKms {
475        /// The KMS key id or ARN.
476        key_id: String,
477        /// Optional region override.
478        #[serde(default)]
479        region: Option<String>,
480    },
481    /// GCP Cloud KMS key version (ES256).
482    GcpKms {
483        /// The key-version resource name.
484        key_version: String,
485        /// Env var holding a GCP OAuth2 access token.
486        access_token_env: String,
487    },
488    /// Azure Key Vault key (ES256).
489    AzureKv {
490        /// The vault base URL.
491        vault_url: String,
492        /// The key name.
493        key: String,
494        /// The key version.
495        key_version: String,
496        /// Env var holding an Azure AD access token.
497        access_token_env: String,
498    },
499    /// PKCS#11 HSM key.
500    Pkcs11 {
501        /// Path to the PKCS#11 module.
502        module: String,
503        /// The token label.
504        token_label: String,
505        /// The key's `CKA_LABEL`.
506        key_label: String,
507        /// Env var holding the user PIN.
508        pin_env: String,
509        /// The key algorithm.
510        #[serde(default)]
511        alg: SignerAlg,
512    },
513}
514
515impl AuthSignerConfig {
516    /// Map the config-file form to the server's runtime [`SignerConfig`].
517    pub fn to_signer_config(&self) -> boatramp_server::signer::SignerConfig {
518        use boatramp_server::signer::SignerConfig;
519        match self {
520            Self::Local { private_key } => SignerConfig::Local {
521                private_key: private_key.clone(),
522            },
523            Self::Vault {
524                address,
525                key,
526                token_env,
527                alg,
528            } => SignerConfig::Vault {
529                address: address.clone(),
530                key: key.clone(),
531                token_env: token_env.clone(),
532                alg: alg.to_token_alg(),
533            },
534            Self::AwsKms { key_id, region } => SignerConfig::AwsKms {
535                key_id: key_id.clone(),
536                region: region.clone(),
537            },
538            Self::GcpKms {
539                key_version,
540                access_token_env,
541            } => SignerConfig::GcpKms {
542                key_version: key_version.clone(),
543                access_token_env: access_token_env.clone(),
544            },
545            Self::AzureKv {
546                vault_url,
547                key,
548                key_version,
549                access_token_env,
550            } => SignerConfig::AzureKv {
551                vault_url: vault_url.clone(),
552                key: key.clone(),
553                key_version: key_version.clone(),
554                access_token_env: access_token_env.clone(),
555            },
556            Self::Pkcs11 {
557                module,
558                token_label,
559                key_label,
560                pin_env,
561                alg,
562            } => SignerConfig::Pkcs11 {
563                module: module.clone(),
564                token_label: token_label.clone(),
565                key_label: key_label.clone(),
566                pin_env: pin_env.clone(),
567                alg: alg.to_token_alg(),
568            },
569        }
570    }
571}
572
573/// `serve` section — server defaults, overridden by flags/env.
574#[derive(Debug, Clone, Default, Deserialize)]
575#[serde(default)]
576pub struct ServeConfig {
577    /// Bind address (e.g. `0.0.0.0:8080`).
578    pub addr: Option<SocketAddr>,
579    /// Data directory for filesystem backends.
580    pub data_dir: Option<PathBuf>,
581    /// Token root **private** key (hex) — issuing node: verifies *and* mints
582    /// tokens / OIDC exchanges.
583    pub auth_root_private_key: Option<String>,
584    /// Token root **public** key (hex) — verify-only node.
585    pub auth_root_public_key: Option<String>,
586    /// Single-use bootstrap secret enabling `POST /api/tokens/bootstrap` (mint the
587    /// first token without an admin bearer). Prefer the `BOATRAMP_BOOTSTRAP_SECRET`
588    /// env / `--bootstrap-secret` flag so it isn't persisted in the config file.
589    pub bootstrap_secret: Option<String>,
590    /// External token signer (`[serve.signer]`): mint with a
591    /// KMS/HSM/Vault-held root key instead of an in-process `auth_root_private_key`.
592    /// Absent ⇒ the in-process key. When set, its public half is the trust anchor.
593    pub signer: Option<AuthSignerConfig>,
594    /// Reject blob uploads larger than this many bytes.
595    pub max_upload_bytes: Option<u64>,
596    /// Abort an upload that stalls for longer than this many seconds.
597    pub upload_idle_timeout_secs: Option<u64>,
598    /// Cap on simultaneous blob uploads.
599    pub max_concurrent_uploads: Option<usize>,
600    /// In a TLS mode, bind this plain-HTTP address on a second listener that
601    /// redirects to HTTPS (dual-listener). Only read in `tls` builds.
602    #[cfg_attr(not(feature = "tls"), allow(dead_code))]
603    pub http_redirect_addr: Option<SocketAddr>,
604    /// Site to serve for a `Host` matching no domain, instead of 404.
605    pub default_site: Option<String>,
606    /// The fleet's canonical public origin (e.g. `https://cp.example.com`) that a
607    /// per-request proof-of-possession must bind to (`aud`). Required for
608    /// holder-bound (`cnf`/PoP) tokens to be usable — a proof's origin is compared
609    /// against this value, never against a `Host`/`X-Forwarded-*` header.
610    pub pop_origin: Option<String>,
611    /// Require a valid control-plane token to view deployment previews.
612    pub protect_previews: bool,
613    /// Rate-limit cluster-wide via the control-plane KV instead of per node.
614    pub cluster_rate_limit: bool,
615    /// Keep the config cache coherent across processes sharing one KV via the
616    /// changelog.
617    pub shared_cache_coherence: bool,
618    /// Cloud blob-change notification provisioning tier (FA-5b2): how boatramp
619    /// obtains the native event pipeline (S3→SQS) that backs a `blob` trigger —
620    /// `dry-run` (print the recipe), `provision` (create + retract), `verify-only`
621    /// (operator pre-wired), or `refuse` (fail closed). Absent ⇒ no provisioning:
622    /// `blob` triggers then work only on a self-watching backend (fs). Only wired
623    /// for the S3 backend (`--features s3`).
624    pub blob_notify_tier: Option<boatramp_core::blob_notify::ProvisionTier>,
625    /// The AWS account id used to scope the provisioned SQS queue's `SendMessage`
626    /// policy (`aws:SourceAccount`). Required when `blob_notify_tier` provisions.
627    pub blob_notify_account_id: Option<String>,
628    /// `[serve.console]` — the embedded web management console. Absent (or
629    /// `enabled: false`) ⇒ not served. This is the **baseline** for the dynamic
630    /// `console.*` daemon-config override, which can enable/move it at runtime
631    /// (`boatramp config set console.enabled true`) without a restart.
632    pub console: Option<ConsoleConfig>,
633}
634
635/// `[serve.console]` — the embedded web console (a Wasm SPA baked into the
636/// binary with the `console` build feature). Opt-in: the static shell holds no
637/// secrets and the `/api` it drives is token-gated, so it is served
638/// **unauthenticated** at a deliberately obscure path (a bearer token can't gate
639/// a top-level browser navigation anyway — the path is the obscurity, the token
640/// is the real gate).
641#[cfg_attr(not(feature = "console"), allow(dead_code))]
642#[derive(Debug, Clone, Default, Deserialize)]
643#[serde(default, deny_unknown_fields)]
644pub struct ConsoleConfig {
645    /// Serve the embedded console (default `false`). Requires the `console` build
646    /// feature; enabling it in a build without that feature is a logged no-op.
647    pub enabled: bool,
648    /// Host(s) the console answers on: `*` (any host, the default), an exact host
649    /// (`console.example.com`), or a leading-wildcard (`*.example.com`).
650    pub host: Option<String>,
651    /// URL path prefix the console mounts at (default `/_console`). Kept under the
652    /// reserved `/_` namespace so it never collides with a published site path.
653    pub path: Option<String>,
654}
655
656/// `publish` section — where and what to deploy (the `sync` target).
657#[derive(Debug, Default, Deserialize)]
658#[serde(default)]
659pub struct PublishConfig {
660    /// Base URL of the boatramp server (e.g. `https://pad.example.com`).
661    pub server: Option<String>,
662    /// Site name to publish to.
663    pub site: Option<String>,
664    /// API token for the control plane (or set `BOATRAMP_TOKEN`).
665    pub token: Option<String>,
666    /// Project this site belongs to (overrides with `--project` / `BOATRAMP_PROJECT`).
667    pub project: Option<String>,
668}
669
670/// `build` section.
671#[derive(Debug, Clone, Deserialize)]
672pub struct BuildConfig {
673    /// Shell command to run (e.g. `npm run build`).
674    pub command: String,
675    /// Directory the build emits, published by `sync` (e.g. `dist`).
676    #[serde(default)]
677    pub output: Option<String>,
678}
679
680/// `bundle` section — the in-process Rust bundler (`bundler` feature).
681#[derive(Debug, Clone, Default, Deserialize)]
682#[serde(default)]
683pub struct BundleConfig {
684    /// Output directory for bundled assets (e.g. `dist`).
685    #[serde(default = "default_bundle_outdir")]
686    pub outdir: String,
687    /// JS/TS entry points bundled by Rolldown (tree-shaken, code-split).
688    pub js: Vec<String>,
689    /// CSS entry points bundled by lightningcss (`@import` inlined).
690    pub css: Vec<String>,
691    /// Minify output (default true).
692    #[serde(default = "default_true")]
693    pub minify: bool,
694}
695
696fn default_bundle_outdir() -> String {
697    "dist".to_string()
698}
699
700fn default_true() -> bool {
701    true
702}
703
704#[cfg(test)]
705mod tests {
706    use super::*;
707
708    fn project(text: &str) -> ProjectConfig {
709        ron_options().from_str(text).unwrap()
710    }
711
712    fn server(text: &str) -> ServerConfig {
713        ron_options().from_str(text).unwrap()
714    }
715
716    #[test]
717    fn empty_project_config_is_default() {
718        let cfg = project("()");
719        assert!(cfg.publish.server.is_none());
720        assert!(cfg.publish.site.is_none());
721        assert!(cfg.build.is_none());
722        assert!(cfg.bundle.is_none());
723        // Routing defaults: schema v1, the single default index candidate.
724        assert_eq!(cfg.routing.version, 1);
725        assert_eq!(cfg.routing.index, vec!["index.html".to_string()]);
726    }
727
728    #[test]
729    fn serve_signer_config_parses_and_maps_each_backend() {
730        use boatramp_core::cose::TokenAlg;
731        use boatramp_server::signer::SignerConfig;
732
733        // RON-native enum tagging (`Vault(...)`); `IMPLICIT_SOME` lets the optional
734        // fields (region) take a bare value or be omitted (→ None). This is the
735        // exact RON documented in the Authentication guide.
736        let vault = server(
737            r#"( serve: ( signer: Vault(
738                address: "https://vault.example:8200",
739                key: "boatramp-root",
740                token_env: "VAULT_TOKEN",
741                alg: Ed25519,
742            ) ) )"#,
743        );
744        match vault.serve.unwrap().signer.unwrap().to_signer_config() {
745            SignerConfig::Vault {
746                address,
747                key,
748                token_env,
749                alg,
750            } => {
751                assert_eq!(address, "https://vault.example:8200");
752                assert_eq!(key, "boatramp-root");
753                assert_eq!(token_env, "VAULT_TOKEN");
754                assert_eq!(alg, TokenAlg::Ed25519);
755            }
756            other => panic!("expected Vault, got {other:?}"),
757        }
758
759        // AWS KMS: region omitted → None; PKCS#11: alg omitted → the ES256 default.
760        let aws =
761            server(r#"( serve: ( signer: AwsKms(key_id: "arn:aws:kms:eu-west-1:1:key/abc") ) )"#);
762        assert!(matches!(
763            aws.serve.unwrap().signer.unwrap().to_signer_config(),
764            SignerConfig::AwsKms { region: None, .. }
765        ));
766
767        let hsm = server(
768            r#"( serve: ( signer: Pkcs11(
769                module: "/usr/lib/softhsm/libsofthsm2.so",
770                token_label: "boatramp",
771                key_label: "root",
772                pin_env: "HSM_PIN",
773            ) ) )"#,
774        );
775        match hsm.serve.unwrap().signer.unwrap().to_signer_config() {
776            SignerConfig::Pkcs11 { alg, .. } => assert_eq!(alg, TokenAlg::Es256),
777            other => panic!("expected Pkcs11, got {other:?}"),
778        }
779    }
780
781    #[test]
782    fn project_config_parses_publish_build_and_routing() {
783        let cfg = project(
784            r#"(
785                publish: ( server: "http://127.0.0.1:8080", site: "demo" ),
786                build: ( command: "npm run build", output: "dist" ),
787                routing: (
788                    clean_urls: true,
789                    redirects: [ (from: "/old/:slug", to: "/new/:slug", status: 301) ],
790                ),
791            )"#,
792        );
793        assert_eq!(cfg.publish.server.as_deref(), Some("http://127.0.0.1:8080"));
794        assert_eq!(cfg.publish.site.as_deref(), Some("demo"));
795        let build = cfg.build.unwrap();
796        assert_eq!(build.command, "npm run build");
797        assert_eq!(build.output.as_deref(), Some("dist"));
798        assert!(cfg.routing.clean_urls);
799        assert_eq!(cfg.routing.redirects.len(), 1);
800        assert_eq!(cfg.routing.redirects[0].status, 301);
801    }
802
803    #[test]
804    fn project_config_rejects_bad_routing_pattern() {
805        // The same compile-check `load` runs: a bad route pattern is an error.
806        let cfg = project(r#"( routing: ( redirects: [ (from: "/a/**/b/**", to: "/x") ] ) )"#);
807        assert!(cfg.routing.compile_check().is_err());
808    }
809
810    #[test]
811    fn empty_server_config_has_no_sections() {
812        let cfg = server("()");
813        assert!(cfg.serve.is_none());
814        assert!(cfg.handlers.is_none());
815        assert!(cfg.cluster.is_none());
816        assert!(cfg.security.is_none());
817    }
818
819    #[test]
820    fn security_section_parses_and_resolves() {
821        // A profile plus an override that wins over it.
822        let cfg = server(
823            r#"(
824                security: (
825                    profile: "dev",
826                    overrides: (
827                        oidc_require_audience: true,
828                        max_upload_bytes: 0,
829                    ),
830                )
831            )"#,
832        );
833        let posture = cfg.security.unwrap().resolve().expect("resolves");
834        // `dev` is loose...
835        assert!(posture.allow_unauthenticated_public_bind);
836        // ...but the explicit override wins over the profile.
837        assert!(posture.oidc_require_audience);
838        assert_eq!(posture.max_upload_bytes, 0); // unlimited
839    }
840
841    #[test]
842    fn cluster_section_parses_the_dynamic_join_shape() {
843        let cfg = server(
844            r#"(
845                cluster: (
846                    listen: "10.0.0.2:7000",
847                    root_pubkeys: ["es256:03a1"],
848                    seeds: ["https://10.0.0.1:8080"],
849                    join_token: "env:BOATRAMP_JOIN_TOKEN",
850                ),
851            )"#,
852        );
853        let cluster = cfg.cluster.unwrap();
854        assert_eq!(
855            cluster.listen,
856            "10.0.0.2:7000".parse::<std::net::SocketAddr>().unwrap()
857        );
858        assert_eq!(cluster.root_pubkeys, vec!["es256:03a1".to_string()]);
859        assert_eq!(cluster.seeds, vec!["https://10.0.0.1:8080".to_string()]);
860        assert_eq!(
861            cluster.join_token.as_deref(),
862            Some("env:BOATRAMP_JOIN_TOKEN")
863        );
864        // store_dir defaults to None (→ <data-dir>/raft at serve time).
865        assert!(cluster.store_dir.is_none());
866    }
867
868    #[test]
869    fn cluster_section_founds_with_just_a_listen_addr() {
870        // A founder needs no seeds/token — just where to bind the mesh.
871        let cfg = server(r#"( cluster: ( listen: "0.0.0.0:7000" ) )"#);
872        let cluster = cfg.cluster.unwrap();
873        assert!(cluster.seeds.is_empty());
874        assert!(cluster.root_pubkeys.is_empty());
875        assert!(cluster.join_token.is_none());
876    }
877
878    #[test]
879    fn sql_binding_single_node_defaults() {
880        // A bare section (or none) means single-node: no url, default dir.
881        let cfg = server(r#"( handlers: ( bindings: ( sql: () ) ) )"#);
882        let sql = cfg.handlers.unwrap().bindings.sql.unwrap();
883        assert!(sql.url.is_none());
884        assert!(sql.dir.is_none());
885    }
886
887    #[test]
888    fn sql_binding_single_node_custom_dir() {
889        let cfg =
890            server(r#"( handlers: ( bindings: ( sql: ( dir: "/var/lib/boatramp/sql" ) ) ) )"#);
891        let sql = cfg.handlers.unwrap().bindings.sql.unwrap();
892        assert_eq!(sql.dir.as_deref(), Some(Path::new("/var/lib/boatramp/sql")));
893        assert!(sql.url.is_none());
894    }
895
896    #[test]
897    fn sql_binding_cluster() {
898        let cfg = server(
899            r#"(
900                handlers: ( bindings: ( sql: (
901                    url: "http://sqld:8080",
902                    admin_url: "http://sqld:9090",
903                    token_env: "BOATRAMP_SQL_TOKEN",
904                ) ) ),
905            )"#,
906        );
907        let sql = cfg.handlers.unwrap().bindings.sql.unwrap();
908        assert_eq!(sql.url.as_deref(), Some("http://sqld:8080"));
909        assert_eq!(sql.admin_url.as_deref(), Some("http://sqld:9090"));
910        assert_eq!(sql.token_env.as_deref(), Some("BOATRAMP_SQL_TOKEN"));
911        assert_eq!(sql.admin_token_env, None);
912    }
913
914    #[test]
915    fn sql_binding_preview_policy() {
916        let cfg = server(
917            r#"(
918                handlers: ( bindings: ( sql: (
919                    preview_mode: "branch",
920                    preview_init: "/etc/boatramp/seed.sql",
921                ) ) ),
922            )"#,
923        );
924        let sql = cfg.handlers.unwrap().bindings.sql.unwrap();
925        assert_eq!(sql.preview_mode.as_deref(), Some("branch"));
926        assert_eq!(
927            sql.preview_init.as_deref(),
928            Some(Path::new("/etc/boatramp/seed.sql"))
929        );
930    }
931
932    #[test]
933    fn sql_binding_external_databases() {
934        let cfg = server(
935            r#"(
936                handlers: ( bindings: ( sql: (
937                    databases: {
938                        "analytics": (
939                            kind: "postgres",
940                            url_env: "ANALYTICS_PG_URL",
941                            pool_max: 16,
942                            read_only: true,
943                        ),
944                        "events": (
945                            kind: "mysql",
946                            url_env: "EVENTS_MYSQL_URL",
947                            read_url_env: "EVENTS_MYSQL_REPLICA_URL",
948                            allow_preview: true,
949                        ),
950                    },
951                ) ) ),
952            )"#,
953        );
954        let sql = cfg.handlers.unwrap().bindings.sql.unwrap();
955        assert_eq!(sql.databases.len(), 2);
956
957        let analytics = &sql.databases["analytics"];
958        assert_eq!(analytics.kind, "postgres");
959        assert_eq!(analytics.url_env, "ANALYTICS_PG_URL");
960        assert_eq!(analytics.pool_max, Some(16));
961        assert!(analytics.read_only);
962        assert!(!analytics.allow_preview);
963        assert!(analytics.read_url_env.is_none());
964
965        let events = &sql.databases["events"];
966        assert_eq!(events.kind, "mysql");
967        assert_eq!(
968            events.read_url_env.as_deref(),
969            Some("EVENTS_MYSQL_REPLICA_URL")
970        );
971        assert!(events.allow_preview);
972        assert!(!events.read_only);
973    }
974
975    /// Path to a file at the repo root (two levels up from this crate).
976    fn repo_root_file(name: &str) -> PathBuf {
977        Path::new(env!("CARGO_MANIFEST_DIR"))
978            .join("../..")
979            .join(name)
980    }
981
982    #[test]
983    fn shipped_project_example_parses() {
984        // The example we ship must always parse + compile-check, so it can't drift
985        // from the schema.
986        let text = std::fs::read_to_string(repo_root_file("examples/site/project.cfg.example"))
987            .expect("example project config is present");
988        let cfg = ProjectConfig::parse(&text).expect("example project config parses");
989        assert_eq!(cfg.publish.server.as_deref(), Some("http://127.0.0.1:8080"));
990        assert_eq!(cfg.build.as_ref().unwrap().command, "npm run build");
991        assert_eq!(
992            cfg.routing.error_documents.get(&404).map(String::as_str),
993            Some("/404.html")
994        );
995    }
996
997    #[test]
998    fn shipped_server_example_parses() {
999        let text = std::fs::read_to_string(repo_root_file("boatramp.cfg.example"))
1000            .expect("example server config is present");
1001        let cfg = ServerConfig::parse(&text).expect("example server config parses");
1002        let serve = cfg.serve.expect("example sets a serve section");
1003        assert_eq!(
1004            serve.addr,
1005            Some("0.0.0.0:8080".parse::<std::net::SocketAddr>().unwrap())
1006        );
1007    }
1008
1009    #[test]
1010    fn secrets_section_parses_local_and_vault() {
1011        let local = server(r#"( secrets: ( envelope: "local", kek_file: "/k/kek" ) )"#)
1012            .secrets
1013            .expect("secrets section");
1014        assert_eq!(local.envelope, "local");
1015        assert_eq!(
1016            local.kek_file.as_deref(),
1017            Some(std::path::Path::new("/k/kek"))
1018        );
1019
1020        let vault = server(
1021            r#"( secrets: ( envelope: "vault", vault: ( addr: "https://vault:8200", key: "certs" ) ) )"#,
1022        )
1023        .secrets
1024        .expect("secrets section");
1025        let v = vault.vault.expect("vault subsection");
1026        assert_eq!(v.addr, "https://vault:8200");
1027        assert_eq!(v.key, "certs");
1028        // The token env defaults to VAULT_TOKEN and is never in the file.
1029        assert_eq!(v.token_env, "VAULT_TOKEN");
1030    }
1031
1032    #[test]
1033    fn serve_section_partial_parses() {
1034        // A partial `serve` section parses — unset fields take their defaults.
1035        let cfg = server(r#"( serve: ( addr: "0.0.0.0:8080", protect_previews: true ) )"#);
1036        let serve = cfg.serve.unwrap();
1037        assert_eq!(
1038            serve.addr,
1039            Some("0.0.0.0:8080".parse::<std::net::SocketAddr>().unwrap())
1040        );
1041        assert!(serve.protect_previews);
1042        assert!(!serve.cluster_rate_limit);
1043        assert!(serve.data_dir.is_none());
1044    }
1045
1046    #[test]
1047    fn serve_console_config_parses() {
1048        // Absent ⇒ no console.
1049        let cfg = server(r#"( serve: ( addr: "0.0.0.0:8080" ) )"#);
1050        assert!(cfg.serve.unwrap().console.is_none());
1051        // Explicit console block with host + path.
1052        let cfg = server(
1053            r#"( serve: ( console: (
1054                enabled: true,
1055                host: "console.example.com",
1056                path: "/_console",
1057            ) ) )"#,
1058        );
1059        let console = cfg.serve.unwrap().console.unwrap();
1060        assert!(console.enabled);
1061        assert_eq!(console.host.as_deref(), Some("console.example.com"));
1062        assert_eq!(console.path.as_deref(), Some("/_console"));
1063        // Bare `enabled` ⇒ host/path take their (server-side) defaults.
1064        let cfg = server(r#"( serve: ( console: ( enabled: true ) ) )"#);
1065        let console = cfg.serve.unwrap().console.unwrap();
1066        assert!(console.enabled);
1067        assert!(console.host.is_none() && console.path.is_none());
1068    }
1069}