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
232/// The first-party signed-kernel content hashes trusted under the **strict**
233/// posture, for this build's **guest arch**. The guest arch mirrors the host: an
234/// x86_64 host boots x86_64 KVM guests (the embedded VMM); an Apple-silicon host
235/// boots aarch64 guests (the Virtualization.framework `vmm-vz` backend). An x86_64
236/// kernel can't boot an aarch64 VM (and vice versa), so each arch trusts only its
237/// own signed `boatramp-vmlinux-<arch>` releases. Bump on each new signed release.
238///
239/// The **relaxed** (single-tenant) posture ignores this list — it verifies only the
240/// content-hash pin — so an operator-supplied kernel boots there regardless of arch.
241fn default_allowed_kernel_hashes() -> Vec<String> {
242    #[cfg(target_arch = "x86_64")]
243    {
244        vec![
245            // v0.2.0 minimal Firecracker 6.1-config kernel: boots under the
246            // firecracker-*binary* backend (ACPI device discovery) but NOT the
247            // in-process embedded VMM. Kept trusted so operators on the currently
248            // published release don't fail strict verification.
249            "cf1e590a9e642be3667131ca35fbf390378a457d8908169d2a169608e299d974".to_string(),
250            // Same kernel + CONFIG_VIRTIO_MMIO_CMDLINE_DEVICES=y (flake `#vmlinux`),
251            // so the embedded VMM binds its virtio-block root over the cmdline
252            // transport. Reproducible build output (deterministic nix build,
253            // verified on KVM); the next signed boatramp-vmlinux release — which
254            // reuses this flake — publishes + signs it, gated by
255            // `vmlinux-release-boot.yml`.
256            "d0dc2098ab2a2a3c1bc72ab61dc85d9e464d798d7e55b6b80525db5ca2f00c5a".to_string(),
257        ]
258    }
259    #[cfg(target_arch = "aarch64")]
260    {
261        vec![
262            // `boatramp-vmlinux-aarch64` v0.2.3 (the Virtualization.framework guest
263            // kernel, flake `#vmlinux` on aarch64-linux — a raw arm64 `Image`). This
264            // release enables the generic PCIe host + virtio-pci so the guest actually
265            // discovers VZ's virtio disk/net/console (the earlier v0.2.2 `be95fb0d…`
266            // built with `CONFIG_PCI` off never booted under VZ and is dropped). This
267            // is the hash of the **published, ES256-signed** release asset (signed by
268            // BOATRAMP_KERNEL_SIGNING_PUBKEY), so a selected `compute.default_kernel`
269            // clears the strict bar out of the box; the boot + scale-to-zero round-trip
270            // was validated against this exact published kernel. NOTE: unlike x86_64,
271            // the aarch64 build is not currently bit-reproducible across build hosts
272            // (same config + size, different build metadata), so pin/verify against the
273            // published `.sha256`/`.sig`, not a local rebuild. Bump on each new release.
274            "d785a48d754e65a4630443301f1fb84cb69cf882336d3cf37055e437b3d8e21f".to_string(),
275        ]
276    }
277    #[cfg(not(any(target_arch = "x86_64", target_arch = "aarch64")))]
278    {
279        Vec::new()
280    }
281}
282
283impl Default for ComputeConfig {
284    fn default() -> Self {
285        Self {
286            bridge: "br-boatramp".to_string(),
287            subnet: "10.0.0.0/24".to_string(),
288            vcpus: 0,
289            mem_mib: 0,
290            kernel_signing_pubkeys: vec![BOATRAMP_KERNEL_SIGNING_PUBKEY.to_string()],
291            kernel_allowed_hashes: default_allowed_kernel_hashes(),
292            region: None,
293            docker_endpoint: boatramp_docker::DockerEndpoint::default(),
294            docker_volume_mode: boatramp_docker::DockerVolumeMode::default(),
295            sql_shim_url: None,
296        }
297    }
298}
299
300/// `cluster` section — self-hosted **cluster mode**. Parsed in
301/// every build so config files stay portable; only *consumed* when the `cluster`
302/// feature is compiled in (`boatramp serve --mode cluster`).
303#[cfg_attr(not(feature = "cluster"), allow(dead_code))]
304#[derive(Debug, Clone, Deserialize)]
305pub struct ClusterConfig {
306    /// Address to bind this node's Raft **peer mesh** on (the `/raft/*` +
307    /// `/stream/*` endpoints) — distinct from the public `serve.addr`.
308    pub listen: SocketAddr,
309    /// The cluster **root anchor set** — the `es256:`/`ed25519:`-tagged public
310    /// keys that define this cluster's identity (a cluster *is* its root key).
311    /// Every join/trust decision verifies against this set. Empty ⇒ falls back to
312    /// `serve.auth_root_public_key` (the single-anchor default). A *set* enables
313    /// make-before-break root rotation.
314    #[serde(default)]
315    pub root_pubkeys: Vec<String>,
316    /// **Seeds** — control-plane addresses of existing cluster members
317    /// (`host:port`), any of which can admit this node. Present ⇒ this node
318    /// **joins** (redeems its `join_token`); absent + no durable state + explicit
319    /// `--cluster-init` ⇒ it **founds**. There is no peer map: members are learned
320    /// from the root-signed join response.
321    #[serde(default)]
322    pub seeds: Vec<String>,
323    /// The single-use bearer **join token** used when `seeds` are set. Keeps the
324    /// secret out of the file via a prefix: `env:VAR`, `path:/file`, or an inline
325    /// literal. Usually supplied via `serve --cluster-join <ticket>` instead.
326    #[serde(default)]
327    pub join_token: Option<String>,
328    /// Directory for this node's **durable** Raft log/state store (node-local;
329    /// distinct from the replicated control plane). Default
330    /// `<data-dir>/raft`.
331    #[serde(default)]
332    pub store_dir: Option<PathBuf>,
333    /// Mesh identity + TLS settings. Absent ⇒ defaults (identity key
334    /// auto-generated under `<data-dir>/mesh/identity.key`).
335    #[serde(default)]
336    pub mesh: Option<MeshConfig>,
337}
338
339/// `[cluster.mesh]` — mesh identity + TLS knobs.
340#[cfg_attr(not(feature = "cluster"), allow(dead_code))]
341#[derive(Debug, Clone, Default, Deserialize)]
342#[serde(default, deny_unknown_fields)]
343pub struct MeshConfig {
344    /// Path to this node's Ed25519 identity key (PKCS#8 DER, `0600`,
345    /// auto-generated). Default `<data-dir>/mesh/identity.key`.
346    pub key_file: Option<PathBuf>,
347    /// Automatic key-rotation cadence (e.g. `"30d"`); `None` = manual only.
348    /// Consumed by the rotation loop.
349    pub key_rotation: Option<String>,
350    /// TTL for a single-use join token (e.g. `"1h"`).
351    pub join_token_ttl: Option<String>,
352    /// Gate mesh `client-write`s behind a control-plane **cluster-write
353    /// capability**, so a trusted peer can't inject arbitrary
354    /// control-plane writes on mesh trust alone. Requires the token root
355    /// **private** key on every node (each mints + presents its own capability);
356    /// default `false`.
357    pub gate_client_writes: Option<bool>,
358}
359
360/// `handlers` section — server-side handler runtime config (read by `serve`).
361/// Parsed in every build (so config files stay portable), but only *consumed*
362/// when the `handlers` feature is compiled in.
363#[cfg_attr(not(feature = "handlers"), allow(dead_code))]
364#[derive(Debug, Clone, Default, Deserialize)]
365#[serde(default)]
366pub struct HandlersConfig {
367    /// `handlers.bindings` — which backend serves each handler binding.
368    pub bindings: BindingsConfig,
369    /// Use the wasmtime **pooling** instance allocator: faster
370    /// instantiation at the cost of a large up-front virtual-memory reservation.
371    /// Off by default — opt in and benchmark for your workload.
372    pub pooling: bool,
373}
374
375/// `handlers.bindings` — per-binding backend configuration. kv/blob reuse the
376/// server's own KV/Storage backends (per-site prefixed); `sql` is the single
377/// libsql backend, whose single-node-vs-cluster split is the only choice.
378#[cfg_attr(not(feature = "handlers"), allow(dead_code))]
379#[derive(Debug, Clone, Default, Deserialize)]
380#[serde(default)]
381pub struct BindingsConfig {
382    /// `handlers.bindings.sql` — libsql settings. Absent ⇒ single-node,
383    /// per-site embedded files under `<data-dir>/handlers-sql`.
384    pub sql: Option<SqlBindingConfig>,
385}
386
387/// libsql settings for the handler `sql` binding — the single SQL backend. Each
388/// site gets a real database boundary (an embedded file per site, or a sqld
389/// namespace per site), never schema separation (which arbitrary guest SQL
390/// escapes). Setting `url` switches from single-node to a shared sqld cluster;
391/// everything else stays identical.
392#[cfg_attr(not(feature = "handlers"), allow(dead_code))]
393#[derive(Debug, Clone, Default, Deserialize)]
394#[serde(default)]
395pub struct SqlBindingConfig {
396    /// Single-node: root directory for the per-site embedded database files
397    /// (default `<data-dir>/handlers-sql`). Ignored when `url` is set.
398    pub dir: Option<PathBuf>,
399    /// Cluster: base sqld data URL (e.g. `http://sqld:8080`). When set, each
400    /// site is a sqld namespace addressed as a subdomain of this URL; `admin_url`
401    /// is then required.
402    pub url: Option<String>,
403    /// Cluster: sqld admin API base URL (e.g. `http://sqld:9090`) for creating
404    /// per-site namespaces. Required when `url` is set.
405    pub admin_url: Option<String>,
406    /// Cluster: optional sqld **read-replica** data URL. When set, handlers'
407    /// read-only `sql` transactions (`open-read-only`) route to this endpoint
408    /// while writes stay on `url` (reads → replicas, writes → primary).
409    /// Reads may lag (eventually consistent). Ignored in
410    /// single-node mode (no `url`).
411    pub replica_url: Option<String>,
412    /// Name of the env var holding the sqld data auth token (optional; never
413    /// the token itself in-file).
414    pub token_env: Option<String>,
415    /// Name of the env var holding the sqld admin API auth key (optional).
416    pub admin_token_env: Option<String>,
417    /// How preview deployments get their SQL database: `empty` (default — a
418    /// fresh isolated db), `branch` (a consistent copy of the site's live db;
419    /// single-node only), or `shared` (the site's live db). See
420    /// `boatramp_core::sql::PreviewSqlMode`.
421    pub preview_mode: Option<String>,
422    /// Path to an idempotent SQL script run when an `empty` preview database is
423    /// first opened (e.g. schema/seed). Ignored in `branch`/`shared` modes.
424    pub preview_init: Option<PathBuf>,
425    /// `handlers.bindings.sql.databases` — external **bring-your-own** databases,
426    /// each opened by name via `sql.open("<name>")`. An operator-configured
427    /// Postgres/MySQL whose *isolation is the operator's* (it's their database),
428    /// so these bypass the per-site libsql boundary and are reachable by any
429    /// handler/function granted the `sql` binding. Needs the `sql-postgres` /
430    /// `sql-mysql` build feature for the engine. A name here shadows the same
431    /// name on the managed libsql default.
432    pub databases: BTreeMap<String, ExternalDatabaseConfig>,
433}
434
435/// One external SQL database for the handler `sql` binding. Its **source** is one
436/// of two mutually-exclusive forms:
437///  - `url_env` — a **bring-your-own** database: the connection URL is a secret,
438///    named indirectly by an env var (never written in the config file).
439///  - `compute` — a database **boatramp runs** as a compute workload: boatramp
440///    derives the connection from the workload's live endpoint (host\:port) plus
441///    the `database`/`user`/`password_env` here, so there is no URL to hand-map and
442///    it follows the workload across restarts (PLAN-managed-compute-sql).
443#[cfg_attr(not(feature = "handlers"), allow(dead_code))]
444#[derive(Debug, Clone, Default, Deserialize)]
445#[serde(default)]
446pub struct ExternalDatabaseConfig {
447    /// Engine: `postgres` (aliases `postgresql`/`pg`) or `mysql` (alias
448    /// `mariadb`).
449    pub kind: String,
450    /// Name of the env var holding the connection URL (e.g.
451    /// `postgres://user:pw@host/db`). Required unless `compute` is set.
452    pub url_env: String,
453    /// Optional env var holding a **read-replica** connection URL. When set,
454    /// `open-read-only` transactions route there; writes stay on `url_env`.
455    pub read_url_env: Option<String>,
456    /// The name of a **compute workload** (a Postgres/MySQL server boatramp runs)
457    /// to source this database from, instead of `url_env`. boatramp resolves the
458    /// workload's live endpoint and builds the connection. Mutually exclusive with
459    /// `url_env`.
460    pub compute: Option<String>,
461    /// The database name inside the compute-backed server (non-secret).
462    pub database: Option<String>,
463    /// The connecting user for the compute-backed server (non-secret).
464    pub user: Option<String>,
465    /// Env var holding the password for `user` on the compute-backed server.
466    /// **Omit to let boatramp fully manage the credential** (PLAN-managed-compute-sql
467    /// Phase 2): it generates a strong password once, seals it with the `[secrets]`
468    /// envelope, injects it into the DB workload's server-init env at launch, and
469    /// connects the handler with it — the operator sets no DB secret at all. Set it
470    /// only to bring your own password for the compute-backed server.
471    pub password_env: Option<String>,
472    /// Maximum pooled connections (default 8).
473    pub pool_max: Option<u32>,
474    /// Open every transaction `READ ONLY` (the engine rejects writes) — for a
475    /// database functions should only read.
476    pub read_only: bool,
477    /// Permit **preview** deployments to reach this database. Default `false`: a
478    /// preview is refused, so it can never touch the operator's live external DB.
479    pub allow_preview: bool,
480    /// Connection/acquire timeout in seconds (default 10).
481    pub connect_timeout_secs: Option<u64>,
482}
483
484impl ExternalDatabaseConfig {
485    /// Validate the source is well-formed: **exactly one** of `url_env` /
486    /// `compute`, and a `compute`-backed database has the connection details
487    /// boatramp can't infer (`database` + `user`). `password_env` is **optional** —
488    /// omit it to let boatramp manage the credential (Phase 2). `name` is the
489    /// binding name, for the error message.
490    #[cfg_attr(not(feature = "handlers"), allow(dead_code))]
491    pub fn validate(&self, name: &str) -> Result<(), String> {
492        let has_url = !self.url_env.is_empty();
493        let has_compute = self.compute.as_deref().is_some_and(|c| !c.is_empty());
494        match (has_url, has_compute) {
495            (true, true) => Err(format!(
496                "sql database {name:?}: set exactly one of `url_env` or `compute`, not both"
497            )),
498            (false, false) => Err(format!(
499                "sql database {name:?}: needs a source — set `url_env` (bring-your-own) or \
500                 `compute` (a database boatramp runs)"
501            )),
502            (false, true) => {
503                // `database` + `user` are non-secret and can't be inferred; a missing
504                // `password_env` is *not* an error — it selects the managed credential.
505                for (field, val) in [("database", &self.database), ("user", &self.user)] {
506                    if val.as_deref().is_none_or(str::is_empty) {
507                        return Err(format!(
508                            "sql database {name:?}: a `compute`-backed database requires `{field}`"
509                        ));
510                    }
511                }
512                Ok(())
513            }
514            (true, false) => Ok(()),
515        }
516    }
517
518    /// Whether this compute-backed database uses a **boatramp-managed** credential
519    /// (Phase 2): `compute` is set and no `password_env` was supplied.
520    #[cfg_attr(not(feature = "handlers"), allow(dead_code))]
521    pub fn is_managed_credential(&self) -> bool {
522        self.compute.as_deref().is_some_and(|c| !c.is_empty())
523            && self.password_env.as_deref().is_none_or(str::is_empty)
524    }
525}
526
527/// The signing algorithm for a signer that can choose one (`Local`, `Vault`,
528/// `Pkcs11`). ES256 is the portable default; the cloud KMS backends are ES256-only
529/// and ignore this. Written as a RON enum: `alg: Es256` / `alg: Ed25519`.
530#[derive(Debug, Clone, Copy, Default, Deserialize)]
531pub enum SignerAlg {
532    /// ECDSA P-256 (COSE ES256) — the default.
533    #[default]
534    Es256,
535    /// Ed25519 (COSE EdDSA).
536    Ed25519,
537}
538
539impl SignerAlg {
540    fn to_token_alg(self) -> boatramp_core::cose::TokenAlg {
541        match self {
542            Self::Es256 => boatramp_core::cose::TokenAlg::Es256,
543            Self::Ed25519 => boatramp_core::cose::TokenAlg::Ed25519,
544        }
545    }
546}
547
548/// External token signer selector (`serve.signer`). Maps to
549/// [`boatramp_server::signer::SignerConfig`]; secrets (tokens/PINs) are resolved
550/// from the named env vars at startup, never stored in config. Written as a RON
551/// enum — `signer: Vault(...)`, `signer: AwsKms(...)`, `signer: Pkcs11(...)`, ….
552#[derive(Debug, Clone, Deserialize)]
553#[serde(deny_unknown_fields)]
554pub enum AuthSignerConfig {
555    /// In-process key (`"<alg>:<hex>"`).
556    Local {
557        /// The private key spec, `"<alg>:<hex>"`.
558        private_key: String,
559    },
560    /// HashiCorp Vault Transit key.
561    Vault {
562        /// Vault base address.
563        address: String,
564        /// The Transit key name.
565        key: String,
566        /// Env var holding the Vault token.
567        token_env: String,
568        /// The key algorithm.
569        #[serde(default)]
570        alg: SignerAlg,
571    },
572    /// AWS KMS asymmetric key (ES256).
573    AwsKms {
574        /// The KMS key id or ARN.
575        key_id: String,
576        /// Optional region override.
577        #[serde(default)]
578        region: Option<String>,
579    },
580    /// GCP Cloud KMS key version (ES256).
581    GcpKms {
582        /// The key-version resource name.
583        key_version: String,
584        /// Env var holding a GCP OAuth2 access token.
585        access_token_env: String,
586    },
587    /// Azure Key Vault key (ES256).
588    AzureKv {
589        /// The vault base URL.
590        vault_url: String,
591        /// The key name.
592        key: String,
593        /// The key version.
594        key_version: String,
595        /// Env var holding an Azure AD access token.
596        access_token_env: String,
597    },
598    /// PKCS#11 HSM key.
599    Pkcs11 {
600        /// Path to the PKCS#11 module.
601        module: String,
602        /// The token label.
603        token_label: String,
604        /// The key's `CKA_LABEL`.
605        key_label: String,
606        /// Env var holding the user PIN.
607        pin_env: String,
608        /// The key algorithm.
609        #[serde(default)]
610        alg: SignerAlg,
611    },
612}
613
614impl AuthSignerConfig {
615    /// Map the config-file form to the server's runtime [`SignerConfig`].
616    pub fn to_signer_config(&self) -> boatramp_server::signer::SignerConfig {
617        use boatramp_server::signer::SignerConfig;
618        match self {
619            Self::Local { private_key } => SignerConfig::Local {
620                private_key: private_key.clone(),
621            },
622            Self::Vault {
623                address,
624                key,
625                token_env,
626                alg,
627            } => SignerConfig::Vault {
628                address: address.clone(),
629                key: key.clone(),
630                token_env: token_env.clone(),
631                alg: alg.to_token_alg(),
632            },
633            Self::AwsKms { key_id, region } => SignerConfig::AwsKms {
634                key_id: key_id.clone(),
635                region: region.clone(),
636            },
637            Self::GcpKms {
638                key_version,
639                access_token_env,
640            } => SignerConfig::GcpKms {
641                key_version: key_version.clone(),
642                access_token_env: access_token_env.clone(),
643            },
644            Self::AzureKv {
645                vault_url,
646                key,
647                key_version,
648                access_token_env,
649            } => SignerConfig::AzureKv {
650                vault_url: vault_url.clone(),
651                key: key.clone(),
652                key_version: key_version.clone(),
653                access_token_env: access_token_env.clone(),
654            },
655            Self::Pkcs11 {
656                module,
657                token_label,
658                key_label,
659                pin_env,
660                alg,
661            } => SignerConfig::Pkcs11 {
662                module: module.clone(),
663                token_label: token_label.clone(),
664                key_label: key_label.clone(),
665                pin_env: pin_env.clone(),
666                alg: alg.to_token_alg(),
667            },
668        }
669    }
670}
671
672/// `serve` section — server defaults, overridden by flags/env.
673#[derive(Debug, Clone, Default, Deserialize)]
674#[serde(default)]
675pub struct ServeConfig {
676    /// Bind address (e.g. `0.0.0.0:8080`).
677    pub addr: Option<SocketAddr>,
678    /// Data directory for filesystem backends.
679    pub data_dir: Option<PathBuf>,
680    /// Token root **private** key (hex) — issuing node: verifies *and* mints
681    /// tokens / OIDC exchanges.
682    pub auth_root_private_key: Option<String>,
683    /// Token root **public** key (hex) — verify-only node.
684    pub auth_root_public_key: Option<String>,
685    /// Single-use bootstrap secret enabling `POST /api/tokens/bootstrap` (mint the
686    /// first token without an admin bearer). Prefer the `BOATRAMP_BOOTSTRAP_SECRET`
687    /// env / `--bootstrap-secret` flag so it isn't persisted in the config file.
688    pub bootstrap_secret: Option<String>,
689    /// External token signer (`[serve.signer]`): mint with a
690    /// KMS/HSM/Vault-held root key instead of an in-process `auth_root_private_key`.
691    /// Absent ⇒ the in-process key. When set, its public half is the trust anchor.
692    pub signer: Option<AuthSignerConfig>,
693    /// Reject blob uploads larger than this many bytes.
694    pub max_upload_bytes: Option<u64>,
695    /// Abort an upload that stalls for longer than this many seconds.
696    pub upload_idle_timeout_secs: Option<u64>,
697    /// Cap on simultaneous blob uploads.
698    pub max_concurrent_uploads: Option<usize>,
699    /// In a TLS mode, bind this plain-HTTP address on a second listener that
700    /// redirects to HTTPS (dual-listener). Only read in `tls` builds.
701    #[cfg_attr(not(feature = "tls"), allow(dead_code))]
702    pub http_redirect_addr: Option<SocketAddr>,
703    /// Site to serve for a `Host` matching no domain, instead of 404.
704    pub default_site: Option<String>,
705    /// The fleet's canonical public origin (e.g. `https://cp.example.com`) that a
706    /// per-request proof-of-possession must bind to (`aud`). Required for
707    /// holder-bound (`cnf`/PoP) tokens to be usable — a proof's origin is compared
708    /// against this value, never against a `Host`/`X-Forwarded-*` header.
709    pub pop_origin: Option<String>,
710    /// Require a valid control-plane token to view deployment previews.
711    pub protect_previews: bool,
712    /// Rate-limit cluster-wide via the control-plane KV instead of per node.
713    pub cluster_rate_limit: bool,
714    /// Keep the config cache coherent across processes sharing one KV via the
715    /// changelog.
716    pub shared_cache_coherence: bool,
717    /// Cloud blob-change notification provisioning tier (FA-5b2): how boatramp
718    /// obtains the native event pipeline (S3→SQS) that backs a `blob` trigger —
719    /// `dry-run` (print the recipe), `provision` (create + retract), `verify-only`
720    /// (operator pre-wired), or `refuse` (fail closed). Absent ⇒ no provisioning:
721    /// `blob` triggers then work only on a self-watching backend (fs). Only wired
722    /// for the S3 backend (`--features s3`).
723    pub blob_notify_tier: Option<boatramp_core::blob_notify::ProvisionTier>,
724    /// The AWS account id used to scope the provisioned SQS queue's `SendMessage`
725    /// policy (`aws:SourceAccount`). Required when `blob_notify_tier` provisions.
726    pub blob_notify_account_id: Option<String>,
727    /// `[serve.console]` — the embedded web management console. Absent (or
728    /// `enabled: false`) ⇒ not served. This is the **baseline** for the dynamic
729    /// `console.*` daemon-config override, which can enable/move it at runtime
730    /// (`boatramp config set console.enabled true`) without a restart.
731    pub console: Option<ConsoleConfig>,
732}
733
734/// `[serve.console]` — the embedded web console (a Wasm SPA baked into the
735/// binary with the `console` build feature). Opt-in: the static shell holds no
736/// secrets and the `/api` it drives is token-gated, so it is served
737/// **unauthenticated** at a deliberately obscure path (a bearer token can't gate
738/// a top-level browser navigation anyway — the path is the obscurity, the token
739/// is the real gate).
740#[cfg_attr(not(feature = "console"), allow(dead_code))]
741#[derive(Debug, Clone, Default, Deserialize)]
742#[serde(default, deny_unknown_fields)]
743pub struct ConsoleConfig {
744    /// Serve the embedded console (default `false`). Requires the `console` build
745    /// feature; enabling it in a build without that feature is a logged no-op.
746    pub enabled: bool,
747    /// Host(s) the console answers on: `*` (any host, the default), an exact host
748    /// (`console.example.com`), or a leading-wildcard (`*.example.com`).
749    pub host: Option<String>,
750    /// URL path prefix the console mounts at (default `/_console`). Kept under the
751    /// reserved `/_` namespace so it never collides with a published site path.
752    pub path: Option<String>,
753}
754
755/// `publish` section — where and what to deploy (the `sync` target).
756#[derive(Debug, Default, Deserialize)]
757#[serde(default)]
758pub struct PublishConfig {
759    /// Base URL of the boatramp server (e.g. `https://pad.example.com`).
760    pub server: Option<String>,
761    /// Site name to publish to.
762    pub site: Option<String>,
763    /// API token for the control plane (or set `BOATRAMP_TOKEN`).
764    pub token: Option<String>,
765    /// Project this site belongs to (overrides with `--project` / `BOATRAMP_PROJECT`).
766    pub project: Option<String>,
767}
768
769/// `build` section.
770#[derive(Debug, Clone, Deserialize)]
771pub struct BuildConfig {
772    /// Shell command to run (e.g. `npm run build`).
773    pub command: String,
774    /// Directory the build emits, published by `sync` (e.g. `dist`).
775    #[serde(default)]
776    pub output: Option<String>,
777}
778
779/// `bundle` section — the in-process Rust bundler (`bundler` feature).
780#[derive(Debug, Clone, Default, Deserialize)]
781#[serde(default)]
782pub struct BundleConfig {
783    /// Output directory for bundled assets (e.g. `dist`).
784    #[serde(default = "default_bundle_outdir")]
785    pub outdir: String,
786    /// JS/TS entry points bundled by Rolldown (tree-shaken, code-split).
787    pub js: Vec<String>,
788    /// CSS entry points bundled by lightningcss (`@import` inlined).
789    pub css: Vec<String>,
790    /// Minify output (default true).
791    #[serde(default = "default_true")]
792    pub minify: bool,
793}
794
795fn default_bundle_outdir() -> String {
796    "dist".to_string()
797}
798
799fn default_true() -> bool {
800    true
801}
802
803#[cfg(test)]
804mod tests {
805    use super::*;
806
807    fn project(text: &str) -> ProjectConfig {
808        ron_options().from_str(text).unwrap()
809    }
810
811    fn server(text: &str) -> ServerConfig {
812        ron_options().from_str(text).unwrap()
813    }
814
815    #[test]
816    fn empty_project_config_is_default() {
817        let cfg = project("()");
818        assert!(cfg.publish.server.is_none());
819        assert!(cfg.publish.site.is_none());
820        assert!(cfg.build.is_none());
821        assert!(cfg.bundle.is_none());
822        // Routing defaults: schema v1, the single default index candidate.
823        assert_eq!(cfg.routing.version, 1);
824        assert_eq!(cfg.routing.index, vec!["index.html".to_string()]);
825    }
826
827    #[test]
828    fn serve_signer_config_parses_and_maps_each_backend() {
829        use boatramp_core::cose::TokenAlg;
830        use boatramp_server::signer::SignerConfig;
831
832        // RON-native enum tagging (`Vault(...)`); `IMPLICIT_SOME` lets the optional
833        // fields (region) take a bare value or be omitted (→ None). This is the
834        // exact RON documented in the Authentication guide.
835        let vault = server(
836            r#"( serve: ( signer: Vault(
837                address: "https://vault.example:8200",
838                key: "boatramp-root",
839                token_env: "VAULT_TOKEN",
840                alg: Ed25519,
841            ) ) )"#,
842        );
843        match vault.serve.unwrap().signer.unwrap().to_signer_config() {
844            SignerConfig::Vault {
845                address,
846                key,
847                token_env,
848                alg,
849            } => {
850                assert_eq!(address, "https://vault.example:8200");
851                assert_eq!(key, "boatramp-root");
852                assert_eq!(token_env, "VAULT_TOKEN");
853                assert_eq!(alg, TokenAlg::Ed25519);
854            }
855            other => panic!("expected Vault, got {other:?}"),
856        }
857
858        // AWS KMS: region omitted → None; PKCS#11: alg omitted → the ES256 default.
859        let aws =
860            server(r#"( serve: ( signer: AwsKms(key_id: "arn:aws:kms:eu-west-1:1:key/abc") ) )"#);
861        assert!(matches!(
862            aws.serve.unwrap().signer.unwrap().to_signer_config(),
863            SignerConfig::AwsKms { region: None, .. }
864        ));
865
866        let hsm = server(
867            r#"( serve: ( signer: Pkcs11(
868                module: "/usr/lib/softhsm/libsofthsm2.so",
869                token_label: "boatramp",
870                key_label: "root",
871                pin_env: "HSM_PIN",
872            ) ) )"#,
873        );
874        match hsm.serve.unwrap().signer.unwrap().to_signer_config() {
875            SignerConfig::Pkcs11 { alg, .. } => assert_eq!(alg, TokenAlg::Es256),
876            other => panic!("expected Pkcs11, got {other:?}"),
877        }
878    }
879
880    #[test]
881    fn project_config_parses_publish_build_and_routing() {
882        let cfg = project(
883            r#"(
884                publish: ( server: "http://127.0.0.1:8080", site: "demo" ),
885                build: ( command: "npm run build", output: "dist" ),
886                routing: (
887                    clean_urls: true,
888                    redirects: [ (from: "/old/:slug", to: "/new/:slug", status: 301) ],
889                ),
890            )"#,
891        );
892        assert_eq!(cfg.publish.server.as_deref(), Some("http://127.0.0.1:8080"));
893        assert_eq!(cfg.publish.site.as_deref(), Some("demo"));
894        let build = cfg.build.unwrap();
895        assert_eq!(build.command, "npm run build");
896        assert_eq!(build.output.as_deref(), Some("dist"));
897        assert!(cfg.routing.clean_urls);
898        assert_eq!(cfg.routing.redirects.len(), 1);
899        assert_eq!(cfg.routing.redirects[0].status, 301);
900    }
901
902    #[test]
903    fn project_config_rejects_bad_routing_pattern() {
904        // The same compile-check `load` runs: a bad route pattern is an error.
905        let cfg = project(r#"( routing: ( redirects: [ (from: "/a/**/b/**", to: "/x") ] ) )"#);
906        assert!(cfg.routing.compile_check().is_err());
907    }
908
909    #[test]
910    fn empty_server_config_has_no_sections() {
911        let cfg = server("()");
912        assert!(cfg.serve.is_none());
913        assert!(cfg.handlers.is_none());
914        assert!(cfg.cluster.is_none());
915        assert!(cfg.security.is_none());
916    }
917
918    #[test]
919    fn security_section_parses_and_resolves() {
920        // A profile plus an override that wins over it.
921        let cfg = server(
922            r#"(
923                security: (
924                    profile: "dev",
925                    overrides: (
926                        oidc_require_audience: true,
927                        max_upload_bytes: 0,
928                    ),
929                )
930            )"#,
931        );
932        let posture = cfg.security.unwrap().resolve().expect("resolves");
933        // `dev` is loose...
934        assert!(posture.allow_unauthenticated_public_bind);
935        // ...but the explicit override wins over the profile.
936        assert!(posture.oidc_require_audience);
937        assert_eq!(posture.max_upload_bytes, 0); // unlimited
938    }
939
940    #[test]
941    fn cluster_section_parses_the_dynamic_join_shape() {
942        let cfg = server(
943            r#"(
944                cluster: (
945                    listen: "10.0.0.2:7000",
946                    root_pubkeys: ["es256:03a1"],
947                    seeds: ["https://10.0.0.1:8080"],
948                    join_token: "env:BOATRAMP_JOIN_TOKEN",
949                ),
950            )"#,
951        );
952        let cluster = cfg.cluster.unwrap();
953        assert_eq!(
954            cluster.listen,
955            "10.0.0.2:7000".parse::<std::net::SocketAddr>().unwrap()
956        );
957        assert_eq!(cluster.root_pubkeys, vec!["es256:03a1".to_string()]);
958        assert_eq!(cluster.seeds, vec!["https://10.0.0.1:8080".to_string()]);
959        assert_eq!(
960            cluster.join_token.as_deref(),
961            Some("env:BOATRAMP_JOIN_TOKEN")
962        );
963        // store_dir defaults to None (→ <data-dir>/raft at serve time).
964        assert!(cluster.store_dir.is_none());
965    }
966
967    #[test]
968    fn cluster_section_founds_with_just_a_listen_addr() {
969        // A founder needs no seeds/token — just where to bind the mesh.
970        let cfg = server(r#"( cluster: ( listen: "0.0.0.0:7000" ) )"#);
971        let cluster = cfg.cluster.unwrap();
972        assert!(cluster.seeds.is_empty());
973        assert!(cluster.root_pubkeys.is_empty());
974        assert!(cluster.join_token.is_none());
975    }
976
977    #[test]
978    fn sql_binding_single_node_defaults() {
979        // A bare section (or none) means single-node: no url, default dir.
980        let cfg = server(r#"( handlers: ( bindings: ( sql: () ) ) )"#);
981        let sql = cfg.handlers.unwrap().bindings.sql.unwrap();
982        assert!(sql.url.is_none());
983        assert!(sql.dir.is_none());
984    }
985
986    #[test]
987    fn sql_binding_single_node_custom_dir() {
988        let cfg =
989            server(r#"( handlers: ( bindings: ( sql: ( dir: "/var/lib/boatramp/sql" ) ) ) )"#);
990        let sql = cfg.handlers.unwrap().bindings.sql.unwrap();
991        assert_eq!(sql.dir.as_deref(), Some(Path::new("/var/lib/boatramp/sql")));
992        assert!(sql.url.is_none());
993    }
994
995    #[test]
996    fn sql_binding_cluster() {
997        let cfg = server(
998            r#"(
999                handlers: ( bindings: ( sql: (
1000                    url: "http://sqld:8080",
1001                    admin_url: "http://sqld:9090",
1002                    token_env: "BOATRAMP_SQL_TOKEN",
1003                ) ) ),
1004            )"#,
1005        );
1006        let sql = cfg.handlers.unwrap().bindings.sql.unwrap();
1007        assert_eq!(sql.url.as_deref(), Some("http://sqld:8080"));
1008        assert_eq!(sql.admin_url.as_deref(), Some("http://sqld:9090"));
1009        assert_eq!(sql.token_env.as_deref(), Some("BOATRAMP_SQL_TOKEN"));
1010        assert_eq!(sql.admin_token_env, None);
1011    }
1012
1013    #[test]
1014    fn sql_binding_preview_policy() {
1015        let cfg = server(
1016            r#"(
1017                handlers: ( bindings: ( sql: (
1018                    preview_mode: "branch",
1019                    preview_init: "/etc/boatramp/seed.sql",
1020                ) ) ),
1021            )"#,
1022        );
1023        let sql = cfg.handlers.unwrap().bindings.sql.unwrap();
1024        assert_eq!(sql.preview_mode.as_deref(), Some("branch"));
1025        assert_eq!(
1026            sql.preview_init.as_deref(),
1027            Some(Path::new("/etc/boatramp/seed.sql"))
1028        );
1029    }
1030
1031    #[test]
1032    fn sql_binding_external_databases() {
1033        let cfg = server(
1034            r#"(
1035                handlers: ( bindings: ( sql: (
1036                    databases: {
1037                        "analytics": (
1038                            kind: "postgres",
1039                            url_env: "ANALYTICS_PG_URL",
1040                            pool_max: 16,
1041                            read_only: true,
1042                        ),
1043                        "events": (
1044                            kind: "mysql",
1045                            url_env: "EVENTS_MYSQL_URL",
1046                            read_url_env: "EVENTS_MYSQL_REPLICA_URL",
1047                            allow_preview: true,
1048                        ),
1049                    },
1050                ) ) ),
1051            )"#,
1052        );
1053        let sql = cfg.handlers.unwrap().bindings.sql.unwrap();
1054        assert_eq!(sql.databases.len(), 2);
1055
1056        let analytics = &sql.databases["analytics"];
1057        assert_eq!(analytics.kind, "postgres");
1058        assert_eq!(analytics.url_env, "ANALYTICS_PG_URL");
1059        assert_eq!(analytics.pool_max, Some(16));
1060        assert!(analytics.read_only);
1061        assert!(!analytics.allow_preview);
1062        assert!(analytics.read_url_env.is_none());
1063
1064        let events = &sql.databases["events"];
1065        assert_eq!(events.kind, "mysql");
1066        assert_eq!(
1067            events.read_url_env.as_deref(),
1068            Some("EVENTS_MYSQL_REPLICA_URL")
1069        );
1070        assert!(events.allow_preview);
1071        assert!(!events.read_only);
1072    }
1073
1074    #[test]
1075    fn sql_binding_compute_backed_database() {
1076        let cfg = server(
1077            r#"(
1078                handlers: ( bindings: ( sql: (
1079                    databases: {
1080                        "analytics": (
1081                            kind: "postgres",
1082                            compute: "pg",
1083                            database: "analytics",
1084                            user: "app",
1085                            password_env: "PG_APP_PW",
1086                        ),
1087                    },
1088                ) ) ),
1089            )"#,
1090        );
1091        let db = &cfg.handlers.unwrap().bindings.sql.unwrap().databases["analytics"];
1092        assert_eq!(db.kind, "postgres");
1093        assert_eq!(db.compute.as_deref(), Some("pg"));
1094        assert_eq!(db.database.as_deref(), Some("analytics"));
1095        assert_eq!(db.user.as_deref(), Some("app"));
1096        assert_eq!(db.password_env.as_deref(), Some("PG_APP_PW"));
1097        assert!(db.url_env.is_empty(), "compute-backed has no url_env");
1098        assert!(db.validate("analytics").is_ok());
1099    }
1100
1101    #[test]
1102    fn sql_binding_source_is_exactly_one_of_url_or_compute() {
1103        // Neither source → error.
1104        assert!(ExternalDatabaseConfig::default().validate("db").is_err());
1105        // Both sources → error.
1106        let both = ExternalDatabaseConfig {
1107            kind: "postgres".into(),
1108            url_env: "PG_URL".into(),
1109            compute: Some("pg".into()),
1110            ..Default::default()
1111        };
1112        assert!(both.validate("db").is_err());
1113        // `url_env` only → ok.
1114        let url = ExternalDatabaseConfig {
1115            kind: "postgres".into(),
1116            url_env: "PG_URL".into(),
1117            ..Default::default()
1118        };
1119        assert!(url.validate("db").is_ok());
1120        // `compute` without the connection details boatramp can't infer → error.
1121        let bare = ExternalDatabaseConfig {
1122            kind: "postgres".into(),
1123            compute: Some("pg".into()),
1124            ..Default::default()
1125        };
1126        assert!(bare.validate("db").is_err());
1127        // `compute` with database/user + a bring-your-own `password_env` → ok, and
1128        // is *not* a managed credential.
1129        let byo = ExternalDatabaseConfig {
1130            kind: "postgres".into(),
1131            compute: Some("pg".into()),
1132            database: Some("analytics".into()),
1133            user: Some("app".into()),
1134            password_env: Some("PG_APP_PW".into()),
1135            ..Default::default()
1136        };
1137        assert!(byo.validate("db").is_ok());
1138        assert!(!byo.is_managed_credential());
1139        // `compute` with database/user but NO `password_env` → ok, and boatramp
1140        // manages the credential (Phase 2).
1141        let managed = ExternalDatabaseConfig {
1142            kind: "postgres".into(),
1143            compute: Some("pg".into()),
1144            database: Some("analytics".into()),
1145            user: Some("app".into()),
1146            ..Default::default()
1147        };
1148        assert!(managed.validate("db").is_ok());
1149        assert!(managed.is_managed_credential());
1150    }
1151
1152    /// Path to a file at the repo root (two levels up from this crate).
1153    fn repo_root_file(name: &str) -> PathBuf {
1154        Path::new(env!("CARGO_MANIFEST_DIR"))
1155            .join("../..")
1156            .join(name)
1157    }
1158
1159    #[test]
1160    fn shipped_project_example_parses() {
1161        // The example we ship must always parse + compile-check, so it can't drift
1162        // from the schema.
1163        let text = std::fs::read_to_string(repo_root_file("examples/site/project.cfg.example"))
1164            .expect("example project config is present");
1165        let cfg = ProjectConfig::parse(&text).expect("example project config parses");
1166        assert_eq!(cfg.publish.server.as_deref(), Some("http://127.0.0.1:8080"));
1167        assert_eq!(cfg.build.as_ref().unwrap().command, "npm run build");
1168        assert_eq!(
1169            cfg.routing.error_documents.get(&404).map(String::as_str),
1170            Some("/404.html")
1171        );
1172    }
1173
1174    #[test]
1175    fn shipped_server_example_parses() {
1176        let text = std::fs::read_to_string(repo_root_file("boatramp.cfg.example"))
1177            .expect("example server config is present");
1178        let cfg = ServerConfig::parse(&text).expect("example server config parses");
1179        let serve = cfg.serve.expect("example sets a serve section");
1180        assert_eq!(
1181            serve.addr,
1182            Some("0.0.0.0:8080".parse::<std::net::SocketAddr>().unwrap())
1183        );
1184    }
1185
1186    #[test]
1187    fn secrets_section_parses_local_and_vault() {
1188        let local = server(r#"( secrets: ( envelope: "local", kek_file: "/k/kek" ) )"#)
1189            .secrets
1190            .expect("secrets section");
1191        assert_eq!(local.envelope, "local");
1192        assert_eq!(
1193            local.kek_file.as_deref(),
1194            Some(std::path::Path::new("/k/kek"))
1195        );
1196
1197        let vault = server(
1198            r#"( secrets: ( envelope: "vault", vault: ( addr: "https://vault:8200", key: "certs" ) ) )"#,
1199        )
1200        .secrets
1201        .expect("secrets section");
1202        let v = vault.vault.expect("vault subsection");
1203        assert_eq!(v.addr, "https://vault:8200");
1204        assert_eq!(v.key, "certs");
1205        // The token env defaults to VAULT_TOKEN and is never in the file.
1206        assert_eq!(v.token_env, "VAULT_TOKEN");
1207    }
1208
1209    #[test]
1210    fn serve_section_partial_parses() {
1211        // A partial `serve` section parses — unset fields take their defaults.
1212        let cfg = server(r#"( serve: ( addr: "0.0.0.0:8080", protect_previews: true ) )"#);
1213        let serve = cfg.serve.unwrap();
1214        assert_eq!(
1215            serve.addr,
1216            Some("0.0.0.0:8080".parse::<std::net::SocketAddr>().unwrap())
1217        );
1218        assert!(serve.protect_previews);
1219        assert!(!serve.cluster_rate_limit);
1220        assert!(serve.data_dir.is_none());
1221    }
1222
1223    #[test]
1224    fn serve_console_config_parses() {
1225        // Absent ⇒ no console.
1226        let cfg = server(r#"( serve: ( addr: "0.0.0.0:8080" ) )"#);
1227        assert!(cfg.serve.unwrap().console.is_none());
1228        // Explicit console block with host + path.
1229        let cfg = server(
1230            r#"( serve: ( console: (
1231                enabled: true,
1232                host: "console.example.com",
1233                path: "/_console",
1234            ) ) )"#,
1235        );
1236        let console = cfg.serve.unwrap().console.unwrap();
1237        assert!(console.enabled);
1238        assert_eq!(console.host.as_deref(), Some("console.example.com"));
1239        assert_eq!(console.path.as_deref(), Some("/_console"));
1240        // Bare `enabled` ⇒ host/path take their (server-side) defaults.
1241        let cfg = server(r#"( serve: ( console: ( enabled: true ) ) )"#);
1242        let console = cfg.serve.unwrap().console.unwrap();
1243        assert!(console.enabled);
1244        assert!(console.host.is_none() && console.path.is_none());
1245    }
1246}