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