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    /// Engine-wide **safety max** on a *connection-bearing* invocation (a site
396    /// handler or a synchronous function/webhook invoke), milliseconds. A route
397    /// or function may declare a *lower* timeout, never a higher one. Kept tight
398    /// on purpose: a client, proxy, and the shared request pool are all blocked
399    /// while a sync handler runs. Absent ⇒ 10s (the historical default). This is
400    /// a node safety ceiling, not a per-invocation budget, and is distinct from
401    /// a per-site `max_timeout_ms`.
402    pub sync_max_timeout_ms: Option<u64>,
403    /// Engine-wide safety max on a *durable async* invocation — the drain that
404    /// runs `?mode=async` calls, workflow steps, cron/queue/blob triggers, and
405    /// `wasi:messaging` consumers, milliseconds. No client is connected and the
406    /// work is retried + dead-lettered, so this can be far larger than the sync
407    /// ceiling: it is what lets a legitimately long background job (e.g. an LLM
408    /// generation) declare and actually get minutes of runtime. Absent ⇒ 15
409    /// minutes. Runs on its own concurrency budget (`async_max_concurrency`), so
410    /// a long job never starves live traffic.
411    pub async_max_timeout_ms: Option<u64>,
412    /// Max concurrent in-flight *async-lane* invocations, kept separate from the
413    /// (larger) request pool so a burst of long background jobs can't exhaust the
414    /// slots live site traffic needs. Absent ⇒ 8.
415    pub async_max_concurrency: Option<usize>,
416    /// Optional CPU **fuel** ceiling for an async-lane invocation. A large async
417    /// timeout bounds only wall-clock; without a fuel bound a CPU-bound guest can
418    /// spin for the whole window. Absent ⇒ unmetered (same as the sync default).
419    pub async_max_fuel: Option<u64>,
420    /// Max wall-clock for a *streaming-lane* response (a `#[handler(stream)]`
421    /// route — SSE, chunked, agent token streaming), milliseconds. A client is
422    /// connected but the body is written incrementally over seconds-to-minutes,
423    /// so this is far larger than the sync ceiling. Runs on its own concurrency
424    /// budget (`streaming_max_concurrency`), isolated from both the fast request
425    /// pool and the async drain. Absent ⇒ 15 minutes.
426    pub streaming_max_timeout_ms: Option<u64>,
427    /// Max concurrent in-flight *streaming-lane* responses, kept separate from the
428    /// request pool and the async drain so a burst of long-lived streams starves
429    /// neither. Absent ⇒ 64.
430    pub streaming_max_concurrency: Option<usize>,
431    /// Optional CPU **fuel** ceiling for a streaming-lane response. Absent ⇒
432    /// unmetered (a stream is I/O-bound on the client, not CPU-bound).
433    pub streaming_max_fuel: Option<u64>,
434    /// Optional ceiling on a guest's **outbound** `wasi:http` call — the connect
435    /// and time-to-first-byte wait — milliseconds, independent of the invocation
436    /// timeout, so a hung upstream is bounded on its own terms. The streaming
437    /// (between-bytes) timeout is left at wasmtime's default so a slow token
438    /// stream is not cut mid-flight. Absent ⇒ wasmtime's default.
439    pub outbound_timeout_ms: Option<u64>,
440}
441
442/// `handlers.bindings` — per-binding backend configuration. kv/blob reuse the
443/// server's own KV/Storage backends (per-site prefixed); `sql` is the single
444/// libsql backend, whose single-node-vs-cluster split is the only choice.
445#[cfg_attr(not(feature = "handlers"), allow(dead_code))]
446#[derive(Debug, Clone, Default, Deserialize)]
447#[serde(default)]
448pub struct BindingsConfig {
449    /// `handlers.bindings.sql` — libsql settings. Absent ⇒ single-node,
450    /// per-site embedded files under `<data-dir>/handlers-sql`.
451    pub sql: Option<SqlBindingConfig>,
452}
453
454/// libsql settings for the handler `sql` binding — the single SQL backend. Each
455/// site gets a real database boundary (an embedded file per site, or a sqld
456/// namespace per site), never schema separation (which arbitrary guest SQL
457/// escapes). Setting `url` switches from single-node to a shared sqld cluster;
458/// everything else stays identical.
459#[cfg_attr(not(feature = "handlers"), allow(dead_code))]
460#[derive(Debug, Clone, Default, Deserialize)]
461#[serde(default)]
462pub struct SqlBindingConfig {
463    /// Single-node: root directory for the per-site embedded database files
464    /// (default `<data-dir>/handlers-sql`). Ignored when `url` is set.
465    pub dir: Option<PathBuf>,
466    /// Cluster: base sqld data URL (e.g. `http://sqld:8080`). When set, each
467    /// site is a sqld namespace addressed as a subdomain of this URL; `admin_url`
468    /// is then required.
469    pub url: Option<String>,
470    /// Cluster: sqld admin API base URL (e.g. `http://sqld:9090`) for creating
471    /// per-site namespaces. Required when `url` is set.
472    pub admin_url: Option<String>,
473    /// Cluster: optional sqld **read-replica** data URL. When set, handlers'
474    /// read-only `sql` transactions (`open-read-only`) route to this endpoint
475    /// while writes stay on `url` (reads → replicas, writes → primary).
476    /// Reads may lag (eventually consistent). Ignored in
477    /// single-node mode (no `url`).
478    pub replica_url: Option<String>,
479    /// Name of the env var holding the sqld data auth token (optional; never
480    /// the token itself in-file).
481    pub token_env: Option<String>,
482    /// Name of the env var holding the sqld admin API auth key (optional).
483    pub admin_token_env: Option<String>,
484    /// How preview deployments get their SQL database: `empty` (default — a
485    /// fresh isolated db), `branch` (a consistent copy of the site's live db;
486    /// single-node only), or `shared` (the site's live db). See
487    /// `boatramp_core::sql::PreviewSqlMode`.
488    pub preview_mode: Option<String>,
489    /// Path to an idempotent SQL script run when an `empty` preview database is
490    /// first opened (e.g. schema/seed). Ignored in `branch`/`shared` modes.
491    pub preview_init: Option<PathBuf>,
492    /// `handlers.bindings.sql.databases` — external **bring-your-own** databases,
493    /// each opened by name via `sql.open("<name>")`. An operator-configured
494    /// Postgres/MySQL whose *isolation is the operator's* (it's their database),
495    /// so these bypass the per-site libsql boundary and are reachable by any
496    /// handler/function granted the `sql` binding. Needs the `sql-postgres` /
497    /// `sql-mysql` build feature for the engine. A name here shadows the same
498    /// name on the managed libsql default.
499    pub databases: BTreeMap<String, ExternalDatabaseConfig>,
500}
501
502/// One external SQL database for the handler `sql` binding. Its **source** is one
503/// of two mutually-exclusive forms:
504///  - `url_env` — a **bring-your-own** database: the connection URL is a secret,
505///    named indirectly by an env var (never written in the config file).
506///  - `compute` — a database **boatramp runs** as a compute workload: boatramp
507///    derives the connection from the workload's live endpoint (host\:port) plus
508///    the `database`/`user`/`password_env` here, so there is no URL to hand-map and
509///    it follows the workload across restarts (PLAN-managed-compute-sql).
510#[cfg_attr(not(feature = "handlers"), allow(dead_code))]
511#[derive(Debug, Clone, Default, Deserialize)]
512#[serde(default)]
513pub struct ExternalDatabaseConfig {
514    /// Engine: `postgres` (aliases `postgresql`/`pg`) or `mysql` (alias
515    /// `mariadb`).
516    pub kind: String,
517    /// Name of the env var holding the connection URL (e.g.
518    /// `postgres://user:pw@host/db`). Required unless `compute` is set.
519    pub url_env: String,
520    /// Optional env var holding a **read-replica** connection URL. When set,
521    /// `open-read-only` transactions route there; writes stay on `url_env`.
522    pub read_url_env: Option<String>,
523    /// The name of a **compute workload** (a Postgres/MySQL server boatramp runs)
524    /// to source this database from, instead of `url_env`. boatramp resolves the
525    /// workload's live endpoint and builds the connection. Mutually exclusive with
526    /// `url_env`.
527    pub compute: Option<String>,
528    /// The database name inside the compute-backed server (non-secret).
529    pub database: Option<String>,
530    /// The connecting user for the compute-backed server (non-secret).
531    pub user: Option<String>,
532    /// Env var holding the password for `user` on the compute-backed server.
533    /// **Omit to let boatramp fully manage the credential** (PLAN-managed-compute-sql
534    /// Phase 2): it generates a strong password once, seals it with the `[secrets]`
535    /// envelope, injects it into the DB workload's server-init env at launch, and
536    /// connects the handler with it — the operator sets no DB secret at all. Set it
537    /// only to bring your own password for the compute-backed server.
538    pub password_env: Option<String>,
539    /// Maximum pooled connections (default 8).
540    pub pool_max: Option<u32>,
541    /// Open every transaction `READ ONLY` (the engine rejects writes) — for a
542    /// database functions should only read.
543    pub read_only: bool,
544    /// Permit **preview** deployments to reach this database. Default `false`: a
545    /// preview is refused, so it can never touch the operator's live external DB.
546    pub allow_preview: bool,
547    /// Connection/acquire timeout in seconds (default 10).
548    pub connect_timeout_secs: Option<u64>,
549}
550
551impl ExternalDatabaseConfig {
552    /// Validate the source is well-formed: **exactly one** of `url_env` /
553    /// `compute`, and a `compute`-backed database has the connection details
554    /// boatramp can't infer (`database` + `user`). `password_env` is **optional** —
555    /// omit it to let boatramp manage the credential (Phase 2). `name` is the
556    /// binding name, for the error message.
557    #[cfg_attr(not(feature = "handlers"), allow(dead_code))]
558    pub fn validate(&self, name: &str) -> Result<(), String> {
559        let has_url = !self.url_env.is_empty();
560        let has_compute = self.compute.as_deref().is_some_and(|c| !c.is_empty());
561        match (has_url, has_compute) {
562            (true, true) => Err(format!(
563                "sql database {name:?}: set exactly one of `url_env` or `compute`, not both"
564            )),
565            (false, false) => Err(format!(
566                "sql database {name:?}: needs a source — set `url_env` (bring-your-own) or \
567                 `compute` (a database boatramp runs)"
568            )),
569            (false, true) => {
570                // `database` + `user` are non-secret and can't be inferred; a missing
571                // `password_env` is *not* an error — it selects the managed credential.
572                for (field, val) in [("database", &self.database), ("user", &self.user)] {
573                    if val.as_deref().is_none_or(str::is_empty) {
574                        return Err(format!(
575                            "sql database {name:?}: a `compute`-backed database requires `{field}`"
576                        ));
577                    }
578                }
579                Ok(())
580            }
581            (true, false) => Ok(()),
582        }
583    }
584
585    /// Whether this compute-backed database uses a **boatramp-managed** credential
586    /// (Phase 2): `compute` is set and no `password_env` was supplied.
587    #[cfg_attr(not(feature = "handlers"), allow(dead_code))]
588    pub fn is_managed_credential(&self) -> bool {
589        self.compute.as_deref().is_some_and(|c| !c.is_empty())
590            && self.password_env.as_deref().is_none_or(str::is_empty)
591    }
592}
593
594/// The signing algorithm for a signer that can choose one (`Local`, `Vault`,
595/// `Pkcs11`). ES256 is the portable default; the cloud KMS backends are ES256-only
596/// and ignore this. Written as a RON enum: `alg: Es256` / `alg: Ed25519`.
597#[derive(Debug, Clone, Copy, Default, Deserialize)]
598pub enum SignerAlg {
599    /// ECDSA P-256 (COSE ES256) — the default.
600    #[default]
601    Es256,
602    /// Ed25519 (COSE EdDSA).
603    Ed25519,
604}
605
606impl SignerAlg {
607    fn to_token_alg(self) -> boatramp_core::cose::TokenAlg {
608        match self {
609            Self::Es256 => boatramp_core::cose::TokenAlg::Es256,
610            Self::Ed25519 => boatramp_core::cose::TokenAlg::Ed25519,
611        }
612    }
613}
614
615/// External token signer selector (`serve.signer`). Maps to
616/// [`boatramp_server::signer::SignerConfig`]; secrets (tokens/PINs) are resolved
617/// from the named env vars at startup, never stored in config. Written as a RON
618/// enum — `signer: Vault(...)`, `signer: AwsKms(...)`, `signer: Pkcs11(...)`, ….
619#[derive(Debug, Clone, Deserialize)]
620#[serde(deny_unknown_fields)]
621pub enum AuthSignerConfig {
622    /// In-process key (`"<alg>:<hex>"`).
623    Local {
624        /// The private key spec, `"<alg>:<hex>"`.
625        private_key: String,
626    },
627    /// HashiCorp Vault Transit key.
628    Vault {
629        /// Vault base address.
630        address: String,
631        /// The Transit key name.
632        key: String,
633        /// Env var holding the Vault token.
634        token_env: String,
635        /// The key algorithm.
636        #[serde(default)]
637        alg: SignerAlg,
638    },
639    /// AWS KMS asymmetric key (ES256).
640    AwsKms {
641        /// The KMS key id or ARN.
642        key_id: String,
643        /// Optional region override.
644        #[serde(default)]
645        region: Option<String>,
646    },
647    /// GCP Cloud KMS key version (ES256).
648    GcpKms {
649        /// The key-version resource name.
650        key_version: String,
651        /// Env var holding a GCP OAuth2 access token.
652        access_token_env: String,
653    },
654    /// Azure Key Vault key (ES256).
655    AzureKv {
656        /// The vault base URL.
657        vault_url: String,
658        /// The key name.
659        key: String,
660        /// The key version.
661        key_version: String,
662        /// Env var holding an Azure AD access token.
663        access_token_env: String,
664    },
665    /// PKCS#11 HSM key.
666    Pkcs11 {
667        /// Path to the PKCS#11 module.
668        module: String,
669        /// The token label.
670        token_label: String,
671        /// The key's `CKA_LABEL`.
672        key_label: String,
673        /// Env var holding the user PIN.
674        pin_env: String,
675        /// The key algorithm.
676        #[serde(default)]
677        alg: SignerAlg,
678    },
679}
680
681impl AuthSignerConfig {
682    /// Map the config-file form to the server's runtime [`SignerConfig`].
683    pub fn to_signer_config(&self) -> boatramp_server::signer::SignerConfig {
684        use boatramp_server::signer::SignerConfig;
685        match self {
686            Self::Local { private_key } => SignerConfig::Local {
687                private_key: private_key.clone(),
688            },
689            Self::Vault {
690                address,
691                key,
692                token_env,
693                alg,
694            } => SignerConfig::Vault {
695                address: address.clone(),
696                key: key.clone(),
697                token_env: token_env.clone(),
698                alg: alg.to_token_alg(),
699            },
700            Self::AwsKms { key_id, region } => SignerConfig::AwsKms {
701                key_id: key_id.clone(),
702                region: region.clone(),
703            },
704            Self::GcpKms {
705                key_version,
706                access_token_env,
707            } => SignerConfig::GcpKms {
708                key_version: key_version.clone(),
709                access_token_env: access_token_env.clone(),
710            },
711            Self::AzureKv {
712                vault_url,
713                key,
714                key_version,
715                access_token_env,
716            } => SignerConfig::AzureKv {
717                vault_url: vault_url.clone(),
718                key: key.clone(),
719                key_version: key_version.clone(),
720                access_token_env: access_token_env.clone(),
721            },
722            Self::Pkcs11 {
723                module,
724                token_label,
725                key_label,
726                pin_env,
727                alg,
728            } => SignerConfig::Pkcs11 {
729                module: module.clone(),
730                token_label: token_label.clone(),
731                key_label: key_label.clone(),
732                pin_env: pin_env.clone(),
733                alg: alg.to_token_alg(),
734            },
735        }
736    }
737}
738
739/// `serve` section — server defaults, overridden by flags/env.
740#[derive(Debug, Clone, Default, Deserialize)]
741#[serde(default)]
742pub struct ServeConfig {
743    /// Bind address (e.g. `0.0.0.0:8080`).
744    pub addr: Option<SocketAddr>,
745    /// Data directory for filesystem backends.
746    pub data_dir: Option<PathBuf>,
747    /// Token root **private** key (hex) — issuing node: verifies *and* mints
748    /// tokens / OIDC exchanges.
749    pub auth_root_private_key: Option<String>,
750    /// Token root **public** key (hex) — verify-only node.
751    pub auth_root_public_key: Option<String>,
752    /// Single-use bootstrap secret enabling `POST /api/tokens/bootstrap` (mint the
753    /// first token without an admin bearer). Prefer the `BOATRAMP_BOOTSTRAP_SECRET`
754    /// env / `--bootstrap-secret` flag so it isn't persisted in the config file.
755    pub bootstrap_secret: Option<String>,
756    /// External token signer (`[serve.signer]`): mint with a
757    /// KMS/HSM/Vault-held root key instead of an in-process `auth_root_private_key`.
758    /// Absent ⇒ the in-process key. When set, its public half is the trust anchor.
759    pub signer: Option<AuthSignerConfig>,
760    /// Reject blob uploads larger than this many bytes.
761    pub max_upload_bytes: Option<u64>,
762    /// Abort an upload that stalls for longer than this many seconds.
763    pub upload_idle_timeout_secs: Option<u64>,
764    /// Cap on simultaneous blob uploads.
765    pub max_concurrent_uploads: Option<usize>,
766    /// In a TLS mode, bind this plain-HTTP address on a second listener that
767    /// redirects to HTTPS (dual-listener). Only read in `tls` builds.
768    #[cfg_attr(not(feature = "tls"), allow(dead_code))]
769    pub http_redirect_addr: Option<SocketAddr>,
770    /// Site to serve for a `Host` matching no domain, instead of 404.
771    pub default_site: Option<String>,
772    /// The fleet's canonical public origin (e.g. `https://cp.example.com`) that a
773    /// per-request proof-of-possession must bind to (`aud`). Required for
774    /// holder-bound (`cnf`/PoP) tokens to be usable — a proof's origin is compared
775    /// against this value, never against a `Host`/`X-Forwarded-*` header.
776    pub pop_origin: Option<String>,
777    /// Require a valid control-plane token to view deployment previews.
778    pub protect_previews: bool,
779    /// Rate-limit cluster-wide via the control-plane KV instead of per node.
780    pub cluster_rate_limit: bool,
781    /// Keep the config cache coherent across processes sharing one KV via the
782    /// changelog.
783    pub shared_cache_coherence: bool,
784    /// Cloud blob-change notification provisioning tier (FA-5b2): how boatramp
785    /// obtains the native event pipeline (S3→SQS) that backs a `blob` trigger —
786    /// `dry-run` (print the recipe), `provision` (create + retract), `verify-only`
787    /// (operator pre-wired), or `refuse` (fail closed). Absent ⇒ no provisioning:
788    /// `blob` triggers then work only on a self-watching backend (fs). Only wired
789    /// for the S3 backend (`--features s3`).
790    pub blob_notify_tier: Option<boatramp_core::blob_notify::ProvisionTier>,
791    /// The AWS account id used to scope the provisioned SQS queue's `SendMessage`
792    /// policy (`aws:SourceAccount`). Required when `blob_notify_tier` provisions.
793    pub blob_notify_account_id: Option<String>,
794    /// `[serve.console]` — the embedded web management console. Absent (or
795    /// `enabled: false`) ⇒ not served. This is the **baseline** for the dynamic
796    /// `console.*` daemon-config override, which can enable/move it at runtime
797    /// (`boatramp config set console.enabled true`) without a restart.
798    pub console: Option<ConsoleConfig>,
799}
800
801/// `[serve.console]` — the embedded web console (a Wasm SPA baked into the
802/// binary with the `console` build feature). Opt-in: the static shell holds no
803/// secrets and the `/api` it drives is token-gated, so it is served
804/// **unauthenticated** at a deliberately obscure path (a bearer token can't gate
805/// a top-level browser navigation anyway — the path is the obscurity, the token
806/// is the real gate).
807#[cfg_attr(not(feature = "console"), allow(dead_code))]
808#[derive(Debug, Clone, Default, Deserialize)]
809#[serde(default, deny_unknown_fields)]
810pub struct ConsoleConfig {
811    /// Serve the embedded console (default `false`). Requires the `console` build
812    /// feature; enabling it in a build without that feature is a logged no-op.
813    pub enabled: bool,
814    /// Host(s) the console answers on: `*` (any host, the default), an exact host
815    /// (`console.example.com`), or a leading-wildcard (`*.example.com`).
816    pub host: Option<String>,
817    /// URL path prefix the console mounts at (default `/_console`). Kept under the
818    /// reserved `/_` namespace so it never collides with a published site path.
819    pub path: Option<String>,
820}
821
822/// `publish` section — where and what to deploy (the `sync` target).
823#[derive(Debug, Default, Deserialize)]
824#[serde(default)]
825pub struct PublishConfig {
826    /// Base URL of the boatramp server (e.g. `https://pad.example.com`).
827    pub server: Option<String>,
828    /// Site name to publish to.
829    pub site: Option<String>,
830    /// API token for the control plane (or set `BOATRAMP_TOKEN`).
831    pub token: Option<String>,
832    /// Project this site belongs to (overrides with `--project` / `BOATRAMP_PROJECT`).
833    pub project: Option<String>,
834}
835
836/// `build` section.
837#[derive(Debug, Clone, Deserialize)]
838pub struct BuildConfig {
839    /// Shell command to run (e.g. `npm run build`).
840    pub command: String,
841    /// Directory the build emits, published by `sync` (e.g. `dist`).
842    #[serde(default)]
843    pub output: Option<String>,
844}
845
846/// `bundle` section — the in-process Rust bundler (`bundler` feature).
847#[derive(Debug, Clone, Default, Deserialize)]
848#[serde(default)]
849pub struct BundleConfig {
850    /// Output directory for bundled assets (e.g. `dist`).
851    #[serde(default = "default_bundle_outdir")]
852    pub outdir: String,
853    /// JS/TS entry points bundled by Rolldown (tree-shaken, code-split).
854    pub js: Vec<String>,
855    /// CSS entry points bundled by lightningcss (`@import` inlined).
856    pub css: Vec<String>,
857    /// Minify output (default true).
858    #[serde(default = "default_true")]
859    pub minify: bool,
860}
861
862fn default_bundle_outdir() -> String {
863    "dist".to_string()
864}
865
866fn default_true() -> bool {
867    true
868}
869
870#[cfg(test)]
871mod tests {
872    use super::*;
873
874    fn project(text: &str) -> ProjectConfig {
875        ron_options().from_str(text).unwrap()
876    }
877
878    fn server(text: &str) -> ServerConfig {
879        ron_options().from_str(text).unwrap()
880    }
881
882    #[test]
883    fn empty_project_config_is_default() {
884        let cfg = project("()");
885        assert!(cfg.publish.server.is_none());
886        assert!(cfg.publish.site.is_none());
887        assert!(cfg.build.is_none());
888        assert!(cfg.bundle.is_none());
889        // Routing defaults: schema v1, the single default index candidate.
890        assert_eq!(cfg.routing.version, 1);
891        assert_eq!(cfg.routing.index, vec!["index.html".to_string()]);
892    }
893
894    #[test]
895    fn serve_signer_config_parses_and_maps_each_backend() {
896        use boatramp_core::cose::TokenAlg;
897        use boatramp_server::signer::SignerConfig;
898
899        // RON-native enum tagging (`Vault(...)`); `IMPLICIT_SOME` lets the optional
900        // fields (region) take a bare value or be omitted (→ None). This is the
901        // exact RON documented in the Authentication guide.
902        let vault = server(
903            r#"( serve: ( signer: Vault(
904                address: "https://vault.example:8200",
905                key: "boatramp-root",
906                token_env: "VAULT_TOKEN",
907                alg: Ed25519,
908            ) ) )"#,
909        );
910        match vault.serve.unwrap().signer.unwrap().to_signer_config() {
911            SignerConfig::Vault {
912                address,
913                key,
914                token_env,
915                alg,
916            } => {
917                assert_eq!(address, "https://vault.example:8200");
918                assert_eq!(key, "boatramp-root");
919                assert_eq!(token_env, "VAULT_TOKEN");
920                assert_eq!(alg, TokenAlg::Ed25519);
921            }
922            other => panic!("expected Vault, got {other:?}"),
923        }
924
925        // AWS KMS: region omitted → None; PKCS#11: alg omitted → the ES256 default.
926        let aws =
927            server(r#"( serve: ( signer: AwsKms(key_id: "arn:aws:kms:eu-west-1:1:key/abc") ) )"#);
928        assert!(matches!(
929            aws.serve.unwrap().signer.unwrap().to_signer_config(),
930            SignerConfig::AwsKms { region: None, .. }
931        ));
932
933        let hsm = server(
934            r#"( serve: ( signer: Pkcs11(
935                module: "/usr/lib/softhsm/libsofthsm2.so",
936                token_label: "boatramp",
937                key_label: "root",
938                pin_env: "HSM_PIN",
939            ) ) )"#,
940        );
941        match hsm.serve.unwrap().signer.unwrap().to_signer_config() {
942            SignerConfig::Pkcs11 { alg, .. } => assert_eq!(alg, TokenAlg::Es256),
943            other => panic!("expected Pkcs11, got {other:?}"),
944        }
945    }
946
947    #[test]
948    fn project_config_parses_publish_build_and_routing() {
949        let cfg = project(
950            r#"(
951                publish: ( server: "http://127.0.0.1:8080", site: "demo" ),
952                build: ( command: "npm run build", output: "dist" ),
953                routing: (
954                    clean_urls: true,
955                    redirects: [ (from: "/old/:slug", to: "/new/:slug", status: 301) ],
956                ),
957            )"#,
958        );
959        assert_eq!(cfg.publish.server.as_deref(), Some("http://127.0.0.1:8080"));
960        assert_eq!(cfg.publish.site.as_deref(), Some("demo"));
961        let build = cfg.build.unwrap();
962        assert_eq!(build.command, "npm run build");
963        assert_eq!(build.output.as_deref(), Some("dist"));
964        assert!(cfg.routing.clean_urls);
965        assert_eq!(cfg.routing.redirects.len(), 1);
966        assert_eq!(cfg.routing.redirects[0].status, 301);
967    }
968
969    #[test]
970    fn project_config_rejects_bad_routing_pattern() {
971        // The same compile-check `load` runs: a bad route pattern is an error.
972        let cfg = project(r#"( routing: ( redirects: [ (from: "/a/**/b/**", to: "/x") ] ) )"#);
973        assert!(cfg.routing.compile_check().is_err());
974    }
975
976    #[test]
977    fn empty_server_config_has_no_sections() {
978        let cfg = server("()");
979        assert!(cfg.serve.is_none());
980        assert!(cfg.handlers.is_none());
981        assert!(cfg.cluster.is_none());
982        assert!(cfg.security.is_none());
983    }
984
985    #[test]
986    fn security_section_parses_and_resolves() {
987        // A profile plus an override that wins over it.
988        let cfg = server(
989            r#"(
990                security: (
991                    profile: "dev",
992                    overrides: (
993                        oidc_require_audience: true,
994                        max_upload_bytes: 0,
995                    ),
996                )
997            )"#,
998        );
999        let posture = cfg.security.unwrap().resolve().expect("resolves");
1000        // `dev` is loose...
1001        assert!(posture.allow_unauthenticated_public_bind);
1002        // ...but the explicit override wins over the profile.
1003        assert!(posture.oidc_require_audience);
1004        assert_eq!(posture.max_upload_bytes, 0); // unlimited
1005    }
1006
1007    #[test]
1008    fn cluster_section_parses_the_dynamic_join_shape() {
1009        let cfg = server(
1010            r#"(
1011                cluster: (
1012                    listen: "10.0.0.2:7000",
1013                    root_pubkeys: ["es256:03a1"],
1014                    seeds: ["https://10.0.0.1:8080"],
1015                    join_token: "env:BOATRAMP_JOIN_TOKEN",
1016                ),
1017            )"#,
1018        );
1019        let cluster = cfg.cluster.unwrap();
1020        assert_eq!(
1021            cluster.listen,
1022            "10.0.0.2:7000".parse::<std::net::SocketAddr>().unwrap()
1023        );
1024        assert_eq!(cluster.root_pubkeys, vec!["es256:03a1".to_string()]);
1025        assert_eq!(cluster.seeds, vec!["https://10.0.0.1:8080".to_string()]);
1026        assert_eq!(
1027            cluster.join_token.as_deref(),
1028            Some("env:BOATRAMP_JOIN_TOKEN")
1029        );
1030        // store_dir defaults to None (→ <data-dir>/raft at serve time).
1031        assert!(cluster.store_dir.is_none());
1032    }
1033
1034    #[test]
1035    fn cluster_section_founds_with_just_a_listen_addr() {
1036        // A founder needs no seeds/token — just where to bind the mesh.
1037        let cfg = server(r#"( cluster: ( listen: "0.0.0.0:7000" ) )"#);
1038        let cluster = cfg.cluster.unwrap();
1039        assert!(cluster.seeds.is_empty());
1040        assert!(cluster.root_pubkeys.is_empty());
1041        assert!(cluster.join_token.is_none());
1042    }
1043
1044    #[test]
1045    fn sql_binding_single_node_defaults() {
1046        // A bare section (or none) means single-node: no url, default dir.
1047        let cfg = server(r#"( handlers: ( bindings: ( sql: () ) ) )"#);
1048        let sql = cfg.handlers.unwrap().bindings.sql.unwrap();
1049        assert!(sql.url.is_none());
1050        assert!(sql.dir.is_none());
1051    }
1052
1053    #[test]
1054    fn sql_binding_single_node_custom_dir() {
1055        let cfg =
1056            server(r#"( handlers: ( bindings: ( sql: ( dir: "/var/lib/boatramp/sql" ) ) ) )"#);
1057        let sql = cfg.handlers.unwrap().bindings.sql.unwrap();
1058        assert_eq!(sql.dir.as_deref(), Some(Path::new("/var/lib/boatramp/sql")));
1059        assert!(sql.url.is_none());
1060    }
1061
1062    #[test]
1063    fn sql_binding_cluster() {
1064        let cfg = server(
1065            r#"(
1066                handlers: ( bindings: ( sql: (
1067                    url: "http://sqld:8080",
1068                    admin_url: "http://sqld:9090",
1069                    token_env: "BOATRAMP_SQL_TOKEN",
1070                ) ) ),
1071            )"#,
1072        );
1073        let sql = cfg.handlers.unwrap().bindings.sql.unwrap();
1074        assert_eq!(sql.url.as_deref(), Some("http://sqld:8080"));
1075        assert_eq!(sql.admin_url.as_deref(), Some("http://sqld:9090"));
1076        assert_eq!(sql.token_env.as_deref(), Some("BOATRAMP_SQL_TOKEN"));
1077        assert_eq!(sql.admin_token_env, None);
1078    }
1079
1080    #[test]
1081    fn sql_binding_preview_policy() {
1082        let cfg = server(
1083            r#"(
1084                handlers: ( bindings: ( sql: (
1085                    preview_mode: "branch",
1086                    preview_init: "/etc/boatramp/seed.sql",
1087                ) ) ),
1088            )"#,
1089        );
1090        let sql = cfg.handlers.unwrap().bindings.sql.unwrap();
1091        assert_eq!(sql.preview_mode.as_deref(), Some("branch"));
1092        assert_eq!(
1093            sql.preview_init.as_deref(),
1094            Some(Path::new("/etc/boatramp/seed.sql"))
1095        );
1096    }
1097
1098    #[test]
1099    fn sql_binding_external_databases() {
1100        let cfg = server(
1101            r#"(
1102                handlers: ( bindings: ( sql: (
1103                    databases: {
1104                        "analytics": (
1105                            kind: "postgres",
1106                            url_env: "ANALYTICS_PG_URL",
1107                            pool_max: 16,
1108                            read_only: true,
1109                        ),
1110                        "events": (
1111                            kind: "mysql",
1112                            url_env: "EVENTS_MYSQL_URL",
1113                            read_url_env: "EVENTS_MYSQL_REPLICA_URL",
1114                            allow_preview: true,
1115                        ),
1116                    },
1117                ) ) ),
1118            )"#,
1119        );
1120        let sql = cfg.handlers.unwrap().bindings.sql.unwrap();
1121        assert_eq!(sql.databases.len(), 2);
1122
1123        let analytics = &sql.databases["analytics"];
1124        assert_eq!(analytics.kind, "postgres");
1125        assert_eq!(analytics.url_env, "ANALYTICS_PG_URL");
1126        assert_eq!(analytics.pool_max, Some(16));
1127        assert!(analytics.read_only);
1128        assert!(!analytics.allow_preview);
1129        assert!(analytics.read_url_env.is_none());
1130
1131        let events = &sql.databases["events"];
1132        assert_eq!(events.kind, "mysql");
1133        assert_eq!(
1134            events.read_url_env.as_deref(),
1135            Some("EVENTS_MYSQL_REPLICA_URL")
1136        );
1137        assert!(events.allow_preview);
1138        assert!(!events.read_only);
1139    }
1140
1141    #[test]
1142    fn sql_binding_compute_backed_database() {
1143        let cfg = server(
1144            r#"(
1145                handlers: ( bindings: ( sql: (
1146                    databases: {
1147                        "analytics": (
1148                            kind: "postgres",
1149                            compute: "pg",
1150                            database: "analytics",
1151                            user: "app",
1152                            password_env: "PG_APP_PW",
1153                        ),
1154                    },
1155                ) ) ),
1156            )"#,
1157        );
1158        let db = &cfg.handlers.unwrap().bindings.sql.unwrap().databases["analytics"];
1159        assert_eq!(db.kind, "postgres");
1160        assert_eq!(db.compute.as_deref(), Some("pg"));
1161        assert_eq!(db.database.as_deref(), Some("analytics"));
1162        assert_eq!(db.user.as_deref(), Some("app"));
1163        assert_eq!(db.password_env.as_deref(), Some("PG_APP_PW"));
1164        assert!(db.url_env.is_empty(), "compute-backed has no url_env");
1165        assert!(db.validate("analytics").is_ok());
1166    }
1167
1168    #[test]
1169    fn sql_binding_source_is_exactly_one_of_url_or_compute() {
1170        // Neither source → error.
1171        assert!(ExternalDatabaseConfig::default().validate("db").is_err());
1172        // Both sources → error.
1173        let both = ExternalDatabaseConfig {
1174            kind: "postgres".into(),
1175            url_env: "PG_URL".into(),
1176            compute: Some("pg".into()),
1177            ..Default::default()
1178        };
1179        assert!(both.validate("db").is_err());
1180        // `url_env` only → ok.
1181        let url = ExternalDatabaseConfig {
1182            kind: "postgres".into(),
1183            url_env: "PG_URL".into(),
1184            ..Default::default()
1185        };
1186        assert!(url.validate("db").is_ok());
1187        // `compute` without the connection details boatramp can't infer → error.
1188        let bare = ExternalDatabaseConfig {
1189            kind: "postgres".into(),
1190            compute: Some("pg".into()),
1191            ..Default::default()
1192        };
1193        assert!(bare.validate("db").is_err());
1194        // `compute` with database/user + a bring-your-own `password_env` → ok, and
1195        // is *not* a managed credential.
1196        let byo = ExternalDatabaseConfig {
1197            kind: "postgres".into(),
1198            compute: Some("pg".into()),
1199            database: Some("analytics".into()),
1200            user: Some("app".into()),
1201            password_env: Some("PG_APP_PW".into()),
1202            ..Default::default()
1203        };
1204        assert!(byo.validate("db").is_ok());
1205        assert!(!byo.is_managed_credential());
1206        // `compute` with database/user but NO `password_env` → ok, and boatramp
1207        // manages the credential (Phase 2).
1208        let managed = ExternalDatabaseConfig {
1209            kind: "postgres".into(),
1210            compute: Some("pg".into()),
1211            database: Some("analytics".into()),
1212            user: Some("app".into()),
1213            ..Default::default()
1214        };
1215        assert!(managed.validate("db").is_ok());
1216        assert!(managed.is_managed_credential());
1217    }
1218
1219    /// Path to a file at the repo root (two levels up from this crate).
1220    fn repo_root_file(name: &str) -> PathBuf {
1221        Path::new(env!("CARGO_MANIFEST_DIR"))
1222            .join("../..")
1223            .join(name)
1224    }
1225
1226    #[test]
1227    fn shipped_project_example_parses() {
1228        // The example we ship must always parse + compile-check, so it can't drift
1229        // from the schema.
1230        let text = std::fs::read_to_string(repo_root_file("examples/site/project.cfg.example"))
1231            .expect("example project config is present");
1232        let cfg = ProjectConfig::parse(&text).expect("example project config parses");
1233        assert_eq!(cfg.publish.server.as_deref(), Some("http://127.0.0.1:8080"));
1234        assert_eq!(cfg.build.as_ref().unwrap().command, "npm run build");
1235        assert_eq!(
1236            cfg.routing.error_documents.get(&404).map(String::as_str),
1237            Some("/404.html")
1238        );
1239    }
1240
1241    #[test]
1242    fn shipped_server_example_parses() {
1243        let text = std::fs::read_to_string(repo_root_file("boatramp.cfg.example"))
1244            .expect("example server config is present");
1245        let cfg = ServerConfig::parse(&text).expect("example server config parses");
1246        let serve = cfg.serve.expect("example sets a serve section");
1247        assert_eq!(
1248            serve.addr,
1249            Some("0.0.0.0:8080".parse::<std::net::SocketAddr>().unwrap())
1250        );
1251    }
1252
1253    #[test]
1254    fn secrets_section_parses_local_and_vault() {
1255        let local = server(r#"( secrets: ( envelope: "local", kek_file: "/k/kek" ) )"#)
1256            .secrets
1257            .expect("secrets section");
1258        assert_eq!(local.envelope, "local");
1259        assert_eq!(
1260            local.kek_file.as_deref(),
1261            Some(std::path::Path::new("/k/kek"))
1262        );
1263
1264        let vault = server(
1265            r#"( secrets: ( envelope: "vault", vault: ( addr: "https://vault:8200", key: "certs" ) ) )"#,
1266        )
1267        .secrets
1268        .expect("secrets section");
1269        let v = vault.vault.expect("vault subsection");
1270        assert_eq!(v.addr, "https://vault:8200");
1271        assert_eq!(v.key, "certs");
1272        // The token env defaults to VAULT_TOKEN and is never in the file.
1273        assert_eq!(v.token_env, "VAULT_TOKEN");
1274    }
1275
1276    #[test]
1277    fn serve_section_partial_parses() {
1278        // A partial `serve` section parses — unset fields take their defaults.
1279        let cfg = server(r#"( serve: ( addr: "0.0.0.0:8080", protect_previews: true ) )"#);
1280        let serve = cfg.serve.unwrap();
1281        assert_eq!(
1282            serve.addr,
1283            Some("0.0.0.0:8080".parse::<std::net::SocketAddr>().unwrap())
1284        );
1285        assert!(serve.protect_previews);
1286        assert!(!serve.cluster_rate_limit);
1287        assert!(serve.data_dir.is_none());
1288    }
1289
1290    #[test]
1291    fn serve_console_config_parses() {
1292        // Absent ⇒ no console.
1293        let cfg = server(r#"( serve: ( addr: "0.0.0.0:8080" ) )"#);
1294        assert!(cfg.serve.unwrap().console.is_none());
1295        // Explicit console block with host + path.
1296        let cfg = server(
1297            r#"( serve: ( console: (
1298                enabled: true,
1299                host: "console.example.com",
1300                path: "/_console",
1301            ) ) )"#,
1302        );
1303        let console = cfg.serve.unwrap().console.unwrap();
1304        assert!(console.enabled);
1305        assert_eq!(console.host.as_deref(), Some("console.example.com"));
1306        assert_eq!(console.path.as_deref(), Some("/_console"));
1307        // Bare `enabled` ⇒ host/path take their (server-side) defaults.
1308        let cfg = server(r#"( serve: ( console: ( enabled: true ) ) )"#);
1309        let console = cfg.serve.unwrap().console.unwrap();
1310        assert!(console.enabled);
1311        assert!(console.host.is_none() && console.path.is_none());
1312    }
1313}