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