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, Serialize};
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/// The wire format an operator-authored config file is decoded as (v0.6.5).
30///
31/// Config files are historically RON. JSON was added as a second **input** format
32/// purely for interop — so a config can be generated from Nickel (`nickel export` →
33/// JSON) and fed to boatramp unchanged. It is an alternative *decoder* into the
34/// **same** typed structs (they all derive serde `Deserialize` with externally-tagged
35/// enums + `deny_unknown_fields`), so JSON preserves every variant name and the same
36/// strictness — no type changes, and the same downstream validation runs either way.
37#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
38#[cfg_attr(feature = "clap", derive(clap::ValueEnum))]
39pub enum ConfigFormat {
40 /// RON (the historical, default format). Selected for every non-`.json`
41 /// extension (`.cfg` / `.ron` / none).
42 #[default]
43 Ron,
44 /// JSON — for configs generated from Nickel (`nickel export`) or any JSON
45 /// pipeline. Selected for a `.json` (case-insensitive) extension.
46 Json,
47}
48
49/// Resolve the [`ConfigFormat`] for a config path.
50///
51/// The rule is explicit and predictable (config is the operator trust boundary, so
52/// there is **no content-sniffing** — a sniff could silently RON-parse a JSON file
53/// into a wrong-but-valid config, and vice versa):
54///
55/// 1. an explicit `override_` (the CLI `--format ron|json`) always wins; else
56/// 2. auto by extension — a `.json` (case-insensitive) extension ⇒ [`ConfigFormat::Json`];
57/// everything else (`.cfg` / `.ron` / no extension) ⇒ [`ConfigFormat::Ron`].
58pub fn resolve_format(path: &Path, override_: Option<ConfigFormat>) -> ConfigFormat {
59 if let Some(fmt) = override_ {
60 return fmt;
61 }
62 match path.extension().and_then(|e| e.to_str()) {
63 Some(ext) if ext.eq_ignore_ascii_case("json") => ConfigFormat::Json,
64 _ => ConfigFormat::Ron,
65 }
66}
67
68/// A failure loading or parsing a local config file (`project.cfg` / `boatramp.cfg`).
69#[derive(Debug, thiserror::Error)]
70pub enum ConfigError {
71 /// Wraps an underlying error with the file path it came from.
72 #[error("{path}: {source}")]
73 File {
74 path: String,
75 #[source]
76 source: Box<Self>,
77 },
78 /// The RON document failed to parse.
79 #[error("invalid config syntax: {0}")]
80 Ron(#[from] ron::error::SpannedError),
81 /// The JSON document failed to parse (JSON config input — e.g. from
82 /// `nickel export`). Same strictness as RON: `deny_unknown_fields` on the
83 /// structs makes a typo'd/unknown key a hard error here, not a silent drop.
84 #[error("invalid JSON config: {0}")]
85 Json(#[from] serde_json::Error),
86 /// The `routing` section failed its compile-check.
87 #[error("routing: {0}")]
88 Routing(#[from] boatramp_core::ConfigError),
89 /// Reading the file failed (other than not-found, which yields defaults).
90 #[error(transparent)]
91 Io(#[from] std::io::Error),
92 /// An environment-variable override could not be parsed (bad number/bool).
93 #[error("environment variable {var}: {reason}")]
94 Env {
95 /// The offending `BOATRAMP_*` variable. Owned because some names are built
96 /// dynamically (the keyed `databases` map, whose members aren't known at
97 /// compile time).
98 var: String,
99 /// Why the value was rejected.
100 reason: String,
101 },
102 /// A `handlers.bindings.sql.databases` binding name is not a safe URL path
103 /// segment — it is threaded verbatim into `/api/sql/{db}/…` and `--db`, so an
104 /// empty/`//`-collapsing or path-separator-bearing name is refused at load
105 /// (fail-closed) rather than emitting a malformed control-plane path.
106 #[error("SQL database binding {name:?}: {reason}{cure}")]
107 InvalidDbName {
108 /// The offending binding name (the `databases` map key).
109 name: String,
110 /// Why it was rejected (from the canonical validator).
111 reason: &'static str,
112 /// A trailing remediation hint (empty unless this is the legacy empty-name
113 /// default case, where it points at the `default` cure).
114 cure: &'static str,
115 },
116 /// A `[serve.blob_backends.<project>]` key is not a valid project name, or is the reserved
117 /// `default` project (which always resolves the global `[serve]` backend). Refused at config load
118 /// (fail-closed) rather than silently binding a project's blobs to the wrong backend.
119 #[error("per-project blob backend {name:?}: {reason}{cure}")]
120 InvalidBlobBackendProject {
121 /// The offending project key (the `blob_backends` map key).
122 name: String,
123 /// Why it was rejected.
124 reason: &'static str,
125 /// A trailing remediation hint.
126 cure: &'static str,
127 },
128 /// A `[serve.listeners.<name>]` (host-owned inbound-TCP listener, PLAN-handler-tcp-inbound) is
129 /// invalid: a blank `component`, a non-positive `max_conns`/timeout, a declared-but-unsupported
130 /// `tls` block (Phase 1 is plaintext-only), or a non-empty `egress_allowlist` (a
131 /// `tcp-connection-host` guest imports only `wasi:io` — it cannot hold `wasi:sockets`). Refused at
132 /// config load (fail-closed, boot-LOUD) rather than binding a listener that would silently
133 /// mislead the operator.
134 #[error("inbound TCP listener {name:?}: {reason}{cure}")]
135 InvalidListener {
136 /// The offending listener key (the `listeners` map key).
137 name: String,
138 /// Why it was rejected.
139 reason: &'static str,
140 /// A trailing remediation hint (empty unless there is a concrete cure to point at).
141 cure: &'static str,
142 },
143 /// The layered config pipeline failed to resolve/extract the merged config (a bad
144 /// numeric/addr env value that figment's lossy coercion rejects, a `[cluster]` missing
145 /// its required `listen`, etc.). The figment error is rendered to a string so
146 /// `ConfigError` stays small.
147 #[error("config resolution: {0}")]
148 Resolve(String),
149}
150
151/// Project configuration, loaded from `project.cfg` (RON) in the project folder.
152///
153/// Read by the client commands (`sync`, `build`, `bundle`, `validate`).
154/// Everything is optional; a missing file is the default.
155#[derive(Debug, Default, Deserialize)]
156#[serde(default)]
157pub struct ProjectConfig {
158 /// Where and how to publish this project.
159 pub publish: PublishConfig,
160 /// Optional build step run before `sync`.
161 pub build: Option<BuildConfig>,
162 /// Optional embedded-bundler step (`bundler` feature).
163 pub bundle: Option<BundleConfig>,
164 /// Deploy-scoped routing/handlers config. Folded into the deployment
165 /// manifest at `sync` (so it is atomic with the content and rolls back with
166 /// it). The bulk of a project's config — redirects, rewrites, headers,
167 /// handlers, consumers, crons, streams.
168 pub routing: DeployConfig,
169}
170
171impl ProjectConfig {
172 /// Parse a `project.cfg` document as **RON** (the default). Kept for the existing
173 /// callers/tests; [`Self::parse_with_format`] is the format-aware entry point.
174 pub fn parse(text: &str) -> Result<Self, ConfigError> {
175 Self::parse_with_format(text, ConfigFormat::Ron)
176 }
177
178 /// Parse a `project.cfg` document in `fmt` (RON or JSON). The deserializer is
179 /// selected by format (RON ⇒ [`ron_options`], JSON ⇒ `serde_json`) into the SAME
180 /// typed struct; the `routing` section is then compile-checked (route patterns,
181 /// cron schedules, imports) regardless of format so a bad config fails fast.
182 pub fn parse_with_format(text: &str, fmt: ConfigFormat) -> Result<Self, ConfigError> {
183 let config: Self = match fmt {
184 ConfigFormat::Ron => ron_options().from_str(text)?,
185 ConfigFormat::Json => serde_json::from_str(text)?,
186 };
187 config.routing.compile_check()?;
188 Ok(config)
189 }
190
191 /// Load from `path`, decoding as RON or JSON per [`resolve_format`] (`override_`
192 /// wins; else `.json` ⇒ JSON, everything else ⇒ RON). A missing file yields the
193 /// default config (unlike an apply manifest).
194 pub fn load(path: &Path, override_: Option<ConfigFormat>) -> Result<Self, ConfigError> {
195 let fmt = resolve_format(path, override_);
196 match std::fs::read_to_string(path) {
197 Ok(contents) => {
198 Self::parse_with_format(&contents, fmt).map_err(|err| ConfigError::File {
199 path: path.display().to_string(),
200 source: Box::new(err),
201 })
202 }
203 Err(err) if err.kind() == std::io::ErrorKind::NotFound => Ok(Self::default()),
204 Err(err) => Err(err.into()),
205 }
206 }
207}
208
209/// Server daemon configuration, loaded from `boatramp.cfg` (RON). Read by
210/// `boatramp serve`; flags/env override the `serve` values.
211#[derive(Debug, Default, Serialize, Deserialize)]
212#[serde(default)]
213pub struct ServerConfig {
214 /// Server defaults for `serve` (flag/env override these).
215 pub serve: Option<ServeConfig>,
216 /// Server-side handler runtime config (which backend serves each binding),
217 /// consumed only with the `handlers` feature.
218 pub handlers: Option<HandlersConfig>,
219 /// Self-hosted cluster mode (consumed only with the `cluster` feature).
220 pub cluster: Option<ClusterConfig>,
221 /// Opt-in **compute** backends. Present ⇒ this node
222 /// runs compute workloads via the backends it can offer; absent ⇒ no compute
223 /// (the reconcile loop stays a no-op).
224 pub compute: Option<ComputeConfig>,
225 /// Operator security posture (the hardening knobs): a profile
226 /// preset + overrides, resolved at startup. Absent ⇒ the strict
227 /// `multi-tenant` default. Operator-only — never part of site config.
228 pub security: Option<boatramp_core::security::SecurityConfig>,
229 /// Secrets-at-rest envelope. Absent ⇒ private
230 /// keys stored cleartext in the (replicated) control plane.
231 pub secrets: Option<SecretsConfig>,
232 /// Overlay forward-flow serve roles (consumed only with the `overlay` feature): stand up a
233 /// relay/ingress and/or egress/terminator so a remote `boatramp forward` can reach in-cluster
234 /// services over the relay-blind overlay. Absent ⇒ this node serves no overlay roles.
235 pub overlay: Option<OverlayServeConfig>,
236}
237
238/// `[overlay]` — the forward-flow **serve roles** this node runs (the server side of
239/// `boatramp forward`). A node may be a **relay/ingress** (accepts external client dials and
240/// forwards them, blind, into the cluster), an **egress/terminator** (fronts local backend
241/// services), or both. A relay's `routes` double as the self-serve **discovery directory**: the
242/// control plane resolves `boatramp forward svc/<name>` against them and mints the dial capability,
243/// so the CLI needs no hand-typed topology (the explicit flags / `overlay grant --ticket` remain for
244/// control-plane-less forwards).
245#[cfg_attr(not(feature = "overlay"), allow(dead_code))]
246#[derive(Debug, Clone, Default, Serialize, Deserialize)]
247#[serde(default, deny_unknown_fields)]
248pub struct OverlayServeConfig {
249 /// This node's overlay identity — an `ed25519:<hex>` seed inline, or a path to a file holding
250 /// one. Auto-generated at `<data-dir>/overlay/identity.key` when unset. This is the identity a
251 /// relay's clients and an egress's relay pin.
252 pub identity: Option<String>,
253 /// The dial-capability **trust root** (`ed25519:`/`es256:` tagged hex) every dial is verified
254 /// against. Defaults to `serve.auth_root_public_key` (the cluster's control-plane root).
255 pub trust_root: Option<String>,
256 /// Whether dials must be end-to-end encrypted (fail-closed). Default `true`.
257 pub encryption_required: Option<bool>,
258 /// Server cap on a minted dial capability's lifetime (seconds). A `POST /api/overlay/dial`
259 /// request's `ttl_secs` is clamped to this (overlay-dial caps are offline-verified — no
260 /// revocation — so an unbounded TTL is a standing risk). Unset ⇒ 24h.
261 pub max_dial_ttl_secs: Option<u64>,
262 /// Bind a **relay/ingress** here (UDP/QUIC). Unset ⇒ this node runs no relay.
263 pub relay_listen: Option<SocketAddr>,
264 /// The relay's transport-layer client-auth posture (Security Blocker #1):
265 /// `"capability-only"` accepts any client key at TLS and rests authorization on the capability
266 /// gate + the egress's E2EE-proven re-authz (self-serve, no pre-enrollment); `"mutual-pin"` keeps
267 /// the `allowed_clients` RPK pin as a strictly-more-restrictive pre-filter. REQUIRED for a relay
268 /// unless `allowed_clients` is non-empty (which defaults to mutual-pin); a relay with neither is a
269 /// hard error — an empty allowlist is never silently treated as accept-any.
270 pub client_auth: Option<String>,
271 /// The client overlay identities (`ed25519:`/`es256:` tagged hex) the relay mutual-authenticates
272 /// — the enrolled operators/clients allowed to dial under `client_auth = "mutual-pin"`. (A
273 /// capability is still required and is the authority; this is the relay's transport-layer
274 /// pre-filter. Ignored under `"capability-only"`.)
275 pub allowed_clients: Vec<String>,
276 /// Relay routing: a requested service → its egress. Used when `relay_listen` is set.
277 pub routes: Vec<OverlayRoute>,
278 /// Reverse ingress (`boatramp expose`): accept exposer REGISTRATIONS on this relay, so a LOCAL
279 /// service published into the cluster (the exposer dials OUT and parks a connection) is reachable
280 /// by a cluster-side `boatramp forward svc/<name>`. Opt-in — a relay accepts exposers only when
281 /// this is `true`; `None`/`false` keeps the forward-only relay. Requires `relay_listen`. The
282 /// registration is holder-bound to an `overlay-publish` capability the relay verifies against
283 /// `trust_root`; first-live-claim-wins on the name.
284 pub accept_exposed: Option<bool>,
285 /// Digit count for the human-typeable pairing SHORT CODE a relay can mint alongside a `bropair1…`
286 /// code (overlay follow-up #2 inc3, `boatramp overlay pair-code --short`): default 8
287 /// (`K = 10^8 ≈ 2^26.6`), floor 7, ceiling 10 (clamped). Independent of `accept_exposed` — read
288 /// only when a relay actually mints/redeems a short code.
289 pub pair_short_code_digits: Option<usize>,
290 /// Per-relay operator choice for the pairing PARK service (owner decision: "the relay manager
291 /// should choose, per relay, whether PARK is offered as an OPEN or AUTHENTICATED service"):
292 /// `"open"` (the DEFAULT) keeps today's behavior — an unauthenticated park, bounded only by the
293 /// existing park budget + per-IP cap, with the human-compared SAS as the trust anchor;
294 /// `"authenticated"` additionally requires the parking accepter to present a holder-bound
295 /// `overlay-pairing-park` capability and prove possession, exactly like `accept_exposed`'s
296 /// exposer-registration path (`register_exposer`). REDEEM stays unauthenticated in BOTH modes —
297 /// the unpaired dialer is, by design, not membership-gated; the SAS backstops it. Read only when a
298 /// relay actually runs the pairing rendezvous (the same `accept_exposed` ingress-router branch
299 /// `pair_short_code_digits` shares).
300 pub pairing_park: Option<String>,
301 /// Bind an **egress/terminator** here (UDP/QUIC). Unset ⇒ this node runs no egress.
302 pub egress_listen: Option<SocketAddr>,
303 /// Egress service map: a service name → the local backend it fronts. Used when `egress_listen`
304 /// is set; a service not listed here is refused (the egress authorizes only what it fronts).
305 pub services: Vec<OverlayService>,
306}
307
308/// One relay route: the egress a requested `service` is forwarded to.
309#[cfg_attr(not(feature = "overlay"), allow(dead_code))]
310#[derive(Debug, Clone, Default, Serialize, Deserialize)]
311#[serde(default, deny_unknown_fields)]
312pub struct OverlayRoute {
313 /// The in-cluster service name (e.g. `svc/db`).
314 pub service: String,
315 /// The egress's overlay UDP address to forward to.
316 pub egress: Option<SocketAddr>,
317 /// The egress's overlay identity (`ed25519:`/`es256:` tagged hex) to pin.
318 pub egress_id: Option<String>,
319}
320
321/// One egress service: the local backend a `service` name fronts.
322#[cfg_attr(not(feature = "overlay"), allow(dead_code))]
323#[derive(Debug, Clone, Default, Serialize, Deserialize)]
324#[serde(default, deny_unknown_fields)]
325pub struct OverlayService {
326 /// The in-cluster service name this egress fronts (e.g. `svc/db`).
327 pub name: String,
328 /// The local backend address the service maps to (e.g. `127.0.0.1:5432`).
329 pub backend: Option<SocketAddr>,
330}
331
332/// `secrets` section — envelope encryption for private keys at rest.
333#[cfg_attr(not(feature = "cluster"), allow(dead_code))]
334#[derive(Debug, Clone, Default, Serialize, Deserialize)]
335#[serde(default, deny_unknown_fields)]
336pub struct SecretsConfig {
337 /// Backend: `"local"` (machine-local AES-256-GCM KEK) or `"vault"` (Vault
338 /// Transit). Empty/other ⇒ no wrapping. In a cluster a local KEK must be the
339 /// **same file on every node** (wrapped certs replicate); Vault avoids that.
340 pub envelope: String,
341 /// Local-KEK key file (`envelope = "local"`). Default
342 /// `<data-dir>/secrets/kek`. Auto-generated `0600` if absent.
343 pub kek_file: Option<PathBuf>,
344 /// Vault Transit config (`envelope = "vault"`).
345 pub vault: Option<VaultSecretsConfig>,
346}
347
348/// Vault Transit settings for `envelope = "vault"`. The token is read from the
349/// environment (`token_env`), never stored in the config file.
350#[cfg_attr(not(all(feature = "cluster", feature = "acme-dns")), allow(dead_code))]
351#[derive(Debug, Clone, Serialize, Deserialize)]
352#[serde(deny_unknown_fields)]
353pub struct VaultSecretsConfig {
354 /// Vault address, e.g. `https://vault:8200`.
355 pub addr: String,
356 /// Transit key name to wrap under.
357 pub key: String,
358 /// Environment variable holding the Vault token (default `VAULT_TOKEN`).
359 #[serde(default = "default_vault_token_env")]
360 pub token_env: String,
361}
362
363fn default_vault_token_env() -> String {
364 "VAULT_TOKEN".to_string()
365}
366
367impl Default for VaultSecretsConfig {
368 fn default() -> Self {
369 Self {
370 addr: String::new(),
371 key: String::new(),
372 token_env: default_vault_token_env(),
373 }
374 }
375}
376
377/// The RESERVED compute-workload name prefix (#501 Stage B LOW-2). boatramp DERIVES the
378/// per-project managed-database server workloads with this prefix
379/// (`boatramp_storage::tenant_provision::DERIVED_MANAGED_DB_PREFIX`), so an operator must
380/// NOT name a static `[handlers].bindings.sql.databases.*.compute` workload with it — a
381/// collision could shadow / alias a derived managed server. Screened fail-closed at
382/// config load ([`ServerConfig::validate_sql_db_names`]). Kept as a literal here (not the
383/// `boatramp-storage` const) so the screen holds on a build without the sql engine
384/// features; the two must stay in sync (a single source of truth would couple config
385/// loading to the optional storage dep).
386const RESERVED_MANAGED_DB_COMPUTE_PREFIX: &str = "bramp-db-";
387
388impl ServerConfig {
389 /// Parse a `boatramp.cfg` document as **RON** (the default). Kept for the existing
390 /// callers/tests; [`Self::parse_with_format`] is the format-aware entry point.
391 pub fn parse(text: &str) -> Result<Self, ConfigError> {
392 Self::parse_with_format(text, ConfigFormat::Ron)
393 }
394
395 /// Parse a `boatramp.cfg` document in `fmt` (RON or JSON). The deserializer is
396 /// selected by format (RON ⇒ [`ron_options`], JSON ⇒ `serde_json`) into the SAME
397 /// typed struct. Db-binding names declared in the file are validated here (the same
398 /// fail-closed check `load` re-runs after the env merge) **regardless of format**, so
399 /// a file-only config path — e.g. `boatramp cloudflare` rendering, or the
400 /// operator-resources loader — is guarded even without going through `load`.
401 pub fn parse_with_format(text: &str, fmt: ConfigFormat) -> Result<Self, ConfigError> {
402 let config: Self = match fmt {
403 ConfigFormat::Ron => ron_options().from_str(text)?,
404 ConfigFormat::Json => serde_json::from_str(text)?,
405 };
406 config.validate_sql_db_names()?;
407 config.validate_blob_backend_projects()?;
408 config.validate_listeners()?;
409 Ok(config)
410 }
411
412 /// Load from `path`, decoding as RON or JSON per [`resolve_format`] (`override_`
413 /// wins; else `.json` ⇒ JSON, everything else ⇒ RON), then layer `BOATRAMP_*`
414 /// environment overrides on top. A missing file yields the default config, so
415 /// `serve` can be configured entirely from the environment (12-factor deployments
416 /// where dropping a `boatramp.cfg` is awkward — fly.io / Cloudflare / containers).
417 ///
418 /// The env-override merge runs AFTER the parse for either format — JSON is only an
419 /// alternative decoder into the same typed struct; it does not change the
420 /// file < env precedence.
421 pub fn load(path: &Path, override_: Option<ConfigFormat>) -> Result<Self, ConfigError> {
422 // The ONE layered pipeline (defaults → file → env), used by serve AND every offline
423 // op. With no explicit CLI flags here, this is file + env; the serve binary passes its
424 // `ValueSource::CommandLine` flags as the top layer via `load_with_flags`.
425 figment_resolve::load_with_figment(
426 path,
427 override_,
428 &EnvSource::Process,
429 figment::value::Dict::new(),
430 )
431 }
432
433 /// Load through the pipeline with an explicit **CLI-flag** top layer. `cli_flags` is a map
434 /// `{BOATRAMP_<NAME>: raw-value}` of the args the operator set on the COMMAND LINE (the
435 /// serve binary builds it from `clap::ArgMatches`, keeping only `ValueSource::CommandLine`
436 /// — so a defaulted `--blobs fs` is absent and never clobbers file/env, subsuming the old
437 /// `--blobs` `var_os` probe). Resolution is `base-seed → file → env → these flags`. Keys
438 /// the overlay doesn't recognise (runtime/selector flags like `--tls`, the cluster-action
439 /// flags) are ignored, so they never enter the config. The binary passes a plain map —
440 /// figment types stay internal to this crate.
441 pub fn load_with_flags(
442 path: &Path,
443 override_: Option<ConfigFormat>,
444 cli_flags: &BTreeMap<String, String>,
445 ) -> Result<Self, ConfigError> {
446 let flags = figment_resolve::flag_overlay_dict(cli_flags);
447 figment_resolve::load_with_figment(path, override_, &EnvSource::Process, flags)
448 }
449
450 /// Serialize the (already-resolved) config for `boatramp config dump`, with the
451 /// secret-bearing fields REDACTED. The config is `Serialize` (for the file layer), which
452 /// would otherwise expose the control-plane root key / bootstrap secret / azure access
453 /// key / signer key / join-token in a dump. Returns pretty JSON (also a valid config
454 /// input format).
455 pub fn dump_redacted(&self) -> Result<String, ConfigError> {
456 figment_resolve::dump_redacted(self)
457 }
458
459 /// Test-only adapter: layer the `BOATRAMP_*` env overlay over `self` (the base/file) THROUGH
460 /// the real figment pipeline. The production Loader-B `apply_env_overrides` is gone; this thin
461 /// delegator keeps the pre-figment env tests — which assert specific resolved fields after
462 /// `cfg.apply_env_overrides(&env(…))` — running against the ONE pipeline (so they are genuine
463 /// figment tests, not a second implementation).
464 #[cfg(test)]
465 fn apply_env_overrides(&mut self, source: &EnvSource) -> Result<(), ConfigError> {
466 *self = figment_resolve::resolve_env_over(self, source)?;
467 Ok(())
468 }
469
470 /// Validate every configured `handlers.bindings.sql.databases` binding name
471 /// through the one canonical [`validate_resource_name`](boatramp_core::project::validate_resource_name)
472 /// (`kind = "database"`). A db-binding name is threaded verbatim into the
473 /// control-plane URL (`/api/sql/{db}/…`, `/api/migrate/{db}/…`) and the CLI
474 /// `--db`, so it must be a non-empty, path-segment-safe identifier — the same rule
475 /// project/site/function names already pass. The empty-string legacy default key
476 /// gets a targeted cure pointing at the reserved `default` name.
477 ///
478 /// Also screens each binding's `compute` field against the
479 /// [`RESERVED_MANAGED_DB_COMPUTE_PREFIX`] (#501 Stage B LOW-2): the `bramp-db-`
480 /// prefix is reserved for the derived per-project managed-DB server workloads, so an
481 /// operator may not point a static BYO binding at a `bramp-db-…` workload.
482 fn validate_sql_db_names(&self) -> Result<(), ConfigError> {
483 let Some(databases) = self
484 .handlers
485 .as_ref()
486 .and_then(|h| h.bindings.sql.as_ref())
487 .map(|s| &s.databases)
488 else {
489 return Ok(());
490 };
491 for (name, db) in databases {
492 if let Err(err) = boatramp_core::project::validate_resource_name("database", name) {
493 // The empty-string case is the pre-v0.5.0 default binding key: point
494 // at the cure (name it `default`, or set nothing and let the reserved
495 // `DEFAULT` token map to `default` automatically). Any other
496 // non-conforming name gets the v0.7.0 slug cure pointing at
497 // `project doctor`. This is a boot-LOUD refusal — an operator learns of
498 // a bad name at `serve` boot, not at the first request.
499 let cure = if name.is_empty() {
500 " — name your default binding `default` (or set \
501 BOATRAMP_HANDLERS_SQL_DB_DEFAULT_*, which now maps to `default` \
502 automatically); see the v0.5.0 CHANGELOG"
503 } else {
504 boatramp_core::project::INVALID_NAME_CURE
505 };
506 return Err(ConfigError::InvalidDbName {
507 name: err.value,
508 reason: err.reason,
509 cure,
510 });
511 }
512 // #501 Stage B LOW-2: the `bramp-db-` compute-workload prefix is RESERVED for
513 // the derived per-project managed-DB server workloads
514 // (`boatramp_storage::tenant_provision::DERIVED_MANAGED_DB_PREFIX`). An operator
515 // must not point a static BYO binding at a `compute` workload with that prefix —
516 // it could shadow / alias a derived managed server. Screen it fail-closed at
517 // config load (cheap: a `starts_with` on an already-parsed field).
518 if let Some(compute) = db.compute.as_deref()
519 && compute.starts_with(RESERVED_MANAGED_DB_COMPUTE_PREFIX)
520 {
521 return Err(ConfigError::InvalidDbName {
522 name: compute.to_string(),
523 reason: "the `bramp-db-` compute-workload prefix is reserved for \
524 boatramp-derived managed-database servers",
525 cure: " — rename the `compute` workload to not start with `bramp-db-`",
526 });
527 }
528 }
529 Ok(())
530 }
531
532 /// Validate every configured `[serve.blob_backends.<project>]` key
533 /// (PLAN-per-project-blob-backend). A key must be a valid project name (the canonical
534 /// [`validate_resource_name`](boatramp_core::project::validate_resource_name), `kind = "project"`),
535 /// and must NOT be the reserved `default` project: the `default` project ALWAYS resolves the global
536 /// `[serve]` backend (invariant 5), so a `[serve.blob_backends.default]` entry would be ambiguous
537 /// (the node-wide backend is configured under `[serve]`, not here). Both are boot-LOUD refusals
538 /// (fail-closed — an operator learns of a bad name at `serve` boot, not at the first request). The
539 /// project the entry binds to is host-routed at serve time, never guest input (invariant 1).
540 fn validate_blob_backend_projects(&self) -> Result<(), ConfigError> {
541 let Some(serve) = self.serve.as_ref() else {
542 return Ok(());
543 };
544 for name in serve.blob_backends.keys() {
545 if name == boatramp_core::project::DEFAULT_PROJECT {
546 return Err(ConfigError::InvalidBlobBackendProject {
547 name: name.clone(),
548 reason: "the reserved `default` project always resolves the global [serve] blob \
549 backend",
550 cure: " — configure the node-wide backend under [serve] (blobs/s3_*), not \
551 [serve.blob_backends.default]",
552 });
553 }
554 if let Err(err) = boatramp_core::project::validate_resource_name("project", name) {
555 return Err(ConfigError::InvalidBlobBackendProject {
556 name: err.value,
557 reason: err.reason,
558 cure: boatramp_core::project::INVALID_NAME_CURE,
559 });
560 }
561 }
562 Ok(())
563 }
564
565 /// Validate every configured `[serve.listeners.<name>]` (PLAN-handler-tcp-inbound), fail-closed +
566 /// boot-LOUD on the fully merged (file + env) map. A host-owned inbound-TCP listener is a new,
567 /// unproven surface, so a half-declared or Phase-1-unsupported one REFUSES the node rather than
568 /// binding something that would silently mislead the operator:
569 /// - a blank `bind` / `component` / `project` / `site` (all required),
570 /// - a `max_conns` / `idle_timeout_ms` / `max_conn_duration_ms` explicitly set to `0`,
571 /// - a declared `tls` block (Phase 1 is plaintext-only — deferred fast-follow),
572 /// - a non-empty `egress_allowlist` (a `tcp-connection-host` guest imports only `wasi:io`; it
573 /// cannot hold `wasi:sockets`, so per-listener outbound egress is a deferred follow-up).
574 fn validate_listeners(&self) -> Result<(), ConfigError> {
575 let Some(serve) = self.serve.as_ref() else {
576 return Ok(());
577 };
578 for (name, l) in &serve.listeners {
579 let err = |reason: &'static str, cure: &'static str| {
580 Err(ConfigError::InvalidListener {
581 name: name.clone(),
582 reason,
583 cure,
584 })
585 };
586 if l.bind.is_none() {
587 return err(
588 "missing `bind` address",
589 " — set `bind = \"0.0.0.0:<port>\"`",
590 );
591 }
592 if l.component.trim().is_empty() {
593 return err("missing `component` (the guest .wasm path)", "");
594 }
595 if l.project.trim().is_empty() {
596 return err("missing `project`", "");
597 }
598 if l.site.trim().is_empty() {
599 return err("missing `site`", "");
600 }
601 if l.max_conns == Some(0) {
602 return err("`max_conns` must be > 0", " — omit it for the default");
603 }
604 if l.idle_timeout_ms == Some(0) {
605 return err(
606 "`idle_timeout_ms` must be > 0",
607 " — omit it for the default",
608 );
609 }
610 if l.max_conn_duration_ms == Some(0) {
611 return err(
612 "`max_conn_duration_ms` must be > 0",
613 " — omit it for the default",
614 );
615 }
616 // Host-side per-listener TLS termination (cap-req 06): a declared `tls` block is honored,
617 // but it MUST name both a cert and a key (the host loads them + terminates TLS, handing the
618 // guest a decrypted plaintext stream). This holds for BOTH implicit TLS (465/993) and
619 // STARTTLS (25/587/143) — STARTTLS still terminates TLS after the in-band upgrade.
620 if let Some(tls) = &l.tls {
621 if tls.cert_file.is_none() || tls.key_file.is_none() {
622 return err(
623 "listener `tls` requires both `cert_file` and `key_file`",
624 " — set cert_file/key_file (PEM), or remove the `tls` block for a plaintext listener",
625 );
626 }
627 // Declarative STARTTLS grammar (cap-req 06, Stage B): the one piece of protocol data.
628 if let Some(st) = &tls.starttls {
629 if st.trigger.trim().is_empty() {
630 return err(
631 "listener `tls.starttls.trigger` must be non-empty",
632 " — e.g. trigger = \"STARTTLS\" (SMTP/IMAP) or \"STLS\" (POP3)",
633 );
634 }
635 if st.response.trim().is_empty() {
636 return err(
637 "listener `tls.starttls.response` must be non-empty",
638 " — the line the host sends before upgrading, e.g. \"220 Ready to start TLS\"",
639 );
640 }
641 // `{tag}` in the response is only meaningful when a tag is captured — otherwise the
642 // literal `{tag}` would leak to the wire.
643 if st.response.contains("{tag}") && !st.tag_capture {
644 return err(
645 "listener `tls.starttls.response` uses `{tag}` but `tag_capture` is false",
646 " — set tag_capture = true (IMAP-style), or remove the {tag} placeholder",
647 );
648 }
649 // trigger/response are matched against / written as a single line — refuse embedded
650 // CR/LF (which would split the line and could inject a second response line).
651 if st.trigger.contains(['\r', '\n']) || st.response.contains(['\r', '\n']) {
652 return err(
653 "listener `tls.starttls` trigger/response must not contain CR or LF",
654 " — they are a single line; the host appends CRLF to the response",
655 );
656 }
657 }
658 // On-demand per-SNI issuance for this listener (cap-req 03 #4) shares the node's one
659 // on-demand engine — it is meaningless (and silently a no-op) unless that engine runs.
660 if tls.on_demand && !serve.on_demand_tls.as_ref().is_some_and(|o| o.enabled) {
661 return err(
662 "listener `tls.on_demand` requires `[serve.on_demand_tls] enabled = true`",
663 " — enable node on-demand TLS, or set on_demand = false to serve only the static cert",
664 );
665 }
666 }
667 if !l.egress_allowlist.is_empty() {
668 return err(
669 "per-listener outbound `egress_allowlist` is not supported (a tcp-connection-host \
670 guest imports only wasi:io — it cannot hold wasi:sockets)",
671 " — remove `egress_allowlist`",
672 );
673 }
674 }
675 Ok(())
676 }
677}
678
679/// The `BOATRAMP_*` variables that populate the `[compute]` section. Kept as one
680/// list so [`ServerConfig::apply_env_overrides`] can decide whether to materialise
681/// an absent section without repeating the names.
682const COMPUTE_ENV_VARS: &[&str] = &[
683 "BOATRAMP_COMPUTE_BRIDGE",
684 "BOATRAMP_COMPUTE_SUBNET",
685 "BOATRAMP_COMPUTE_VCPUS",
686 "BOATRAMP_COMPUTE_MEM_MIB",
687 "BOATRAMP_COMPUTE_REGION",
688 "BOATRAMP_COMPUTE_SQL_SHIM_URL",
689 "BOATRAMP_COMPUTE_BLOB_SHIM_URL",
690 "BOATRAMP_COMPUTE_MESSAGING_SHIM_URL",
691 "BOATRAMP_COMPUTE_BLOB_SHIM_MAX_OBJECT_BYTES",
692 "BOATRAMP_COMPUTE_MANAGED_DB_PRIVILEGE",
693 "BOATRAMP_COMPUTE_DOCKER_ENDPOINT",
694 "BOATRAMP_COMPUTE_DOCKER_VOLUME_MODE",
695 "BOATRAMP_COMPUTE_KERNEL_SIGNING_PUBKEYS",
696 "BOATRAMP_COMPUTE_KERNEL_ALLOWED_HASHES",
697 "BOATRAMP_COMPUTE_INTERNAL_DNS",
698 "BOATRAMP_COMPUTE_DNS_UPSTREAM",
699 "BOATRAMP_COMPUTE_DNS_DOMAIN",
700 "BOATRAMP_COMPUTE_PG_CLIENT_IMAGE",
701 "BOATRAMP_COMPUTE_MYSQL_CLIENT_IMAGE",
702];
703
704/// The `BOATRAMP_*` variables that populate the `[security]` section.
705const SECURITY_ENV_VARS: &[&str] = &[
706 "BOATRAMP_SECURITY_PROFILE",
707 "BOATRAMP_SECURITY_ALLOW_UNAUTHENTICATED_PUBLIC_BIND",
708 "BOATRAMP_SECURITY_MAX_UPLOAD_BYTES",
709 "BOATRAMP_SECURITY_ALLOW_SITE_UNIX_UPSTREAMS",
710 "BOATRAMP_SECURITY_ALLOW_SITE_PRIVATE_UPSTREAMS",
711 "BOATRAMP_SECURITY_ALLOW_GUEST_PRIVATE_EGRESS",
712 "BOATRAMP_SECURITY_ALLOW_GUEST_SELF_EGRESS",
713 "BOATRAMP_SECURITY_ALLOW_GUEST_EGRESS_EXTRA_CA",
714 "BOATRAMP_SECURITY_ALLOW_GUEST_TCP_EGRESS",
715 "BOATRAMP_SECURITY_ALLOW_GUEST_TCP_LISTENER",
716 "BOATRAMP_SECURITY_MAX_HANDLER_BLOB_BYTES",
717 "BOATRAMP_SECURITY_MAX_COMPONENT_BYTES",
718 "BOATRAMP_SECURITY_OIDC_REQUIRE_AUDIENCE",
719 "BOATRAMP_SECURITY_DOMAIN_VERIFY_ALLOW_PRIVATE",
720 "BOATRAMP_SECURITY_DOMAIN_VERIFY_SELF_SERVE",
721 "BOATRAMP_SECURITY_ALLOW_SHARED_KERNEL_COMPUTE",
722 "BOATRAMP_SECURITY_ALLOW_COMPUTE_EXEC",
723 "BOATRAMP_SECURITY_ALLOW_DEV_BLOB_BIND",
724 "BOATRAMP_SECURITY_ALLOW_DEV_MESSAGING_BIND",
725 "BOATRAMP_SECURITY_RATELIMIT_FAIL_OPEN",
726 "BOATRAMP_SECURITY_ALLOW_IMPLICIT_ROUTING",
727 "BOATRAMP_SECURITY_REQUIRE_POP",
728 "BOATRAMP_SECURITY_REQUIRE_DOMAIN_VERIFICATION",
729 "BOATRAMP_SECURITY_ALLOW_ENV_SECRET_REFS",
730 "BOATRAMP_SECURITY_REQUIRE_TENANCY_DECLARATION",
731 "BOATRAMP_SECURITY_ALLOW_CROSS_TENANT_DB",
732 "BOATRAMP_SECURITY_ALLOW_GUEST_MINT_CAPABILITY",
733 "BOATRAMP_SECURITY_MAX_GUEST_CAPABILITY_TTL_SECS",
734 "BOATRAMP_SECURITY_ALLOW_GUEST_EMAIL",
735 "BOATRAMP_SECURITY_ALLOW_GUEST_ADMIN_DOMAINS",
736 "BOATRAMP_SECURITY_ALLOW_GUEST_ADMIN_EMAIL",
737 "BOATRAMP_SECURITY_ALLOW_GUEST_ADMIN_SITE",
738 "BOATRAMP_SECURITY_ALLOW_GUEST_ADMIN_SECRETS",
739];
740
741/// The `BOATRAMP_*` variables that populate `handlers.bindings.sql`.
742const SQL_ENV_VARS: &[&str] = &[
743 "BOATRAMP_HANDLERS_SQL_DIR",
744 "BOATRAMP_HANDLERS_SQL_URL",
745 "BOATRAMP_HANDLERS_SQL_ADMIN_URL",
746 "BOATRAMP_HANDLERS_SQL_REPLICA_URL",
747 "BOATRAMP_HANDLERS_SQL_TOKEN_ENV",
748 "BOATRAMP_HANDLERS_SQL_ADMIN_TOKEN_ENV",
749 "BOATRAMP_HANDLERS_SQL_PREVIEW_MODE",
750 "BOATRAMP_HANDLERS_SQL_PREVIEW_INIT",
751 "BOATRAMP_HANDLERS_SQL_DEPROVISION_GRACE_SECS",
752 "BOATRAMP_HANDLERS_SQL_MIGRATE_TRUSTED_EXTENSIONS",
753 "BOATRAMP_HANDLERS_SQL_MAX_DECLARED_DATABASES",
754 "BOATRAMP_HANDLERS_SQL_MAX_DECLARED_VOLUME_MIB",
755];
756
757/// The `[handlers]` JWKS-freshness env levers (two-tier own/foreign refresh + hard-ttl + prewarm),
758/// mirroring the `jwks_*` fields on [`HandlersConfig`]. Kept in sync by the forgot-a-knob guard test.
759const JWKS_ENV_VARS: &[&str] = &[
760 "BOATRAMP_HANDLERS_JWKS_REFRESH_SECS",
761 "BOATRAMP_HANDLERS_JWKS_HARD_TTL_SECS",
762 "BOATRAMP_HANDLERS_JWKS_FOREIGN_REFRESH_SECS",
763 "BOATRAMP_HANDLERS_JWKS_FOREIGN_HARD_TTL_SECS",
764 "BOATRAMP_HANDLERS_JWKS_PREWARM",
765];
766
767/// The `[handlers]` concurrency-lane env levers (per-component serve-admission gate + the global
768/// sync/async lane ceilings), mirroring the `serve_concurrency` / `sync_max_concurrency` /
769/// `async_max_concurrency` fields on [`HandlersConfig`]. Kept in sync by the forgot-a-knob guard test.
770const HANDLER_CONCURRENCY_ENV_VARS: &[&str] = &[
771 "BOATRAMP_HANDLERS_SERVE_CONCURRENCY",
772 "BOATRAMP_HANDLERS_SYNC_MAX_CONCURRENCY",
773 "BOATRAMP_HANDLERS_ASYNC_MAX_CONCURRENCY",
774];
775
776/// The `[handlers]` hedged-blob-read env levers (serve-path fetch-tail cut), mirroring the
777/// `blob_hedge_delay_ms` / `blob_hedge_max_inflight` fields on [`HandlersConfig`]. Kept in sync by the
778/// forgot-a-knob guard test.
779const HANDLER_BLOB_HEDGE_ENV_VARS: &[&str] = &[
780 "BOATRAMP_HANDLERS_BLOB_HEDGE_DELAY_MS",
781 "BOATRAMP_HANDLERS_BLOB_HEDGE_MAX_INFLIGHT",
782];
783
784/// The `[handlers]` cold-start env levers (cap-req 09): the warm floor + the portable AOT
785/// artifact cache, mirroring the `keep_warm_max` / `aot_artifact_cache` /
786/// `aot_artifact_max_bytes` fields on [`HandlersConfig`]. Kept in sync by the forgot-a-knob
787/// guard test.
788const HANDLER_COLDSTART_ENV_VARS: &[&str] = &[
789 "BOATRAMP_HANDLERS_KEEP_WARM_MAX",
790 "BOATRAMP_HANDLERS_AOT_ARTIFACT_CACHE",
791 "BOATRAMP_HANDLERS_AOT_ARTIFACT_MAX_BYTES",
792];
793
794/// The `[serve.s3_ingress_cloud]` env levers (the blob-upload minter's cloud-brokering policy),
795/// mirroring the fields on [`S3IngressCloud`]. Kept in sync by the forgot-a-knob guard test. These are
796/// policy toggles only; the signing credential stays the sealed `[secrets]` one.
797const S3_INGRESS_CLOUD_ENV_VARS: &[&str] = &[
798 "BOATRAMP_S3_INGRESS_CLOUD_AWS_ROLE_ARN",
799 "BOATRAMP_S3_INGRESS_CLOUD_AWS_USE_FEDERATION_TOKEN",
800 "BOATRAMP_S3_INGRESS_CLOUD_AWS_PRESIGNED_ONLY",
801 "BOATRAMP_S3_INGRESS_CLOUD_GCS_CLIENT_EMAIL",
802 "BOATRAMP_S3_INGRESS_CLOUD_AZURE_ACCOUNT",
803 "BOATRAMP_S3_INGRESS_CLOUD_AZURE_SERVICE_URL",
804 "BOATRAMP_S3_INGRESS_CLOUD_AZURE_HNS",
805];
806
807/// The fixed prefix of a keyed `handlers.bindings.sql.databases` variable —
808/// `BOATRAMP_HANDLERS_SQL_DB_<NAME>_<FIELD>`. Member names aren't known ahead of
809/// time (there is no config file to enumerate them), so they are discovered by
810/// scanning the environment for this prefix.
811const SQL_DB_ENV_PREFIX: &str = "BOATRAMP_HANDLERS_SQL_DB_";
812
813/// The recognised `_<FIELD>` suffixes of a `databases` variable, ordered so a
814/// name-isolating strip matches the **longest** suffix first (`_READ_URL_ENV`
815/// before `_URL_ENV`). Each mirrors a field of [`ExternalDatabaseConfig`].
816const SQL_DB_FIELD_SUFFIXES: &[&str] = &[
817 "_STARTUP_GRACE_SECS",
818 "_CONNECT_TIMEOUT_SECS",
819 // `_SESSION_GUC` / `_TENANT_GUC` / `_TENANT_ALL_MARKER` before `_TENANT`/`_TENANT_SCOPE`
820 // (longest-first name isolation).
821 "_SESSION_GUC",
822 "_TENANT_ALL_MARKER",
823 "_TENANT_GUC",
824 "_VOLUME_SIZE_MIB",
825 "_READ_URL_ENV",
826 "_PASSWORD_ENV",
827 "_ALLOW_PREVIEW",
828 "_URL_ENV",
829 "_DATABASE",
830 "_READ_ONLY",
831 "_POOL_MAX",
832 "_RLS_SESSION",
833 "_TENANT_SCOPE",
834 "_COMPUTE",
835 "_TENANT",
836 "_IMAGE",
837 "_KIND",
838 "_USER",
839];
840
841/// The fixed prefix of a keyed `[serve.blob_backends.<project>]` variable —
842/// `BOATRAMP_SERVE_BLOB_BACKEND_<PROJECT>_<FIELD>` (PLAN-per-project-blob-backend). Member project
843/// names aren't known ahead of time (there is no config file to enumerate them), so they are discovered
844/// by scanning the environment for this prefix — mirroring [`SQL_DB_ENV_PREFIX`].
845const BLOB_BACKEND_ENV_PREFIX: &str = "BOATRAMP_SERVE_BLOB_BACKEND_";
846
847/// The recognised `_<FIELD>` suffixes of a `[serve.blob_backends]` variable, ordered so a
848/// name-isolating strip matches the **longest** suffix first (so `_S3_SECRET_ACCESS_KEY` wins over any
849/// shorter overlap). Each mirrors a field of [`BlobBackendConfig`] (the sealed credential's two public
850/// refs are flattened as `_S3_ACCESS_KEY_ID` / `_S3_SECRET_ACCESS_KEY`). Kept in sync by the
851/// `blob_backend_env_covers_every_field` forgot-a-knob guard test.
852const BLOB_BACKEND_FIELD_SUFFIXES: &[&str] = &[
853 "_S3_SECRET_ACCESS_KEY",
854 "_S3_ACCESS_KEY_ID",
855 "_S3_PATH_STYLE",
856 "_S3_ENDPOINT",
857 "_S3_BUCKET",
858 "_S3_REGION",
859 "_KIND",
860];
861
862/// The fixed prefix of a keyed `[serve.listeners.<name>]` variable —
863/// `BOATRAMP_SERVE_LISTENER_<NAME>_<FIELD>` (PLAN-handler-tcp-inbound). Listener names aren't known
864/// ahead of time (there is no config file to enumerate them under env-only config), so they are
865/// discovered by scanning the environment for this prefix — mirroring [`BLOB_BACKEND_ENV_PREFIX`].
866const LISTENER_ENV_PREFIX: &str = "BOATRAMP_SERVE_LISTENER_";
867
868/// The recognised `_<FIELD>` suffixes of a `[serve.listeners]` variable, ordered so a name-isolating
869/// strip matches the **longest** suffix first (so `_MAX_CONN_DURATION_MS` wins over `_MAX_CONNS`). Each
870/// mirrors a SCALAR field of [`ListenerConfig`]; the structured fields (`imports`/`env`/`tenancy`) and
871/// the Phase-1-refused `tls`/`egress_allowlist` are set only from the config file. `_IMPORTS` is a
872/// comma-separated list. Kept in sync by the `listener_env_covers_every_field` forgot-a-knob guard.
873const LISTENER_FIELD_SUFFIXES: &[&str] = &[
874 "_MAX_CONN_DURATION_MS",
875 "_IDLE_TIMEOUT_MS",
876 "_MAX_CONNS",
877 "_COMPONENT",
878 "_IMPORTS",
879 "_PROJECT",
880 "_BIND",
881 "_SITE",
882];
883
884/// The `BOATRAMP_*` variables that populate the `[secrets]` section (excluding the
885/// nested `vault` sub-config, gated separately by [`SECRETS_VAULT_ENV_VARS`]).
886const SECRETS_ENV_VARS: &[&str] = &[
887 "BOATRAMP_SECRETS_ENVELOPE",
888 "BOATRAMP_SECRETS_KEK_FILE",
889 "BOATRAMP_SECRETS_VAULT_ADDR",
890 "BOATRAMP_SECRETS_VAULT_KEY",
891 "BOATRAMP_SECRETS_VAULT_TOKEN_ENV",
892];
893
894/// The `BOATRAMP_*` variables that populate the nested `[secrets.vault]` sub-config.
895const SECRETS_VAULT_ENV_VARS: &[&str] = &[
896 "BOATRAMP_SECRETS_VAULT_ADDR",
897 "BOATRAMP_SECRETS_VAULT_KEY",
898 "BOATRAMP_SECRETS_VAULT_TOKEN_ENV",
899];
900
901/// The `BOATRAMP_*` variables that populate the `[cluster]` section fields (the
902/// section's own config, distinct from the founding/joining *action* flags
903/// `BOATRAMP_CLUSTER_INIT` / `_JOIN` / `_ADVERTISE_ADDR`, which are `serve` clap
904/// args and are deliberately not listed here).
905const CLUSTER_ENV_VARS: &[&str] = &[
906 "BOATRAMP_CLUSTER_LISTEN",
907 "BOATRAMP_CLUSTER_ROOT_PUBKEYS",
908 "BOATRAMP_CLUSTER_SEEDS",
909 "BOATRAMP_CLUSTER_JOIN_TOKEN",
910 "BOATRAMP_CLUSTER_STORE_DIR",
911 "BOATRAMP_CLUSTER_MESH_KEY_FILE",
912 "BOATRAMP_CLUSTER_MESH_KEY_ROTATION",
913 "BOATRAMP_CLUSTER_MESH_JOIN_TOKEN_TTL",
914 "BOATRAMP_CLUSTER_MESH_GATE_CLIENT_WRITES",
915];
916
917/// Where env-override values come from: the real process environment, or an explicit map
918/// (the CLI-flag layer, which reuses the env overlay to turn `{BOATRAMP_<NAME>: value}`
919/// command-line flags into a figment dict; and deterministic unit tests — no racy,
920/// process-global `std::env`).
921pub(crate) enum EnvSource {
922 /// The live process environment (`std::env::var`).
923 Process,
924 /// A fixed name→value map (the CLI-flag layer + tests).
925 Map(BTreeMap<String, String>),
926}
927
928impl EnvSource {
929 /// The value of `var`, if set to a non-empty string. An empty value is treated
930 /// as unset so an accidental `VAR=` doesn't clobber a file value with `""`.
931 fn get(&self, var: &str) -> Option<String> {
932 let raw = match self {
933 Self::Process => std::env::var(var).ok(),
934 Self::Map(m) => m.get(var).cloned(),
935 };
936 raw.filter(|v| !v.is_empty())
937 }
938
939 /// Whether any of `vars` is set (to a non-empty value).
940 fn any(&self, vars: &[&str]) -> bool {
941 vars.iter().any(|v| self.get(v).is_some())
942 }
943
944 /// The full set of variable names visible to this source. Used to discover the
945 /// keyed-map member names from the environment (there is no config file to
946 /// enumerate them). Returned owned so it doesn't borrow the process env.
947 fn names(&self) -> Box<dyn Iterator<Item = String> + '_> {
948 match self {
949 Self::Process => Box::new(std::env::vars().map(|(k, _)| k)),
950 Self::Map(m) => Box::new(m.keys().cloned()),
951 }
952 }
953
954 /// The distinct `<NAME>` tokens of every `BOATRAMP_HANDLERS_SQL_DB_<NAME>_<FIELD>`
955 /// variable that is set. The name is everything between the fixed prefix and the
956 /// *last* `_<FIELD>` segment, so a database name may itself contain underscores
957 /// (the field suffix is one of a known set). Returned sorted + de-duplicated so
958 /// the map is built deterministically.
959 fn sql_database_names(&self) -> Vec<String> {
960 let mut names: Vec<String> = self
961 .names()
962 .filter(|n| n.starts_with(SQL_DB_ENV_PREFIX) && self.get(n).is_some())
963 .filter_map(|n| {
964 let rest = n.strip_prefix(SQL_DB_ENV_PREFIX)?;
965 // Strip the recognised field suffix to isolate `<NAME>`. The suffixes
966 // are matched longest-first so `READ_URL_ENV` wins over `URL_ENV`.
967 SQL_DB_FIELD_SUFFIXES
968 .iter()
969 .find_map(|suffix| rest.strip_suffix(suffix))
970 .filter(|name| !name.is_empty())
971 .map(str::to_string)
972 })
973 .collect();
974 names.sort();
975 names.dedup();
976 names
977 }
978
979 /// The distinct `<PROJECT>` tokens of every `BOATRAMP_SERVE_BLOB_BACKEND_<PROJECT>_<FIELD>`
980 /// variable that is set (PLAN-per-project-blob-backend). The name is everything between the fixed
981 /// prefix and the *last* `_<FIELD>` segment, so a project name may itself contain underscores (the
982 /// field suffix is one of a known set, matched longest-first). Returned sorted + de-duplicated so
983 /// the map is built deterministically. Mirrors [`Self::sql_database_names`].
984 fn blob_backend_projects(&self) -> Vec<String> {
985 let mut names: Vec<String> = self
986 .names()
987 .filter(|n| n.starts_with(BLOB_BACKEND_ENV_PREFIX) && self.get(n).is_some())
988 .filter_map(|n| {
989 let rest = n.strip_prefix(BLOB_BACKEND_ENV_PREFIX)?;
990 BLOB_BACKEND_FIELD_SUFFIXES
991 .iter()
992 .find_map(|suffix| rest.strip_suffix(suffix))
993 .filter(|name| !name.is_empty())
994 .map(str::to_string)
995 })
996 .collect();
997 names.sort();
998 names.dedup();
999 names
1000 }
1001
1002 /// The distinct `<NAME>` tokens of every `BOATRAMP_SERVE_LISTENER_<NAME>_<FIELD>` variable that is
1003 /// set (PLAN-handler-tcp-inbound). The name is everything between the fixed prefix and the *last*
1004 /// `_<FIELD>` segment (suffixes matched longest-first), so a listener name may itself contain
1005 /// underscores. Returned sorted + de-duplicated so the map is built deterministically. Mirrors
1006 /// [`Self::blob_backend_projects`].
1007 fn listener_names(&self) -> Vec<String> {
1008 let mut names: Vec<String> = self
1009 .names()
1010 .filter(|n| n.starts_with(LISTENER_ENV_PREFIX) && self.get(n).is_some())
1011 .filter_map(|n| {
1012 let rest = n.strip_prefix(LISTENER_ENV_PREFIX)?;
1013 LISTENER_FIELD_SUFFIXES
1014 .iter()
1015 .find_map(|suffix| rest.strip_suffix(suffix))
1016 .filter(|name| !name.is_empty())
1017 .map(str::to_string)
1018 })
1019 .collect();
1020 names.sort();
1021 names.dedup();
1022 names
1023 }
1024
1025 /// Parse `var` as a **comma-separated** list of non-empty trimmed items, e.g.
1026 /// the kernel trust anchors. A single value (no comma) yields a one-element
1027 /// list. Empty items are dropped so a trailing comma or doubled separator is
1028 /// tolerated. `Ok(None)` when unset; `Some(Vec::new())` never happens (an
1029 /// all-empty value is treated as unset by [`Self::get`]).
1030 fn parse_list(&self, var: &str) -> Option<Vec<String>> {
1031 self.get(var).map(|raw| {
1032 raw.split(',')
1033 .map(str::trim)
1034 .filter(|s| !s.is_empty())
1035 .map(str::to_string)
1036 .collect()
1037 })
1038 }
1039}
1040
1041/// How a **managed database** (PLAN-managed-compute-sql) runs its stock image on a
1042/// shared-kernel backend, whose entrypoint would otherwise fail under the dropped-`ALL`
1043/// hardening. `rootless` (the default) needs no capabilities and works under any
1044/// posture; `caps` is the fallback for an image that won't run rootless.
1045#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
1046#[serde(rename_all = "lowercase")]
1047pub enum ManagedDbPrivilege {
1048 /// Run the DB as its image's user (`999:999` for the official postgres/mysql
1049 /// images) against a pre-owned volume — no added capabilities, any posture.
1050 #[default]
1051 Rootless,
1052 /// Add the minimal capability set the entrypoint needs (`CHOWN`, `DAC_OVERRIDE`,
1053 /// `FOWNER`, `SETUID`, `SETGID`). Honored only under the single-tenant posture.
1054 Caps,
1055}
1056
1057/// `compute` section — opt-in compute backends. Present
1058/// ⇒ `serve` registers the backends this node can offer and advertises them to
1059/// the scheduler; backends are capability-detected (container on Linux, remote
1060/// docker when a daemon is reachable, VMM when `/dev/kvm` exists).
1061#[derive(Debug, Clone, Serialize, Deserialize)]
1062#[serde(default, deny_unknown_fields)]
1063pub struct ComputeConfig {
1064 /// Bridge the container veths / VM taps attach to (default `br-boatramp`).
1065 pub bridge: String,
1066 /// Guest IP subnet (default `10.0.0.0/24`).
1067 pub subnet: String,
1068 /// vCPUs this node advertises as schedulable (`0` ⇒ detect from the host).
1069 pub vcpus: u32,
1070 /// Memory (MiB) this node advertises as schedulable (`0` ⇒ a 1 GiB default).
1071 pub mem_mib: u32,
1072 /// **Static** kernel-signing public keys (`"<alg>:<hex>"`) — the trust anchor
1073 /// for the posture-scaled kernel bar. Under `multi-tenant`, a dynamically-
1074 /// selected default kernel must carry a signature verifying against one of
1075 /// these. Host-access-gated (never in the KV tier); changing it needs a
1076 /// restart. Empty ⇒ no kernel may be signed-verified (strict posture then
1077 /// accepts none).
1078 pub kernel_signing_pubkeys: Vec<String>,
1079 /// **Static** allow-list of kernel content hashes (sha256 hex) a dynamic
1080 /// default may select under `multi-tenant`. Host-access-gated. Empty ⇒ no
1081 /// kernel is allow-listed.
1082 pub kernel_allowed_hashes: Vec<String>,
1083 /// This node's **region** tag (FA-8). Advertised on the compute `Node` so a
1084 /// gateway routing to a `compute:`-backed workload with `--lb nearest` sends
1085 /// each request to the nearest replica by its node's region — no manual
1086 /// `--region` map. `None` ⇒ region-agnostic.
1087 pub region: Option<String>,
1088 /// How the remote-Docker backend reports a workload's reachable endpoint.
1089 /// `published` (default) publishes the container port on `127.0.0.1:<ephemeral>`
1090 /// so a host-native `serve` reaches it on any daemon (incl. Docker Desktop /
1091 /// macOS, where the bridge IP is not host-routable); `bridge` routes to the
1092 /// container bridge IP directly (only when `serve` shares the daemon's network).
1093 pub docker_endpoint: boatramp_docker::DockerEndpoint,
1094 /// How the remote-Docker backend backs a workload's persistent volumes.
1095 /// `named` (default) attaches a daemon-managed `docker volume` by name (portable
1096 /// across daemons + Docker Desktop / macOS); `bind` bind-mounts a host directory
1097 /// under `<data_dir>/compute/volumes/<name>` (local daemon only).
1098 pub docker_volume_mode: boatramp_docker::DockerVolumeMode,
1099 /// Wall-clock backstop (seconds) for one project export/import client run
1100 /// (`run_ephemeral`: a `pg_dump`/`pg_restore` container). `0` (default) keeps the
1101 /// backend's generous built-in default (6h). Raise it for a very large migration so
1102 /// the backstop never kills legitimate work; the real unreachable-DSN hang is bounded
1103 /// far tighter by the client's own connect timeout.
1104 #[serde(default)]
1105 pub docker_ephemeral_timeout_secs: u64,
1106 /// Guest-reachable base URL of the compute **sql-shim** (PLAN-compute-bindings) —
1107 /// e.g. `http://10.0.0.1:8081` (the compute bridge gateway) or the docker bridge
1108 /// gateway. Set ⇒ a workload's `--bind sql` reaches the managed database through a
1109 /// listener bound on the **host:port this URL names** (the bridge-gateway IP /
1110 /// loopback — NOT all interfaces; a token-gated tenant-SQL data plane must not be
1111 /// off-node reachable). `None` (default) ⇒ compute sql bindings off.
1112 #[serde(default, skip_serializing_if = "Option::is_none")]
1113 #[cfg_attr(not(feature = "handlers"), allow(dead_code))]
1114 pub sql_shim_url: Option<String>,
1115 /// Guest-reachable base URL of the compute **blob-shim** (PLAN-compute-bindings) —
1116 /// e.g. `http://10.0.0.1:8082` (the compute bridge gateway) or the docker bridge
1117 /// gateway. Set ⇒ a workload's `--bind blob` reaches the SAME per-site
1118 /// `hblob/{qualified-site}/…` blob namespace a `wasi:blobstore` handler sees, through a
1119 /// listener bound on the **host:port this URL names** (the bridge-gateway IP /
1120 /// loopback — NOT all interfaces; the token-gated `hblob/{site}/` data plane must not
1121 /// be off-node reachable). `None` (default) ⇒ compute blob bindings off. The direct
1122 /// analogue of [`Self::sql_shim_url`].
1123 #[serde(default, skip_serializing_if = "Option::is_none")]
1124 #[cfg_attr(not(feature = "handlers"), allow(dead_code))]
1125 pub blob_shim_url: Option<String>,
1126 /// Guest-reachable base URL of the compute **messaging-shim** (PLAN-compute-bindings) —
1127 /// e.g. `http://10.0.0.1:8083` (the compute bridge gateway) or the docker bridge gateway.
1128 /// Set ⇒ a workload's `--bind messaging` reaches BOTH halves of the SAME `{project}/bus/
1129 /// <topic>` project bus a `wasi:messaging` handler sees — `POST /publish/{topic}` AND the
1130 /// consume ops `POST /claim/{topic}`, `POST /ack`, `POST /nack` — through a listener bound
1131 /// on the **host:port this URL names** (the bridge-gateway IP / loopback — NOT all
1132 /// interfaces; the token-gated `{project}/bus/` data plane must not be off-node reachable).
1133 /// `None` (default) ⇒ compute messaging bindings off. The direct analogue of
1134 /// [`Self::sql_shim_url`] / [`Self::blob_shim_url`].
1135 #[serde(default, skip_serializing_if = "Option::is_none")]
1136 #[cfg_attr(not(feature = "handlers"), allow(dead_code))]
1137 pub messaging_shim_url: Option<String>,
1138 /// Per-object PUT ceiling (bytes) for the compute blob-shim — bounds a single write so a
1139 /// compromised/buggy workload cannot exhaust node/bucket storage with one unbounded PUT (`413`
1140 /// on an oversize PUT). `None` (default) ⇒ the shim's built-in default (5 GiB, S3's single-PUT
1141 /// limit); `Some(0)` ⇒ unlimited.
1142 #[serde(default, skip_serializing_if = "Option::is_none")]
1143 #[cfg_attr(not(feature = "handlers"), allow(dead_code))]
1144 pub blob_shim_max_object_bytes: Option<u64>,
1145 /// Privilege strategy for a managed database's stock image on a shared-kernel
1146 /// backend (see [`ManagedDbPrivilege`]). `rootless` by default.
1147 #[serde(default)]
1148 #[cfg_attr(not(feature = "handlers"), allow(dead_code))]
1149 pub managed_db_privilege: ManagedDbPrivilege,
1150 /// Per-project **internal DNS** (service discovery): run a lightweight resolver
1151 /// on the bridge gateway so a guest can reach peers by name (`<workload>` /
1152 /// `<workload>.<project>.<dns_domain>`) instead of a numeric IP, scoped to its
1153 /// own project. Default **on** — it activates only when the container backend +
1154 /// bridge come up, so a node without them is unaffected. `false` disables it and
1155 /// leaves each image's own `/etc/resolv.conf`.
1156 #[serde(default = "default_internal_dns")]
1157 pub internal_dns: bool,
1158 /// The upstream resolver the internal DNS forwards non-internal queries to
1159 /// (external names + non-`A`/`AAAA` types), so the resolver is the guest's single
1160 /// nameserver. `"host:port"`; default `1.1.1.1:53`.
1161 #[serde(default = "default_dns_upstream")]
1162 pub dns_upstream: String,
1163 /// The internal DNS suffix names live under (`<workload>.<project>.<dns_domain>`);
1164 /// also the `search` domain written into each container's resolv.conf. Default
1165 /// `boatramp.internal`.
1166 #[serde(default = "default_dns_domain")]
1167 pub dns_domain: String,
1168 /// **Air-gap override** for the project export/import **client images** the native
1169 /// container backend runs via `run_ephemeral` (a `pg_dump`/`pg_restore`/`mysqldump`/
1170 /// `mysql`/`psql` one-shot). Maps a client image reference → a **preloaded rootfs**, so
1171 /// an export/import can run with NO registry pull on an isolated node. The value is
1172 /// either an **absolute host path** to an already-unpacked rootfs directory (used
1173 /// verbatim), or a **Storage blob hash** of a rootfs tar the backend stages like any
1174 /// `RootSource::Tar`. Empty (the default) ⇒ every client image is pulled + built
1175 /// on demand over the registry HTTP API (daemonless), the same path `materialize`
1176 /// uses. Only the native `container` backend consults this; the remote `docker`
1177 /// backend pulls through its daemon. Example:
1178 ///
1179 /// ```toml
1180 /// [compute.client_image_rootfs]
1181 /// "pgvector/pgvector:pg16" = "/var/lib/boatramp/client-rootfs/pg16"
1182 /// "mysql:8.0" = "9f86d0818...<rootfs-tar-blob-sha256>"
1183 /// ```
1184 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
1185 #[cfg_attr(not(target_os = "linux"), allow(dead_code))]
1186 pub client_image_rootfs: BTreeMap<String, String>,
1187 /// **Digest-pin / override** for the Postgres client image the project export/import + `sql exec`
1188 /// seams run via `run_ephemeral` (`pg_dump`/`pg_restore`/`psql`). When set, this image reference is
1189 /// used VERBATIM instead of the version-computed `pgvector/pgvector:pg{major}` tag — so an operator
1190 /// can pin it by digest (`pgvector/pgvector:pg16@sha256:<hex>`) and have it accepted under the
1191 /// multi-tenant posture (which refuses an un-pinned mutable-tag pull), with NO rootfs staging:
1192 /// boatramp pulls + runs it through the normal on-demand path. The lighter-weight alternative to
1193 /// [`Self::client_image_rootfs`] for a node with registry egress. `None` (default) ⇒ the computed
1194 /// tag. Env: `BOATRAMP_COMPUTE_PG_CLIENT_IMAGE`.
1195 #[serde(default, skip_serializing_if = "Option::is_none")]
1196 #[cfg_attr(not(target_os = "linux"), allow(dead_code))]
1197 pub pg_client_image: Option<String>,
1198 /// MySQL counterpart of [`Self::pg_client_image`] — pins/overrides the `mysql:<maj.min>` client
1199 /// image for the export/import/`sql exec` `run_ephemeral` (`mysqldump`/`mysql`). Env:
1200 /// `BOATRAMP_COMPUTE_MYSQL_CLIENT_IMAGE`.
1201 #[serde(default, skip_serializing_if = "Option::is_none")]
1202 #[cfg_attr(not(target_os = "linux"), allow(dead_code))]
1203 pub mysql_client_image: Option<String>,
1204}
1205
1206/// Default for [`ComputeConfig::internal_dns`] — on (activates only with the
1207/// container backend + bridge).
1208fn default_internal_dns() -> bool {
1209 true
1210}
1211
1212/// Default upstream resolver for [`ComputeConfig::dns_upstream`].
1213fn default_dns_upstream() -> String {
1214 "1.1.1.1:53".to_string()
1215}
1216
1217/// Default internal DNS suffix for [`ComputeConfig::dns_domain`].
1218fn default_dns_domain() -> String {
1219 boatramp_container::dns::DEFAULT_INTERNAL_DOMAIN.to_string()
1220}
1221
1222/// The built-in **boatramp kernel-signing public key** (`es256:…`), whose private
1223/// half lives as the `KERNEL_SIGNING_KEY` Actions secret in
1224/// [`BoatRamp/boatramp-vmlinux`](https://github.com/BoatRamp/boatramp-vmlinux).
1225/// Shipped as a default trust anchor so the first-party signed `boatramp-vmlinux`
1226/// verifies out of the box under the strict posture. An operator can replace
1227/// `kernel_signing_pubkeys` to trust only their own keys.
1228pub const BOATRAMP_KERNEL_SIGNING_PUBKEY: &str =
1229 "es256:02c4e4af2e9cba6ba6745c513f193622e6674a8b2d0187ebea5612f5b46a7eade4";
1230
1231/// The first-party signed-kernel content hashes trusted under the **strict**
1232/// posture, for this build's **guest arch**. The guest arch mirrors the host: an
1233/// x86_64 host boots x86_64 KVM guests (the embedded VMM); an Apple-silicon host
1234/// boots aarch64 guests (the Virtualization.framework `vmm-vz` backend). An x86_64
1235/// kernel can't boot an aarch64 VM (and vice versa), so each arch trusts only its
1236/// own signed `boatramp-vmlinux-<arch>` releases. Bump on each new signed release.
1237///
1238/// The **relaxed** (single-tenant) posture ignores this list — it verifies only the
1239/// content-hash pin — so an operator-supplied kernel boots there regardless of arch.
1240fn default_allowed_kernel_hashes() -> Vec<String> {
1241 #[cfg(target_arch = "x86_64")]
1242 {
1243 vec![
1244 // v0.2.0 minimal Firecracker 6.1-config kernel: boots under the
1245 // firecracker-*binary* backend (ACPI device discovery) but NOT the
1246 // in-process embedded VMM. Kept trusted so operators on the currently
1247 // published release don't fail strict verification.
1248 "cf1e590a9e642be3667131ca35fbf390378a457d8908169d2a169608e299d974".to_string(),
1249 // Same kernel + CONFIG_VIRTIO_MMIO_CMDLINE_DEVICES=y (flake `#vmlinux`),
1250 // so the embedded VMM binds its virtio-block root over the cmdline
1251 // transport. Reproducible build output (deterministic nix build,
1252 // verified on KVM); the next signed boatramp-vmlinux release — which
1253 // reuses this flake — publishes + signs it, gated by
1254 // `vmlinux-release-boot.yml`.
1255 "d0dc2098ab2a2a3c1bc72ab61dc85d9e464d798d7e55b6b80525db5ca2f00c5a".to_string(),
1256 ]
1257 }
1258 #[cfg(target_arch = "aarch64")]
1259 {
1260 vec![
1261 // `boatramp-vmlinux-aarch64` v0.2.3 (the Virtualization.framework guest
1262 // kernel, flake `#vmlinux` on aarch64-linux — a raw arm64 `Image`). This
1263 // release enables the generic PCIe host + virtio-pci so the guest actually
1264 // discovers VZ's virtio disk/net/console (the earlier v0.2.2 `be95fb0d…`
1265 // built with `CONFIG_PCI` off never booted under VZ and is dropped). This
1266 // is the hash of the **published, ES256-signed** release asset (signed by
1267 // BOATRAMP_KERNEL_SIGNING_PUBKEY), so a selected `compute.default_kernel`
1268 // clears the strict bar out of the box; the boot + scale-to-zero round-trip
1269 // was validated against this exact published kernel. NOTE: unlike x86_64,
1270 // the aarch64 build is not currently bit-reproducible across build hosts
1271 // (same config + size, different build metadata), so pin/verify against the
1272 // published `.sha256`/`.sig`, not a local rebuild. Bump on each new release.
1273 "d785a48d754e65a4630443301f1fb84cb69cf882336d3cf37055e437b3d8e21f".to_string(),
1274 ]
1275 }
1276 #[cfg(not(any(target_arch = "x86_64", target_arch = "aarch64")))]
1277 {
1278 Vec::new()
1279 }
1280}
1281
1282impl Default for ComputeConfig {
1283 fn default() -> Self {
1284 Self {
1285 bridge: "br-boatramp".to_string(),
1286 subnet: "10.0.0.0/24".to_string(),
1287 vcpus: 0,
1288 mem_mib: 0,
1289 kernel_signing_pubkeys: vec![BOATRAMP_KERNEL_SIGNING_PUBKEY.to_string()],
1290 kernel_allowed_hashes: default_allowed_kernel_hashes(),
1291 region: None,
1292 docker_endpoint: boatramp_docker::DockerEndpoint::default(),
1293 docker_volume_mode: boatramp_docker::DockerVolumeMode::default(),
1294 docker_ephemeral_timeout_secs: 0,
1295 sql_shim_url: None,
1296 blob_shim_url: None,
1297 messaging_shim_url: None,
1298 blob_shim_max_object_bytes: None,
1299 managed_db_privilege: ManagedDbPrivilege::default(),
1300 internal_dns: default_internal_dns(),
1301 dns_upstream: default_dns_upstream(),
1302 dns_domain: default_dns_domain(),
1303 client_image_rootfs: BTreeMap::new(),
1304 pg_client_image: None,
1305 mysql_client_image: None,
1306 }
1307 }
1308}
1309
1310/// `cluster` section — self-hosted **cluster mode**. Parsed in
1311/// every build so config files stay portable; only *consumed* when the `cluster`
1312/// feature is compiled in (`boatramp serve --mode cluster`).
1313#[cfg_attr(not(feature = "cluster"), allow(dead_code))]
1314#[derive(Debug, Clone, Serialize, Deserialize)]
1315pub struct ClusterConfig {
1316 /// Address to bind this node's Raft **peer mesh** on (the `/raft/*` +
1317 /// `/stream/*` endpoints) — distinct from the public `serve.addr`.
1318 pub listen: SocketAddr,
1319 /// The cluster **root anchor set** — the `es256:`/`ed25519:`-tagged public
1320 /// keys that define this cluster's identity (a cluster *is* its root key).
1321 /// Every join/trust decision verifies against this set. Empty ⇒ falls back to
1322 /// `serve.auth_root_public_key` (the single-anchor default). A *set* enables
1323 /// make-before-break root rotation.
1324 #[serde(default)]
1325 pub root_pubkeys: Vec<String>,
1326 /// **Seeds** — control-plane addresses of existing cluster members
1327 /// (`host:port`), any of which can admit this node. Present ⇒ this node
1328 /// **joins** (redeems its `join_token`); absent + no durable state + explicit
1329 /// `--cluster-init` ⇒ it **founds**. There is no peer map: members are learned
1330 /// from the root-signed join response.
1331 #[serde(default)]
1332 pub seeds: Vec<String>,
1333 /// The single-use bearer **join token** used when `seeds` are set. Keeps the
1334 /// secret out of the file via a prefix: `env:VAR`, `path:/file`, or an inline
1335 /// literal. Usually supplied via `serve --cluster-join <ticket>` instead.
1336 #[serde(default)]
1337 pub join_token: Option<String>,
1338 /// Directory for this node's **durable** Raft log/state store (node-local;
1339 /// distinct from the replicated control plane). Default
1340 /// `<data-dir>/raft`.
1341 #[serde(default)]
1342 pub store_dir: Option<PathBuf>,
1343 /// Mesh identity + TLS settings. Absent ⇒ defaults (identity key
1344 /// auto-generated under `<data-dir>/mesh/identity.key`).
1345 #[serde(default)]
1346 pub mesh: Option<MeshConfig>,
1347}
1348
1349/// `[cluster.mesh]` — mesh identity + TLS knobs.
1350#[cfg_attr(not(feature = "cluster"), allow(dead_code))]
1351#[derive(Debug, Clone, Default, Serialize, Deserialize)]
1352#[serde(default, deny_unknown_fields)]
1353pub struct MeshConfig {
1354 /// Path to this node's Ed25519 identity key (PKCS#8 DER, `0600`,
1355 /// auto-generated). Default `<data-dir>/mesh/identity.key`.
1356 pub key_file: Option<PathBuf>,
1357 /// Automatic key-rotation cadence (e.g. `"30d"`); `None` = manual only.
1358 /// Consumed by the rotation loop.
1359 pub key_rotation: Option<String>,
1360 /// TTL for a single-use join token (e.g. `"1h"`).
1361 pub join_token_ttl: Option<String>,
1362 /// Gate mesh `client-write`s behind a control-plane **cluster-write
1363 /// capability**, so a trusted peer can't inject arbitrary
1364 /// control-plane writes on mesh trust alone. Requires the token root
1365 /// **private** key on every node (each mints + presents its own capability);
1366 /// default `false`.
1367 pub gate_client_writes: Option<bool>,
1368 /// Which transport carries the Raft peer-mesh RPC (IU-9): `"http"` (default — reqwest/axum
1369 /// over the mutual-TLS mesh) or `"overlay"` (boatramp's own overlay-QUIC fabric, reusing the
1370 /// mesh identity + live trust set verbatim). `None` ⇒ `"http"`. Both bind the same
1371 /// `cluster.listen` address — HTTP over TCP, overlay over UDP/QUIC.
1372 pub transport: Option<String>,
1373}
1374
1375/// `handlers` section — server-side handler runtime config (read by `serve`).
1376/// Parsed in every build (so config files stay portable), but only *consumed*
1377/// when the `handlers` feature is compiled in.
1378#[cfg_attr(not(feature = "handlers"), allow(dead_code))]
1379#[derive(Debug, Clone, Default, Serialize, Deserialize)]
1380#[serde(default)]
1381pub struct HandlersConfig {
1382 /// `handlers.bindings` — which backend serves each handler binding.
1383 pub bindings: BindingsConfig,
1384 /// Use the wasmtime **pooling** instance allocator: faster
1385 /// instantiation at the cost of a large up-front virtual-memory reservation.
1386 /// Off by default — opt in and benchmark for your workload.
1387 pub pooling: bool,
1388 /// Capacity of the per-lane **warm compile cache** — how many distinct compiled+linked components
1389 /// (keyed by content hash) stay resident per lane (request / consumer / session). A component
1390 /// evicted here (LRU, once the node serves more than this many distinct components on a lane) pays
1391 /// a cold cranelift recompile on its next request. Absent ⇒ 64 (the historical default). Raise it
1392 /// on a node that serves more than ~64 components so none is evicted; the `/api/instance-stats`
1393 /// surface reports `warm_capacity` + `evictions` so the right value is measured, not guessed.
1394 #[serde(default, skip_serializing_if = "Option::is_none")]
1395 pub instance_cache_size: Option<usize>,
1396 /// **Warm floor** (cold-start cap-req 09): the maximum number of request components PINNED
1397 /// in a never-evicted set, so a latency-critical face never cold-starts under LRU capacity
1398 /// pressure. Absent/`0` ⇒ off (the plain LRU). Each activated request component is pinned
1399 /// up to this cap (first-come); size it ≥ your latency-critical handler count. Pinned
1400 /// components cost one resident instance each on top of the LRU, so keep it modest.
1401 #[serde(default, skip_serializing_if = "Option::is_none")]
1402 pub keep_warm_max: Option<usize>,
1403 /// **Portable cross-node AOT artifact cache** (cold-start cap-req 09). When `true` AND a
1404 /// `[secrets]` envelope is configured, a node publishes each request component's precompiled
1405 /// artifact (cluster-MAC-authenticated) to the shared blob store, and a FRESH replica
1406 /// hydrates it instead of recompiling from source. Default **off** (opt-in): it loads
1407 /// native code off the shared store, so it is gated on the cluster secret + a MAC check.
1408 /// A node without the envelope silently never participates (it still compiles + warm-caches).
1409 #[serde(default, skip_serializing_if = "Option::is_none")]
1410 pub aot_artifact_cache: Option<bool>,
1411 /// Per-artifact size ceiling for the AOT cache (bytes; `0` ⇒ unlimited). Native code is
1412 /// large; an artifact over this is neither published nor (beyond a hard safety ceiling)
1413 /// read. Absent ⇒ a generous default. Only consulted when `aot_artifact_cache` is on.
1414 #[serde(default, skip_serializing_if = "Option::is_none")]
1415 pub aot_artifact_max_bytes: Option<u64>,
1416 /// **Blob container-marker cache size** (entries). Every blob container open re-`HEAD`s the
1417 /// `.boatramp-container` ownership marker — a second serial object-store round-trip per serve. A
1418 /// process-wide, positive-only cache of VERIFIED markers (keyed by the fully-resolved, tenant-confined
1419 /// container prefix; invalidated on container delete) skips that HEAD for an already-verified
1420 /// container WITHOUT touching confinement (`container_access` still runs on every op). Absent ⇒ 4096;
1421 /// `0` disables the cache (every open re-HEADs). A node rarely has more than a handful of live
1422 /// containers, so the default is generous headroom.
1423 #[serde(default, skip_serializing_if = "Option::is_none")]
1424 pub blob_marker_cache_entries: Option<usize>,
1425 /// **Hedged blob-read delay** (milliseconds). When a serve's object GET has not returned within this
1426 /// many ms, the host races a SECOND GET and takes whichever lands first — cutting the serve-path
1427 /// fetch tail on an external store (measured: `blob_range` p50 ≈ 16ms but p99 ≈ 727ms, with CPU
1428 /// idle). Blob reads are idempotent, so the hedge is always safe; the loser is cancelled. Absent/`0`
1429 /// ⇒ disabled (one GET per read). Set it a little above the warm p90 (e.g. 60–100ms) so only the
1430 /// genuinely-slow tail hedges. Pairs with [`blob_hedge_max_inflight`](Self::blob_hedge_max_inflight).
1431 #[serde(default, skip_serializing_if = "Option::is_none")]
1432 pub blob_hedge_delay_ms: Option<u64>,
1433 /// **Concurrent-hedge cap** — the max number of in-flight hedge (second) reads at once. Guards against
1434 /// a hedge storm when the whole store is slow (every read would otherwise double): over the cap a slow
1435 /// read simply waits on its single request. Absent ⇒ a small internal default (16). Only meaningful
1436 /// when [`blob_hedge_delay_ms`](Self::blob_hedge_delay_ms) is set.
1437 #[serde(default, skip_serializing_if = "Option::is_none")]
1438 pub blob_hedge_max_inflight: Option<usize>,
1439 /// **Per-component serve-admission concurrency** (image-serve-latency Ask B). Caps how many
1440 /// requests to the SAME component (keyed by content hash) are concurrently inside the expensive
1441 /// `build_bindings` + instantiate + serve-to-head region; a burst beyond it (e.g. a gallery firing
1442 /// dozens of `/img` thumbnails) queues cheaply on a semaphore instead of oversubscribing the tokio
1443 /// workers, which on a small-core node makes each request's await-resumptions pile up into a
1444 /// multi-second scheduling stall (the measured `bindgap`). Absent ⇒ a host-parallelism default
1445 /// (`available_parallelism * 4`, floored at 8) so a small node is bounded out of the box; `0`
1446 /// disables the gate (legacy unbounded serve). Raise it on a big node, or lower it if one hot
1447 /// component should be tighter; `/api/instance-stats` + the `bindgap` Server-Timing phase make the
1448 /// right value measurable.
1449 #[serde(default, skip_serializing_if = "Option::is_none")]
1450 pub serve_concurrency: Option<usize>,
1451 /// Engine-wide **safety max** on a *connection-bearing* invocation (a site
1452 /// handler or a synchronous function/webhook invoke), milliseconds. A route
1453 /// or function may declare a *lower* timeout, never a higher one. Kept tight
1454 /// on purpose: a client, proxy, and the shared request pool are all blocked
1455 /// while a sync handler runs. Absent ⇒ 10s (the historical default). This is
1456 /// a node safety ceiling, not a per-invocation budget, and is distinct from
1457 /// a per-site `max_timeout_ms`.
1458 pub sync_max_timeout_ms: Option<u64>,
1459 /// Max concurrent in-flight *sync-lane* invocations node-wide — the GLOBAL ceiling every
1460 /// connection-bearing serve (site handler, synchronous invoke, and the `/graphql` gateway's
1461 /// subgraph fan-out) passes through, distinct from the PER-COMPONENT `serve_concurrency` gate.
1462 /// Absent ⇒ a host-parallelism default (`available_parallelism * 4`, floored at **64** — so it is
1463 /// unchanged on nodes up to ~16 vCPU and only scales ABOVE that). Without this, the lane was pinned
1464 /// at 64 regardless of host size, so adding vCPUs past ~16 bought no extra concurrent live
1465 /// throughput and there was no knob to lift it. Raise it on a big node to let the sync lane use more
1466 /// cores; lower it to cap aggregate live concurrency. Read once at startup. NOTE: with `[handlers]
1467 /// pooling` on, the shared instance pool is sized off the summed lane concurrencies, so a larger
1468 /// value enlarges the up-front virtual reservation (the non-pooling default sizes memory
1469 /// per-invocation and is unaffected). Unlike `serve_concurrency`, `0` is NOT "disable" — the
1470 /// global sync lane is a required safety ceiling, so a configured `0` is rejected (falls back to
1471 /// the host default, with a loud WARN at startup).
1472 pub sync_max_concurrency: Option<usize>,
1473 /// Emit the per-phase `Server-Timing` RESPONSE HEADER to clients. Default **off** (absent ⇒
1474 /// `false`): the per-phase breakdown always goes to the structured phase-timing LOG (operator
1475 /// observability), but putting it on the wire exposes internal phase structure + a timing
1476 /// side-channel to every caller. Turn it on for a debugging window (e.g. correlating a client's
1477 /// slow request to a host phase), off in production. Read once at startup.
1478 #[serde(default, skip_serializing_if = "Option::is_none")]
1479 pub server_timing: Option<bool>,
1480 /// Engine-wide safety max on a *durable async* invocation — the drain that
1481 /// runs `?mode=async` calls, workflow steps, cron/queue/blob triggers, and
1482 /// `wasi:messaging` consumers, milliseconds. No client is connected and the
1483 /// work is retried + dead-lettered, so this can be far larger than the sync
1484 /// ceiling: it is what lets a legitimately long background job (e.g. an LLM
1485 /// generation) declare and actually get minutes of runtime. Absent ⇒ 15
1486 /// minutes. Runs on its own concurrency budget (`async_max_concurrency`), so
1487 /// a long job never starves live traffic.
1488 pub async_max_timeout_ms: Option<u64>,
1489 /// Max concurrent in-flight *async-lane* invocations, kept separate from the
1490 /// (larger) request pool so a burst of long background jobs can't exhaust the
1491 /// slots live site traffic needs. Absent ⇒ 8.
1492 pub async_max_concurrency: Option<usize>,
1493 /// Optional CPU **fuel** ceiling for an async-lane invocation. A large async
1494 /// timeout bounds only wall-clock; without a fuel bound a CPU-bound guest can
1495 /// spin for the whole window. Absent ⇒ unmetered (same as the sync default).
1496 pub async_max_fuel: Option<u64>,
1497 /// Per-component WASM linear-memory **ceiling** for the *async* lane, in MiB —
1498 /// the durable `wasi:messaging` / workflow-step lane where heavy, retryable jobs
1499 /// (image decode+resize, PDF, document processing) belong. This RAISES the lane
1500 /// ceiling above the 64 MiB default; a component's own `limits.memory_mb` (or the
1501 /// site `max_memory_mb`) then clamps it back **down** from here — so an operator
1502 /// sets the lane high enough for the heaviest consumer and each component
1503 /// right-sizes itself. Absent ⇒ 64 MiB (unchanged for every existing component;
1504 /// no component can raise its own memory above this operator-set ceiling). With
1505 /// `[handlers] pooling` on, the shared pool is sized off the largest lane ceiling;
1506 /// see the virtual-reservation note on `pooling`.
1507 pub async_max_memory_mb: Option<usize>,
1508 /// Per-component WASM linear-memory ceiling for the *sync* (request) lane, MiB.
1509 /// Absent ⇒ 64 MiB. Same semantics as [`async_max_memory_mb`](Self::async_max_memory_mb)
1510 /// (raises the lane ceiling; a component clamps down). Raising the sync lane means
1511 /// many concurrent request instances can each reach this ceiling, so weigh it
1512 /// against the request pool's size.
1513 pub sync_max_memory_mb: Option<usize>,
1514 /// Per-component WASM linear-memory ceiling for the *streaming* lane, MiB.
1515 /// Absent ⇒ 64 MiB. Same semantics as [`async_max_memory_mb`](Self::async_max_memory_mb).
1516 pub streaming_max_memory_mb: Option<usize>,
1517 /// **Relaxed messaging-publish durability** — the max number of published
1518 /// messages that may be acknowledged from the in-memory buffer BEFORE a durable
1519 /// checkpoint is forced. **Absent / `0` ⇒ strong durability (the default):**
1520 /// every `publish()` returns only after the message is crash-durable — a
1521 /// *stronger* guarantee than NATS JetStream's default sync publish. Set `N > 0`
1522 /// to opt a node into fast-ack (publish returns on the buffer insert, ~10µs
1523 /// instead of ~one flush interval), at the cost of a **bounded loss window: up
1524 /// to `N` acknowledged-but-unflushed messages are lost on a process crash / OOM
1525 /// / SIGKILL / power loss** before the next flush. Affects ONLY the messaging
1526 /// bus publish path — control-plane, auth, and consumer ack/redelivery
1527 /// durability are unaffected. Single-node only (cluster durability is
1528 /// replication). A node with `N > 0` logs a warning at startup.
1529 pub messaging_max_unflushed_msgs: Option<usize>,
1530 /// **Event-driven delivery — safety-net reconcile cadence** (ms). The coarse timer the delivery
1531 /// drainer falls back to when no fast-path wake fires: it drains the durable ready-set and fires
1532 /// lease-expiry redelivery via the per-message due-heap, so a dropped wake or a time-based
1533 /// visibility never stalls delivery beyond this interval. It never scans idle topics (an idle
1534 /// fleet costs ~0). Absent ⇒ ~2 s. Lower for tighter redelivery latency at more wakeups; raise to
1535 /// quiet a large idle fleet further.
1536 pub messaging_safetynet_interval_ms: Option<u64>,
1537 /// **Event-driven delivery — ready-set rebuild cadence** (ms). The long-cadence self-heal that
1538 /// re-derives the ready-set from the authoritative message index — recovering a marker lost to a
1539 /// crash between the index write and the ready write, pruning a stale marker, and self-populating
1540 /// a fresh/upgraded node's ready-set. This is the one full-ish scan, so it runs rarely. Absent ⇒
1541 /// ~30 s. The correctness backstop for the ready-set (a lost marker costs at most one rebuild
1542 /// interval of latency, never a lost message).
1543 pub messaging_readyset_rebuild_interval_ms: Option<u64>,
1544 /// Max wall-clock for a *streaming-lane* response (a `#[handler(stream)]`
1545 /// route — SSE, chunked, agent token streaming), milliseconds. A client is
1546 /// connected but the body is written incrementally over seconds-to-minutes,
1547 /// so this is far larger than the sync ceiling. Runs on its own concurrency
1548 /// budget (`streaming_max_concurrency`), isolated from both the fast request
1549 /// pool and the async drain. Absent ⇒ 15 minutes.
1550 pub streaming_max_timeout_ms: Option<u64>,
1551 /// Max concurrent in-flight *streaming-lane* responses, kept separate from the
1552 /// request pool and the async drain so a burst of long-lived streams starves
1553 /// neither. Absent ⇒ 64.
1554 pub streaming_max_concurrency: Option<usize>,
1555 /// Optional CPU **fuel** ceiling for a streaming-lane response. Absent ⇒
1556 /// unmetered (a stream is I/O-bound on the client, not CPU-bound).
1557 pub streaming_max_fuel: Option<u64>,
1558 /// **Idle cap** for a streaming-lane response (ms): if the handler emits no body frame to the
1559 /// client for this long, the host tears the stream down and reclaims its lane slot — the
1560 /// slowloris bound for the streaming lane, so a `streaming_max_concurrency`-sized burst of
1561 /// silent streams can't hold every slot. A well-behaved SSE stream sends heartbeats well inside
1562 /// it. The absolute lifetime stays bounded by `streaming_max_timeout_ms`. Floored at 1 s. Absent
1563 /// ⇒ 600 s (matches the `[stream]` fan-out idle window).
1564 pub streaming_idle_timeout_ms: Option<u64>,
1565 /// Optional ceiling on a guest's **outbound** `wasi:http` call — the connect
1566 /// and time-to-first-byte wait — milliseconds, independent of the invocation
1567 /// timeout, so a hung upstream is bounded on its own terms. The streaming
1568 /// (between-bytes) timeout is left at wasmtime's default so a slow token
1569 /// stream is not cut mid-flight. Absent ⇒ wasmtime's default.
1570 pub outbound_timeout_ms: Option<u64>,
1571 /// **JWKS freshness — `own` (first-party) tier: background-refresh age** (seconds). The soft age at
1572 /// which a node-fixed `token_claims.jwks_url`/`jwks_env` verifier is refreshed in the BACKGROUND
1573 /// (the current keys keep serving — no request blocks on the fetch). Absent ⇒ 120 s. Floored at 60 s.
1574 #[serde(default, skip_serializing_if = "Option::is_none")]
1575 pub jwks_refresh_secs: Option<u64>,
1576 /// **JWKS freshness — `own` tier: hard TTL / revocation bound** (seconds). The age past which the
1577 /// first-party keys are no longer served and a request BLOCKS on a fresh fetch (fail-closed on
1578 /// failure) — caps how long a key revoked at the IdP can keep verifying. Absent ⇒ 600 s. Must be
1579 /// `> jwks_refresh_secs` (else clamped up, with a warning). Floored at 60 s.
1580 #[serde(default, skip_serializing_if = "Option::is_none")]
1581 pub jwks_hard_ttl_secs: Option<u64>,
1582 /// **JWKS freshness — `foreign` (user-declared multi-issuer) tier: background-refresh age**
1583 /// (seconds). As [`jwks_refresh_secs`](Self::jwks_refresh_secs) but for the multi-issuer
1584 /// (`issuer_trust`+`jwks` discovery) path, which is less trusted. Absent ⇒ 60 s. Floored at 60 s.
1585 #[serde(default, skip_serializing_if = "Option::is_none")]
1586 pub jwks_foreign_refresh_secs: Option<u64>,
1587 /// **JWKS freshness — `foreign` tier: hard TTL / revocation bound** (seconds). As
1588 /// [`jwks_hard_ttl_secs`](Self::jwks_hard_ttl_secs) but for user-declared issuers — typically set
1589 /// TIGHTER (faster revocation of a potentially-compromised foreign key). Absent ⇒ 300 s. Must be
1590 /// `> jwks_foreign_refresh_secs`. Floored at 60 s.
1591 #[serde(default, skip_serializing_if = "Option::is_none")]
1592 pub jwks_foreign_hard_ttl_secs: Option<u64>,
1593 /// **JWKS pre-warm at startup.** When on (the default), the node fetches each configured
1594 /// first-party (`own`-tier) `jwks_url` at startup so even the FIRST request is instant; foreign
1595 /// (user-declared) issuers can't be pre-warmed (they aren't known until a token arrives). Set
1596 /// `false` to skip startup JWKS fetches (the first request per issuer then pays the fetch). Absent ⇒ on.
1597 #[serde(default, skip_serializing_if = "Option::is_none")]
1598 pub jwks_prewarm: Option<bool>,
1599}
1600
1601/// `handlers.bindings` — per-binding backend configuration. kv/blob reuse the
1602/// server's own KV/Storage backends (per-site prefixed); `sql` is the single
1603/// libsql backend, whose single-node-vs-cluster split is the only choice.
1604#[cfg_attr(not(feature = "handlers"), allow(dead_code))]
1605#[derive(Debug, Clone, Default, Serialize, Deserialize)]
1606#[serde(default)]
1607pub struct BindingsConfig {
1608 /// `handlers.bindings.sql` — libsql settings. Absent ⇒ single-node,
1609 /// per-site embedded files under `<data-dir>/handlers-sql`.
1610 pub sql: Option<SqlBindingConfig>,
1611}
1612
1613/// libsql settings for the handler `sql` binding — the single SQL backend. Each
1614/// site gets a real database boundary (an embedded file per site, or a sqld
1615/// namespace per site), never schema separation (which arbitrary guest SQL
1616/// escapes). Setting `url` switches from single-node to a shared sqld cluster;
1617/// everything else stays identical.
1618#[cfg_attr(not(feature = "handlers"), allow(dead_code))]
1619#[derive(Debug, Clone, Default, Serialize, Deserialize)]
1620#[serde(default)]
1621pub struct SqlBindingConfig {
1622 /// Single-node: root directory for the per-site embedded database files
1623 /// (default `<data-dir>/handlers-sql`). Ignored when `url` is set.
1624 pub dir: Option<PathBuf>,
1625 /// Cluster: base sqld data URL (e.g. `http://sqld:8080`). When set, each
1626 /// site is a sqld namespace addressed as a subdomain of this URL; `admin_url`
1627 /// is then required.
1628 pub url: Option<String>,
1629 /// Cluster: sqld admin API base URL (e.g. `http://sqld:9090`) for creating
1630 /// per-site namespaces. Required when `url` is set.
1631 pub admin_url: Option<String>,
1632 /// Cluster: optional sqld **read-replica** data URL. When set, handlers'
1633 /// read-only `sql` transactions (`open-read-only`) route to this endpoint
1634 /// while writes stay on `url` (reads → replicas, writes → primary).
1635 /// Reads may lag (eventually consistent). Ignored in
1636 /// single-node mode (no `url`).
1637 pub replica_url: Option<String>,
1638 /// Name of the env var holding the sqld data auth token (optional; never
1639 /// the token itself in-file).
1640 pub token_env: Option<String>,
1641 /// Name of the env var holding the sqld admin API auth key (optional).
1642 pub admin_token_env: Option<String>,
1643 /// How preview deployments get their SQL database: `empty` (default — a
1644 /// fresh isolated db), `branch` (a consistent copy of the site's live db;
1645 /// single-node only), or `shared` (the site's live db). See
1646 /// `boatramp_core::sql::PreviewSqlMode`.
1647 pub preview_mode: Option<String>,
1648 /// Path to an idempotent SQL script run when an `empty` preview database is
1649 /// first opened (e.g. schema/seed). Ignored in `branch`/`shared` modes.
1650 pub preview_init: Option<PathBuf>,
1651 /// `handlers.bindings.sql.databases` — external **bring-your-own** databases,
1652 /// each opened by name via `sql.open("<name>")`. An operator-configured
1653 /// Postgres/MySQL whose *isolation is the operator's* (it's their database),
1654 /// so these bypass the per-site libsql boundary and are reachable by any
1655 /// handler/function granted the `sql` binding. Needs the `sql-postgres` /
1656 /// `sql-mysql` build feature for the engine. A name here shadows the same
1657 /// name on the managed libsql default.
1658 pub databases: BTreeMap<String, ExternalDatabaseConfig>,
1659 /// **Soft-delete grace window** for a per-tenant managed database, in seconds
1660 /// (env `BOATRAMP_HANDLERS_SQL_DEPROVISION_GRACE_SECS`). When a project/site is
1661 /// deleted, a **Shared + Postgres** tenant is *soft*-deleted (its database is
1662 /// renamed aside and its role disabled) and stays recoverable for this long
1663 /// before a reaper hard-drops it — see
1664 /// [`tenant_sql`](crate::tenant_sql). `None` ⇒ the 7-day default
1665 /// (`DEFAULT_DEPROVISION_GRACE_SECS`); `0` ⇒ disable the soft path (immediate,
1666 /// irreversible hard drop everywhere). MySQL and all `Single` tenants always
1667 /// hard-drop immediately (the engine/cell can't be renamed aside safely), so this
1668 /// knob only affects the Shared-Postgres cell.
1669 pub deprovision_grace_secs: Option<u64>,
1670 /// **Trusted-extension allowlist** for the owner-gated schema-migration surface — the ONLY
1671 /// Postgres extensions a migration `Extension` step may enable (a name not here is refused
1672 /// fail-closed). A raw `sql` migration step may not `CREATE EXTENSION` at all, so this list is
1673 /// the single, operator-controlled gate on which extensions a project can install via
1674 /// migrations. Empty / `None` ⇒ no extension may be enabled through a migration (the safest
1675 /// default). Keep it tight (e.g. `["pgcrypto", "uuid-ossp", "citext"]`); an entry like
1676 /// `dblink`/`postgres_fdw` deliberately widens cross-database reach, so add those only knowingly.
1677 ///
1678 /// Env-settable (12-factor parity) via **`BOATRAMP_HANDLERS_SQL_MIGRATE_TRUSTED_EXTENSIONS`** —
1679 /// a comma-separated list (`pg_trgm,pgcrypto`), env-over-file, unset ⇒ the file value. Only an
1680 /// input path; the allowlist semantics (the `Extension`-step gate, the fail-closed refusal of an
1681 /// unlisted name, the `sql`-step `CREATE EXTENSION` ban) are unchanged.
1682 pub migrate_trusted_extensions: Option<Vec<String>>,
1683 /// **Per-project declared-database COUNT ceiling** (#501 Stage B MEDIUM-1 — the
1684 /// disk-exhaustion / errno-28 guard). The maximum number of `databases:` entries a
1685 /// single project may declare; a declare that would exceed it is refused fail-closed
1686 /// (a 422-class error). Each declared DB eagerly provisions a 10–200 GiB volume, so
1687 /// without this a `Project·Admin` could declare an unbounded number and exhaust the
1688 /// node's disk. `None` ⇒ the built-in default
1689 /// (`apply_db_caps::DEFAULT_MAX_DECLARED_DATABASES_PER_PROJECT`, 16); `0` ⇒ declaring
1690 /// any managed database is disabled on this node. Env-settable via
1691 /// **`BOATRAMP_HANDLERS_SQL_MAX_DECLARED_DATABASES`** (env-over-file).
1692 pub max_declared_databases: Option<usize>,
1693 /// **Per-project aggregate declared-VOLUME ceiling**, in MiB (#501 Stage B
1694 /// MEDIUM-1). The maximum SUM of `volume_size_mib` across all of a project's declared
1695 /// databases; a declare whose incoming volume would push the project's total past
1696 /// this is refused fail-closed. `None` ⇒ the built-in default
1697 /// (`apply_db_caps::DEFAULT_MAX_DECLARED_VOLUME_MIB`, 512 GiB); `0` ⇒ disable managed
1698 /// declarations on this node (the aggregate can never fit a non-zero volume). Env-settable via
1699 /// **`BOATRAMP_HANDLERS_SQL_MAX_DECLARED_VOLUME_MIB`** (env-over-file).
1700 pub max_declared_volume_mib: Option<u64>,
1701}
1702
1703/// One external SQL database for the handler `sql` binding. Its **source** is one
1704/// of two mutually-exclusive forms:
1705/// - `url_env` — a **bring-your-own** database: the connection URL is a secret,
1706/// named indirectly by an env var (never written in the config file).
1707/// - `compute` — a database **boatramp runs** as a compute workload: boatramp
1708/// derives the connection from the workload's live endpoint (host\:port) plus
1709/// the `database`/`user`/`password_env` here, so there is no URL to hand-map and
1710/// it follows the workload across restarts (PLAN-managed-compute-sql).
1711#[cfg_attr(not(feature = "handlers"), allow(dead_code))]
1712#[derive(Debug, Clone, Default, Serialize, Deserialize)]
1713#[serde(default)]
1714pub struct ExternalDatabaseConfig {
1715 /// Engine: `postgres` (aliases `postgresql`/`pg`), `mysql` (alias
1716 /// `mariadb`), or `libsql` (aliases `sqlite`/`sqlite3`) — the embedded
1717 /// SQLite-compatible engine (single-node file, or a remote sqld primary via
1718 /// `url_env`). A `libsql` entry needs neither `compute` nor an external URL for
1719 /// the single-node case: it names an on-disk file via [`path`](Self::path).
1720 pub kind: String,
1721 /// Name of the env var holding the connection URL (e.g.
1722 /// `postgres://user:pw@host/db`). Required unless `compute` is set — or, for a
1723 /// single-node `libsql` database, unless `path` is set (an embedded file needs
1724 /// no URL/secret).
1725 pub url_env: String,
1726 /// Optional env var holding a **read-replica** connection URL. When set,
1727 /// `open-read-only` transactions route there; writes stay on `url_env`.
1728 pub read_url_env: Option<String>,
1729 /// Optional env var holding a **DDL/migration** connection URL for the
1730 /// **owner-role analog** of the schema-migration surface — a login that is
1731 /// DDL-capable *and distinct from the runtime binding user* (`user` /
1732 /// `url_env`). Its whole purpose is to keep migration DDL off the runtime
1733 /// tenant identity, mirroring the Postgres owner-role split (Postgres mints a
1734 /// per-tenant non-superuser owner role automatically; MySQL has no such role
1735 /// model, so the DDL identity must be supplied explicitly).
1736 ///
1737 /// **MySQL:** required to run schema migrations. Point it at an admin/DDL
1738 /// login (e.g. `mysql://root:…@host/db` or a purpose-made `_migrate` grant
1739 /// with `CREATE, ALTER, DROP, INDEX, REFERENCES` on the schema) that is **not**
1740 /// the runtime `user`. If it is unset (or resolves to the same identity as the
1741 /// runtime binding), migrate **refuses** fail-closed rather than run owner-DDL
1742 /// as the runtime tenant user — there is no owner/runtime split to fall back
1743 /// on. Ignored by the normal handler `sql` path; read only by the migration
1744 /// runner.
1745 ///
1746 /// **Postgres:** ignored — the per-project non-superuser owner role +
1747 /// its sealed credential are minted automatically at provision, so no
1748 /// operator-supplied DDL URL is needed (a set value is harmless and unused).
1749 pub migration_url_env: Option<String>,
1750 /// The name of a **compute workload** (a Postgres/MySQL server boatramp runs)
1751 /// to source this database from, instead of `url_env`. boatramp resolves the
1752 /// workload's live endpoint and builds the connection. Mutually exclusive with
1753 /// `url_env`.
1754 ///
1755 /// **Reserved prefix (#501 Stage B LOW-2):** do NOT name a static workload with the
1756 /// `bramp-db-` prefix — it is reserved for the per-project managed-database servers
1757 /// boatramp derives for declarative `databases:` entries
1758 /// (`boatramp_storage::tenant_provision::DERIVED_MANAGED_DB_PREFIX`). A `bramp-db-…`
1759 /// value here is refused fail-closed at config load
1760 /// ([`ConfigError::InvalidDbName`](crate::config::ConfigError::InvalidDbName)).
1761 pub compute: Option<String>,
1762 /// The database name inside the compute-backed server (non-secret).
1763 pub database: Option<String>,
1764 /// The connecting user for the compute-backed server (non-secret).
1765 pub user: Option<String>,
1766 /// Env var holding the password for `user` on the compute-backed server.
1767 /// **Omit to let boatramp fully manage the credential** (PLAN-managed-compute-sql
1768 /// Phase 2): it generates a strong password once, seals it with the `[secrets]`
1769 /// envelope, injects it into the DB workload's server-init env at launch, and
1770 /// connects the handler with it — the operator sets no DB secret at all. Set it
1771 /// only to bring your own password for the compute-backed server.
1772 pub password_env: Option<String>,
1773 /// Maximum pooled connections (default 8).
1774 pub pool_max: Option<u32>,
1775 /// Open every transaction `READ ONLY` (the engine rejects writes) — for a
1776 /// database functions should only read.
1777 pub read_only: bool,
1778 /// Permit **preview** deployments to reach this database. Default `false`: a
1779 /// preview is refused, so it can never touch the operator's live external DB.
1780 pub allow_preview: bool,
1781 /// Connection/acquire timeout in seconds (default 10).
1782 pub connect_timeout_secs: Option<u64>,
1783 /// The stock OCI image for a **managed co-located** database (`compute` set, no
1784 /// `password_env`). When omitted, boatramp auto-registers the workload from the
1785 /// engine's default image (`pgvector/pgvector:pg16` for postgres, `mysql:8.0`
1786 /// for mysql). Ignored for a bring-your-own (`url_env`) database.
1787 pub image: Option<String>,
1788 /// The persistent data-volume size in MiB for a **managed co-located** database
1789 /// (default 10240 = 10 GiB). Ignored for a bring-your-own database.
1790 pub volume_size_mib: Option<u32>,
1791 /// Startup grace (seconds) for a **managed co-located** database: how long a
1792 /// freshly launched server has to finish its first `initdb` before the reconcile
1793 /// loop treats a still-unhealthy replica as a broken launch to stop + relaunch.
1794 /// When set it overrides the engine default the synthesizer picks (Postgres 60,
1795 /// MySQL 120). Omit to use that default. Ignored for a bring-your-own database.
1796 pub startup_grace_secs: Option<u32>,
1797 /// **Isolation mechanism** for a compute-backed managed database (2×2 axis 1).
1798 /// `single` (default) — a *dedicated* database server (its own container) per
1799 /// tenant; `shared` — *one* server hosting a permission-separated database + role
1800 /// per tenant. Ignored for a bring-your-own (`url_env`) database.
1801 pub tenant: TenantIsolation,
1802 /// **Tenant grain** for a compute-backed managed database (2×2 axis 2). `project`
1803 /// (default) — a tenant is a project; `site` — a tenant is a site. A tenant may
1804 /// hold several databases (one per binding that names it); it gets one login role
1805 /// and sealed credential per (tenant, server), granted on all its own databases
1806 /// and none of another tenant's. The reserved `default` project uses the plain
1807 /// configured name, so a single-tenant install is just one ordinary database.
1808 pub tenant_scope: TenantScope,
1809 /// **Opt-in** (default `false`): inject the request's `boatramp.project` /
1810 /// `boatramp.site` into the SQL session at each transaction start (Postgres
1811 /// `set_config` GUC, MySQL session var), so hand-written **native RLS** policies
1812 /// can key on them per-request. The GraphQL data connector's row-level policy is
1813 /// claim-sourced and needs nothing here; this is for hand-rolled RLS on the plain
1814 /// `sql.open` path (Postgres — the engine with native row-level security).
1815 ///
1816 /// # Trust model — read before relying on this for isolation
1817 ///
1818 /// `rls_session` **provides** the request's tenant to the SQL session for an app's
1819 /// RLS to key on. It is **not** a general hostile-guest boundary:
1820 ///
1821 /// - The reserved keys (`boatramp.*` / `@boatramp_*`) are **protected** from guest
1822 /// override — a handler statement that tries to `set_config('boatramp.…', …)` /
1823 /// `SET boatramp.… ` / `SET @boatramp_… ` (or `RESET`/`DISCARD` them) is refused,
1824 /// so a guest cannot spoof its injected tenant.
1825 /// - But the **real tenant-isolation boundary** is the **per-tenant database +
1826 /// role** (`tenant = single` / `shared`), which a compromised handler cannot
1827 /// cross regardless of what it does in-session. `rls_session` is a convenience
1828 /// for app-authored RLS *within* a tenant's own database, layered on top of that
1829 /// boundary — not a substitute for it.
1830 /// - For untrusted data, prefer **claim-sourced** enforcement (the GraphQL data
1831 /// connector's row-level policy), which derives the tenant from the verified
1832 /// request, not from anything the handler's SQL can influence.
1833 pub rls_session: bool,
1834 /// The Postgres session GUC name an app's RLS policies read for the host-resolved **tenant**
1835 /// (e.g. `app.tenant_id`), set per request/write on the `rls_session` path so RLS mirrors
1836 /// boatramp's injected predicate as a defense-in-depth backstop (v0.4.20). Only honored when
1837 /// `rls_session` is on and the backend is Postgres. `None` ⇒ not exposed (today's behavior).
1838 /// The guest can never set this GUC itself (its namespace becomes reserved).
1839 #[serde(default)]
1840 pub tenant_guc: Option<String>,
1841 /// The session GUC name for the anonymous **session** axis (e.g. `app.session_id`), the
1842 /// disjoint-column sibling of `tenant_guc` for `TenantOrSession` tables. `None` ⇒ not exposed.
1843 #[serde(default)]
1844 pub session_guc: Option<String>,
1845 /// A reserved sentinel value written to `tenant_guc` on an **`all`-scoped READ** (v0.4.21), so a
1846 /// table that opts in with `USING (… OR current_setting(tenant_guc, true) = '<marker>')` opens
1847 /// cross-tenant for the audited `all` twins. Pick a value that can **never** be a real tenant id
1848 /// (e.g. `*` or `__all__`). Only honored with `tenant_guc` set + `rls_session` on + Postgres.
1849 /// `None`/empty ⇒ `all` reads leave the GUC untouched (v0.4.20 fail-closed behavior). The guest
1850 /// can never set it — the `tenant_guc` namespace is already reserved against guest writes.
1851 #[serde(default)]
1852 pub tenant_all_marker: Option<String>,
1853 /// The on-disk file path for a single-node **`libsql`** database (`kind: "libsql"`), e.g.
1854 /// `/data/app.db`. The parent directory is created if absent. Used only by the embedded engine;
1855 /// ignored for `postgres`/`mysql` and for a remote-sqld `libsql` binding (which uses `url_env`).
1856 /// A `libsql` entry sets exactly one of `path` (single-node file) or `url_env` (remote sqld).
1857 #[serde(default)]
1858 pub path: Option<PathBuf>,
1859}
1860
1861/// How a managed compute-backed database is physically isolated per tenant (2×2 axis
1862/// 1). `Single` = a dedicated server (container) per tenant (isolation by separate
1863/// process); `Shared` = one server with a per-tenant database + login role (isolation
1864/// by grants — Postgres `REVOKE CONNECT FROM PUBLIC` + owner grant; MySQL per-schema
1865/// grant), so a tenant's role cannot connect to another tenant's database.
1866#[cfg_attr(not(feature = "handlers"), allow(dead_code))]
1867#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
1868#[serde(rename_all = "lowercase")]
1869pub enum TenantIsolation {
1870 /// A dedicated database server (its own container) per tenant. The default.
1871 #[default]
1872 Single,
1873 /// One shared server hosting a per-tenant database + role (grant-isolated).
1874 Shared,
1875}
1876
1877/// The grain of a tenant for a managed compute-backed database (2×2 axis 2) —
1878/// `Project` (default) or `Site`. The two grains are parallel; the isolation
1879/// mechanism is [`TenantIsolation`].
1880#[cfg_attr(not(feature = "handlers"), allow(dead_code))]
1881#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
1882#[serde(rename_all = "lowercase")]
1883pub enum TenantScope {
1884 /// A tenant is a **project** (the default).
1885 #[default]
1886 Project,
1887 /// A tenant is a **site** (finer than project).
1888 Site,
1889}
1890
1891impl ExternalDatabaseConfig {
1892 /// Validate the source is well-formed: **exactly one** of `url_env` /
1893 /// `compute`, and a `compute`-backed database has the connection details
1894 /// boatramp can't infer (`database` + `user`). `password_env` is **optional** —
1895 /// omit it to let boatramp manage the credential (Phase 2). `name` is the
1896 /// binding name, for the error message.
1897 #[cfg_attr(not(feature = "handlers"), allow(dead_code))]
1898 pub fn validate(&self, name: &str) -> Result<(), String> {
1899 let has_url = !self.url_env.is_empty();
1900 let has_compute = self.compute.as_deref().is_some_and(|c| !c.is_empty());
1901 let has_path = self
1902 .path
1903 .as_deref()
1904 .is_some_and(|p| !p.as_os_str().is_empty());
1905
1906 // A `libsql`/`sqlite` entry is the embedded engine: single-node via `path`, or remote sqld
1907 // via `url_env` — never `compute` (boatramp doesn't run a libsql server workload). Validate
1908 // it on its own axis (exactly one of `path` / `url_env`), and reject `path` on the external
1909 // engines (a Postgres/MySQL binding has no on-disk file).
1910 let is_libsql = matches!(
1911 self.kind.trim().to_ascii_lowercase().as_str(),
1912 "libsql" | "sqlite" | "sqlite3"
1913 );
1914 if is_libsql {
1915 if has_compute {
1916 return Err(format!(
1917 "sql database {name:?}: a `libsql` database is the embedded engine — set `path` \
1918 (single-node file) or `url_env` (remote sqld), not `compute`"
1919 ));
1920 }
1921 return match (has_path, has_url) {
1922 (true, true) => Err(format!(
1923 "sql database {name:?}: a `libsql` database sets exactly one of `path` \
1924 (single-node file) or `url_env` (remote sqld), not both"
1925 )),
1926 (false, false) => Err(format!(
1927 "sql database {name:?}: a `libsql` database needs a source — set `path` \
1928 (single-node file) or `url_env` (remote sqld)"
1929 )),
1930 _ => Ok(()),
1931 };
1932 }
1933 if has_path {
1934 return Err(format!(
1935 "sql database {name:?}: `path` is only valid for a `libsql` database (the embedded \
1936 engine); a {} binding uses `url_env` or `compute`",
1937 self.kind
1938 ));
1939 }
1940
1941 match (has_url, has_compute) {
1942 (true, true) => Err(format!(
1943 "sql database {name:?}: set exactly one of `url_env` or `compute`, not both"
1944 )),
1945 (false, false) => Err(format!(
1946 "sql database {name:?}: needs a source — set `url_env` (bring-your-own) or \
1947 `compute` (a database boatramp runs)"
1948 )),
1949 (false, true) => {
1950 // `database` + `user` are non-secret and can't be inferred; a missing
1951 // `password_env` is *not* an error — it selects the managed credential.
1952 for (field, val) in [("database", &self.database), ("user", &self.user)] {
1953 if val.as_deref().is_none_or(str::is_empty) {
1954 return Err(format!(
1955 "sql database {name:?}: a `compute`-backed database requires `{field}`"
1956 ));
1957 }
1958 }
1959 Ok(())
1960 }
1961 (true, false) => Ok(()),
1962 }
1963 }
1964
1965 /// Whether this compute-backed database uses a **boatramp-managed** credential
1966 /// (Phase 2): `compute` is set and no `password_env` was supplied.
1967 #[cfg_attr(not(feature = "handlers"), allow(dead_code))]
1968 pub fn is_managed_credential(&self) -> bool {
1969 self.compute.as_deref().is_some_and(|c| !c.is_empty())
1970 && self.password_env.as_deref().is_none_or(str::is_empty)
1971 }
1972}
1973
1974/// The signing algorithm for a signer that can choose one (`Local`, `Vault`,
1975/// `Pkcs11`). ES256 is the portable default; the cloud KMS backends are ES256-only
1976/// and ignore this. Written as a RON enum: `alg: Es256` / `alg: Ed25519`.
1977#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize)]
1978pub enum SignerAlg {
1979 /// ECDSA P-256 (COSE ES256) — the default.
1980 #[default]
1981 Es256,
1982 /// Ed25519 (COSE EdDSA).
1983 Ed25519,
1984}
1985
1986impl SignerAlg {
1987 fn to_token_alg(self) -> boatramp_core::cose::TokenAlg {
1988 match self {
1989 Self::Es256 => boatramp_core::cose::TokenAlg::Es256,
1990 Self::Ed25519 => boatramp_core::cose::TokenAlg::Ed25519,
1991 }
1992 }
1993}
1994
1995/// External token signer selector (`serve.signer`). Maps to
1996/// [`boatramp_server::signer::SignerConfig`]; secrets (tokens/PINs) are resolved
1997/// from the named env vars at startup, never stored in config. Written as a RON
1998/// enum — `signer: Vault(...)`, `signer: AwsKms(...)`, `signer: Pkcs11(...)`, ….
1999#[derive(Debug, Clone, Serialize, Deserialize)]
2000#[serde(deny_unknown_fields)]
2001pub enum AuthSignerConfig {
2002 /// In-process key (`"<alg>:<hex>"`).
2003 Local {
2004 /// The private key spec, `"<alg>:<hex>"`.
2005 private_key: String,
2006 },
2007 /// HashiCorp Vault Transit key.
2008 Vault {
2009 /// Vault base address.
2010 address: String,
2011 /// The Transit key name.
2012 key: String,
2013 /// Env var holding the Vault token.
2014 token_env: String,
2015 /// The key algorithm.
2016 #[serde(default)]
2017 alg: SignerAlg,
2018 },
2019 /// AWS KMS asymmetric key (ES256).
2020 AwsKms {
2021 /// The KMS key id or ARN.
2022 key_id: String,
2023 /// Optional region override.
2024 #[serde(default)]
2025 region: Option<String>,
2026 },
2027 /// GCP Cloud KMS key version (ES256).
2028 GcpKms {
2029 /// The key-version resource name.
2030 key_version: String,
2031 /// Env var holding a GCP OAuth2 access token.
2032 access_token_env: String,
2033 },
2034 /// Azure Key Vault key (ES256).
2035 AzureKv {
2036 /// The vault base URL.
2037 vault_url: String,
2038 /// The key name.
2039 key: String,
2040 /// The key version.
2041 key_version: String,
2042 /// Env var holding an Azure AD access token.
2043 access_token_env: String,
2044 },
2045 /// PKCS#11 HSM key.
2046 Pkcs11 {
2047 /// Path to the PKCS#11 module.
2048 module: String,
2049 /// The token label.
2050 token_label: String,
2051 /// The key's `CKA_LABEL`.
2052 key_label: String,
2053 /// Env var holding the user PIN.
2054 pin_env: String,
2055 /// The key algorithm.
2056 #[serde(default)]
2057 alg: SignerAlg,
2058 },
2059}
2060
2061impl AuthSignerConfig {
2062 /// Map the config-file form to the server's runtime [`SignerConfig`].
2063 pub fn to_signer_config(&self) -> boatramp_server::signer::SignerConfig {
2064 use boatramp_server::signer::SignerConfig;
2065 match self {
2066 Self::Local { private_key } => SignerConfig::Local {
2067 private_key: private_key.clone(),
2068 },
2069 Self::Vault {
2070 address,
2071 key,
2072 token_env,
2073 alg,
2074 } => SignerConfig::Vault {
2075 address: address.clone(),
2076 key: key.clone(),
2077 token_env: token_env.clone(),
2078 alg: alg.to_token_alg(),
2079 },
2080 Self::AwsKms { key_id, region } => SignerConfig::AwsKms {
2081 key_id: key_id.clone(),
2082 region: region.clone(),
2083 },
2084 Self::GcpKms {
2085 key_version,
2086 access_token_env,
2087 } => SignerConfig::GcpKms {
2088 key_version: key_version.clone(),
2089 access_token_env: access_token_env.clone(),
2090 },
2091 Self::AzureKv {
2092 vault_url,
2093 key,
2094 key_version,
2095 access_token_env,
2096 } => SignerConfig::AzureKv {
2097 vault_url: vault_url.clone(),
2098 key: key.clone(),
2099 key_version: key_version.clone(),
2100 access_token_env: access_token_env.clone(),
2101 },
2102 Self::Pkcs11 {
2103 module,
2104 token_label,
2105 key_label,
2106 pin_env,
2107 alg,
2108 } => SignerConfig::Pkcs11 {
2109 module: module.clone(),
2110 token_label: token_label.clone(),
2111 key_label: key_label.clone(),
2112 pin_env: pin_env.clone(),
2113 alg: alg.to_token_alg(),
2114 },
2115 }
2116 }
2117}
2118
2119/// `serve` section — server defaults, overridden by flags/env.
2120#[derive(Debug, Clone, Default, Serialize, Deserialize)]
2121#[serde(default)]
2122pub struct ServeConfig {
2123 /// Bind address (e.g. `0.0.0.0:8080`).
2124 pub addr: Option<SocketAddr>,
2125 /// Data directory for filesystem backends.
2126 pub data_dir: Option<PathBuf>,
2127 /// Blob object-store backend (`fs`/`s3`/`gcs`/`azure`) — the config-level analog of the
2128 /// `--blobs` flag. Absent ⇒ the flag/env decides (`--blobs`/`BOATRAMP_BLOBS`, default `fs`).
2129 /// The flag/env still wins over this (uniform `serve` precedence). Read primarily by `boatramp
2130 /// blob migrate`, which builds a source/destination backend from a config file alone; `serve`
2131 /// also honours it as the config-level fallback under the flag.
2132 pub blobs: Option<crate::backends::BlobBackend>,
2133 /// S3 bucket (`--blobs s3`). Config-level fallback for `--s3-bucket`/`BOATRAMP_S3_BUCKET`.
2134 pub s3_bucket: Option<String>,
2135 /// S3 endpoint URL (e.g. a MinIO/R2/Tigris endpoint). Fallback for `--s3-endpoint`.
2136 pub s3_endpoint: Option<String>,
2137 /// S3 region. Fallback for `--s3-region`.
2138 pub s3_region: Option<String>,
2139 /// Use S3 path-style addressing (required by MinIO). Fallback for `--s3-path-style`.
2140 pub s3_path_style: bool,
2141 /// GCS bucket (`--blobs gcs`). Fallback for `--gcs-bucket`.
2142 pub gcs_bucket: Option<String>,
2143 /// GCS storage endpoint URL (e.g. a `fake-gcs-server` emulator). Fallback for `--gcs-endpoint`.
2144 pub gcs_endpoint: Option<String>,
2145 /// Skip GCS credential resolution (anonymous — the emulator). Fallback for `--gcs-anonymous`.
2146 pub gcs_anonymous: bool,
2147 /// Azure storage account name (`--blobs azure`). Fallback for `--azure-account`.
2148 pub azure_account: Option<String>,
2149 /// Azure container name (`--blobs azure`). Fallback for `--azure-container`.
2150 pub azure_container: Option<String>,
2151 /// Azure storage account access key (shared-key auth). Fallback for `--azure-access-key`.
2152 /// Prefer the env/flag over persisting a key in the config file.
2153 pub azure_access_key: Option<String>,
2154 /// Use the Azurite emulator (well-known dev credentials + local endpoint). Fallback for
2155 /// `--azure-emulator`.
2156 pub azure_emulator: bool,
2157 /// `[serve.blob_fallback]` — a **read-only SECONDARY blob backend** for a zero-downtime
2158 /// backend switch (blob-backend migration Part 2). When set, serving reads the PRIMARY (the
2159 /// `blobs`/`s3_*`/`gcs_*`/`azure_*` fields above) first and, on a definitive miss for a
2160 /// boatramp-owned key, falls through to this secondary — so a `--blobs` switch (fs→cloud,
2161 /// provider→provider, region→region) has no serving gap while `boatramp blob migrate` drains
2162 /// the secondary into the primary. **Writes are primary-only**; the secondary is never written
2163 /// or deleted. This is a **bounded transition aid**: drain, verify, then remove this block and
2164 /// restart (the node logs a prominent startup WARNING while it is active, and GC prune is
2165 /// refused). Absent ⇒ no fallback (unchanged). See [`BlobFallbackConfig`].
2166 pub blob_fallback: Option<BlobFallbackConfig>,
2167 /// `[serve.blob_backends.<project>]` — **per-project** blob object-store overrides
2168 /// (PLAN-per-project-blob-backend). A project named here serves its `wasi:blobstore` data from its
2169 /// OWN bucket/endpoint/credential instead of the one node-wide `[serve]` backend; a project with NO
2170 /// entry — and the reserved `default` project — resolves the global default (invariant 5: an
2171 /// all-global deployment is byte-for-byte unchanged). Operator-configured (node config + sealed
2172 /// `[secrets]`), mirroring `[handlers.bindings.sql.databases]`; a project OWNER declaring its own
2173 /// backend is out of scope for this cut. Each entry's sealed S3 credential is a secret **reference**
2174 /// (`boatramp:`/`env:`), never inlined (invariant 3). Empty ⇒ no overrides (the common case). See
2175 /// [`BlobBackendConfig`]. Env parity: `BOATRAMP_SERVE_BLOB_BACKEND_<PROJECT>_*`.
2176 pub blob_backends: BTreeMap<String, BlobBackendConfig>,
2177 /// Token root **private** key (hex) — issuing node: verifies *and* mints
2178 /// tokens / OIDC exchanges.
2179 pub auth_root_private_key: Option<String>,
2180 /// Token root **public** key (hex) — verify-only node.
2181 pub auth_root_public_key: Option<String>,
2182 /// Single-use bootstrap secret enabling `POST /api/tokens/bootstrap` (mint the
2183 /// first token without an admin bearer). Prefer the `BOATRAMP_BOOTSTRAP_SECRET`
2184 /// env / `--bootstrap-secret` flag so it isn't persisted in the config file.
2185 pub bootstrap_secret: Option<String>,
2186 /// External token signer (`[serve.signer]`): mint with a
2187 /// KMS/HSM/Vault-held root key instead of an in-process `auth_root_private_key`.
2188 /// Absent ⇒ the in-process key. When set, its public half is the trust anchor.
2189 pub signer: Option<AuthSignerConfig>,
2190 /// Reject blob uploads larger than this many bytes.
2191 pub max_upload_bytes: Option<u64>,
2192 /// Abort an upload that stalls for longer than this many seconds.
2193 pub upload_idle_timeout_secs: Option<u64>,
2194 /// Cap on simultaneous blob uploads.
2195 pub max_concurrent_uploads: Option<usize>,
2196 /// In a TLS mode, bind this plain-HTTP address on a second listener that
2197 /// redirects to HTTPS (dual-listener). Only read in `tls` builds.
2198 #[cfg_attr(not(feature = "tls"), allow(dead_code))]
2199 pub http_redirect_addr: Option<SocketAddr>,
2200 /// Site to serve for a `Host` matching no domain, instead of 404.
2201 pub default_site: Option<String>,
2202 /// The fleet's canonical public origin (e.g. `https://cp.example.com`) that a
2203 /// per-request proof-of-possession must bind to (`aud`). Required for
2204 /// holder-bound (`cnf`/PoP) tokens to be usable — a proof's origin is compared
2205 /// against this value, never against a `Host`/`X-Forwarded-*` header.
2206 pub pop_origin: Option<String>,
2207 /// Require a valid control-plane token to view deployment previews.
2208 pub protect_previews: bool,
2209 /// Rate-limit cluster-wide via the control-plane KV instead of per node.
2210 pub cluster_rate_limit: bool,
2211 /// Keep the config cache coherent across processes sharing one KV via the
2212 /// changelog.
2213 pub shared_cache_coherence: bool,
2214 /// Cloud blob-change notification provisioning tier (FA-5b2): how boatramp
2215 /// obtains the native event pipeline (S3→SQS) that backs a `blob` trigger —
2216 /// `dry-run` (print the recipe), `provision` (create + retract), `verify-only`
2217 /// (operator pre-wired), or `refuse` (fail closed). Absent ⇒ no provisioning:
2218 /// `blob` triggers then work only on a self-watching backend (fs). Only wired
2219 /// for the S3 backend (`--features s3`).
2220 pub blob_notify_tier: Option<boatramp_core::blob_notify::ProvisionTier>,
2221 /// The AWS account id used to scope the provisioned SQS queue's `SendMessage`
2222 /// policy (`aws:SourceAccount`). Required when `blob_notify_tier` provisions.
2223 pub blob_notify_account_id: Option<String>,
2224 /// `[serve.console]` — the embedded web management console. Absent (or
2225 /// `enabled: false`) ⇒ not served. This is the **baseline** for the dynamic
2226 /// `console.*` daemon-config override, which can enable/move it at runtime
2227 /// (`boatramp config set console.enabled true`) without a restart.
2228 pub console: Option<ConsoleConfig>,
2229 /// Bind address for the **dedicated local S3-ingress listener** (PLAN-blob-s3-ingress,
2230 /// Architect HIGH-4). Absent ⇒ the local S3 face is NOT served (it is opt-in — a deployment that
2231 /// only mints cloud-brokered credentials never needs it). This is a SEPARATE listener from the
2232 /// control-plane `addr`: it has its own SigV4 auth surface and never reaches `serve_by_host` or
2233 /// the `/api` router.
2234 pub s3_ingress_addr: Option<SocketAddr>,
2235 /// Path to the **dedicated S3-ingress root secret** file (raw 32 bytes) — the independently-
2236 /// rotatable HKDF root for `secret_access_key` derivation (hard domain separation from the
2237 /// `[secrets]` KEK + the COSE signing key). Like `[secrets].kek_file`, this holds a *path*, never
2238 /// key material in the config text, and (in a cluster) the **same file must be present on every
2239 /// node** so every node derives the same `secret_access_key`. Absent on a single node ⇒ an
2240 /// ephemeral per-process root is auto-generated; absent on a **multi-node** deployment ⇒ the S3
2241 /// face is refused to enable (fail-closed — credentials would otherwise be un-verifiable across
2242 /// nodes). Prefer the `BOATRAMP_S3_INGRESS_SECRET_FILE` env / flag so the path stays out of the
2243 /// committed config where that matters operationally.
2244 pub s3_ingress_secret_file: Option<PathBuf>,
2245 /// The publicly-reachable base URL an external client targets for the local S3 face — what a
2246 /// **minted** upload credential (`boatramp:handlers/blob-upload` guest mint / `boatramp blob
2247 /// mint-upload` operator) embeds as its endpoint (a presigned-put URL prefix, or the SDK endpoint
2248 /// for temp-credentials). Absent ⇒ derived from `s3_ingress_addr` as `http://<addr>` (fine for a
2249 /// same-host dev/test loop; set it explicitly to the TLS-terminated public URL in production).
2250 /// Only consulted when guest/operator upload minting is wired (`blob-upload` feature + the face
2251 /// enabled).
2252 pub s3_ingress_public_url: Option<String>,
2253 /// Operator ceiling (seconds) on a minted upload credential's TTL — a guest/operator can only
2254 /// request a SHORTER lifetime (the mint clamps to this). Absent ⇒ a conservative default
2255 /// ([`DEFAULT_S3_INGRESS_MINT_MAX_TTL_SECS`]). A `0` disables minting entirely (the binding is
2256 /// never attached).
2257 pub s3_ingress_mint_max_ttl_secs: Option<u64>,
2258 /// Operator ceiling (bytes) on a minted credential's `max_bytes` constraint — a guest can only
2259 /// request a SMALLER cap (clamped to this). Absent ⇒ no host-side max-bytes clamp (the per-container
2260 /// ceiling at the face still applies).
2261 pub s3_ingress_mint_max_bytes: Option<u64>,
2262 /// **Cloud brokering** (M4): when the node's blob backend is a cloud object store (S3/GCS/Azure)
2263 /// and this is set, minting brokers a NATIVE scoped credential (STS session policy / signed URL +
2264 /// CAB / user-delegation SAS) so the client uploads DIRECTLY to the real store (bytes never transit
2265 /// the node) — INSTEAD of the local S3 face. Absent ⇒ the local face is used (an fs/in-memory
2266 /// backend, or a cloud backend that re-transits through the local face). See [`S3IngressCloud`].
2267 pub s3_ingress_cloud: Option<S3IngressCloud>,
2268 /// **Node-level base S3 credential source** (`[serve.s3_credential]`, task #505). When set, BOTH the
2269 /// S3 blob **object backend** (`--blobs s3`) and the AWS blob-upload **cloud minter**
2270 /// (`[serve.s3_ingress_cloud]`) source their base AWS credential from boatramp's `[secrets]` sealed
2271 /// store instead of the ambient `AWS_ACCESS_KEY_ID`/`AWS_SECRET_ACCESS_KEY` env chain. ONE shared
2272 /// source (both consumers read the SAME bucket key). Absent ⇒ the ambient AWS env chain (current
2273 /// behavior, non-breaking). Requires a `[secrets]` envelope when the `secret_access_key` is a sealed
2274 /// `boatramp:`/`env:` ref — a configured ref with no envelope is a **startup error** (fail-closed, no
2275 /// silent env fallback). See [`S3CredentialConfig`].
2276 pub s3_credential: Option<S3CredentialConfig>,
2277 /// `[serve.kv]` — control-plane SlateDB KV durability cadence + shutdown budget (v0.9.0
2278 /// KV-recovery). Absent ⇒ the defaults (periodic checkpoint ON at
2279 /// [`DEFAULT_KV_CHECKPOINT_INTERVAL_SECS`], close budget [`DEFAULT_KV_CLOSE_DEADLINE_SECS`]).
2280 /// See [`KvConfig`].
2281 pub kv: Option<KvConfig>,
2282 /// `[serve.listeners.<name>]` — host-owned **inbound-TCP listeners** (PLAN-handler-tcp-inbound).
2283 /// Each declares a bind address + a target guest `tcp-connection-handler` component (pinned to a
2284 /// project + site + Dimension-0 tenancy): the node binds + listens + accepts and re-enters the
2285 /// guest once per ALREADY-ACCEPTED connection, handing it only the connection's `wasi:io` streams
2286 /// (the guest NEVER receives `wasi:sockets`). GATED on the posture `allow_guest_tcp_listener` (off
2287 /// under multi-tenant) AND the declaration here — both must hold. Empty ⇒ no listeners (the common
2288 /// case; serving is byte-for-byte unchanged). Env parity: `BOATRAMP_SERVE_LISTENER_<NAME>_*`. See
2289 /// [`ListenerConfig`].
2290 #[serde(default)]
2291 pub listeners: BTreeMap<String, ListenerConfig>,
2292 /// `[serve.on_demand_tls]` — on-demand per-SNI ACME issuance at scale (cap-req 03). Absent or
2293 /// `enabled = false` ⇒ OFF (the static `--tls acme-dns` resolver is byte-for-byte unchanged). When
2294 /// on, the edge issues + caches a cert on the first TLS handshake for an unknown-but-#02-**verified**
2295 /// custom domain, gated so an arbitrary/unverified SNI is refused (fail-closed). File-configured.
2296 /// See [`OnDemandTlsConfig`].
2297 #[serde(default, skip_serializing_if = "Option::is_none")]
2298 pub on_demand_tls: Option<OnDemandTlsConfig>,
2299}
2300
2301/// `[serve.on_demand_tls]` — on-demand per-SNI TLS issuance (cap-req 03). Off unless `enabled`. When
2302/// on, an unknown-but-#02-verified SNI triggers issuance at handshake time (the client retries once
2303/// the cert is warm); an unauthorized SNI is refused, so a flood of unknown names can't become an ACME
2304/// storm. The ACME account + issued certs persist in the control-plane cert store and replicate across
2305/// the cluster (the leader issues; followers serve the replicated cert).
2306#[derive(Debug, Clone, Default, Serialize, Deserialize)]
2307#[serde(default, deny_unknown_fields)]
2308pub struct OnDemandTlsConfig {
2309 /// Master toggle. `false` (default) ⇒ the whole feature is off.
2310 pub enabled: bool,
2311 /// How to prove control of a name to the CA. `tls-alpn-01` (default) validates on the 443 edge (no
2312 /// extra port); `dns-01` uses the node's configured ACME DNS provider (an operator-controlled zone).
2313 pub challenge: OnDemandChallenge,
2314 /// ACME directory URL. Absent ⇒ the ACME client default (Let's Encrypt production).
2315 #[serde(skip_serializing_if = "Option::is_none")]
2316 pub directory_url: Option<String>,
2317 /// ACME account contact email (optional).
2318 #[serde(skip_serializing_if = "Option::is_none")]
2319 pub contact_email: Option<String>,
2320 /// Max concurrent in-flight issuances (global). Absent ⇒ 4.
2321 #[serde(skip_serializing_if = "Option::is_none")]
2322 pub max_inflight: Option<usize>,
2323 /// How long a refused/failed SNI is negatively cached (seconds). Absent ⇒ 300.
2324 #[serde(skip_serializing_if = "Option::is_none")]
2325 pub negative_ttl_secs: Option<u64>,
2326 /// Max CA orders per rolling hour (the account rate-limit floor). Absent ⇒ 50; `0` ⇒ unlimited.
2327 #[serde(skip_serializing_if = "Option::is_none")]
2328 pub rate_limit_per_hour: Option<u32>,
2329}
2330
2331/// How [`OnDemandTlsConfig`] proves control of a name to the CA.
2332#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
2333#[serde(rename_all = "kebab-case")]
2334pub enum OnDemandChallenge {
2335 /// TLS-ALPN-01 on the 443 edge (default) — no extra port.
2336 #[default]
2337 TlsAlpn01,
2338 /// DNS-01 via the node's configured ACME DNS provider (an operator-controlled zone / wildcard).
2339 Dns01,
2340}
2341
2342/// `[serve.listeners.<name>]` — a **host-owned inbound-TCP listener** (PLAN-handler-tcp-inbound). The
2343/// node binds + listens + accepts on `bind` and dispatches each accepted connection to the guest
2344/// `component`'s `tcp-connection-handler` export, with tenancy OPERATOR-PINNED here (a raw socket
2345/// carries no Host/path/principal, so there is nothing per-connection to resolve). The guest is handed
2346/// only the connection's `wasi:io` byte streams — it holds NO `wasi:sockets` authority (bind stays
2347/// host-side). Modeled on [`boatramp_core::function::FunctionConfig`] / the session route config.
2348///
2349/// Phase 1 is **plaintext-only** and **no per-listener egress**: a declared `tls` block or a non-empty
2350/// `egress_allowlist` is REFUSED at config load (fail-closed, boot-LOUD) rather than silently ignored —
2351/// per-listener host-TLS and outbound egress are deferred follow-ups. See [`validate_listeners`].
2352#[derive(Debug, Clone, Default, Serialize, Deserialize)]
2353#[serde(default, deny_unknown_fields)]
2354pub struct ListenerConfig {
2355 /// The address the node binds + listens + accepts on (e.g. `0.0.0.0:9000`). **Required** (a blank
2356 /// `bind` is refused at config load).
2357 pub bind: Option<SocketAddr>,
2358 /// Path to the guest `.wasm` within the pinned site's deployment (exports `tcp-connection-handler`).
2359 /// **Required**.
2360 pub component: String,
2361 /// The project this listener's component is deployed under (host-resolved, never guest input). The
2362 /// active deployment of `project`/`site` is what the accept loop serves. **Required**.
2363 pub project: String,
2364 /// The site within `project` whose active deployment holds `component`. **Required**.
2365 pub site: String,
2366 /// Requested capabilities (interface names; see `KNOWN_IMPORTS`). A listener component declares
2367 /// whatever `sql`/`orm`/`kv`/… it uses per connection — NOT `wasi:sockets` (the host owns the
2368 /// socket; a `tcp-connection-host` guest imports only `wasi:io`, handed the accepted streams).
2369 #[serde(default, skip_serializing_if = "Vec::is_empty")]
2370 pub imports: Vec<String>,
2371 /// Static environment variables injected into the component (never secrets).
2372 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
2373 pub env: BTreeMap<String, String>,
2374 /// DEFERRED (Phase 1): a per-listener outbound-TCP allowlist. A `tcp-connection-host` guest imports
2375 /// ONLY `wasi:io` — it cannot hold `wasi:sockets` — so this is unusable in Phase 1 and a non-empty
2376 /// value is REFUSED at config load (fail-closed) rather than silently dropped. Kept for forward
2377 /// parity with the handler/session `egress_allowlist`.
2378 #[serde(default, skip_serializing_if = "Vec::is_empty")]
2379 pub egress_allowlist: Vec<String>,
2380 /// Operator-pinned Dimension-0 tenancy for this listener's `sql`/`orm` (resolved once from this
2381 /// config, carried on every connection — nothing per-connection to resolve from). Absent ⇒ plain
2382 /// (project = database).
2383 #[serde(
2384 default,
2385 deserialize_with = "boatramp_core::tenancy::de_opt_tenancy",
2386 skip_serializing_if = "Option::is_none"
2387 )]
2388 pub tenancy: Option<boatramp_core::tenancy::Tenancy>,
2389 /// DEFERRED (Phase 1): per-listener host-TLS. Phase 1 ships plaintext-only; a declared `tls` block
2390 /// is REFUSED at config load (fail-closed) so an operator is never misled into thinking a listener
2391 /// terminates TLS when it does not. Terminate TLS in front of boatramp, or wait for the fast-follow.
2392 #[serde(default, skip_serializing_if = "Option::is_none")]
2393 pub tls: Option<ListenerTlsConfig>,
2394 /// Cap on simultaneously-live connections for THIS listener (a per-listener DoS bound on top of the
2395 /// engine's conn-lane ceiling). `0` is refused; absent ⇒ [`DEFAULT_LISTENER_MAX_CONNS`].
2396 pub max_conns: Option<usize>,
2397 /// Tear a connection down after this many milliseconds with NO bytes in either direction (idle
2398 /// timeout — the conn lane replaces the per-invocation epoch deadline with this). `0` is refused;
2399 /// absent ⇒ [`DEFAULT_LISTENER_IDLE_TIMEOUT_MS`].
2400 pub idle_timeout_ms: Option<u64>,
2401 /// Absolute cap (milliseconds) on a single connection's lifetime regardless of activity. `0` is
2402 /// refused; absent ⇒ [`DEFAULT_LISTENER_MAX_CONN_DURATION_MS`].
2403 pub max_conn_duration_ms: Option<u64>,
2404 /// How the accepted connection is driven (cap-req 08). [`ListenerMode::Connection`] (default) is the
2405 /// long-lived model: the guest's `tcp-connection-handler` holds the connection — and ONE wasm
2406 /// instance — for the connection's whole life. [`ListenerMode::Session`] drives the connection
2407 /// through the re-entrant **session** model instead: the host owns the socket, re-enters the guest's
2408 /// `session-handler` per inbound batch carrying a host-held checkpoint, and holds NO instance between
2409 /// batches — so thousands of mostly-idle connections (IMAP IDLE, long-poll) cost ~a socket each, not
2410 /// an instance each, and a protocol-idle-but-alive connection is never torn down for inactivity
2411 /// (only a dead peer or `max_conn_duration` reaps it). The component must export `session-handler`,
2412 /// not `tcp-connection-handler`. Additive + back-compat: absent ⇒ `Connection` (unchanged).
2413 #[serde(default)]
2414 pub mode: ListenerMode,
2415}
2416
2417/// How a `[serve.listeners.<name>]` drives each accepted connection (cap-req 08). See
2418/// [`ListenerConfig::mode`].
2419#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
2420#[serde(rename_all = "kebab-case")]
2421pub enum ListenerMode {
2422 /// Long-lived `tcp-connection-handler` — one wasm instance pinned per connection for its whole life
2423 /// (the original inbound-TCP model). The default.
2424 #[default]
2425 Connection,
2426 /// Re-entrant `session-handler` — the host owns the socket and drives it through the session model,
2427 /// holding NO instance between inbound batches (idle ⇒ socket + checkpoint only). A quiet, PARKED
2428 /// connection (blocked on the socket read between batches) is NOT evicted for inactivity — only the
2429 /// absolute `max_conn_duration_ms` cap and dead-peer detection (EOF) end it, so a protocol-idle but
2430 /// alive peer (IMAP IDLE) survives. In this mode `idle_timeout_ms` is reinterpreted as the
2431 /// per-re-entry **processing deadline** — the max wall-clock ONE re-entry may spend (instantiate +
2432 /// handle + write its response) — bounding a guest stalled on a slow/zero-window peer so it cannot
2433 /// pin a session-pool slot + instance; a re-entry that exceeds it is cancelled and the connection
2434 /// closed. Re-entries run on a DEDICATED concurrency pool, never the shared async lane.
2435 Session,
2436}
2437
2438/// Per-listener host-side TLS material (cap-req 06). The host terminates TLS and hands the guest a
2439/// decrypted plaintext stream (the guest does no crypto). With `starttls` absent this is **implicit
2440/// TLS** (handshake at accept — 465/993); with `starttls` present it is **STARTTLS** (plaintext
2441/// dialog, in-band upgrade on the declared trigger — 25/587/143). Either way requires both
2442/// `cert_file` and `key_file`. File-only (never set from the env overlay).
2443#[derive(Debug, Clone, Default, Serialize, Deserialize)]
2444#[serde(deny_unknown_fields)]
2445pub struct ListenerTlsConfig {
2446 /// PEM certificate chain path.
2447 pub cert_file: Option<PathBuf>,
2448 /// PEM private-key path.
2449 pub key_file: Option<PathBuf>,
2450 /// Absent ⇒ implicit TLS (handshake at accept). Present ⇒ STARTTLS (plaintext until the declared
2451 /// trigger, then an in-band upgrade). Still requires `cert_file` + `key_file`.
2452 #[serde(default, skip_serializing_if = "Option::is_none")]
2453 pub starttls: Option<ListenerStarttlsConfig>,
2454 /// Opt this listener into **on-demand per-SNI issuance** (cap-req 03 #4): a client that negotiates
2455 /// TLS with a verified custom-domain SNI terminating here gets a cert issued the same way the public
2456 /// edge does, sharing the one `[serve.on_demand_tls]` engine (one issuance budget, one cluster
2457 /// certreq single-flight). Requires `[serve.on_demand_tls]` enabled at the node. The listener's own
2458 /// `cert_file` still serves `server_names` (and an SNI-less handshake). Default `false` ⇒ the static
2459 /// cert alone (unchanged). This is transport-level only — it carries no notion of what protocol runs
2460 /// over the listener.
2461 ///
2462 /// **Project-scoped** (Security review Finding B): a listener is bound to exactly one project (its
2463 /// `project`), and that project may front many domains (its tenants/sites). On-demand serving here
2464 /// is restricted to SNIs whose owning project is *this* project — the listener never serves (nor
2465 /// routes to its guest) a cert for another project's domain, even though all certs share the one
2466 /// engine + cache. Point an `on_demand` listener only at a guest that is meant to handle that whole
2467 /// project's domains.
2468 #[serde(default)]
2469 pub on_demand: bool,
2470 /// SNI names the listener's own static `cert_file` serves directly (an SNI match here wins before
2471 /// on-demand). Absent/empty ⇒ the static cert serves only SNI-less handshakes (via the no-SNI
2472 /// fallback); every presented SNI then goes to on-demand. Only meaningful with `on_demand = true`.
2473 #[serde(default, skip_serializing_if = "Option::is_none")]
2474 pub server_names: Option<Vec<String>>,
2475}
2476
2477/// Declarative STARTTLS grammar (cap-req 06, Stage B) — protocol-agnostic **data**. The host runs a
2478/// generic trigger→response→wrap engine driven entirely by these fields; no SMTP/IMAP/POP3 shapes are
2479/// hardcoded in the server. Examples:
2480/// SMTP — `(trigger: "STARTTLS", response: "220 2.0.0 Ready to start TLS")`;
2481/// POP3 — `(trigger: "STLS", response: "+OK begin TLS negotiation")`;
2482/// IMAP — `(trigger: "STARTTLS", response: "{tag} OK begin TLS negotiation", tag_capture: true)`.
2483#[derive(Debug, Clone, Default, Serialize, Deserialize)]
2484#[serde(deny_unknown_fields)]
2485pub struct ListenerStarttlsConfig {
2486 /// The command the host watches for in the client→server direction, matched at a line boundary,
2487 /// ASCII-case-insensitively. With `tag_capture` this is the token AFTER the leading tag.
2488 pub trigger: String,
2489 /// The single line the host writes to the client right before the handshake. `{tag}` is
2490 /// substituted with the captured tag (only valid when `tag_capture`); the host appends CRLF.
2491 pub response: String,
2492 /// IMAP-shaped: capture the leading whitespace-delimited token of the trigger line and echo it
2493 /// (verbatim) into `{tag}`.
2494 #[serde(default)]
2495 pub tag_capture: bool,
2496}
2497
2498/// Default per-listener live-connection cap when `[serve.listeners.<name>] max_conns` is unset
2499/// (PLAN-handler-tcp-inbound). 256 — a generous but bounded ceiling on top of the engine conn lane.
2500pub const DEFAULT_LISTENER_MAX_CONNS: usize = 256;
2501
2502/// Default per-listener idle timeout (ms) when `idle_timeout_ms` is unset — 60s. A connection with no
2503/// bytes in either direction for this long is torn down (so a connection that opens and sends nothing
2504/// can't hold a store + instance + conn-lane permit forever).
2505pub const DEFAULT_LISTENER_IDLE_TIMEOUT_MS: u64 = 60_000;
2506
2507/// Default per-listener absolute max-connection-duration (ms) when `max_conn_duration_ms` is unset —
2508/// 1h. Bounds a single connection's lifetime regardless of activity (CPU is wall-clock-bounded here,
2509/// since the conn lane disables the per-invocation CPU-fuel budget).
2510pub const DEFAULT_LISTENER_MAX_CONN_DURATION_MS: u64 = 3_600_000;
2511
2512/// `[serve.s3_credential]` — a **node-level base S3 credential source** (#505) sourcing the base AWS
2513/// credential from boatramp's `[secrets]` sealed store rather than the ambient env chain. Consumed by
2514/// BOTH the S3 blob object backend and the AWS blob-upload cloud minter (one shared source, since it is
2515/// the same bucket key). Additive/non-breaking: absent ⇒ the ambient AWS env chain (unchanged).
2516///
2517/// The `access_key_id` is a public identifier (plain config). The `secret_access_key` is a **secret
2518/// reference** in the same scheme the guest `secrets` map uses: `boatramp:<name>` (the project-scoped
2519/// sealed store, resolved under the reserved default project — multi-tenant-safe, never the host env),
2520/// `env:<VAR>` / a bare `<VAR>` (the operator's own environment — honored only when the posture's
2521/// `allow_env_secret_refs` is set), unsealed at serve startup via the `[secrets]` [`KeyEnvelope`]. The
2522/// resolved plaintext is held **in memory only** (never env/argv/git/logs); see the redacted
2523/// `SealedS3Credential` the resolver produces.
2524#[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize)]
2525#[serde(deny_unknown_fields)]
2526pub struct S3CredentialConfig {
2527 /// The AWS **access key id** — a public identifier, not a secret, so it is plain config (mirrors
2528 /// how an `access_key_id` is a public value in the S3-ingress credential model). Empty is refused
2529 /// at resolution.
2530 pub access_key_id: String,
2531 /// The **secret access key**, expressed as a secret **reference** (never the raw secret in the
2532 /// config text): `boatramp:<name>` (the project-scoped sealed store), `env:<VAR>` or a bare `<VAR>`
2533 /// (the operator env, posture-gated by `allow_env_secret_refs`). Unsealed at startup via the
2534 /// `[secrets]` envelope; the resolved value is redacted from `Debug`/logs. A `boatramp:`/`env:`
2535 /// ref configured with NO `[secrets]` envelope is a fail-closed startup error.
2536 pub secret_access_key: String,
2537}
2538
2539/// `[serve.blob_backends.<project>]` — a **per-project** blob object-store backend
2540/// (PLAN-per-project-blob-backend). Same backend-descriptor shape as the `[serve]` primary's S3 fields
2541/// plus its OWN sealed base S3 credential (`#505` path), so project ACME can point its `wasi:blobstore`
2542/// at its own bucket/endpoint/account. Key-prefix confinement (`container_access`) still runs on top —
2543/// a separate bucket adds PHYSICAL isolation, it does not replace the confinement (invariant 2).
2544///
2545/// Operator-configured; the backend is bound to the serve's **host-resolved** project at serve wiring,
2546/// never to guest input (invariant 1). The sealed credential is resolved under THIS project's sealed
2547/// `[secrets]` store at wiring; a declared backend whose credential/bucket cannot be built REFUSES the
2548/// serve (fail-closed — never a silent fallback to the global or another project's backend, invariant
2549/// 4). First cut is S3 (and `fs`, which is degenerate — it shares the node blob dir, so only a cloud
2550/// bucket gives physical isolation); a per-project `gcs`/`azure` needs its own descriptor fields and is
2551/// a follow-up (declaring one fails closed at build — the required bucket/account is absent).
2552#[derive(Debug, Clone, Default, Serialize, Deserialize)]
2553#[serde(deny_unknown_fields)]
2554pub struct BlobBackendConfig {
2555 /// The backend kind (`fs`/`s3`/`gcs`/`azure`). **Required** (mirrors the SQL binding's required
2556 /// `kind`): a per-project backend with no explicit kind is a startup error, so a forgotten
2557 /// `blobs = "s3"` can't silently build an `fs` backend at the shared node dir that would NOT
2558 /// isolate the project's blobs. Resolved at serve wiring (fail-closed when absent).
2559 pub blobs: Option<crate::backends::BlobBackend>,
2560 /// S3 bucket (`blobs = s3`) — the project's OWN bucket.
2561 pub s3_bucket: Option<String>,
2562 /// S3 endpoint URL (a MinIO/R2/Tigris endpoint) for this project's backend.
2563 pub s3_endpoint: Option<String>,
2564 /// S3 region for this project's backend.
2565 pub s3_region: Option<String>,
2566 /// Use S3 path-style addressing (MinIO) for this project's backend.
2567 #[serde(default)]
2568 pub s3_path_style: bool,
2569 /// This project's OWN sealed base S3 credential (`#505`) — resolved through the SAME
2570 /// `resolve_s3_credential` path as the node primary, but keyed under THIS project's sealed store
2571 /// (`boatramp:<name>` resolves against `project`'s secrets, not the node default). The
2572 /// `access_key_id` is a public identifier; `secret_access_key` is a `boatramp:`/`env:` **reference**
2573 /// (never the raw secret in config, invariant 3). Absent ⇒ the ambient AWS env chain.
2574 pub s3_credential: Option<S3CredentialConfig>,
2575}
2576
2577/// `[serve.blob_fallback]` — a **read-only SECONDARY blob backend** for a zero-downtime backend switch
2578/// (blob-backend migration Part 2). Same backend-descriptor shape as the PRIMARY (`[serve]`'s
2579/// `blobs`/`s3_*`/`gcs_*`/`azure_*` fields) so a source/dest is fully described by config, plus its OWN
2580/// optional `s3_credential` (the secondary can source its base S3 credential from the sealed `[secrets]`
2581/// store via its own `boatramp:`/`env:` ref, #505). Constructed exactly like the primary but with NO
2582/// watcher provisioning (a read-only drain source never watches). Serving wraps
2583/// `FallbackStorage::new(primary, secondary, …)` so a primary miss on a boatramp-owned key falls through
2584/// to this secondary; writes/deletes are primary-only.
2585///
2586/// The secondary is **never** handed to the blob-upload/STS minter — external ingress mints against the
2587/// PRIMARY only (the new backend the client should upload to), so this credential never reaches the
2588/// minter path.
2589#[derive(Debug, Clone, Default, Serialize, Deserialize)]
2590#[serde(deny_unknown_fields)]
2591pub struct BlobFallbackConfig {
2592 /// The secondary blob backend (`fs`/`s3`/`gcs`/`azure`) — the OLD backend to fall back to on a
2593 /// primary miss. Absent ⇒ `fs` (the default, matching the primary's `blobs` default).
2594 pub blobs: Option<crate::backends::BlobBackend>,
2595 /// S3 bucket (secondary `blobs = s3`).
2596 pub s3_bucket: Option<String>,
2597 /// S3 endpoint URL (a MinIO/R2/Tigris endpoint) for the secondary.
2598 pub s3_endpoint: Option<String>,
2599 /// S3 region for the secondary.
2600 pub s3_region: Option<String>,
2601 /// Use S3 path-style addressing (MinIO) for the secondary.
2602 #[serde(default)]
2603 pub s3_path_style: bool,
2604 /// The secondary's OWN node-level sealed base S3 credential source (#505) — resolved through the
2605 /// SAME `resolve_s3_credential` path as the primary (same fail-closed posture, no second parser).
2606 /// Absent ⇒ the ambient AWS env chain (unchanged).
2607 pub s3_credential: Option<S3CredentialConfig>,
2608 /// GCS bucket (secondary `blobs = gcs`).
2609 pub gcs_bucket: Option<String>,
2610 /// GCS storage endpoint URL (a `fake-gcs-server` emulator) for the secondary.
2611 pub gcs_endpoint: Option<String>,
2612 /// Skip GCS credential resolution (anonymous — the emulator) for the secondary.
2613 #[serde(default)]
2614 pub gcs_anonymous: bool,
2615 /// Azure storage account name (secondary `blobs = azure`).
2616 pub azure_account: Option<String>,
2617 /// Azure container name for the secondary.
2618 pub azure_container: Option<String>,
2619 /// Azure storage account access key (shared-key auth) for the secondary.
2620 pub azure_access_key: Option<String>,
2621 /// Use the Azurite emulator for the secondary.
2622 #[serde(default)]
2623 pub azure_emulator: bool,
2624 /// Bound (seconds) on each secondary read so a wedged secondary degrades a primary miss to
2625 /// `NotFound` instead of hanging the serve path. Absent ⇒ [`DEFAULT_BLOB_FALLBACK_TIMEOUT_SECS`].
2626 pub secondary_timeout_secs: Option<u64>,
2627}
2628
2629/// Default bound (seconds) on a `[serve.blob_fallback]` secondary read when
2630/// `secondary_timeout_secs` is unset: 5s — long enough for a cloud round-trip, short enough that a
2631/// wedged secondary degrades a primary miss to `NotFound` promptly rather than hanging serving.
2632pub const DEFAULT_BLOB_FALLBACK_TIMEOUT_SECS: u64 = 5;
2633
2634/// Default control-plane KV **periodic checkpoint** cadence (seconds) when `[serve.kv]
2635/// checkpoint_interval` is unset (v0.9.0 KV-recovery, C1). The cadence advances the durable frontier
2636/// (WAL→L0 MemTable freeze) so the self-heal-on-open trailing-tail loss window is bounded to at most
2637/// this interval for anything NOT already frontier-synced by a crown-jewel write. 10s balances a tiny
2638/// loss window against manifest-PUT churn; an idle store's checkpoint is a dirty-gated no-op regardless.
2639pub const DEFAULT_KV_CHECKPOINT_INTERVAL_SECS: u64 = 10;
2640
2641/// Default **graceful-close budget** (seconds) when `[serve.kv] close_deadline` is unset (v0.9.0
2642/// KV-recovery, C12). The shutdown drain+close is abandoned only after this budget — GENEROUS (not the
2643/// old hardcoded 3s, which self-exited BEFORE fly's SIGKILL grace and left the frontier un-advanced =
2644/// the exact torn tail we prevent). With continuous checkpointing (C1/C2) the close is cheap, so this
2645/// budget rarely bites; operators should still raise fly `kill_timeout` to ≥ their measured drain+close.
2646pub const DEFAULT_KV_CLOSE_DEADLINE_SECS: u64 = 20;
2647
2648/// Default control-plane SlateDB **online maintenance-GC** cadence (seconds) when `[serve.kv.slatedb]
2649/// gc_interval` is unset (kv-data-observability durable fix). The supervised writer task reclaims the
2650/// stale manifest/compactions/WAL/compacted objects the embedded GC would — SURVIVING the transient
2651/// tick error that kills the unsupervised embedded GC permanently (the 16.5 GB manifest-retention
2652/// leak). 900s (15 min) matches the cadence of the embedded GC's own protective-checkpoint window, so
2653/// freshly-superseded SSTs age out of their checkpoint before the next reclaim; a 0 DISABLES the task.
2654pub const DEFAULT_KV_GC_INTERVAL_SECS: u64 = 900;
2655
2656/// Default **minimum object age** (seconds) before the online maintenance GC will reclaim an object,
2657/// when `[serve.kv.slatedb] gc_min_age` is unset. 3600s (1h) is deliberately CONSERVATIVE: the online
2658/// GC only deletes objects the latest manifest no longer references, but a read replica polling the
2659/// shared store could still be mid-scan over a manifest generation that just became stale — a min_age
2660/// this large guarantees such a needed-but-unreferenced object is never a deletion candidate while any
2661/// plausible replica scan is in flight. A 0 (or unset) falls back to this default — it is never zero
2662/// (a zero min_age would reintroduce exactly the mid-scan deletion hazard this bound closes).
2663pub const DEFAULT_KV_GC_MIN_AGE_SECS: u64 = 3600;
2664
2665/// `[serve.kv]` — control-plane KV configuration. The backend itself is selected by `--kv` /
2666/// `BOATRAMP_KV` (`slatedb` default, `sql`, `memory`, `cloudflare`); this block holds the
2667/// backend-specific settings, nested so a knob can never silently mislead under the wrong backend
2668/// (UX-C3): the SlateDB durability knobs live under [`slatedb`](Self::slatedb), and the SQL
2669/// connection under [`sql`](Self::sql). Absent block ⇒ the SlateDB defaults apply.
2670#[derive(Debug, Clone, Default, Serialize, Deserialize)]
2671#[serde(default, deny_unknown_fields)]
2672pub struct KvConfig {
2673 /// `[serve.kv.slatedb]` — SlateDB-specific durability knobs (checkpoint cadence + close budget).
2674 /// Nested under `slatedb` (UX-C3) so they don't appear to apply under `--kv sql` / `--kv memory`.
2675 /// Absent ⇒ both defaults (checkpoint cadence ON, generous close budget).
2676 pub slatedb: Option<SlatedbKvConfig>,
2677 /// `[serve.kv.sql]` — the SQL KV backend's connection (`--kv sql`). Absent under `--kv sql` ⇒ the
2678 /// backend is configured entirely by the `BOATRAMP_KV_SQL_*` env (resolved at serve wiring).
2679 pub sql: Option<SqlKvConfig>,
2680}
2681
2682impl KvConfig {
2683 /// The resolved periodic-checkpoint interval (SlateDB): `None` ⇒ cadence DISABLED (explicit `0`);
2684 /// else the configured seconds, or [`DEFAULT_KV_CHECKPOINT_INTERVAL_SECS`] when unset/absent.
2685 pub fn checkpoint_interval(&self) -> Option<std::time::Duration> {
2686 match self.slatedb.as_ref().and_then(|s| s.checkpoint_interval) {
2687 Some(0) => None,
2688 Some(secs) => Some(std::time::Duration::from_secs(secs)),
2689 None => Some(std::time::Duration::from_secs(
2690 DEFAULT_KV_CHECKPOINT_INTERVAL_SECS,
2691 )),
2692 }
2693 }
2694
2695 /// The resolved graceful-close budget (SlateDB). A configured `0` (or unset/absent) falls back to
2696 /// [`DEFAULT_KV_CLOSE_DEADLINE_SECS`] — the budget must be positive so a genuinely-wedged close
2697 /// still cannot hang shutdown forever, while never being the too-tight 3s that caused the incident.
2698 pub fn close_deadline(&self) -> std::time::Duration {
2699 match self.slatedb.as_ref().and_then(|s| s.close_deadline) {
2700 Some(secs) if secs > 0 => std::time::Duration::from_secs(secs),
2701 _ => std::time::Duration::from_secs(DEFAULT_KV_CLOSE_DEADLINE_SECS),
2702 }
2703 }
2704
2705 /// The resolved online maintenance-GC cadence (SlateDB): `None` ⇒ the task is DISABLED (explicit
2706 /// `0`); else the configured seconds, or [`DEFAULT_KV_GC_INTERVAL_SECS`] when unset/absent.
2707 pub fn gc_interval(&self) -> Option<std::time::Duration> {
2708 match self.slatedb.as_ref().and_then(|s| s.gc_interval) {
2709 Some(0) => None,
2710 Some(secs) => Some(std::time::Duration::from_secs(secs)),
2711 None => Some(std::time::Duration::from_secs(DEFAULT_KV_GC_INTERVAL_SECS)),
2712 }
2713 }
2714
2715 /// The resolved online maintenance-GC minimum object age (SlateDB). A configured `0` (or
2716 /// unset/absent) falls back to [`DEFAULT_KV_GC_MIN_AGE_SECS`] — never zero, so a reader replica
2717 /// mid-scan over a just-superseded manifest generation is always protected.
2718 pub fn gc_min_age(&self) -> std::time::Duration {
2719 match self.slatedb.as_ref().and_then(|s| s.gc_min_age) {
2720 Some(secs) if secs > 0 => std::time::Duration::from_secs(secs),
2721 _ => std::time::Duration::from_secs(DEFAULT_KV_GC_MIN_AGE_SECS),
2722 }
2723 }
2724}
2725
2726/// `[serve.kv.slatedb]` — control-plane SlateDB KV durability knobs (v0.9.0 KV-recovery). Both are
2727/// backstops/tuning: the crown-jewel per-write frontier-sync (C2) is unconditional and independent of
2728/// these. Absent ⇒ both defaults apply (checkpoint cadence ON, generous close budget). (v0.12.0 UX-C3:
2729/// MOVED here from the `[serve.kv]` top level so they do not appear to apply under a non-SlateDB
2730/// backend; with `deny_unknown_fields` a pre-v0.12.0 top-level knob now fails loud rather than
2731/// silently misleading.)
2732#[derive(Debug, Clone, Default, Serialize, Deserialize)]
2733#[serde(default, deny_unknown_fields)]
2734pub struct SlatedbKvConfig {
2735 /// Periodic checkpoint cadence, seconds. Unset ⇒ [`DEFAULT_KV_CHECKPOINT_INTERVAL_SECS`] (ON).
2736 /// `0` DISABLES the cadence (the crown-jewel per-write frontier-sync still runs; only the
2737 /// backstop that bounds the loss window for derived/relaxed writes is off).
2738 pub checkpoint_interval: Option<u64>,
2739 /// Graceful drain+close budget, seconds. Unset ⇒ [`DEFAULT_KV_CLOSE_DEADLINE_SECS`]. `0` is
2740 /// rejected up to the default (a zero budget would abandon every close, guaranteeing a torn tail).
2741 pub close_deadline: Option<u64>,
2742 /// **Online maintenance-GC cadence**, seconds (kv-data-observability durable fix). Unset ⇒
2743 /// [`DEFAULT_KV_GC_INTERVAL_SECS`] (ON). `0` DISABLES the supervised GC task entirely (leaving only
2744 /// SlateDB's embedded GC — which dies permanently on its first transient tick error, the leak this
2745 /// task works around; disable only if you run an external offline `boatramp kv compact` cadence).
2746 pub gc_interval: Option<u64>,
2747 /// **Online maintenance-GC minimum object age**, seconds. Unset (or `0`) ⇒
2748 /// [`DEFAULT_KV_GC_MIN_AGE_SECS`] (1h) — never zero, so a reader replica mid-scan over a
2749 /// just-superseded manifest generation can never have a needed object reclaimed out from under it.
2750 /// A tuned positive value is honored (e.g. a single-node deploy with no read replicas may lower it).
2751 /// CAVEAT: lowering it is UNSAFE whenever ANY read replica polls this shared store — a value below
2752 /// the time a replica may spend mid-scan reintroduces the "object reclaimed out from under a
2753 /// reader" hazard. Only lower it on a node you are certain has no read replicas.
2754 pub gc_min_age: Option<u64>,
2755}
2756
2757/// `[serve.kv.sql]` — the **SQL control-plane KV** backend connection (`--kv sql`). The connection
2758/// URL is NEVER written in the config (UX-C2): a bring-your-own / remote engine names the env var
2759/// holding it via [`url_env`](Self::url_env) (mirroring `ExternalDatabaseConfig`), while an embedded
2760/// single-node SQLite database names an on-disk file via [`path`](Self::path). Every field is also
2761/// settable by `BOATRAMP_KV_SQL_*` env (resolved at serve wiring). **This workstream (build-order
2762/// step 1) wires `sqlite` (libsql-local) only**; `postgres`/`mysql` are later workstreams.
2763#[derive(Debug, Clone, Default, Serialize, Deserialize)]
2764#[serde(default, deny_unknown_fields)]
2765pub struct SqlKvConfig {
2766 /// Engine: `sqlite` (aliases `sqlite3`/`libsql`) — the embedded single-node file; `postgres`
2767 /// (aliases `postgresql`/`pg`) or `mysql` (alias `mariadb`) — the multi-writer engines (later
2768 /// workstreams), the same alias set as the `databases:` block. Empty ⇒ `sqlite`.
2769 pub kind: String,
2770 /// Name of the env var holding the connection URL (e.g. `postgres://…`, or a remote sqld URL) —
2771 /// NEVER a raw URL in the config. Unused for an embedded single-node `sqlite` database (which
2772 /// uses [`path`](Self::path)).
2773 pub url_env: Option<String>,
2774 /// On-disk file path for an embedded single-node `sqlite` KV (e.g. `/data/kv.db`). The parent
2775 /// directory is created if absent. Ignored for `postgres`/`mysql` and for a remote-sqld URL.
2776 pub path: Option<String>,
2777 /// Maximum pooled connections for a `postgres`/`mysql` KV (later workstreams). Ignored for the
2778 /// embedded `sqlite` path (one `Database` handle, connections opened per op).
2779 pub pool_max: Option<u32>,
2780}
2781
2782/// `[serve.s3_ingress_cloud]` — the cloud-brokering knobs for the M4 blob-upload minter (which native
2783/// credential the mint brokers when the node's blob backend is a cloud object store). Only the fields
2784/// for the active blob backend are consulted; a `None` here ⇒ the local S3 face mints.
2785#[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize)]
2786pub struct S3IngressCloud {
2787 /// **AWS**: the IAM role ARN the base credential assumes to broker the scoped session-policy
2788 /// credential (`sts:AssumeRole`, the default). Absent AND `aws_use_federation_token = true` ⇒
2789 /// `sts:GetFederationToken` is used instead (for an IAM-user base credential).
2790 pub aws_role_arn: Option<String>,
2791 /// **AWS**: use `sts:GetFederationToken` instead of `AssumeRole` (IAM-user deployments). Requires
2792 /// the base credential to be a real IAM user, not itself a session.
2793 #[serde(default)]
2794 pub aws_use_federation_token: bool,
2795 /// **AWS**: the S3-compatible backend has NO STS (Tigris/R2/MinIO): mint single-object presigned PUTs
2796 /// only. Prefix/multipart mints are refused (they require STS). Mutually exclusive with
2797 /// `aws_role_arn`/`aws_use_federation_token` (a misconfiguration that set both fails loud at wiring,
2798 /// never silently picks one). The presigned PUT is signed from the node's base S3 credential — the
2799 /// SAME source the S3 blob backend uses — so no new credential is needed. Default `false`.
2800 #[serde(default)]
2801 pub aws_presigned_only: bool,
2802 /// **GCS**: the service-account client email whose V4 signed URLs / IAM-signed uploads the minter
2803 /// produces (used in the signing scope). Absent ⇒ resolved from ADC.
2804 pub gcs_client_email: Option<String>,
2805 /// **Azure**: the storage account name (for the SAS signature + the blob URL). Absent ⇒ taken from
2806 /// the `azure_account` blob-backend arg.
2807 pub azure_account: Option<String>,
2808 /// **Azure**: the blob service URL (`https://{account}.blob.core.windows.net/`). Absent ⇒ derived
2809 /// from the account name.
2810 pub azure_service_url: Option<String>,
2811 /// **Azure**: declare the storage account has a **hierarchical namespace** (HNS/ADLS-Gen2). A
2812 /// directory-scoped SAS only actually confines to a sub-prefix on an HNS account; on a flat account
2813 /// it silently degrades to container-wide (Security LOW-1). So a PREFIX mint is refused unless this
2814 /// is `true`. Default `false` (fail-closed). A single-key mint is unaffected.
2815 #[serde(default)]
2816 pub azure_hns: bool,
2817}
2818
2819/// The default operator ceiling on a minted S3 upload credential's TTL when
2820/// `[serve].s3_ingress_mint_max_ttl_secs` is unset: 1 hour — long enough for a browser UGC upload or a
2821/// bulk-agent burst, short enough to bound a leaked short-lived credential.
2822pub const DEFAULT_S3_INGRESS_MINT_MAX_TTL_SECS: u64 = 3600;
2823
2824/// `[serve.console]` — the embedded web console (a Wasm SPA baked into the
2825/// binary with the `console` build feature). Opt-in: the static shell holds no
2826/// secrets and the `/api` it drives is token-gated, so it is served
2827/// **unauthenticated** at a deliberately obscure path (a bearer token can't gate
2828/// a top-level browser navigation anyway — the path is the obscurity, the token
2829/// is the real gate).
2830#[cfg_attr(not(feature = "console"), allow(dead_code))]
2831#[derive(Debug, Clone, Default, Serialize, Deserialize)]
2832#[serde(default, deny_unknown_fields)]
2833pub struct ConsoleConfig {
2834 /// Serve the embedded console (default `false`). Requires the `console` build
2835 /// feature; enabling it in a build without that feature is a logged no-op.
2836 pub enabled: bool,
2837 /// Host(s) the console answers on: `*` (any host, the default), an exact host
2838 /// (`console.example.com`), or a leading-wildcard (`*.example.com`).
2839 pub host: Option<String>,
2840 /// URL path prefix the console mounts at (default `/_console`). Kept under the
2841 /// reserved `/_` namespace so it never collides with a published site path.
2842 pub path: Option<String>,
2843}
2844
2845/// `publish` section — where and what to deploy (the `sync` target).
2846#[derive(Debug, Default, Deserialize)]
2847#[serde(default)]
2848pub struct PublishConfig {
2849 /// Base URL of the boatramp server (e.g. `https://pad.example.com`).
2850 pub server: Option<String>,
2851 /// Site name to publish to.
2852 pub site: Option<String>,
2853 /// API token for the control plane (or set `BOATRAMP_TOKEN`).
2854 pub token: Option<String>,
2855 /// Project this site belongs to (overrides with `--project` / `BOATRAMP_PROJECT`).
2856 pub project: Option<String>,
2857}
2858
2859/// `build` section.
2860#[derive(Debug, Clone, Deserialize, serde::Serialize)]
2861pub struct BuildConfig {
2862 /// Shell command to run (e.g. `npm run build`).
2863 pub command: String,
2864 /// Directory the build emits, published by `sync` (e.g. `dist`).
2865 #[serde(default, skip_serializing_if = "Option::is_none")]
2866 pub output: Option<String>,
2867}
2868
2869/// `bundle` section — the in-process Rust bundler (`bundler` feature).
2870#[derive(Debug, Clone, Default, Deserialize)]
2871#[serde(default)]
2872pub struct BundleConfig {
2873 /// Output directory for bundled assets (e.g. `dist`).
2874 #[serde(default = "default_bundle_outdir")]
2875 pub outdir: String,
2876 /// JS/TS entry points bundled by Rolldown (tree-shaken, code-split).
2877 pub js: Vec<String>,
2878 /// CSS entry points bundled by lightningcss (`@import` inlined).
2879 pub css: Vec<String>,
2880 /// Minify output (default true).
2881 #[serde(default = "default_true")]
2882 pub minify: bool,
2883}
2884
2885fn default_bundle_outdir() -> String {
2886 "dist".to_string()
2887}
2888
2889fn default_true() -> bool {
2890 true
2891}
2892
2893#[cfg(test)]
2894mod tests {
2895 use super::*;
2896
2897 fn project(text: &str) -> ProjectConfig {
2898 ron_options().from_str(text).unwrap()
2899 }
2900
2901 fn server(text: &str) -> ServerConfig {
2902 ron_options().from_str(text).unwrap()
2903 }
2904
2905 /// Build an [`EnvSource::Map`] from `(name, value)` pairs for deterministic
2906 /// override tests (no process-global `std::env` mutation).
2907 fn env(pairs: &[(&str, &str)]) -> EnvSource {
2908 EnvSource::Map(
2909 pairs
2910 .iter()
2911 .map(|(k, v)| (k.to_string(), v.to_string()))
2912 .collect(),
2913 )
2914 }
2915
2916 #[test]
2917 fn env_overrides_configure_all_three_sections_with_no_file() {
2918 // The crux of the ask: with NO `boatramp.cfg` at all (the default config),
2919 // env vars alone materialise + populate the compute, security, and handler
2920 // `sql` sections. `ServerConfig::default()` has all three absent.
2921 let mut cfg = ServerConfig::default();
2922 assert!(cfg.compute.is_none() && cfg.security.is_none() && cfg.handlers.is_none());
2923
2924 cfg.apply_env_overrides(&env(&[
2925 ("BOATRAMP_COMPUTE_VCPUS", "8"),
2926 ("BOATRAMP_COMPUTE_MEM_MIB", "4096"),
2927 ("BOATRAMP_COMPUTE_REGION", "eu-central"),
2928 ("BOATRAMP_SECURITY_PROFILE", "single-tenant"),
2929 ("BOATRAMP_SECURITY_ALLOW_SITE_PRIVATE_UPSTREAMS", "true"),
2930 ("BOATRAMP_SECURITY_MAX_UPLOAD_BYTES", "1048576"),
2931 ("BOATRAMP_HANDLERS_SQL_URL", "http://sqld:8080"),
2932 ("BOATRAMP_HANDLERS_SQL_ADMIN_URL", "http://sqld:9090"),
2933 ]))
2934 .expect("valid env overrides apply");
2935
2936 // compute: the section now exists with the env values (and defaults elsewhere).
2937 let compute = cfg.compute.expect("compute materialised from env");
2938 assert_eq!(compute.vcpus, 8);
2939 assert_eq!(compute.mem_mib, 4096);
2940 assert_eq!(compute.region.as_deref(), Some("eu-central"));
2941 assert_eq!(compute.bridge, "br-boatramp"); // untouched default
2942
2943 // security: profile + an override both took, and the posture resolves.
2944 let security = cfg.security.expect("security materialised from env");
2945 assert_eq!(security.profile.as_deref(), Some("single-tenant"));
2946 let posture = security.resolve().expect("resolves");
2947 assert!(posture.allow_site_private_upstreams);
2948 assert_eq!(posture.max_upload_bytes, 1_048_576);
2949
2950 // handler sql: the nested handlers.bindings.sql chain was created.
2951 let sql = cfg
2952 .handlers
2953 .expect("handlers materialised from env")
2954 .bindings
2955 .sql
2956 .expect("sql binding materialised from env");
2957 assert_eq!(sql.url.as_deref(), Some("http://sqld:8080"));
2958 assert_eq!(sql.admin_url.as_deref(), Some("http://sqld:9090"));
2959 }
2960
2961 #[test]
2962 fn internal_dns_defaults_on_with_the_standard_upstream_and_domain() {
2963 // The `[compute]` defaults: internal DNS on, forwarding to 1.1.1.1:53, names
2964 // under `boatramp.internal`.
2965 let compute = ComputeConfig::default();
2966 assert!(compute.internal_dns, "internal DNS is on by default");
2967 assert_eq!(compute.dns_upstream, "1.1.1.1:53");
2968 assert_eq!(compute.dns_domain, "boatramp.internal");
2969 }
2970
2971 #[test]
2972 fn internal_dns_knobs_parse_from_a_file() {
2973 // A file can turn it off and override the upstream + domain.
2974 let cfg = server(
2975 r#"(
2976 compute: ( internal_dns: false, dns_upstream: "10.0.0.53:53", dns_domain: "svc.internal" ),
2977 )"#,
2978 );
2979 let compute = cfg.compute.expect("compute section");
2980 assert!(!compute.internal_dns);
2981 assert_eq!(compute.dns_upstream, "10.0.0.53:53");
2982 assert_eq!(compute.dns_domain, "svc.internal");
2983 }
2984
2985 #[test]
2986 fn internal_dns_knobs_are_env_settable() {
2987 // Env alone materialises `[compute]` and sets each internal-DNS knob (and an
2988 // unrecognised bool spelling is a clear error, exercised by parse_bool).
2989 let mut cfg = ServerConfig::default();
2990 cfg.apply_env_overrides(&env(&[
2991 ("BOATRAMP_COMPUTE_INTERNAL_DNS", "off"),
2992 ("BOATRAMP_COMPUTE_DNS_UPSTREAM", "9.9.9.9:53"),
2993 ("BOATRAMP_COMPUTE_DNS_DOMAIN", "corp.internal"),
2994 ]))
2995 .expect("valid env overrides apply");
2996 let compute = cfg.compute.expect("compute materialised from env");
2997 assert!(!compute.internal_dns, "env `off` disables internal DNS");
2998 assert_eq!(compute.dns_upstream, "9.9.9.9:53");
2999 assert_eq!(compute.dns_domain, "corp.internal");
3000 }
3001
3002 #[test]
3003 fn env_override_wins_over_file_value_but_unset_defers() {
3004 // A file that set each section; env then overrides one field per section
3005 // and leaves the rest of the file value in place (precedence: env > file).
3006 let mut cfg = server(
3007 r#"(
3008 compute: ( vcpus: 2, mem_mib: 512, region: "us-east" ),
3009 security: ( profile: "multi-tenant" ),
3010 handlers: ( bindings: ( sql: ( url: "http://file:8080", admin_url: "http://file:9090" ) ) ),
3011 )"#,
3012 );
3013
3014 cfg.apply_env_overrides(&env(&[
3015 ("BOATRAMP_COMPUTE_VCPUS", "16"),
3016 ("BOATRAMP_SECURITY_PROFILE", "dev"),
3017 ("BOATRAMP_HANDLERS_SQL_URL", "http://env:8080"),
3018 ]))
3019 .expect("valid env overrides apply");
3020
3021 let compute = cfg.compute.unwrap();
3022 assert_eq!(compute.vcpus, 16, "env wins over the file vcpus");
3023 assert_eq!(compute.mem_mib, 512, "unset env defers to the file mem_mib");
3024 assert_eq!(
3025 compute.region.as_deref(),
3026 Some("us-east"),
3027 "unset env defers to the file region"
3028 );
3029
3030 assert_eq!(
3031 cfg.security.unwrap().profile.as_deref(),
3032 Some("dev"),
3033 "env profile wins over the file profile"
3034 );
3035
3036 let sql = cfg.handlers.unwrap().bindings.sql.unwrap();
3037 assert_eq!(
3038 sql.url.as_deref(),
3039 Some("http://env:8080"),
3040 "env wins over the file sql url"
3041 );
3042 assert_eq!(
3043 sql.admin_url.as_deref(),
3044 Some("http://file:9090"),
3045 "unset env defers to the file sql admin_url"
3046 );
3047 }
3048
3049 #[test]
3050 fn env_overrides_leave_unmentioned_sections_absent() {
3051 // With no relevant env vars set, an empty config stays empty — the sections
3052 // are materialised only on demand, so an unset environment adds nothing.
3053 let mut cfg = ServerConfig::default();
3054 cfg.apply_env_overrides(&env(&[("SOME_UNRELATED_VAR", "x")]))
3055 .expect("no-op env applies");
3056 assert!(cfg.compute.is_none());
3057 assert!(cfg.security.is_none());
3058 assert!(cfg.handlers.is_none());
3059 assert!(cfg.secrets.is_none());
3060 assert!(cfg.cluster.is_none());
3061 }
3062
3063 #[test]
3064 fn env_bool_accepts_common_spellings_and_rejects_garbage() {
3065 // Truthy/falsey spellings all parse.
3066 for (raw, want) in [
3067 ("true", true),
3068 ("1", true),
3069 ("YES", true),
3070 ("On", true),
3071 ("false", false),
3072 ("0", false),
3073 ("no", false),
3074 ("OFF", false),
3075 ] {
3076 let mut cfg = ServerConfig::default();
3077 cfg.apply_env_overrides(&env(&[("BOATRAMP_SECURITY_REQUIRE_POP", raw)]))
3078 .expect("boolean parses");
3079 assert_eq!(
3080 cfg.security.unwrap().overrides.require_pop,
3081 Some(want),
3082 "{raw:?} ⇒ {want}"
3083 );
3084 }
3085 // A non-boolean value is a clear error, not a silent default. (The pipeline rejects it
3086 // LOUDLY at extract as a `Resolve` error — figment's message names the field path, not
3087 // the env var, but a malformed value is never silently defaulted.)
3088 let mut cfg = ServerConfig::default();
3089 let err = cfg
3090 .apply_env_overrides(&env(&[("BOATRAMP_SECURITY_REQUIRE_POP", "maybe")]))
3091 .expect_err("garbage boolean is rejected");
3092 assert!(
3093 matches!(err, ConfigError::Resolve(_)),
3094 "garbage bool must fail loudly, got {err:?}"
3095 );
3096 }
3097
3098 #[test]
3099 fn env_number_parse_error_is_loud() {
3100 // A non-numeric numeric var is rejected LOUDLY (never silently defaulted).
3101 let mut cfg = ServerConfig::default();
3102 let err = cfg
3103 .apply_env_overrides(&env(&[("BOATRAMP_COMPUTE_VCPUS", "lots")]))
3104 .expect_err("garbage number is rejected");
3105 assert!(
3106 matches!(err, ConfigError::Resolve(_)),
3107 "garbage number must fail loudly, got {err:?}"
3108 );
3109 }
3110
3111 #[test]
3112 fn empty_env_value_is_treated_as_unset() {
3113 // `VAR=` (empty) must not clobber a file value with an empty string.
3114 let mut cfg = server(r#"( compute: ( region: "us-east" ) )"#);
3115 cfg.apply_env_overrides(&env(&[("BOATRAMP_COMPUTE_REGION", "")]))
3116 .expect("empty env applies as a no-op");
3117 assert_eq!(
3118 cfg.compute.unwrap().region.as_deref(),
3119 Some("us-east"),
3120 "an empty env value leaves the file value in place"
3121 );
3122 }
3123
3124 #[test]
3125 fn env_configures_managed_postgres_secrets_and_privilege_with_no_file() {
3126 // The construens acceptance case: with NO `boatramp.cfg` at all, the
3127 // environment alone stands up a managed co-located Postgres. It configures
3128 // the default (`"default"`-named, v0.5.0) database in
3129 // `handlers.bindings.sql.databases` (kind=postgres, compute=pg, database+user
3130 // set), the `[secrets]` envelope (local + a kek path so the managed credential
3131 // can be sealed), and `compute.managed_db_privilege = rootless`. All three
3132 // sections start absent.
3133 let mut cfg = ServerConfig::default();
3134 assert!(cfg.handlers.is_none() && cfg.secrets.is_none() && cfg.compute.is_none());
3135
3136 cfg.apply_env_overrides(&env(&[
3137 // The default database is addressed by the reserved `DEFAULT` token,
3138 // which maps to the reserved real name `"default"` (v0.5.0).
3139 ("BOATRAMP_HANDLERS_SQL_DB_DEFAULT_KIND", "postgres"),
3140 ("BOATRAMP_HANDLERS_SQL_DB_DEFAULT_COMPUTE", "pg"),
3141 ("BOATRAMP_HANDLERS_SQL_DB_DEFAULT_DATABASE", "appdb"),
3142 ("BOATRAMP_HANDLERS_SQL_DB_DEFAULT_USER", "app"),
3143 // Secrets: the local envelope + a KEK path (never key material).
3144 ("BOATRAMP_SECRETS_ENVELOPE", "local"),
3145 ("BOATRAMP_SECRETS_KEK_FILE", "/var/lib/boatramp/secrets/kek"),
3146 // The shared-kernel DB privilege strategy.
3147 ("BOATRAMP_COMPUTE_MANAGED_DB_PRIVILEGE", "rootless"),
3148 ]))
3149 .expect("valid env overrides apply");
3150
3151 // The default (`"default"`-keyed) managed database exists with the right source.
3152 let sql = cfg
3153 .handlers
3154 .expect("handlers materialised from env")
3155 .bindings
3156 .sql
3157 .expect("sql binding materialised from env");
3158 let db = sql
3159 .databases
3160 .get(boatramp_core::project::DEFAULT_DB_NAME)
3161 .expect("the default `default`-named database was created from DEFAULT");
3162 assert!(
3163 !sql.databases.contains_key(""),
3164 "the empty-string key is never produced (v0.5.0)"
3165 );
3166 assert_eq!(db.kind, "postgres");
3167 assert_eq!(db.compute.as_deref(), Some("pg"));
3168 assert_eq!(db.database.as_deref(), Some("appdb"));
3169 assert_eq!(db.user.as_deref(), Some("app"));
3170 // No `password_env` ⇒ boatramp manages the credential (Phase 2), and the
3171 // compute-backed source validates.
3172 assert!(db.password_env.is_none());
3173 assert!(db.is_managed_credential());
3174 assert!(db.validate("").is_ok());
3175
3176 // The secrets envelope + KEK path took (the path is a location, not a key).
3177 let secrets = cfg.secrets.expect("secrets materialised from env");
3178 assert_eq!(secrets.envelope, "local");
3179 assert_eq!(
3180 secrets.kek_file.as_deref(),
3181 Some(Path::new("/var/lib/boatramp/secrets/kek"))
3182 );
3183 assert!(
3184 secrets.vault.is_none(),
3185 "no vault vars ⇒ no vault sub-config"
3186 );
3187
3188 // The managed-DB privilege strategy resolved from its lowercase variant.
3189 let compute = cfg.compute.expect("compute materialised from env");
3190 assert_eq!(compute.managed_db_privilege, ManagedDbPrivilege::Rootless);
3191 }
3192
3193 #[test]
3194 fn env_declares_named_databases_and_merges_over_the_file() {
3195 // A file declares one database; the env overrides one of its fields and
3196 // ADDS a second, discovering both member names from the environment.
3197 let mut cfg = server(
3198 r#"(
3199 handlers: ( bindings: ( sql: (
3200 databases: {
3201 "analytics": ( kind: "postgres", url_env: "FILE_PG_URL", pool_max: 4 ),
3202 },
3203 ) ) ),
3204 )"#,
3205 );
3206 cfg.apply_env_overrides(&env(&[
3207 // Override the file database's pool size (merge by key, per field).
3208 ("BOATRAMP_HANDLERS_SQL_DB_analytics_POOL_MAX", "32"),
3209 // Add a brand-new database whose name has an underscore, exercising the
3210 // longest-suffix name isolation (`_READ_URL_ENV`, not `_URL_ENV`).
3211 ("BOATRAMP_HANDLERS_SQL_DB_events_log_KIND", "mysql"),
3212 ("BOATRAMP_HANDLERS_SQL_DB_events_log_URL_ENV", "EVENTS_URL"),
3213 (
3214 "BOATRAMP_HANDLERS_SQL_DB_events_log_READ_URL_ENV",
3215 "EVENTS_RO_URL",
3216 ),
3217 ("BOATRAMP_HANDLERS_SQL_DB_events_log_READ_ONLY", "true"),
3218 ]))
3219 .expect("valid env overrides apply");
3220
3221 let sql = cfg.handlers.unwrap().bindings.sql.unwrap();
3222 assert_eq!(sql.databases.len(), 2);
3223
3224 let analytics = &sql.databases["analytics"];
3225 assert_eq!(
3226 analytics.pool_max,
3227 Some(32),
3228 "env pool_max wins over the file"
3229 );
3230 assert_eq!(
3231 analytics.url_env, "FILE_PG_URL",
3232 "the file's url_env survives (env didn't touch it)"
3233 );
3234
3235 let events = &sql.databases["events_log"];
3236 assert_eq!(events.kind, "mysql");
3237 assert_eq!(events.url_env, "EVENTS_URL");
3238 assert_eq!(events.read_url_env.as_deref(), Some("EVENTS_RO_URL"));
3239 assert!(events.read_only);
3240 }
3241
3242 #[test]
3243 fn default_token_maps_to_the_reserved_default_name_not_empty() {
3244 // v0.5.0 breaking change: the reserved `DEFAULT` env token maps to the real
3245 // name `"default"` (a valid URL path segment), never the empty string. This is
3246 // what makes the default binding addressable as `--db default` and keeps every
3247 // db-name ingress path-segment-safe.
3248 let mut cfg = ServerConfig::default();
3249 cfg.apply_env_overrides(&env(&[
3250 ("BOATRAMP_HANDLERS_SQL_DB_DEFAULT_KIND", "postgres"),
3251 ("BOATRAMP_HANDLERS_SQL_DB_DEFAULT_URL_ENV", "PG_URL"),
3252 ]))
3253 .expect("valid env overrides apply");
3254 let databases = cfg.handlers.unwrap().bindings.sql.unwrap().databases;
3255 assert!(
3256 databases.contains_key(boatramp_core::project::DEFAULT_DB_NAME),
3257 "DEFAULT → the reserved `default` key"
3258 );
3259 assert!(
3260 !databases.contains_key(""),
3261 "the empty-string key is never produced"
3262 );
3263 }
3264
3265 #[test]
3266 fn empty_string_db_binding_name_is_rejected_with_a_cure() {
3267 // A `boatramp.cfg` that literally writes the legacy empty-string default key
3268 // fails closed on load (it would emit a `//` control-plane path), and the
3269 // error points at the cure (`default`).
3270 let err = ServerConfig::parse(
3271 r#"(
3272 handlers: ( bindings: ( sql: (
3273 databases: {
3274 "": ( kind: "postgres", url_env: "PG_URL" ),
3275 },
3276 ) ) ),
3277 )"#,
3278 )
3279 .expect_err("an empty-string db binding name is refused");
3280 match err {
3281 ConfigError::InvalidDbName { name, reason, cure } => {
3282 assert_eq!(name, "");
3283 assert!(reason.contains("empty"), "reason names the emptiness");
3284 assert!(
3285 cure.contains("default") && cure.contains("CHANGELOG"),
3286 "the cure points at `default` + the CHANGELOG"
3287 );
3288 }
3289 other => panic!("expected ConfigError::InvalidDbName, got {other:?}"),
3290 }
3291 }
3292
3293 #[test]
3294 fn path_separator_db_binding_name_is_rejected() {
3295 // A non-slug name (contains `/`) is refused with the v0.7.0 slug reason and the
3296 // slug cure (pointing at `project doctor`) — NOT the empty-default cure (the fix
3297 // is to rename it to a valid slug, not adopt `default`). Boot-LOUD.
3298 let err = ServerConfig::parse(
3299 r#"(
3300 handlers: ( bindings: ( sql: (
3301 databases: {
3302 "a/b": ( kind: "postgres", url_env: "PG_URL" ),
3303 },
3304 ) ) ),
3305 )"#,
3306 )
3307 .expect_err("a `/`-bearing db binding name is refused");
3308 match err {
3309 ConfigError::InvalidDbName { name, reason, cure } => {
3310 assert_eq!(name, "a/b");
3311 // The v0.7.0 slug reason (a positive statement of the allowlist).
3312 assert!(
3313 reason.contains("valid slug"),
3314 "reason states the slug rule, got {reason:?}"
3315 );
3316 // The slug cure points at `project doctor`, not the empty-default cure.
3317 assert_eq!(cure, boatramp_core::project::INVALID_NAME_CURE);
3318 assert!(!cure.contains("CHANGELOG"), "not the empty-default cure");
3319 }
3320 other => panic!("expected ConfigError::InvalidDbName, got {other:?}"),
3321 }
3322 }
3323
3324 #[test]
3325 fn reserved_bramp_db_compute_prefix_is_rejected() {
3326 // #501 Stage B LOW-2: a static BYO binding may not point `compute` at a
3327 // `bramp-db-…` workload (reserved for derived managed-DB servers) — refused
3328 // fail-closed at config load.
3329 let err = ServerConfig::parse(
3330 r#"(
3331 handlers: ( bindings: ( sql: (
3332 databases: {
3333 "byo": ( kind: "postgres", compute: "bramp-db-acme-app", database: "d", user: "u" ),
3334 },
3335 ) ) ),
3336 )"#,
3337 )
3338 .expect_err("a `bramp-db-` compute workload is refused");
3339 match err {
3340 ConfigError::InvalidDbName { name, reason, cure } => {
3341 assert_eq!(name, "bramp-db-acme-app");
3342 assert!(reason.contains("reserved"), "reason names the reservation");
3343 assert!(cure.contains("bramp-db-"), "the cure names the prefix");
3344 }
3345 other => panic!("expected ConfigError::InvalidDbName, got {other:?}"),
3346 }
3347 // A NON-reserved compute workload for a BYO binding still loads fine.
3348 ServerConfig::parse(
3349 r#"(
3350 handlers: ( bindings: ( sql: (
3351 databases: {
3352 "byo": ( kind: "postgres", compute: "my-pg", database: "d", user: "u" ),
3353 },
3354 ) ) ),
3355 )"#,
3356 )
3357 .expect("a non-reserved compute workload loads");
3358 }
3359
3360 #[test]
3361 fn env_sets_managed_db_startup_grace() {
3362 // The per-binding startup-grace override is env-settable like the other
3363 // managed scalars, discovered by the `_STARTUP_GRACE_SECS` suffix.
3364 let mut cfg = ServerConfig::default();
3365 cfg.apply_env_overrides(&env(&[
3366 ("BOATRAMP_HANDLERS_SQL_DB_DEFAULT_KIND", "postgres"),
3367 ("BOATRAMP_HANDLERS_SQL_DB_DEFAULT_COMPUTE", "pg"),
3368 ("BOATRAMP_HANDLERS_SQL_DB_DEFAULT_DATABASE", "appdb"),
3369 ("BOATRAMP_HANDLERS_SQL_DB_DEFAULT_USER", "app"),
3370 ("BOATRAMP_HANDLERS_SQL_DB_DEFAULT_STARTUP_GRACE_SECS", "90"),
3371 ]))
3372 .expect("valid env overrides apply");
3373 let db = &cfg.handlers.unwrap().bindings.sql.unwrap().databases
3374 [boatramp_core::project::DEFAULT_DB_NAME];
3375 assert_eq!(db.startup_grace_secs, Some(90));
3376 }
3377
3378 #[test]
3379 fn env_sets_rls_gucs_and_all_marker_without_suffix_collision() {
3380 // The RLS GUC names + the v0.4.21 all-read marker are env-settable. `_TENANT_ALL_MARKER`
3381 // and `_TENANT_GUC` must NOT be shadowed by the shorter `_TENANT` suffix (longest-first
3382 // isolation) — a `_TENANT` value would otherwise swallow the DB-name split.
3383 let mut cfg = ServerConfig::default();
3384 cfg.apply_env_overrides(&env(&[
3385 ("BOATRAMP_HANDLERS_SQL_DB_DEFAULT_KIND", "postgres"),
3386 ("BOATRAMP_HANDLERS_SQL_DB_DEFAULT_DATABASE", "appdb"),
3387 (
3388 "BOATRAMP_HANDLERS_SQL_DB_DEFAULT_TENANT_GUC",
3389 "app.tenant_id",
3390 ),
3391 (
3392 "BOATRAMP_HANDLERS_SQL_DB_DEFAULT_SESSION_GUC",
3393 "app.session_id",
3394 ),
3395 ("BOATRAMP_HANDLERS_SQL_DB_DEFAULT_TENANT_ALL_MARKER", "*"),
3396 ]))
3397 .expect("valid env overrides apply");
3398 let db = &cfg.handlers.unwrap().bindings.sql.unwrap().databases
3399 [boatramp_core::project::DEFAULT_DB_NAME];
3400 assert_eq!(db.tenant_guc.as_deref(), Some("app.tenant_id"));
3401 assert_eq!(db.session_guc.as_deref(), Some("app.session_id"));
3402 assert_eq!(db.tenant_all_marker.as_deref(), Some("*"));
3403 }
3404
3405 #[test]
3406 fn env_enum_parse_error_is_loud() {
3407 // An unknown enum value is rejected LOUDLY at extract (never silently defaulted). The
3408 // pipeline's `Resolve` error carries figment's message (which names the field + the
3409 // unknown variant), not the old hand-built "one of rootless/caps" text.
3410 let mut cfg = ServerConfig::default();
3411 let err = cfg
3412 .apply_env_overrides(&env(&[(
3413 "BOATRAMP_COMPUTE_MANAGED_DB_PRIVILEGE",
3414 "superuser",
3415 )]))
3416 .expect_err("unknown enum variant is rejected");
3417 assert!(
3418 matches!(err, ConfigError::Resolve(_)),
3419 "unknown enum variant must fail loudly, got {err:?}"
3420 );
3421 // The docker enums map their lowercase serde variants too.
3422 let mut cfg = ServerConfig::default();
3423 cfg.apply_env_overrides(&env(&[
3424 ("BOATRAMP_COMPUTE_DOCKER_ENDPOINT", "bridge"),
3425 ("BOATRAMP_COMPUTE_DOCKER_VOLUME_MODE", "bind"),
3426 ]))
3427 .expect("known enum variants parse");
3428 let compute = cfg.compute.unwrap();
3429 assert_eq!(
3430 compute.docker_endpoint,
3431 boatramp_docker::DockerEndpoint::Bridge
3432 );
3433 assert_eq!(
3434 compute.docker_volume_mode,
3435 boatramp_docker::DockerVolumeMode::Bind
3436 );
3437 }
3438
3439 #[test]
3440 fn env_trust_anchors_parse_as_a_comma_separated_list() {
3441 // The kernel trust anchors are comma-separated (whitespace trimmed, empty
3442 // items dropped so a trailing comma is tolerated). A file default is
3443 // fully replaced, not appended to.
3444 let mut cfg = ServerConfig::default();
3445 cfg.apply_env_overrides(&env(&[
3446 (
3447 "BOATRAMP_COMPUTE_KERNEL_SIGNING_PUBKEYS",
3448 " es256:aa , es256:bb ,",
3449 ),
3450 ("BOATRAMP_COMPUTE_KERNEL_ALLOWED_HASHES", "deadbeef"),
3451 ]))
3452 .expect("valid list env applies");
3453 let compute = cfg.compute.unwrap();
3454 assert_eq!(
3455 compute.kernel_signing_pubkeys,
3456 vec!["es256:aa".to_string(), "es256:bb".to_string()],
3457 "trimmed, comma-split, trailing-empty dropped, defaults replaced"
3458 );
3459 assert_eq!(
3460 compute.kernel_allowed_hashes,
3461 vec!["deadbeef".to_string()],
3462 "a single value is a one-element list"
3463 );
3464 }
3465
3466 #[test]
3467 fn env_configures_secrets_vault_subconfig() {
3468 // The vault sub-config materialises only when a vault var is set, and the
3469 // token stays indirected via a variable NAME (`token_env`), never inline.
3470 let mut cfg = ServerConfig::default();
3471 cfg.apply_env_overrides(&env(&[
3472 ("BOATRAMP_SECRETS_ENVELOPE", "vault"),
3473 ("BOATRAMP_SECRETS_VAULT_ADDR", "https://vault:8200"),
3474 ("BOATRAMP_SECRETS_VAULT_KEY", "certs"),
3475 ]))
3476 .expect("valid env overrides apply");
3477 let secrets = cfg.secrets.unwrap();
3478 assert_eq!(secrets.envelope, "vault");
3479 let vault = secrets.vault.expect("vault sub-config materialised");
3480 assert_eq!(vault.addr, "https://vault:8200");
3481 assert_eq!(vault.key, "certs");
3482 // token_env defaults to VAULT_TOKEN when not overridden.
3483 assert_eq!(vault.token_env, "VAULT_TOKEN");
3484 }
3485
3486 #[test]
3487 fn env_materialises_and_overrides_the_cluster_section() {
3488 // With no file, a `BOATRAMP_CLUSTER_LISTEN` materialises the section; the
3489 // remaining fields (lists, join token, mesh) layer on. The founding/joining
3490 // action flags (`BOATRAMP_CLUSTER_INIT`/`_JOIN`) are separate `serve` args
3491 // and are not part of this section.
3492 let mut cfg = ServerConfig::default();
3493 cfg.apply_env_overrides(&env(&[
3494 ("BOATRAMP_CLUSTER_LISTEN", "10.0.0.2:7000"),
3495 ("BOATRAMP_CLUSTER_ROOT_PUBKEYS", "es256:aa,es256:bb"),
3496 ("BOATRAMP_CLUSTER_SEEDS", "https://10.0.0.1:8080"),
3497 ("BOATRAMP_CLUSTER_JOIN_TOKEN", "env:BOATRAMP_JOIN_TOKEN"),
3498 ("BOATRAMP_CLUSTER_STORE_DIR", "/var/lib/boatramp/raft"),
3499 ("BOATRAMP_CLUSTER_MESH_GATE_CLIENT_WRITES", "true"),
3500 ]))
3501 .expect("valid env overrides apply");
3502 let cluster = cfg.cluster.expect("cluster materialised from env");
3503 assert_eq!(
3504 cluster.listen,
3505 "10.0.0.2:7000".parse::<std::net::SocketAddr>().unwrap()
3506 );
3507 assert_eq!(
3508 cluster.root_pubkeys,
3509 vec!["es256:aa".to_string(), "es256:bb".to_string()]
3510 );
3511 assert_eq!(cluster.seeds, vec!["https://10.0.0.1:8080".to_string()]);
3512 assert_eq!(
3513 cluster.join_token.as_deref(),
3514 Some("env:BOATRAMP_JOIN_TOKEN")
3515 );
3516 assert_eq!(
3517 cluster.store_dir.as_deref(),
3518 Some(Path::new("/var/lib/boatramp/raft"))
3519 );
3520 assert_eq!(
3521 cluster.mesh.expect("mesh sub-config").gate_client_writes,
3522 Some(true)
3523 );
3524
3525 // Decision 4: a `[cluster]` without its required `listen` (here: a non-listen cluster
3526 // var alone, no file section) now FAILS LOUDLY at extract — the old loader silently
3527 // dropped the section, which could mask a misconfigured cluster.
3528 let mut cfg = ServerConfig::default();
3529 let err = cfg
3530 .apply_env_overrides(&env(&[("BOATRAMP_CLUSTER_SEEDS", "https://10.0.0.1:8080")]))
3531 .expect_err("a cluster section without `listen` must fail loudly");
3532 assert!(
3533 matches!(err, ConfigError::Resolve(_)),
3534 "cluster-without-listen must be a loud resolution error, got {err:?}"
3535 );
3536 }
3537
3538 #[test]
3539 fn env_cluster_listen_overrides_a_file_section() {
3540 // A file `[cluster]` section: env overrides `listen` and adds seeds.
3541 let mut cfg = server(r#"( cluster: ( listen: "0.0.0.0:7000" ) )"#);
3542 cfg.apply_env_overrides(&env(&[
3543 ("BOATRAMP_CLUSTER_LISTEN", "10.0.0.9:7000"),
3544 ("BOATRAMP_CLUSTER_SEEDS", "https://seed:8080"),
3545 ]))
3546 .expect("applies");
3547 let cluster = cfg.cluster.unwrap();
3548 assert_eq!(
3549 cluster.listen,
3550 "10.0.0.9:7000".parse::<std::net::SocketAddr>().unwrap(),
3551 "env listen wins over the file"
3552 );
3553 assert_eq!(cluster.seeds, vec!["https://seed:8080".to_string()]);
3554 }
3555
3556 #[test]
3557 fn empty_project_config_is_default() {
3558 let cfg = project("()");
3559 assert!(cfg.publish.server.is_none());
3560 assert!(cfg.publish.site.is_none());
3561 assert!(cfg.build.is_none());
3562 assert!(cfg.bundle.is_none());
3563 // Routing defaults: schema v1, the single default index candidate.
3564 assert_eq!(cfg.routing.version, 1);
3565 assert_eq!(cfg.routing.index, vec!["index.html".to_string()]);
3566 }
3567
3568 #[test]
3569 fn serve_signer_config_parses_and_maps_each_backend() {
3570 use boatramp_core::cose::TokenAlg;
3571 use boatramp_server::signer::SignerConfig;
3572
3573 // RON-native enum tagging (`Vault(...)`); `IMPLICIT_SOME` lets the optional
3574 // fields (region) take a bare value or be omitted (→ None). This is the
3575 // exact RON documented in the Authentication guide.
3576 let vault = server(
3577 r#"( serve: ( signer: Vault(
3578 address: "https://vault.example:8200",
3579 key: "boatramp-root",
3580 token_env: "VAULT_TOKEN",
3581 alg: Ed25519,
3582 ) ) )"#,
3583 );
3584 match vault.serve.unwrap().signer.unwrap().to_signer_config() {
3585 SignerConfig::Vault {
3586 address,
3587 key,
3588 token_env,
3589 alg,
3590 } => {
3591 assert_eq!(address, "https://vault.example:8200");
3592 assert_eq!(key, "boatramp-root");
3593 assert_eq!(token_env, "VAULT_TOKEN");
3594 assert_eq!(alg, TokenAlg::Ed25519);
3595 }
3596 other => panic!("expected Vault, got {other:?}"),
3597 }
3598
3599 // AWS KMS: region omitted → None; PKCS#11: alg omitted → the ES256 default.
3600 let aws =
3601 server(r#"( serve: ( signer: AwsKms(key_id: "arn:aws:kms:eu-west-1:1:key/abc") ) )"#);
3602 assert!(matches!(
3603 aws.serve.unwrap().signer.unwrap().to_signer_config(),
3604 SignerConfig::AwsKms { region: None, .. }
3605 ));
3606
3607 let hsm = server(
3608 r#"( serve: ( signer: Pkcs11(
3609 module: "/usr/lib/softhsm/libsofthsm2.so",
3610 token_label: "boatramp",
3611 key_label: "root",
3612 pin_env: "HSM_PIN",
3613 ) ) )"#,
3614 );
3615 match hsm.serve.unwrap().signer.unwrap().to_signer_config() {
3616 SignerConfig::Pkcs11 { alg, .. } => assert_eq!(alg, TokenAlg::Es256),
3617 other => panic!("expected Pkcs11, got {other:?}"),
3618 }
3619 }
3620
3621 #[test]
3622 fn project_config_parses_publish_build_and_routing() {
3623 let cfg = project(
3624 r#"(
3625 publish: ( server: "http://127.0.0.1:8080", site: "demo" ),
3626 build: ( command: "npm run build", output: "dist" ),
3627 routing: (
3628 clean_urls: true,
3629 redirects: [ (from: "/old/:slug", to: "/new/:slug", status: 301) ],
3630 ),
3631 )"#,
3632 );
3633 assert_eq!(cfg.publish.server.as_deref(), Some("http://127.0.0.1:8080"));
3634 assert_eq!(cfg.publish.site.as_deref(), Some("demo"));
3635 let build = cfg.build.unwrap();
3636 assert_eq!(build.command, "npm run build");
3637 assert_eq!(build.output.as_deref(), Some("dist"));
3638 assert!(cfg.routing.clean_urls);
3639 assert_eq!(cfg.routing.redirects.len(), 1);
3640 assert_eq!(cfg.routing.redirects[0].status, 301);
3641 }
3642
3643 #[test]
3644 fn project_config_rejects_bad_routing_pattern() {
3645 // The same compile-check `load` runs: a bad route pattern is an error.
3646 let cfg = project(r#"( routing: ( redirects: [ (from: "/a/**/b/**", to: "/x") ] ) )"#);
3647 assert!(cfg.routing.compile_check().is_err());
3648 }
3649
3650 #[test]
3651 fn empty_server_config_has_no_sections() {
3652 let cfg = server("()");
3653 assert!(cfg.serve.is_none());
3654 assert!(cfg.handlers.is_none());
3655 assert!(cfg.cluster.is_none());
3656 assert!(cfg.security.is_none());
3657 }
3658
3659 #[test]
3660 fn security_section_parses_and_resolves() {
3661 // A profile plus an override that wins over it.
3662 let cfg = server(
3663 r#"(
3664 security: (
3665 profile: "dev",
3666 overrides: (
3667 oidc_require_audience: true,
3668 max_upload_bytes: 0,
3669 ),
3670 )
3671 )"#,
3672 );
3673 let posture = cfg.security.unwrap().resolve().expect("resolves");
3674 // `dev` is loose...
3675 assert!(posture.allow_unauthenticated_public_bind);
3676 // ...but the explicit override wins over the profile.
3677 assert!(posture.oidc_require_audience);
3678 assert_eq!(posture.max_upload_bytes, 0); // unlimited
3679 }
3680
3681 #[test]
3682 fn env_wires_allow_env_secret_refs_over_the_multi_tenant_default() {
3683 // With no file, the multi-tenant default leaves host-env secret refs off;
3684 // the env knob re-enables them (env > default), same as the other posture bools.
3685 let mut cfg = ServerConfig::default();
3686 cfg.apply_env_overrides(&env(&[("BOATRAMP_SECURITY_ALLOW_ENV_SECRET_REFS", "true")]))
3687 .expect("valid env override applies");
3688 let posture = cfg
3689 .security
3690 .expect("security materialised from env")
3691 .resolve()
3692 .expect("resolves");
3693 assert!(posture.allow_env_secret_refs);
3694 }
3695
3696 #[test]
3697 fn env_wires_the_multi_tenant_subknobs_over_the_default() {
3698 // Gap 4b: the four multi-tenant sub-knobs were file-only; env now sets them (env > the
3699 // multi-tenant preset default), so a 12-factor deploy can tune tenancy isolation + guest
3700 // capability minting with no `boatramp.cfg`. Verified: strict declaration stays on while
3701 // cross-tenant `all` twins + guest cap-mint are permitted (they compose — Gap 4.3).
3702 let mut cfg = ServerConfig::default();
3703 cfg.apply_env_overrides(&env(&[
3704 ("BOATRAMP_SECURITY_PROFILE", "multi-tenant"),
3705 ("BOATRAMP_SECURITY_REQUIRE_TENANCY_DECLARATION", "true"),
3706 ("BOATRAMP_SECURITY_ALLOW_CROSS_TENANT_DB", "true"),
3707 ("BOATRAMP_SECURITY_ALLOW_GUEST_MINT_CAPABILITY", "true"),
3708 ("BOATRAMP_SECURITY_MAX_GUEST_CAPABILITY_TTL_SECS", "1800"),
3709 ]))
3710 .expect("valid env overrides apply");
3711 let posture = cfg
3712 .security
3713 .expect("security materialised from env")
3714 .resolve()
3715 .expect("resolves");
3716 assert!(posture.require_tenancy_declaration);
3717 assert!(posture.allow_cross_tenant_db);
3718 assert!(posture.allow_guest_mint_capability);
3719 assert_eq!(posture.max_guest_capability_ttl_secs, 1800);
3720 }
3721
3722 #[test]
3723 fn env_wires_the_remaining_guest_feature_knobs_over_the_multi_tenant_default() {
3724 // v0.4.18 env parity: `allow_guest_email` (which regressed prod SMTP on the P48 cutover —
3725 // multi-tenant defaults it OFF and there was no env lever), its egress sibling
3726 // `allow_guest_egress_extra_ca` (shipped config-only in v0.4.17), and the four
3727 // `allow_guest_admin_*` self-config knobs were all missing from the env map. Each preset
3728 // defaults them OFF under `multi-tenant`; the env knob must now flip each back on for a
3729 // 12-factor env-only fleet, exactly like `allow_guest_mint_capability`.
3730 let mut cfg = ServerConfig::default();
3731 cfg.apply_env_overrides(&env(&[
3732 ("BOATRAMP_SECURITY_PROFILE", "multi-tenant"),
3733 ("BOATRAMP_SECURITY_ALLOW_GUEST_EMAIL", "true"),
3734 ("BOATRAMP_SECURITY_ALLOW_GUEST_EGRESS_EXTRA_CA", "true"),
3735 ("BOATRAMP_SECURITY_ALLOW_GUEST_ADMIN_DOMAINS", "true"),
3736 ("BOATRAMP_SECURITY_ALLOW_GUEST_ADMIN_EMAIL", "true"),
3737 ("BOATRAMP_SECURITY_ALLOW_GUEST_ADMIN_SITE", "true"),
3738 ("BOATRAMP_SECURITY_ALLOW_GUEST_ADMIN_SECRETS", "true"),
3739 ]))
3740 .expect("valid env overrides apply");
3741 let security = cfg.security.expect("security materialised from env");
3742 let posture = security.resolve().expect("resolves");
3743 // Every one flips on over the multi-tenant preset default (which is `false` for all six).
3744 assert!(posture.allow_guest_email, "guest email re-enabled via env");
3745 assert!(posture.allow_guest_egress_extra_ca);
3746 assert!(posture.allow_guest_admin_domains);
3747 assert!(posture.allow_guest_admin_email);
3748 assert!(posture.allow_guest_admin_site);
3749 assert!(posture.allow_guest_admin_secrets);
3750 // `security explain` attributes each to the override/env source (not the profile preset).
3751 let explained = security.explain().expect("explains");
3752 for knob in [
3753 "allow_guest_email",
3754 "allow_guest_egress_extra_ca",
3755 "allow_guest_admin_domains",
3756 "allow_guest_admin_email",
3757 "allow_guest_admin_site",
3758 "allow_guest_admin_secrets",
3759 ] {
3760 assert!(
3761 explained
3762 .lines()
3763 .any(|l| l.contains(knob) && l.contains("true") && l.contains("(override)")),
3764 "explain shows {knob} = true (override): \n{explained}"
3765 );
3766 }
3767 }
3768
3769 #[test]
3770 fn each_guest_feature_env_var_moves_its_own_posture_field() {
3771 // Cross-wiring guard: set each of the guest-feature vars ALONE over the multi-tenant
3772 // default and assert THAT var's own resolved field flips — so a copy-paste arm mapping a var
3773 // to the wrong field (or an unregistered var that never materialises the section) fails here.
3774 // Complements `every_posture_override_field_has_an_env_mapping` below (which proves coverage
3775 // by field name but not that each arm targets the right field).
3776 for (var, check) in [
3777 (
3778 "BOATRAMP_SECURITY_ALLOW_GUEST_EMAIL",
3779 (|p: &boatramp_core::security::SecurityPosture| p.allow_guest_email)
3780 as fn(&boatramp_core::security::SecurityPosture) -> bool,
3781 ),
3782 ("BOATRAMP_SECURITY_ALLOW_GUEST_EGRESS_EXTRA_CA", |p| {
3783 p.allow_guest_egress_extra_ca
3784 }),
3785 ("BOATRAMP_SECURITY_ALLOW_GUEST_TCP_EGRESS", |p| {
3786 p.allow_guest_tcp_egress
3787 }),
3788 ("BOATRAMP_SECURITY_ALLOW_GUEST_TCP_LISTENER", |p| {
3789 p.allow_guest_tcp_listener
3790 }),
3791 ("BOATRAMP_SECURITY_ALLOW_GUEST_ADMIN_DOMAINS", |p| {
3792 p.allow_guest_admin_domains
3793 }),
3794 ("BOATRAMP_SECURITY_ALLOW_GUEST_ADMIN_EMAIL", |p| {
3795 p.allow_guest_admin_email
3796 }),
3797 ("BOATRAMP_SECURITY_ALLOW_GUEST_ADMIN_SITE", |p| {
3798 p.allow_guest_admin_site
3799 }),
3800 ("BOATRAMP_SECURITY_ALLOW_GUEST_ADMIN_SECRETS", |p| {
3801 p.allow_guest_admin_secrets
3802 }),
3803 ] {
3804 let mut cfg = ServerConfig::default();
3805 cfg.apply_env_overrides(&env(&[
3806 ("BOATRAMP_SECURITY_PROFILE", "multi-tenant"),
3807 (var, "true"),
3808 ]))
3809 .unwrap_or_else(|e| panic!("{var} applies: {e}"));
3810 let posture = cfg
3811 .security
3812 .unwrap_or_else(|| panic!("{var} materialises the security section"))
3813 .resolve()
3814 .expect("resolves");
3815 assert!(check(&posture), "{var} did not flip the resolved posture");
3816 }
3817 }
3818
3819 #[test]
3820 fn every_posture_override_field_has_an_env_mapping() {
3821 // Exhaustive guard against the EXACT class of gap v0.4.18 closes — a `PostureOverrides`
3822 // field a 12-factor fleet can set in `[security.overrides]` but NOT via env — for EVERY
3823 // field, now and in the future. Enumerate the struct's fields structurally (serialize a
3824 // default instance; every field renders as a key) and assert each maps to a registered
3825 // `BOATRAMP_SECURITY_<UPPER(field)>` in `SECURITY_ENV_VARS`. A new override field added
3826 // without an env var (or a var left out of the registry) fails here — so the omission that
3827 // regressed `allow_guest_email` can't silently recur. The registry entry is load-bearing:
3828 // `apply_env_overrides` only materialises the section when `source.any(SECURITY_ENV_VARS)`.
3829 let all = serde_json::to_value(boatramp_core::security::PostureOverrides::default())
3830 .expect("PostureOverrides serializes");
3831 let fields = all.as_object().expect("a struct is a JSON object");
3832 assert!(!fields.is_empty(), "expected some override fields");
3833 for field in fields.keys() {
3834 let var = format!("BOATRAMP_SECURITY_{}", field.to_uppercase());
3835 assert!(
3836 SECURITY_ENV_VARS.contains(&var.as_str()),
3837 "PostureOverrides field `{field}` has no env mapping — add `{var}` to \
3838 SECURITY_ENV_VARS + an arm in apply_env_overrides (the v0.4.18 forgot-a-knob guard)"
3839 );
3840 }
3841 }
3842
3843 #[test]
3844 fn cluster_section_parses_the_dynamic_join_shape() {
3845 let cfg = server(
3846 r#"(
3847 cluster: (
3848 listen: "10.0.0.2:7000",
3849 root_pubkeys: ["es256:03a1"],
3850 seeds: ["https://10.0.0.1:8080"],
3851 join_token: "env:BOATRAMP_JOIN_TOKEN",
3852 ),
3853 )"#,
3854 );
3855 let cluster = cfg.cluster.unwrap();
3856 assert_eq!(
3857 cluster.listen,
3858 "10.0.0.2:7000".parse::<std::net::SocketAddr>().unwrap()
3859 );
3860 assert_eq!(cluster.root_pubkeys, vec!["es256:03a1".to_string()]);
3861 assert_eq!(cluster.seeds, vec!["https://10.0.0.1:8080".to_string()]);
3862 assert_eq!(
3863 cluster.join_token.as_deref(),
3864 Some("env:BOATRAMP_JOIN_TOKEN")
3865 );
3866 // store_dir defaults to None (→ <data-dir>/raft at serve time).
3867 assert!(cluster.store_dir.is_none());
3868 }
3869
3870 #[test]
3871 fn cluster_section_founds_with_just_a_listen_addr() {
3872 // A founder needs no seeds/token — just where to bind the mesh.
3873 let cfg = server(r#"( cluster: ( listen: "0.0.0.0:7000" ) )"#);
3874 let cluster = cfg.cluster.unwrap();
3875 assert!(cluster.seeds.is_empty());
3876 assert!(cluster.root_pubkeys.is_empty());
3877 assert!(cluster.join_token.is_none());
3878 }
3879
3880 #[test]
3881 fn sql_binding_single_node_defaults() {
3882 // A bare section (or none) means single-node: no url, default dir.
3883 let cfg = server(r#"( handlers: ( bindings: ( sql: () ) ) )"#);
3884 let sql = cfg.handlers.unwrap().bindings.sql.unwrap();
3885 assert!(sql.url.is_none());
3886 assert!(sql.dir.is_none());
3887 }
3888
3889 #[test]
3890 fn sql_binding_single_node_custom_dir() {
3891 let cfg =
3892 server(r#"( handlers: ( bindings: ( sql: ( dir: "/var/lib/boatramp/sql" ) ) ) )"#);
3893 let sql = cfg.handlers.unwrap().bindings.sql.unwrap();
3894 assert_eq!(sql.dir.as_deref(), Some(Path::new("/var/lib/boatramp/sql")));
3895 assert!(sql.url.is_none());
3896 }
3897
3898 #[test]
3899 fn sql_binding_cluster() {
3900 let cfg = server(
3901 r#"(
3902 handlers: ( bindings: ( sql: (
3903 url: "http://sqld:8080",
3904 admin_url: "http://sqld:9090",
3905 token_env: "BOATRAMP_SQL_TOKEN",
3906 ) ) ),
3907 )"#,
3908 );
3909 let sql = cfg.handlers.unwrap().bindings.sql.unwrap();
3910 assert_eq!(sql.url.as_deref(), Some("http://sqld:8080"));
3911 assert_eq!(sql.admin_url.as_deref(), Some("http://sqld:9090"));
3912 assert_eq!(sql.token_env.as_deref(), Some("BOATRAMP_SQL_TOKEN"));
3913 assert_eq!(sql.admin_token_env, None);
3914 }
3915
3916 #[test]
3917 fn sql_binding_env_only_sets_trusted_extensions_and_declared_caps() {
3918 // The crux of the ask: with NO `boatramp.cfg`, env vars alone materialise + populate the
3919 // sql binding's migration trusted-extension allowlist (a parse_list, comma-separated +
3920 // trimmed) and the declared-DB ceilings — so a fly `[env]`-only fleet can allowlist
3921 // `pg_trgm` without a `[[files]] boatramp.cfg` edit + a server roll.
3922 let mut cfg = ServerConfig::default();
3923 assert!(cfg.handlers.is_none());
3924 cfg.apply_env_overrides(&env(&[
3925 (
3926 "BOATRAMP_HANDLERS_SQL_MIGRATE_TRUSTED_EXTENSIONS",
3927 "pg_trgm, pgcrypto",
3928 ),
3929 ("BOATRAMP_HANDLERS_SQL_MAX_DECLARED_DATABASES", "32"),
3930 ("BOATRAMP_HANDLERS_SQL_MAX_DECLARED_VOLUME_MIB", "1048576"),
3931 ]))
3932 .expect("valid env overrides apply");
3933 let sql = cfg
3934 .handlers
3935 .expect("handlers materialised from env")
3936 .bindings
3937 .sql
3938 .expect("sql binding materialised from the trusted-extensions var alone");
3939 assert_eq!(
3940 sql.migrate_trusted_extensions.as_deref(),
3941 Some(&["pg_trgm".to_string(), "pgcrypto".to_string()][..]),
3942 "the allowlist is the comma-split, trimmed env list (source = env)"
3943 );
3944 assert_eq!(sql.max_declared_databases, Some(32));
3945 assert_eq!(sql.max_declared_volume_mib, Some(1_048_576));
3946 }
3947
3948 #[test]
3949 fn sql_binding_env_over_file_for_trusted_extensions() {
3950 // Field-level env-over-file precedence: a file allowlist is overridden ONLY for the var that
3951 // is set; an unset var keeps the file value (never clobbered to empty).
3952 let mut cfg = server(
3953 r#"(
3954 handlers: ( bindings: ( sql: (
3955 migrate_trusted_extensions: ["citext"],
3956 max_declared_databases: 8,
3957 ) ) ),
3958 )"#,
3959 );
3960 cfg.apply_env_overrides(&env(&[(
3961 "BOATRAMP_HANDLERS_SQL_MIGRATE_TRUSTED_EXTENSIONS",
3962 "pg_trgm",
3963 )]))
3964 .expect("env overrides apply");
3965 let sql = cfg.handlers.unwrap().bindings.sql.unwrap();
3966 assert_eq!(
3967 sql.migrate_trusted_extensions.as_deref(),
3968 Some(&["pg_trgm".to_string()][..]),
3969 "env wins over the file allowlist for the var that is set"
3970 );
3971 assert_eq!(
3972 sql.max_declared_databases,
3973 Some(8),
3974 "a var left unset keeps the file value (not clobbered)"
3975 );
3976 }
3977
3978 #[test]
3979 fn every_sql_binding_scalar_has_an_env_mapping() {
3980 // Forgot-a-knob guard (the v0.4.18 shape, for `handlers.bindings.sql`): every env-mappable
3981 // SCALAR field on SqlBindingConfig must have a `BOATRAMP_HANDLERS_SQL_*` entry in
3982 // SQL_ENV_VARS, so a file-less (fly `[env]`-only) fleet can set it without a `boatramp.cfg`
3983 // + server roll — the EXACT gap that left `migrate_trusted_extensions` env-unsettable. The
3984 // destructure is the compile-time half: a NEW field added to SqlBindingConfig breaks this
3985 // test until it is classified below (a scalar → add a var here + a registry entry + an
3986 // overlay arm; or the `databases` map, which is discovered by the
3987 // `BOATRAMP_HANDLERS_SQL_DB_<NAME>_*` prefix scan, not a scalar var). The loop is the runtime
3988 // half: each classified scalar is actually registered.
3989 let SqlBindingConfig {
3990 dir: _,
3991 url: _,
3992 admin_url: _,
3993 replica_url: _,
3994 token_env: _,
3995 admin_token_env: _,
3996 preview_mode: _,
3997 preview_init: _,
3998 // NOT a scalar env var: the keyed external-database map, discovered by prefix scan.
3999 databases: _,
4000 deprovision_grace_secs: _,
4001 migrate_trusted_extensions: _,
4002 max_declared_databases: _,
4003 max_declared_volume_mib: _,
4004 } = SqlBindingConfig::default();
4005 for var in [
4006 "BOATRAMP_HANDLERS_SQL_DIR",
4007 "BOATRAMP_HANDLERS_SQL_URL",
4008 "BOATRAMP_HANDLERS_SQL_ADMIN_URL",
4009 "BOATRAMP_HANDLERS_SQL_REPLICA_URL",
4010 "BOATRAMP_HANDLERS_SQL_TOKEN_ENV",
4011 "BOATRAMP_HANDLERS_SQL_ADMIN_TOKEN_ENV",
4012 "BOATRAMP_HANDLERS_SQL_PREVIEW_MODE",
4013 "BOATRAMP_HANDLERS_SQL_PREVIEW_INIT",
4014 "BOATRAMP_HANDLERS_SQL_DEPROVISION_GRACE_SECS",
4015 "BOATRAMP_HANDLERS_SQL_MIGRATE_TRUSTED_EXTENSIONS",
4016 "BOATRAMP_HANDLERS_SQL_MAX_DECLARED_DATABASES",
4017 "BOATRAMP_HANDLERS_SQL_MAX_DECLARED_VOLUME_MIB",
4018 ] {
4019 assert!(
4020 SQL_ENV_VARS.contains(&var),
4021 "{var} missing from SQL_ENV_VARS — a sql-binding scalar lost its env lever \
4022 (the forgot-a-knob gap); add it to the registry + an overlay arm"
4023 );
4024 }
4025 }
4026
4027 #[test]
4028 fn env_wires_the_jwks_freshness_knobs_over_the_default() {
4029 // The two-tier JWKS freshness knobs are env-settable (12-factor parity), and every lever is
4030 // registered in JWKS_ENV_VARS — a forgot-a-knob guard so a new `jwks_*` field can't silently
4031 // lose its env override.
4032 let mut cfg = ServerConfig::default();
4033 assert!(cfg.handlers.is_none());
4034 cfg.apply_env_overrides(&env(&[
4035 ("BOATRAMP_HANDLERS_JWKS_REFRESH_SECS", "90"),
4036 ("BOATRAMP_HANDLERS_JWKS_HARD_TTL_SECS", "450"),
4037 ("BOATRAMP_HANDLERS_JWKS_FOREIGN_REFRESH_SECS", "30"),
4038 ("BOATRAMP_HANDLERS_JWKS_FOREIGN_HARD_TTL_SECS", "150"),
4039 ("BOATRAMP_HANDLERS_JWKS_PREWARM", "false"),
4040 ]))
4041 .expect("valid env overrides apply");
4042 let h = cfg.handlers.expect("handlers materialised from env");
4043 assert_eq!(h.jwks_refresh_secs, Some(90));
4044 assert_eq!(h.jwks_hard_ttl_secs, Some(450));
4045 assert_eq!(h.jwks_foreign_refresh_secs, Some(30));
4046 assert_eq!(h.jwks_foreign_hard_ttl_secs, Some(150));
4047 assert_eq!(h.jwks_prewarm, Some(false));
4048 for var in [
4049 "BOATRAMP_HANDLERS_JWKS_REFRESH_SECS",
4050 "BOATRAMP_HANDLERS_JWKS_HARD_TTL_SECS",
4051 "BOATRAMP_HANDLERS_JWKS_FOREIGN_REFRESH_SECS",
4052 "BOATRAMP_HANDLERS_JWKS_FOREIGN_HARD_TTL_SECS",
4053 "BOATRAMP_HANDLERS_JWKS_PREWARM",
4054 ] {
4055 assert!(
4056 JWKS_ENV_VARS.contains(&var),
4057 "{var} missing from JWKS_ENV_VARS — a JWKS freshness knob lost its env lever"
4058 );
4059 }
4060 }
4061
4062 #[test]
4063 fn env_wires_the_handler_concurrency_knobs_over_the_default() {
4064 // The per-component serve-admission gate + the two lane ceilings are env-settable (12-factor
4065 // parity), and every lever is registered in HANDLER_CONCURRENCY_ENV_VARS — a forgot-a-knob guard
4066 // so a new concurrency field can't silently lose its env override and get pinned back into a
4067 // `boatramp.cfg`. `serve_concurrency = 0` is the MEANINGFUL "disable the gate" value and must
4068 // round-trip as `Some(0)`, not be dropped.
4069 let mut cfg = ServerConfig::default();
4070 assert!(cfg.handlers.is_none());
4071 cfg.apply_env_overrides(&env(&[
4072 ("BOATRAMP_HANDLERS_SERVE_CONCURRENCY", "0"),
4073 ("BOATRAMP_HANDLERS_SYNC_MAX_CONCURRENCY", "128"),
4074 ("BOATRAMP_HANDLERS_ASYNC_MAX_CONCURRENCY", "16"),
4075 ]))
4076 .expect("valid env overrides apply");
4077 let h = cfg.handlers.expect("handlers materialised from env");
4078 assert_eq!(h.serve_concurrency, Some(0), "0 = disable must round-trip");
4079 assert_eq!(h.sync_max_concurrency, Some(128));
4080 assert_eq!(h.async_max_concurrency, Some(16));
4081 for var in [
4082 "BOATRAMP_HANDLERS_SERVE_CONCURRENCY",
4083 "BOATRAMP_HANDLERS_SYNC_MAX_CONCURRENCY",
4084 "BOATRAMP_HANDLERS_ASYNC_MAX_CONCURRENCY",
4085 ] {
4086 assert!(
4087 HANDLER_CONCURRENCY_ENV_VARS.contains(&var),
4088 "{var} missing from HANDLER_CONCURRENCY_ENV_VARS — a concurrency knob lost its env lever"
4089 );
4090 }
4091 }
4092
4093 #[test]
4094 fn env_wires_the_blob_hedge_knobs_over_the_default() {
4095 // The hedged-read tail knobs are env-settable so a file-less fleet can turn hedging on and tune
4096 // it; every lever is registered in HANDLER_BLOB_HEDGE_ENV_VARS (forgot-a-knob guard).
4097 let mut cfg = ServerConfig::default();
4098 assert!(cfg.handlers.is_none());
4099 cfg.apply_env_overrides(&env(&[
4100 ("BOATRAMP_HANDLERS_BLOB_HEDGE_DELAY_MS", "80"),
4101 ("BOATRAMP_HANDLERS_BLOB_HEDGE_MAX_INFLIGHT", "24"),
4102 ]))
4103 .expect("valid env overrides apply");
4104 let h = cfg.handlers.expect("handlers materialised from env");
4105 assert_eq!(h.blob_hedge_delay_ms, Some(80));
4106 assert_eq!(h.blob_hedge_max_inflight, Some(24));
4107 for var in [
4108 "BOATRAMP_HANDLERS_BLOB_HEDGE_DELAY_MS",
4109 "BOATRAMP_HANDLERS_BLOB_HEDGE_MAX_INFLIGHT",
4110 ] {
4111 assert!(
4112 HANDLER_BLOB_HEDGE_ENV_VARS.contains(&var),
4113 "{var} missing from HANDLER_BLOB_HEDGE_ENV_VARS — a hedge knob lost its env lever"
4114 );
4115 }
4116 }
4117
4118 #[test]
4119 fn env_wires_the_coldstart_knobs_over_the_default() {
4120 // The warm floor + portable AOT cache (cap-req 09) are env-settable (12-factor parity);
4121 // every lever is registered in HANDLER_COLDSTART_ENV_VARS — a forgot-a-knob guard.
4122 let mut cfg = ServerConfig::default();
4123 assert!(cfg.handlers.is_none());
4124 cfg.apply_env_overrides(&env(&[
4125 ("BOATRAMP_HANDLERS_KEEP_WARM_MAX", "8"),
4126 ("BOATRAMP_HANDLERS_AOT_ARTIFACT_CACHE", "true"),
4127 ("BOATRAMP_HANDLERS_AOT_ARTIFACT_MAX_BYTES", "268435456"),
4128 ]))
4129 .expect("valid env overrides apply");
4130 let h = cfg.handlers.expect("handlers materialised from env");
4131 assert_eq!(h.keep_warm_max, Some(8));
4132 assert_eq!(h.aot_artifact_cache, Some(true));
4133 assert_eq!(h.aot_artifact_max_bytes, Some(268_435_456));
4134 for var in [
4135 "BOATRAMP_HANDLERS_KEEP_WARM_MAX",
4136 "BOATRAMP_HANDLERS_AOT_ARTIFACT_CACHE",
4137 "BOATRAMP_HANDLERS_AOT_ARTIFACT_MAX_BYTES",
4138 ] {
4139 assert!(
4140 HANDLER_COLDSTART_ENV_VARS.contains(&var),
4141 "{var} missing from HANDLER_COLDSTART_ENV_VARS — a cold-start knob lost its env lever"
4142 );
4143 }
4144 }
4145
4146 #[test]
4147 fn env_wires_the_s3_ingress_cloud_knobs_over_the_default() {
4148 // The blob-upload minter's cloud-brokering policy is env-settable, so the Tigris presigned-only
4149 // deployment needs no `boatramp.cfg` for it. Every lever is registered in
4150 // S3_INGRESS_CLOUD_ENV_VARS (forgot-a-knob guard). The signing credential is NOT here — it stays
4151 // the sealed `[secrets]` one; these are policy toggles only.
4152 let mut cfg = ServerConfig::default();
4153 assert!(cfg.serve.is_none());
4154 cfg.apply_env_overrides(&env(&[(
4155 "BOATRAMP_S3_INGRESS_CLOUD_AWS_PRESIGNED_ONLY",
4156 "true",
4157 )]))
4158 .expect("valid env overrides apply");
4159 let ic = cfg
4160 .serve
4161 .expect("serve materialised from env")
4162 .s3_ingress_cloud
4163 .expect("s3_ingress_cloud materialised from env");
4164 assert!(ic.aws_presigned_only, "presigned-only toggled on via env");
4165 assert!(
4166 !ic.aws_use_federation_token,
4167 "untouched toggle stays default"
4168 );
4169 assert!(ic.aws_role_arn.is_none(), "untouched field stays None");
4170 for var in S3_INGRESS_CLOUD_ENV_VARS {
4171 assert!(
4172 var.starts_with("BOATRAMP_S3_INGRESS_CLOUD_"),
4173 "{var} is not an s3_ingress_cloud lever"
4174 );
4175 }
4176 }
4177
4178 #[test]
4179 fn env_wires_the_per_project_blob_backend_over_the_default() {
4180 // PLAN-per-project-blob-backend: a keyed `[serve.blob_backends.<project>]` map discovered from
4181 // the env with NO config file, mirroring the SQL `databases` map. The project name may contain
4182 // underscores (name isolation strips the LONGEST field suffix). The sealed credential is a
4183 // REFERENCE (`boatramp:`/`env:`), never the raw secret (invariant 3).
4184 let mut cfg = ServerConfig::default();
4185 assert!(cfg.serve.is_none());
4186 cfg.apply_env_overrides(&env(&[
4187 ("BOATRAMP_SERVE_BLOB_BACKEND_acme_eu_KIND", "s3"),
4188 (
4189 "BOATRAMP_SERVE_BLOB_BACKEND_acme_eu_S3_BUCKET",
4190 "acme-eu-blobs",
4191 ),
4192 (
4193 "BOATRAMP_SERVE_BLOB_BACKEND_acme_eu_S3_ENDPOINT",
4194 "https://s3.eu.example.com",
4195 ),
4196 ("BOATRAMP_SERVE_BLOB_BACKEND_acme_eu_S3_REGION", "eu-west-1"),
4197 ("BOATRAMP_SERVE_BLOB_BACKEND_acme_eu_S3_PATH_STYLE", "true"),
4198 (
4199 "BOATRAMP_SERVE_BLOB_BACKEND_acme_eu_S3_ACCESS_KEY_ID",
4200 "AKIAACME",
4201 ),
4202 (
4203 "BOATRAMP_SERVE_BLOB_BACKEND_acme_eu_S3_SECRET_ACCESS_KEY",
4204 "boatramp:acme-eu-s3",
4205 ),
4206 ]))
4207 .expect("valid per-project blob-backend env overrides apply");
4208 let serve = cfg.serve.expect("serve materialised from env");
4209 let be = serve.blob_backends.get("acme_eu").expect(
4210 "the acme_eu per-project backend was discovered from env (underscore survives name \
4211 isolation)",
4212 );
4213 assert_eq!(be.blobs, Some(crate::backends::BlobBackend::S3));
4214 assert_eq!(be.s3_bucket.as_deref(), Some("acme-eu-blobs"));
4215 assert_eq!(be.s3_endpoint.as_deref(), Some("https://s3.eu.example.com"));
4216 assert_eq!(be.s3_region.as_deref(), Some("eu-west-1"));
4217 assert!(be.s3_path_style);
4218 let cred = be
4219 .s3_credential
4220 .as_ref()
4221 .expect("sealed credential materialised from its two refs");
4222 assert_eq!(cred.access_key_id, "AKIAACME");
4223 // The secret is the REFERENCE as written — never an inlined secret value (invariant 3).
4224 assert_eq!(cred.secret_access_key, "boatramp:acme-eu-s3");
4225 }
4226
4227 #[test]
4228 fn blob_backend_env_covers_every_field() {
4229 // Forgot-a-knob guard (mirrors the SQL-DB + hedge guards): every field of `BlobBackendConfig`
4230 // reachable from config MUST have an env suffix in `BLOB_BACKEND_FIELD_SUFFIXES`, so a newly
4231 // added field can't silently lose its env lever. Set every suffix for one project and assert
4232 // each field landed; assert the suffix set is exactly the expected one (no stale/missing lever).
4233 let expected: &[&str] = &[
4234 "_KIND",
4235 "_S3_BUCKET",
4236 "_S3_ENDPOINT",
4237 "_S3_REGION",
4238 "_S3_PATH_STYLE",
4239 "_S3_ACCESS_KEY_ID",
4240 "_S3_SECRET_ACCESS_KEY",
4241 ];
4242 for suffix in expected {
4243 assert!(
4244 BLOB_BACKEND_FIELD_SUFFIXES.contains(suffix),
4245 "{suffix} missing from BLOB_BACKEND_FIELD_SUFFIXES — a blob-backend field lost its \
4246 env lever"
4247 );
4248 }
4249 assert_eq!(
4250 BLOB_BACKEND_FIELD_SUFFIXES.len(),
4251 expected.len(),
4252 "BLOB_BACKEND_FIELD_SUFFIXES has a suffix with no matching expected field (stale lever)"
4253 );
4254 }
4255
4256 #[test]
4257 fn env_wires_an_inbound_tcp_listener_with_no_file() {
4258 // PLAN-handler-tcp-inbound: a keyed `[serve.listeners.<name>]` map discovered from env with NO
4259 // config file (mirrors the blob-backend map). The listener name may contain underscores (name
4260 // isolation strips the LONGEST field suffix — `edge_api` survives).
4261 let mut cfg = ServerConfig::default();
4262 assert!(cfg.serve.is_none());
4263 cfg.apply_env_overrides(&env(&[
4264 ("BOATRAMP_SERVE_LISTENER_edge_api_BIND", "0.0.0.0:9000"),
4265 ("BOATRAMP_SERVE_LISTENER_edge_api_COMPONENT", "echo.wasm"),
4266 ("BOATRAMP_SERVE_LISTENER_edge_api_PROJECT", "acme"),
4267 ("BOATRAMP_SERVE_LISTENER_edge_api_SITE", "prod"),
4268 (
4269 "BOATRAMP_SERVE_LISTENER_edge_api_IMPORTS",
4270 "sql,wasi:keyvalue",
4271 ),
4272 ("BOATRAMP_SERVE_LISTENER_edge_api_MAX_CONNS", "32"),
4273 ("BOATRAMP_SERVE_LISTENER_edge_api_IDLE_TIMEOUT_MS", "15000"),
4274 (
4275 "BOATRAMP_SERVE_LISTENER_edge_api_MAX_CONN_DURATION_MS",
4276 "120000",
4277 ),
4278 ]))
4279 .expect("valid inbound-TCP listener env overrides apply + validate");
4280 let serve = cfg.serve.expect("serve materialised from env");
4281 let l = serve.listeners.get("edge_api").expect(
4282 "the edge_api listener was discovered from env (underscore survives isolation)",
4283 );
4284 assert_eq!(l.bind, Some("0.0.0.0:9000".parse().unwrap()));
4285 assert_eq!(l.component, "echo.wasm");
4286 assert_eq!(l.project, "acme");
4287 assert_eq!(l.site, "prod");
4288 assert_eq!(
4289 l.imports,
4290 vec!["sql".to_string(), "wasi:keyvalue".to_string()]
4291 );
4292 assert_eq!(l.max_conns, Some(32));
4293 assert_eq!(l.idle_timeout_ms, Some(15000));
4294 assert_eq!(l.max_conn_duration_ms, Some(120000));
4295 }
4296
4297 #[test]
4298 fn listener_validation_fails_closed() {
4299 // A half-declared or Phase-1-unsupported listener REFUSES the node (boot-LOUD), never binds
4300 // something that would silently mislead the operator (PLAN-handler-tcp-inbound).
4301 // (a) a missing bind.
4302 let err = ServerConfig::parse(
4303 r#"( serve: ( listeners: { "l": ( component: "c.wasm", project: "p", site: "s" ) } ) )"#,
4304 )
4305 .expect_err("a listener with no bind must be refused");
4306 assert!(
4307 matches!(err, ConfigError::InvalidListener { .. }),
4308 "{err:?}"
4309 );
4310 // (b) a `tls` block MISSING cert_file/key_file is refused (cap-req 06: host-TLS needs both).
4311 let err = ServerConfig::parse(
4312 r#"( serve: ( listeners: { "l": ( bind: "0.0.0.0:9000", component: "c.wasm", project: "p", site: "s", tls: ( cert_file: "x.pem" ) ) } ) )"#,
4313 )
4314 .expect_err("a tls block without a key_file must be refused");
4315 assert!(
4316 matches!(err, ConfigError::InvalidListener { .. }),
4317 "{err:?}"
4318 );
4319 // (c) a non-empty egress_allowlist (a tcp-connection-host guest can't hold wasi:sockets).
4320 let err = ServerConfig::parse(
4321 r#"( serve: ( listeners: { "l": ( bind: "0.0.0.0:9000", component: "c.wasm", project: "p", site: "s", egress_allowlist: ["x:443"] ) } ) )"#,
4322 )
4323 .expect_err("a non-empty per-listener egress_allowlist must be refused in Phase 1");
4324 assert!(
4325 matches!(err, ConfigError::InvalidListener { .. }),
4326 "{err:?}"
4327 );
4328 // (d) a valid plaintext listener parses.
4329 ServerConfig::parse(
4330 r#"( serve: ( listeners: { "l": ( bind: "0.0.0.0:9000", component: "c.wasm", project: "p", site: "s" ) } ) )"#,
4331 )
4332 .expect("a fully-declared plaintext listener is valid");
4333 // (e) a well-formed TLS listener (cert + key) now PARSES (cap-req 06).
4334 ServerConfig::parse(
4335 r#"( serve: ( listeners: { "l": ( bind: "0.0.0.0:9000", component: "c.wasm", project: "p", site: "s", tls: ( cert_file: "x.pem", key_file: "y.pem" ) ) } ) )"#,
4336 )
4337 .expect("a TLS listener with cert_file + key_file is valid");
4338 // (f) a well-formed STARTTLS listener (cert + key + grammar) PARSES (cap-req 06, Stage B) —
4339 // SMTP-shaped and IMAP tag-capture-shaped.
4340 ServerConfig::parse(
4341 r#"( serve: ( listeners: { "l": ( bind: "0.0.0.0:587", component: "c.wasm", project: "p", site: "s", tls: ( cert_file: "x.pem", key_file: "y.pem", starttls: ( trigger: "STARTTLS", response: "220 2.0.0 Ready to start TLS" ) ) ) } ) )"#,
4342 )
4343 .expect("a well-formed SMTP STARTTLS listener is valid");
4344 ServerConfig::parse(
4345 r#"( serve: ( listeners: { "l": ( bind: "0.0.0.0:143", component: "c.wasm", project: "p", site: "s", tls: ( cert_file: "x.pem", key_file: "y.pem", starttls: ( trigger: "STARTTLS", response: "{tag} OK begin TLS", tag_capture: true ) ) ) } ) )"#,
4346 )
4347 .expect("a well-formed IMAP tag-capture STARTTLS listener is valid");
4348 // (g) `{tag}` in the response without tag_capture is refused (the literal would leak to the wire).
4349 let err = ServerConfig::parse(
4350 r#"( serve: ( listeners: { "l": ( bind: "0.0.0.0:587", component: "c.wasm", project: "p", site: "s", tls: ( cert_file: "x.pem", key_file: "y.pem", starttls: ( trigger: "STARTTLS", response: "{tag} OK" ) ) ) } ) )"#,
4351 )
4352 .expect_err("`{tag}` without tag_capture must be refused");
4353 assert!(
4354 matches!(err, ConfigError::InvalidListener { .. }),
4355 "{err:?}"
4356 );
4357 // (h) an empty trigger is refused.
4358 let err = ServerConfig::parse(
4359 r#"( serve: ( listeners: { "l": ( bind: "0.0.0.0:587", component: "c.wasm", project: "p", site: "s", tls: ( cert_file: "x.pem", key_file: "y.pem", starttls: ( trigger: "", response: "220 ok" ) ) ) } ) )"#,
4360 )
4361 .expect_err("an empty STARTTLS trigger must be refused");
4362 assert!(
4363 matches!(err, ConfigError::InvalidListener { .. }),
4364 "{err:?}"
4365 );
4366 // (i) a STARTTLS grammar WITHOUT cert/key is refused (STARTTLS still terminates TLS).
4367 let err = ServerConfig::parse(
4368 r#"( serve: ( listeners: { "l": ( bind: "0.0.0.0:587", component: "c.wasm", project: "p", site: "s", tls: ( starttls: ( trigger: "STARTTLS", response: "220 ok" ) ) ) } ) )"#,
4369 )
4370 .expect_err("a STARTTLS grammar without cert/key must be refused");
4371 assert!(
4372 matches!(err, ConfigError::InvalidListener { .. }),
4373 "{err:?}"
4374 );
4375 // (j) a listener `tls.on_demand = true` WITHOUT node on-demand TLS enabled is refused (cap-req
4376 // 03 #4): the per-SNI engine it would share does not exist, so it would silently no-op.
4377 let err = ServerConfig::parse(
4378 r#"( serve: ( listeners: { "l": ( bind: "0.0.0.0:465", component: "c.wasm", project: "p", site: "s", tls: ( cert_file: "x.pem", key_file: "y.pem", on_demand: true ) ) } ) )"#,
4379 )
4380 .expect_err("listener on_demand without [serve.on_demand_tls] enabled must be refused");
4381 assert!(
4382 matches!(err, ConfigError::InvalidListener { .. }),
4383 "{err:?}"
4384 );
4385 // (k) the same listener WITH node on-demand TLS enabled (+ its own cert/key + server_names)
4386 // parses — it shares the one engine.
4387 ServerConfig::parse(
4388 r#"( serve: ( on_demand_tls: ( enabled: true ), listeners: { "l": ( bind: "0.0.0.0:465", component: "c.wasm", project: "p", site: "s", tls: ( cert_file: "x.pem", key_file: "y.pem", on_demand: true, server_names: ["mail.example.test"] ) ) } ) )"#,
4389 )
4390 .expect("a listener on_demand with node on-demand TLS enabled is valid");
4391 }
4392
4393 #[test]
4394 fn listener_env_covers_every_scalar_field() {
4395 // Forgot-a-knob guard (mirrors the blob-backend guard): every SCALAR field of `ListenerConfig`
4396 // with an env lever MUST have a suffix in `LISTENER_FIELD_SUFFIXES`, so a newly added scalar
4397 // can't silently lose its env knob. (The structured `imports`/`env`/`tenancy` + Phase-1-refused
4398 // `tls`/`egress_allowlist` are deliberately file-only; `_IMPORTS` is the one list lever.)
4399 let expected: &[&str] = &[
4400 "_BIND",
4401 "_COMPONENT",
4402 "_PROJECT",
4403 "_SITE",
4404 "_IMPORTS",
4405 "_MAX_CONNS",
4406 "_IDLE_TIMEOUT_MS",
4407 "_MAX_CONN_DURATION_MS",
4408 ];
4409 for suffix in expected {
4410 assert!(
4411 LISTENER_FIELD_SUFFIXES.contains(suffix),
4412 "{suffix} missing from LISTENER_FIELD_SUFFIXES — a listener field lost its env lever"
4413 );
4414 }
4415 assert_eq!(
4416 LISTENER_FIELD_SUFFIXES.len(),
4417 expected.len(),
4418 "LISTENER_FIELD_SUFFIXES has a suffix with no matching expected field (stale lever)"
4419 );
4420 }
4421
4422 #[test]
4423 fn blob_backend_rejects_the_reserved_default_project() {
4424 // Invariant 5: the reserved `default` project ALWAYS resolves the global `[serve]` backend, so
4425 // a `[serve.blob_backends.default]` entry is refused at load (fail-closed, boot-loud) — the
4426 // node-wide backend is configured under `[serve]`, not here.
4427 let err = ServerConfig::parse(
4428 r#"( serve: ( blob_backends: { "default": ( blobs: s3, s3_bucket: "x" ) } ) )"#,
4429 )
4430 .expect_err("a `default`-keyed per-project blob backend must be refused");
4431 assert!(
4432 matches!(err, ConfigError::InvalidBlobBackendProject { .. }),
4433 "reserved-default blob backend is InvalidBlobBackendProject, got {err:?}"
4434 );
4435 }
4436
4437 #[test]
4438 fn blob_backend_rejects_an_unsafe_project_name() {
4439 // A `blob_backends` key is a project name threaded into the per-project data-plane scope, so it
4440 // runs the canonical slug validator (fail-closed on a path-traversal / injection shape).
4441 let err = ServerConfig::parse(
4442 r#"( serve: ( blob_backends: { "../evil": ( blobs: s3, s3_bucket: "x" ) } ) )"#,
4443 )
4444 .expect_err("a path-traversal project key must be refused");
4445 assert!(
4446 matches!(err, ConfigError::InvalidBlobBackendProject { .. }),
4447 "unsafe blob-backend project name is InvalidBlobBackendProject, got {err:?}"
4448 );
4449 }
4450
4451 #[test]
4452 fn blob_backend_config_rejects_unknown_fields_and_inlined_secret_stays_a_ref() {
4453 // `deny_unknown_fields` on `BlobBackendConfig` + its `S3CredentialConfig` catches a typo'd key
4454 // at load; and the sealed credential's `secret_access_key` is stored verbatim as the REFERENCE
4455 // the operator wrote (a `boatramp:` name), never re-interpreted into a raw secret.
4456 let cfg = ServerConfig::parse(
4457 r#"( serve: ( blob_backends: { "acme": (
4458 blobs: s3,
4459 s3_bucket: "acme-blobs",
4460 s3_credential: ( access_key_id: "AKIA", secret_access_key: "boatramp:acme" ),
4461 ) } ) )"#,
4462 )
4463 .expect("a well-formed per-project blob backend parses");
4464 let be = cfg
4465 .serve
4466 .unwrap()
4467 .blob_backends
4468 .remove("acme")
4469 .expect("acme backend parsed");
4470 assert_eq!(be.blobs, Some(crate::backends::BlobBackend::S3));
4471 assert_eq!(
4472 be.s3_credential.unwrap().secret_access_key,
4473 "boatramp:acme",
4474 "the secret stays the indirect reference, never an inlined secret"
4475 );
4476 let bad = ServerConfig::parse(
4477 r#"( serve: ( blob_backends: { "acme": ( blobs: s3, bogus: 1 ) } ) )"#,
4478 );
4479 assert!(
4480 bad.is_err(),
4481 "an unknown [serve.blob_backends.<p>] field must be rejected (deny_unknown_fields)"
4482 );
4483 }
4484
4485 #[test]
4486 fn sql_binding_preview_policy() {
4487 let cfg = server(
4488 r#"(
4489 handlers: ( bindings: ( sql: (
4490 preview_mode: "branch",
4491 preview_init: "/etc/boatramp/seed.sql",
4492 ) ) ),
4493 )"#,
4494 );
4495 let sql = cfg.handlers.unwrap().bindings.sql.unwrap();
4496 assert_eq!(sql.preview_mode.as_deref(), Some("branch"));
4497 assert_eq!(
4498 sql.preview_init.as_deref(),
4499 Some(Path::new("/etc/boatramp/seed.sql"))
4500 );
4501 }
4502
4503 #[test]
4504 fn sql_binding_external_databases() {
4505 let cfg = server(
4506 r#"(
4507 handlers: ( bindings: ( sql: (
4508 databases: {
4509 "analytics": (
4510 kind: "postgres",
4511 url_env: "ANALYTICS_PG_URL",
4512 pool_max: 16,
4513 read_only: true,
4514 ),
4515 "events": (
4516 kind: "mysql",
4517 url_env: "EVENTS_MYSQL_URL",
4518 read_url_env: "EVENTS_MYSQL_REPLICA_URL",
4519 allow_preview: true,
4520 ),
4521 },
4522 ) ) ),
4523 )"#,
4524 );
4525 let sql = cfg.handlers.unwrap().bindings.sql.unwrap();
4526 assert_eq!(sql.databases.len(), 2);
4527
4528 let analytics = &sql.databases["analytics"];
4529 assert_eq!(analytics.kind, "postgres");
4530 assert_eq!(analytics.url_env, "ANALYTICS_PG_URL");
4531 assert_eq!(analytics.pool_max, Some(16));
4532 assert!(analytics.read_only);
4533 assert!(!analytics.allow_preview);
4534 assert!(analytics.read_url_env.is_none());
4535
4536 let events = &sql.databases["events"];
4537 assert_eq!(events.kind, "mysql");
4538 assert_eq!(
4539 events.read_url_env.as_deref(),
4540 Some("EVENTS_MYSQL_REPLICA_URL")
4541 );
4542 assert!(events.allow_preview);
4543 assert!(!events.read_only);
4544 }
4545
4546 #[test]
4547 fn sql_binding_compute_backed_database() {
4548 let cfg = server(
4549 r#"(
4550 handlers: ( bindings: ( sql: (
4551 databases: {
4552 "analytics": (
4553 kind: "postgres",
4554 compute: "pg",
4555 database: "analytics",
4556 user: "app",
4557 password_env: "PG_APP_PW",
4558 ),
4559 },
4560 ) ) ),
4561 )"#,
4562 );
4563 let db = &cfg.handlers.unwrap().bindings.sql.unwrap().databases["analytics"];
4564 assert_eq!(db.kind, "postgres");
4565 assert_eq!(db.compute.as_deref(), Some("pg"));
4566 assert_eq!(db.database.as_deref(), Some("analytics"));
4567 assert_eq!(db.user.as_deref(), Some("app"));
4568 assert_eq!(db.password_env.as_deref(), Some("PG_APP_PW"));
4569 assert!(db.url_env.is_empty(), "compute-backed has no url_env");
4570 assert!(db.validate("analytics").is_ok());
4571 }
4572
4573 #[test]
4574 fn sql_binding_source_is_exactly_one_of_url_or_compute() {
4575 // Neither source → error.
4576 assert!(ExternalDatabaseConfig::default().validate("db").is_err());
4577 // Both sources → error.
4578 let both = ExternalDatabaseConfig {
4579 kind: "postgres".into(),
4580 url_env: "PG_URL".into(),
4581 compute: Some("pg".into()),
4582 ..Default::default()
4583 };
4584 assert!(both.validate("db").is_err());
4585 // `url_env` only → ok.
4586 let url = ExternalDatabaseConfig {
4587 kind: "postgres".into(),
4588 url_env: "PG_URL".into(),
4589 ..Default::default()
4590 };
4591 assert!(url.validate("db").is_ok());
4592 // `compute` without the connection details boatramp can't infer → error.
4593 let bare = ExternalDatabaseConfig {
4594 kind: "postgres".into(),
4595 compute: Some("pg".into()),
4596 ..Default::default()
4597 };
4598 assert!(bare.validate("db").is_err());
4599 // `compute` with database/user + a bring-your-own `password_env` → ok, and
4600 // is *not* a managed credential.
4601 let byo = ExternalDatabaseConfig {
4602 kind: "postgres".into(),
4603 compute: Some("pg".into()),
4604 database: Some("analytics".into()),
4605 user: Some("app".into()),
4606 password_env: Some("PG_APP_PW".into()),
4607 ..Default::default()
4608 };
4609 assert!(byo.validate("db").is_ok());
4610 assert!(!byo.is_managed_credential());
4611 // `compute` with database/user but NO `password_env` → ok, and boatramp
4612 // manages the credential (Phase 2).
4613 let managed = ExternalDatabaseConfig {
4614 kind: "postgres".into(),
4615 compute: Some("pg".into()),
4616 database: Some("analytics".into()),
4617 user: Some("app".into()),
4618 ..Default::default()
4619 };
4620 assert!(managed.validate("db").is_ok());
4621 assert!(managed.is_managed_credential());
4622 }
4623
4624 #[test]
4625 fn libsql_source_is_exactly_one_of_path_or_url() {
4626 // A single-node `libsql` file (path only) → ok.
4627 let file = ExternalDatabaseConfig {
4628 kind: "libsql".into(),
4629 path: Some("/data/app.db".into()),
4630 ..Default::default()
4631 };
4632 assert!(file.validate("app").is_ok());
4633 // `sqlite` alias works the same.
4634 let sqlite = ExternalDatabaseConfig {
4635 kind: "sqlite".into(),
4636 path: Some("/data/app.db".into()),
4637 ..Default::default()
4638 };
4639 assert!(sqlite.validate("app").is_ok());
4640 // A remote-sqld `libsql` (url_env only) → ok.
4641 let remote = ExternalDatabaseConfig {
4642 kind: "libsql".into(),
4643 url_env: "LIBSQL_URL".into(),
4644 ..Default::default()
4645 };
4646 assert!(remote.validate("app").is_ok());
4647 // Neither `path` nor `url_env` → error.
4648 let neither = ExternalDatabaseConfig {
4649 kind: "libsql".into(),
4650 ..Default::default()
4651 };
4652 assert!(neither.validate("app").is_err());
4653 // Both `path` and `url_env` → error (exactly one).
4654 let both = ExternalDatabaseConfig {
4655 kind: "libsql".into(),
4656 path: Some("/data/app.db".into()),
4657 url_env: "LIBSQL_URL".into(),
4658 ..Default::default()
4659 };
4660 assert!(both.validate("app").is_err());
4661 // `compute` on a `libsql` binding → error (boatramp doesn't run a libsql server workload).
4662 let compute = ExternalDatabaseConfig {
4663 kind: "libsql".into(),
4664 compute: Some("x".into()),
4665 path: Some("/data/app.db".into()),
4666 ..Default::default()
4667 };
4668 assert!(compute.validate("app").is_err());
4669 // `path` on a NON-libsql (postgres) binding → error (only libsql has an on-disk file).
4670 let pg_path = ExternalDatabaseConfig {
4671 kind: "postgres".into(),
4672 url_env: "PG_URL".into(),
4673 path: Some("/data/app.db".into()),
4674 ..Default::default()
4675 };
4676 assert!(pg_path.validate("db").is_err());
4677 }
4678
4679 /// Path to a file at the repo root (two levels up from this crate).
4680 fn repo_root_file(name: &str) -> PathBuf {
4681 Path::new(env!("CARGO_MANIFEST_DIR"))
4682 .join("../..")
4683 .join(name)
4684 }
4685
4686 #[test]
4687 fn shipped_project_example_parses() {
4688 // The example we ship must always parse + compile-check, so it can't drift
4689 // from the schema.
4690 let text = std::fs::read_to_string(repo_root_file("examples/site/project.cfg.example"))
4691 .expect("example project config is present");
4692 let cfg = ProjectConfig::parse(&text).expect("example project config parses");
4693 assert_eq!(cfg.publish.server.as_deref(), Some("http://127.0.0.1:8080"));
4694 assert_eq!(cfg.build.as_ref().unwrap().command, "npm run build");
4695 assert_eq!(
4696 cfg.routing.error_documents.get(&404).map(String::as_str),
4697 Some("/404.html")
4698 );
4699 }
4700
4701 #[test]
4702 fn shipped_server_example_parses() {
4703 let text = std::fs::read_to_string(repo_root_file("boatramp.cfg.example"))
4704 .expect("example server config is present");
4705 let cfg = ServerConfig::parse(&text).expect("example server config parses");
4706 let serve = cfg.serve.expect("example sets a serve section");
4707 assert_eq!(
4708 serve.addr,
4709 Some("0.0.0.0:8080".parse::<std::net::SocketAddr>().unwrap())
4710 );
4711 }
4712
4713 #[test]
4714 fn secrets_section_parses_local_and_vault() {
4715 let local = server(r#"( secrets: ( envelope: "local", kek_file: "/k/kek" ) )"#)
4716 .secrets
4717 .expect("secrets section");
4718 assert_eq!(local.envelope, "local");
4719 assert_eq!(
4720 local.kek_file.as_deref(),
4721 Some(std::path::Path::new("/k/kek"))
4722 );
4723
4724 let vault = server(
4725 r#"( secrets: ( envelope: "vault", vault: ( addr: "https://vault:8200", key: "certs" ) ) )"#,
4726 )
4727 .secrets
4728 .expect("secrets section");
4729 let v = vault.vault.expect("vault subsection");
4730 assert_eq!(v.addr, "https://vault:8200");
4731 assert_eq!(v.key, "certs");
4732 // The token env defaults to VAULT_TOKEN and is never in the file.
4733 assert_eq!(v.token_env, "VAULT_TOKEN");
4734 }
4735
4736 #[test]
4737 fn serve_section_partial_parses() {
4738 // A partial `serve` section parses — unset fields take their defaults.
4739 let cfg = server(r#"( serve: ( addr: "0.0.0.0:8080", protect_previews: true ) )"#);
4740 let serve = cfg.serve.unwrap();
4741 assert_eq!(
4742 serve.addr,
4743 Some("0.0.0.0:8080".parse::<std::net::SocketAddr>().unwrap())
4744 );
4745 assert!(serve.protect_previews);
4746 assert!(!serve.cluster_rate_limit);
4747 assert!(serve.data_dir.is_none());
4748 }
4749
4750 #[test]
4751 fn serve_console_config_parses() {
4752 // Absent ⇒ no console.
4753 let cfg = server(r#"( serve: ( addr: "0.0.0.0:8080" ) )"#);
4754 assert!(cfg.serve.unwrap().console.is_none());
4755 // Explicit console block with host + path.
4756 let cfg = server(
4757 r#"( serve: ( console: (
4758 enabled: true,
4759 host: "console.example.com",
4760 path: "/_console",
4761 ) ) )"#,
4762 );
4763 let console = cfg.serve.unwrap().console.unwrap();
4764 assert!(console.enabled);
4765 assert_eq!(console.host.as_deref(), Some("console.example.com"));
4766 assert_eq!(console.path.as_deref(), Some("/_console"));
4767 // Bare `enabled` ⇒ host/path take their (server-side) defaults.
4768 let cfg = server(r#"( serve: ( console: ( enabled: true ) ) )"#);
4769 let console = cfg.serve.unwrap().console.unwrap();
4770 assert!(console.enabled);
4771 assert!(console.host.is_none() && console.path.is_none());
4772 }
4773
4774 #[test]
4775 fn serve_s3_credential_config_parses() {
4776 // #505: absent ⇒ no sealed source (the ambient AWS env chain).
4777 let cfg = server(r#"( serve: ( addr: "0.0.0.0:8080" ) )"#);
4778 assert!(cfg.serve.unwrap().s3_credential.is_none());
4779 // An explicit `[serve.s3_credential]`: a plain `access_key_id` + a `boatramp:` sealed
4780 // `secret_access_key` ref (the config text carries only the REFERENCE, never the secret).
4781 let cfg = server(
4782 r#"( serve: ( s3_credential: (
4783 access_key_id: "tid_public_akid",
4784 secret_access_key: "boatramp:tigris-secret",
4785 ) ) )"#,
4786 );
4787 let cred = cfg.serve.unwrap().s3_credential.unwrap();
4788 assert_eq!(cred.access_key_id, "tid_public_akid");
4789 assert_eq!(cred.secret_access_key, "boatramp:tigris-secret");
4790 // An unknown field is rejected (`deny_unknown_fields`) — a fat-fingered key fails fast.
4791 let err: Result<ServerConfig, _> = ron_options().from_str(
4792 r#"( serve: ( s3_credential: ( access_key_id: "x", secret_access_key: "boatramp:y", bogus: 1 ) ) )"#,
4793 );
4794 assert!(
4795 err.is_err(),
4796 "unknown [serve.s3_credential] field must be rejected"
4797 );
4798 }
4799
4800 #[test]
4801 fn serve_blob_fallback_config_parses() {
4802 // Blob-backend migration Part 2: absent ⇒ no fallback (the read-through composite is not wired).
4803 let cfg = server(r#"( serve: ( addr: "0.0.0.0:8080" ) )"#);
4804 assert!(cfg.serve.unwrap().blob_fallback.is_none());
4805 // A `[serve.blob_fallback]` secondary: the OLD fs backend to drain while the primary is s3,
4806 // with its own sealed S3 credential ref and a custom secondary timeout.
4807 let cfg = server(
4808 r#"( serve: (
4809 blobs: s3,
4810 s3_bucket: "new-bucket",
4811 blob_fallback: (
4812 blobs: fs,
4813 secondary_timeout_secs: 3,
4814 s3_credential: (
4815 access_key_id: "old_akid",
4816 secret_access_key: "boatramp:old-secret",
4817 ),
4818 ),
4819 ) )"#,
4820 );
4821 let serve = cfg.serve.unwrap();
4822 let fb = serve.blob_fallback.unwrap();
4823 assert_eq!(fb.blobs, Some(crate::backends::BlobBackend::Fs));
4824 assert_eq!(fb.secondary_timeout_secs, Some(3));
4825 let cred = fb.s3_credential.unwrap();
4826 assert_eq!(cred.access_key_id, "old_akid");
4827 assert_eq!(cred.secret_access_key, "boatramp:old-secret");
4828 // An unknown field is rejected (`deny_unknown_fields`).
4829 let err: Result<ServerConfig, _> =
4830 ron_options().from_str(r#"( serve: ( blob_fallback: ( blobs: fs, bogus: 1 ) ) )"#);
4831 assert!(
4832 err.is_err(),
4833 "unknown [serve.blob_fallback] field must be rejected"
4834 );
4835 }
4836
4837 #[test]
4838 fn serve_kv_config_parses_and_defaults() {
4839 // Absent `[serve.kv]` ⇒ the defaults: periodic checkpoint ON at the default cadence, and the
4840 // generous default close budget (NOT the old 3s).
4841 let cfg = server(r#"( serve: ( addr: "0.0.0.0:8080" ) )"#);
4842 assert!(cfg.serve.unwrap().kv.is_none());
4843 let default_kv = super::KvConfig::default();
4844 assert_eq!(
4845 default_kv.checkpoint_interval(),
4846 Some(std::time::Duration::from_secs(
4847 super::DEFAULT_KV_CHECKPOINT_INTERVAL_SECS
4848 )),
4849 "an absent/unset checkpoint_interval defaults to the ON cadence"
4850 );
4851 assert_eq!(
4852 default_kv.close_deadline(),
4853 std::time::Duration::from_secs(super::DEFAULT_KV_CLOSE_DEADLINE_SECS),
4854 "an absent/unset close_deadline defaults to the generous budget"
4855 );
4856 // The online maintenance-GC knobs default ON (15 min) with a conservative 1h min_age.
4857 assert_eq!(
4858 default_kv.gc_interval(),
4859 Some(std::time::Duration::from_secs(
4860 super::DEFAULT_KV_GC_INTERVAL_SECS
4861 )),
4862 "an absent/unset gc_interval defaults to the ON cadence"
4863 );
4864 assert_eq!(
4865 default_kv.gc_min_age(),
4866 std::time::Duration::from_secs(super::DEFAULT_KV_GC_MIN_AGE_SECS),
4867 "an absent/unset gc_min_age defaults to the conservative 1h floor"
4868 );
4869
4870 // An explicit block: a tuned cadence + a tuned close budget + tuned GC knobs, now nested under
4871 // `slatedb` (UX-C3) so they never appear to apply under a non-SlateDB backend.
4872 let cfg = server(
4873 r#"( serve: ( kv: ( slatedb: ( checkpoint_interval: 5, close_deadline: 30, gc_interval: 300, gc_min_age: 600 ) ) ) )"#,
4874 );
4875 let kv = cfg.serve.unwrap().kv.unwrap();
4876 assert_eq!(
4877 kv.checkpoint_interval(),
4878 Some(std::time::Duration::from_secs(5))
4879 );
4880 assert_eq!(kv.close_deadline(), std::time::Duration::from_secs(30));
4881 assert_eq!(kv.gc_interval(), Some(std::time::Duration::from_secs(300)));
4882 assert_eq!(kv.gc_min_age(), std::time::Duration::from_secs(600));
4883
4884 // checkpoint_interval = 0 DISABLES the cadence; a 0 close_deadline falls back to the default
4885 // (a zero close budget would abandon every close, guaranteeing a torn tail — never allowed).
4886 // gc_interval = 0 DISABLES the maintenance task; a 0 gc_min_age clamps up to the default (a
4887 // zero min_age would reintroduce the reader-mid-scan deletion hazard — never allowed).
4888 let cfg = server(
4889 r#"( serve: ( kv: ( slatedb: ( checkpoint_interval: 0, close_deadline: 0, gc_interval: 0, gc_min_age: 0 ) ) ) )"#,
4890 );
4891 let kv = cfg.serve.unwrap().kv.unwrap();
4892 assert_eq!(kv.checkpoint_interval(), None, "0 disables the cadence");
4893 assert_eq!(
4894 kv.close_deadline(),
4895 std::time::Duration::from_secs(super::DEFAULT_KV_CLOSE_DEADLINE_SECS),
4896 "a 0 close_deadline is clamped up to the default, never zero"
4897 );
4898 assert_eq!(kv.gc_interval(), None, "0 disables the maintenance GC task");
4899 assert_eq!(
4900 kv.gc_min_age(),
4901 std::time::Duration::from_secs(super::DEFAULT_KV_GC_MIN_AGE_SECS),
4902 "a 0 gc_min_age is clamped up to the conservative default, never zero"
4903 );
4904
4905 // The SQL KV backend connection parses under `sql` (UX-C2: `url_env`, never a raw URL).
4906 let cfg = server(r#"( serve: ( kv: ( sql: ( kind: "sqlite", path: "/data/kv.db" ) ) ) )"#);
4907 let sql = cfg.serve.unwrap().kv.unwrap().sql.unwrap();
4908 assert_eq!(sql.kind, "sqlite");
4909 assert_eq!(sql.path.as_deref(), Some("/data/kv.db"));
4910
4911 // UX-C3: a pre-v0.12.0 TOP-LEVEL durability knob now fails loud (it moved under `slatedb`),
4912 // never silently mislead — `deny_unknown_fields` rejects it at the `[serve.kv]` level.
4913 let err: Result<ServerConfig, _> =
4914 ron_options().from_str(r#"( serve: ( kv: ( checkpoint_interval: 5 ) ) )"#);
4915 assert!(
4916 err.is_err(),
4917 "a top-level checkpoint_interval must be rejected (moved under [serve.kv.slatedb])"
4918 );
4919
4920 // An unknown field inside the `slatedb` sub-block is rejected (`deny_unknown_fields`).
4921 let err: Result<ServerConfig, _> = ron_options()
4922 .from_str(r#"( serve: ( kv: ( slatedb: ( checkpoint_interval: 5, bogus: 1 ) ) ) )"#);
4923 assert!(
4924 err.is_err(),
4925 "unknown [serve.kv.slatedb] field must be rejected"
4926 );
4927 }
4928
4929 // =======================================================================
4930 // JSON config input gate (v0.6.5) — serve/project config + detection half.
4931 //
4932 // ROBUST-successor gate (continuing the v0.6.4 blob-purge style): a `#[test]`
4933 // battery whose sole CI contract is the ordinary `cargo test` exit code — NO
4934 // grepped uppercase marker, NO bash env-var mutation loop. Every test is prefixed
4935 // `config_json_gate_` so the CI lane filters with `cargo test … config_json`. The
4936 // apply-manifest half (version current-schema-only, bad-route compile-check) lives
4937 // in `boatramp::apply`'s test module under the same prefix.
4938 // =======================================================================
4939
4940 /// Detection: `resolve_format` follows the explicit-override-wins, else
4941 /// `.json`⇒Json / everything-else⇒Ron rule (no content-sniffing).
4942 #[test]
4943 fn config_json_gate_resolve_format_table() {
4944 use std::path::Path;
4945 // Auto by extension.
4946 assert_eq!(
4947 resolve_format(Path::new("boatramp.json"), None),
4948 ConfigFormat::Json
4949 );
4950 assert_eq!(
4951 resolve_format(Path::new("apply.cfg"), None),
4952 ConfigFormat::Ron
4953 );
4954 assert_eq!(
4955 resolve_format(Path::new("apply.ron"), None),
4956 ConfigFormat::Ron
4957 );
4958 // No extension ⇒ Ron.
4959 assert_eq!(resolve_format(Path::new("apply"), None), ConfigFormat::Ron);
4960 // Case-insensitive `.json`.
4961 assert_eq!(
4962 resolve_format(Path::new("x.JSON"), None),
4963 ConfigFormat::Json
4964 );
4965 // Explicit override wins BOTH ways.
4966 assert_eq!(
4967 resolve_format(Path::new("x.json"), Some(ConfigFormat::Ron)),
4968 ConfigFormat::Ron
4969 );
4970 assert_eq!(
4971 resolve_format(Path::new("x.cfg"), Some(ConfigFormat::Json)),
4972 ConfigFormat::Json
4973 );
4974 }
4975
4976 /// Equivalence: a representative serve config authored in RON and in equivalent
4977 /// JSON parses to the SAME field values — including the externally-tagged
4978 /// enum-variant field `[serve].blobs` (`BlobBackend::S3`; RON `s3` ≡ JSON `"s3"`),
4979 /// proving variant-name fidelity through the JSON decoder.
4980 #[test]
4981 fn config_json_gate_serve_ron_and_json_are_equivalent() {
4982 let ron = r#"( serve: ( addr: "0.0.0.0:8080", blobs: s3, s3_bucket: "b" ) )"#;
4983 let json = r#"{ "serve": { "addr": "0.0.0.0:8080", "blobs": "s3", "s3_bucket": "b" } }"#;
4984 let from_ron = ServerConfig::parse_with_format(ron, ConfigFormat::Ron).unwrap();
4985 let from_json = ServerConfig::parse_with_format(json, ConfigFormat::Json).unwrap();
4986 let s_ron = from_ron.serve.unwrap();
4987 let s_json = from_json.serve.unwrap();
4988 assert_eq!(s_ron.blobs, Some(crate::backends::BlobBackend::S3));
4989 assert_eq!(s_json.blobs, Some(crate::backends::BlobBackend::S3));
4990 assert_eq!(s_ron.blobs, s_json.blobs, "the enum variant survives JSON");
4991 assert_eq!(s_ron.addr, s_json.addr);
4992 assert_eq!(s_ron.s3_bucket, s_json.s3_bucket);
4993 assert_eq!(s_json.s3_bucket.as_deref(), Some("b"));
4994 }
4995
4996 /// Equivalence (project): a `project.cfg` authored in RON and in equivalent JSON
4997 /// parses to the same publish target.
4998 #[test]
4999 fn config_json_gate_project_ron_and_json_are_equivalent() {
5000 let ron = r#"( publish: ( project: "team-x" ) )"#;
5001 let json = r#"{ "publish": { "project": "team-x" } }"#;
5002 let from_ron = ProjectConfig::parse_with_format(ron, ConfigFormat::Ron).unwrap();
5003 let from_json = ProjectConfig::parse_with_format(json, ConfigFormat::Json).unwrap();
5004 assert_eq!(from_ron.publish.project.as_deref(), Some("team-x"));
5005 assert_eq!(from_ron.publish.project, from_json.publish.project);
5006 }
5007
5008 /// `deny_unknown_fields` parity: a JSON serve config with an extra/typo'd field is
5009 /// a hard parse error, not a silent drop (the `[serve.blob_fallback]`
5010 /// `deny_unknown_fields` struct is the RON parity partner tested above).
5011 #[test]
5012 fn config_json_gate_serve_json_denies_unknown_fields() {
5013 let json = r#"{ "serve": { "blob_fallback": { "blobs": "fs", "bogus": 1 } } }"#;
5014 assert!(
5015 ServerConfig::parse_with_format(json, ConfigFormat::Json).is_err(),
5016 "an unknown JSON field must be rejected (deny_unknown_fields), same as RON"
5017 );
5018 }
5019
5020 /// No-bypass: post-parse validation runs regardless of format. A JSON serve config
5021 /// with an invalid `handlers.bindings.sql.databases` db-name (a `/`-bearing,
5022 /// non-URL-path-safe name) is rejected identically to RON — the SAME
5023 /// `ConfigError::InvalidDbName`, from the SAME `validate_sql_db_names` choke point.
5024 #[test]
5025 fn config_json_gate_json_bad_db_name_is_rejected_like_ron() {
5026 // The invalid binding name `a/b` (a path separator) fails the canonical
5027 // resource-name validator that `validate_sql_db_names` runs after the parse.
5028 let json = r#"{ "handlers": { "bindings": { "sql": {
5029 "databases": { "a/b": { "kind": "postgres", "url_env": "DB_URL" } }
5030 } } } }"#;
5031 let ron = r#"( handlers: ( bindings: ( sql: (
5032 databases: { "a/b": ( kind: "postgres", url_env: "DB_URL" ) }
5033 ) ) ) )"#;
5034 let json_err = ServerConfig::parse_with_format(json, ConfigFormat::Json)
5035 .expect_err("a bad db-name in a JSON config must be rejected");
5036 let ron_err = ServerConfig::parse_with_format(ron, ConfigFormat::Ron)
5037 .expect_err("a bad db-name in a RON config must be rejected");
5038 assert!(
5039 matches!(json_err, ConfigError::InvalidDbName { .. }),
5040 "JSON bad db-name is InvalidDbName, got {json_err:?}"
5041 );
5042 assert!(
5043 matches!(ron_err, ConfigError::InvalidDbName { .. }),
5044 "RON bad db-name is InvalidDbName, got {ron_err:?}"
5045 );
5046 }
5047
5048 /// Anti-hollow (typed, in-process): a document valid as JSON but NOT as RON MUST
5049 /// parse under `Json` and FAIL under `Ron`. If `parse_with_format` ignored `fmt`
5050 /// and always decoded RON, the JSON leg would fail — so the format selection is
5051 /// proven load-bearing, with no env var and no marker.
5052 #[test]
5053 fn config_json_gate_serve_format_selection_is_load_bearing() {
5054 // A bare JSON object is valid JSON for `ServerConfig`, not valid RON for it
5055 // (RON structs use `( … )`, not a brace map).
5056 let doc = r#"{ "serve": { "s3_bucket": "only-json" } }"#;
5057 let as_json = ServerConfig::parse_with_format(doc, ConfigFormat::Json).unwrap();
5058 assert_eq!(
5059 as_json.serve.unwrap().s3_bucket.as_deref(),
5060 Some("only-json")
5061 );
5062 assert!(
5063 ServerConfig::parse_with_format(doc, ConfigFormat::Ron).is_err(),
5064 "the same document must FAIL under Ron — else the fmt selection is hollow"
5065 );
5066 }
5067}
5068
5069// ============================================================================
5070// The single figment-based config resolver (serve + every offline op).
5071// ============================================================================
5072//
5073// This module is the config system (shipped in v0.35.0; design record in
5074// docs/config-figment-migration.md). `load_with_figment` merges, in order,
5075// base-seed → file → `BOATRAMP_*` env → explicit CLI flags
5076// into ONE `ServerConfig`, used by `ServerConfig::load` (serve AND the offline ops:
5077// `migrate`, `blob`, `token`). It REPLACED the three hand-rolled env loaders:
5078//
5079// A. the serve clap `#[arg(env = …)]` layer (serve-only),
5080// B. `apply_env_overrides` (ran in `load`, so everywhere), and
5081// C. ad-hoc `std::env::var` reads in serve (serve-only).
5082//
5083// The core bug it fixed: A & C were serve-only, so `BOATRAMP_S3_BUCKET` (and the
5084// serve/kv knobs) were honored by `serve` but NOT by `migrate`/`blob` — the offline
5085// ops that most need them. Now the env surface is uniform across all subcommands.
5086//
5087// ## Design: emit strings, extract lossy
5088//
5089// The env/flag overlay emits every scalar as a STRING value (trimmed), lists as
5090// arrays, and the (rare) rename_all enums as their lowercased token. Nothing is
5091// parsed here, so the overlay is infallible. At extraction `Figment::extract_lossy`
5092// coerces each string to the target field's type:
5093// * bool fields — via `Value::to_bool_lossy` (`true/yes/1/on` + `false/no/0/off`,
5094// case-insensitive — the spellings the old `parse_bool` accepted);
5095// * numeric fields — via `to_num_lossy` (a non-numeric value fails to deserialize
5096// LOUDLY — a malformed value is rejected, never silently defaulted);
5097// * string / enum / path / socket-addr fields read the string directly.
5098// A string destined for a string field is never coerced (lossy only fires when the
5099// TARGET is bool/number), so a numeric-looking bucket name or region survives.
5100//
5101// ## Faithful, drift-proof mapping
5102//
5103// The fixed-var overlay is DRIVEN BY the `*_ENV_VARS` const tables (+ the explicit
5104// `SERVE_SCALARS` / `SERVE_KV` alias tables for the irregular serve names), deriving
5105// each config path by the section's rule (drop `serve`, drop `bindings`, drop
5106// `overrides`, …). Those tables are now the SINGLE source of truth; the forgot-a-knob
5107// guard tests assert every struct field has a table entry, and the drift guards assert
5108// every table entry is honored by the overlay — field ↔ var ↔ overlay, no drift.
5109pub(crate) mod figment_resolve {
5110 use super::*;
5111 use figment::providers::Serialized;
5112 use figment::value::{Dict, Map as FigMap, Tag, Value};
5113 use figment::{Error, Figment, Metadata, Profile, Provider};
5114
5115 /// Vars whose value is a comma-separated list (trimmed, empty items dropped —
5116 /// `EnvSource::parse_list` semantics), emitted as a figment `Array`.
5117 const LIST_VARS: &[&str] = &[
5118 "BOATRAMP_COMPUTE_KERNEL_SIGNING_PUBKEYS",
5119 "BOATRAMP_COMPUTE_KERNEL_ALLOWED_HASHES",
5120 "BOATRAMP_HANDLERS_SQL_MIGRATE_TRUSTED_EXTENSIONS",
5121 "BOATRAMP_CLUSTER_ROOT_PUBKEYS",
5122 "BOATRAMP_CLUSTER_SEEDS",
5123 ];
5124
5125 /// Vars whose target is a `rename_all = "lowercase"` enum with no `FromStr`.
5126 /// `apply_env_overrides` matches these case-insensitively against a lowercase
5127 /// variant table; we emit the lowercased token so serde deserializes the same
5128 /// variant. (The per-backend `_KIND` inside the blob-backends map is handled inline.)
5129 const ENUM_VARS: &[&str] = &[
5130 "BOATRAMP_BLOBS",
5131 "BOATRAMP_COMPUTE_MANAGED_DB_PRIVILEGE",
5132 "BOATRAMP_COMPUTE_DOCKER_ENDPOINT",
5133 "BOATRAMP_COMPUTE_DOCKER_VOLUME_MODE",
5134 ];
5135
5136 /// The `serve.*` scalar aliases (the former Loader-A clap `#[arg(env)]` surface,
5137 /// unified here). Explicit (env → path) pairs because the env names are irregular —
5138 /// they drop the `serve` segment (`BOATRAMP_ADDR`, not `BOATRAMP_SERVE_ADDR`) and one
5139 /// is a field-name mismatch (`BOATRAMP_UPLOAD_IDLE_TIMEOUT` → `upload_idle_timeout_secs`)
5140 /// — so the mapping is aliased, never path-derived (risk P1). Bool/numeric fields are
5141 /// emitted as strings and coerced by `extract_lossy`; `blobs` is in `ENUM_VARS`.
5142 /// (The file-only serve fields — `s3_ingress_*`, `blob_notify_*`, `console`, `signer`,
5143 /// `blob_fallback`, `s3_credential` — have no clap/env today and stay file-only, carried
5144 /// by the figment file layer.) `auth_root_private_key` / `bootstrap_secret` /
5145 /// `azure_access_key` are secret-bearing config fields (as they are today via clap); they
5146 /// resolve into the config but are REDACTED by `config dump`/`explain`.
5147 const SERVE_SCALARS: &[(&str, &[&str])] = &[
5148 ("BOATRAMP_BLOBS", &["serve", "blobs"]),
5149 ("BOATRAMP_S3_BUCKET", &["serve", "s3_bucket"]),
5150 ("BOATRAMP_S3_ENDPOINT", &["serve", "s3_endpoint"]),
5151 ("BOATRAMP_S3_REGION", &["serve", "s3_region"]),
5152 ("BOATRAMP_S3_PATH_STYLE", &["serve", "s3_path_style"]),
5153 ("BOATRAMP_ADDR", &["serve", "addr"]),
5154 ("BOATRAMP_DATA_DIR", &["serve", "data_dir"]),
5155 ("BOATRAMP_GCS_BUCKET", &["serve", "gcs_bucket"]),
5156 ("BOATRAMP_GCS_ENDPOINT", &["serve", "gcs_endpoint"]),
5157 ("BOATRAMP_GCS_ANONYMOUS", &["serve", "gcs_anonymous"]),
5158 ("BOATRAMP_AZURE_ACCOUNT", &["serve", "azure_account"]),
5159 ("BOATRAMP_AZURE_CONTAINER", &["serve", "azure_container"]),
5160 ("BOATRAMP_AZURE_ACCESS_KEY", &["serve", "azure_access_key"]),
5161 ("BOATRAMP_AZURE_EMULATOR", &["serve", "azure_emulator"]),
5162 (
5163 "BOATRAMP_AUTH_ROOT_PRIVATE_KEY",
5164 &["serve", "auth_root_private_key"],
5165 ),
5166 (
5167 "BOATRAMP_AUTH_ROOT_PUBLIC_KEY",
5168 &["serve", "auth_root_public_key"],
5169 ),
5170 ("BOATRAMP_BOOTSTRAP_SECRET", &["serve", "bootstrap_secret"]),
5171 ("BOATRAMP_MAX_UPLOAD_BYTES", &["serve", "max_upload_bytes"]),
5172 (
5173 "BOATRAMP_UPLOAD_IDLE_TIMEOUT",
5174 &["serve", "upload_idle_timeout_secs"],
5175 ),
5176 (
5177 "BOATRAMP_MAX_CONCURRENT_UPLOADS",
5178 &["serve", "max_concurrent_uploads"],
5179 ),
5180 (
5181 "BOATRAMP_HTTP_REDIRECT_ADDR",
5182 &["serve", "http_redirect_addr"],
5183 ),
5184 ("BOATRAMP_DEFAULT_SITE", &["serve", "default_site"]),
5185 ("BOATRAMP_POP_ORIGIN", &["serve", "pop_origin"]),
5186 ("BOATRAMP_PROTECT_PREVIEWS", &["serve", "protect_previews"]),
5187 (
5188 "BOATRAMP_CLUSTER_RATE_LIMIT",
5189 &["serve", "cluster_rate_limit"],
5190 ),
5191 (
5192 "BOATRAMP_SHARED_CACHE_COHERENCE",
5193 &["serve", "shared_cache_coherence"],
5194 ),
5195 ];
5196
5197 /// The `serve.kv.*` aliases (the former Loader-C ad-hoc `std::env::var` surface). The env
5198 /// names drop BOTH `serve` and (for slatedb) the `slatedb` segment, so they are aliased
5199 /// explicitly (risk P1/P10). The `0`-disables-cadence semantics are preserved by
5200 /// `KvConfig::{checkpoint_interval,gc_interval}` reading the resolved `Some(0)`.
5201 /// (The Loader-C RUNTIME knobs that are NOT config fields — `BOATRAMP_KV_AUTHZ_FENCE_SECS`,
5202 /// `BOATRAMP_POD_NAME`, `BOATRAMP_COMPUTE_RECONCILE_TICK_MS`/`_NET_DEBUG` — stay as direct
5203 /// serve reads and are intentionally NOT mapped into the config, matching today.)
5204 const SERVE_KV: &[(&str, &[&str])] = &[
5205 (
5206 "BOATRAMP_KV_CHECKPOINT_INTERVAL",
5207 &["serve", "kv", "slatedb", "checkpoint_interval"],
5208 ),
5209 (
5210 "BOATRAMP_KV_CLOSE_DEADLINE",
5211 &["serve", "kv", "slatedb", "close_deadline"],
5212 ),
5213 (
5214 "BOATRAMP_KV_GC_INTERVAL",
5215 &["serve", "kv", "slatedb", "gc_interval"],
5216 ),
5217 (
5218 "BOATRAMP_KV_GC_MIN_AGE",
5219 &["serve", "kv", "slatedb", "gc_min_age"],
5220 ),
5221 ("BOATRAMP_KV_SQL_KIND", &["serve", "kv", "sql", "kind"]),
5222 ("BOATRAMP_KV_SQL_PATH", &["serve", "kv", "sql", "path"]),
5223 (
5224 "BOATRAMP_KV_SQL_URL_ENV",
5225 &["serve", "kv", "sql", "url_env"],
5226 ),
5227 (
5228 "BOATRAMP_KV_SQL_POOL_MAX",
5229 &["serve", "kv", "sql", "pool_max"],
5230 ),
5231 ];
5232
5233 /// Insert `value` at the nested `path`, creating intermediate dicts as needed.
5234 fn put(dict: &mut Dict, path: &[&str], value: Value) {
5235 let (last, parents) = path.split_last().expect("path is non-empty");
5236 let mut cursor = dict;
5237 for seg in parents {
5238 let entry = cursor
5239 .entry((*seg).to_string())
5240 .or_insert_with(|| Value::Dict(Tag::Default, Dict::new()));
5241 if !matches!(entry, Value::Dict(..)) {
5242 *entry = Value::Dict(Tag::Default, Dict::new());
5243 }
5244 cursor = match entry {
5245 Value::Dict(_, inner) => inner,
5246 _ => unreachable!("entry was just forced to a Dict"),
5247 };
5248 }
5249 cursor.insert((*last).to_string(), value);
5250 }
5251
5252 /// Emit the right value KIND for `var` (list / enum / plain scalar) at `path`,
5253 /// iff the var is set to a non-empty value.
5254 ///
5255 /// Scalar values are **trimmed**: the legacy `parse_bool`/`parse`/`parse_enum` all did
5256 /// `.trim()`, and figment's `to_bool_lossy` does NOT trim — so without this a templated
5257 /// `BOATRAMP_..._BOOL="true\n"` (fly.toml / k8s block scalar) would fail to coerce
5258 /// instead of parsing `true`. Trimming the string scalars too is harmless (a config
5259 /// value's surrounding whitespace is never meaningful, and `get` already treats a
5260 /// whitespace-only value as unset). A trimmed-to-empty value is dropped (unset).
5261 fn emit(dict: &mut Dict, source: &EnvSource, var: &str, path: &[&str]) {
5262 if LIST_VARS.contains(&var) {
5263 if let Some(items) = source.parse_list(var) {
5264 put(dict, path, Value::from(items));
5265 }
5266 } else if ENUM_VARS.contains(&var) {
5267 if let Some(v) = source.get(var) {
5268 put(dict, path, Value::from(v.trim().to_ascii_lowercase()));
5269 }
5270 } else if let Some(v) = source.get(var) {
5271 let trimmed = v.trim();
5272 if !trimmed.is_empty() {
5273 put(dict, path, Value::from(trimmed.to_string()));
5274 }
5275 }
5276 }
5277
5278 /// `var` with `prefix` stripped, lowercased — the config field name for the
5279 /// section whose env vars are `<prefix><FIELD>` (the inverse of the uppercasing
5280 /// the forgot-a-knob guards assert).
5281 fn field_of(var: &str, prefix: &str) -> String {
5282 var.strip_prefix(prefix)
5283 .expect("var belongs to this section's prefix")
5284 .to_ascii_lowercase()
5285 }
5286
5287 /// Build the `BOATRAMP_*` environment overlay as a figment `Dict`. Infallible
5288 /// (see the module docs); a malformed value is rejected at `extract_lossy`.
5289 pub(crate) fn env_overlay_dict(source: &EnvSource) -> Dict {
5290 let mut d = Dict::new();
5291
5292 // --- serve.* scalars (former Loader-A) + serve.kv.* (former Loader-C) ----
5293 for (var, path) in SERVE_SCALARS.iter().chain(SERVE_KV) {
5294 emit(&mut d, source, var, path);
5295 }
5296
5297 // --- compute (`compute.<field>`) ----------------------------------------
5298 for var in COMPUTE_ENV_VARS {
5299 let field = field_of(var, "BOATRAMP_COMPUTE_");
5300 emit(&mut d, source, var, &["compute", field.as_str()]);
5301 }
5302
5303 // --- security (`security.profile` + `security.overrides.<field>`) -------
5304 for var in SECURITY_ENV_VARS {
5305 if *var == "BOATRAMP_SECURITY_PROFILE" {
5306 emit(&mut d, source, var, &["security", "profile"]);
5307 } else {
5308 let field = field_of(var, "BOATRAMP_SECURITY_");
5309 emit(
5310 &mut d,
5311 source,
5312 var,
5313 &["security", "overrides", field.as_str()],
5314 );
5315 }
5316 }
5317
5318 // --- handlers: sql binding scalars (`handlers.bindings.sql.<field>`) ----
5319 // (`bindings` is dropped from the env name — the P1 rename the alias rule
5320 // reproduces.)
5321 for var in SQL_ENV_VARS {
5322 let field = field_of(var, "BOATRAMP_HANDLERS_SQL_");
5323 emit(
5324 &mut d,
5325 source,
5326 var,
5327 &["handlers", "bindings", "sql", field.as_str()],
5328 );
5329 }
5330
5331 // --- handlers: jwks / concurrency / blob-hedge scalars (`handlers.<f>`) --
5332 for var in JWKS_ENV_VARS
5333 .iter()
5334 .chain(HANDLER_CONCURRENCY_ENV_VARS)
5335 .chain(HANDLER_BLOB_HEDGE_ENV_VARS)
5336 .chain(HANDLER_COLDSTART_ENV_VARS)
5337 {
5338 let field = field_of(var, "BOATRAMP_HANDLERS_");
5339 emit(&mut d, source, var, &["handlers", field.as_str()]);
5340 }
5341
5342 // --- serve.s3_ingress_cloud (`serve` dropped from the env name) ---------
5343 for var in S3_INGRESS_CLOUD_ENV_VARS {
5344 let field = field_of(var, "BOATRAMP_S3_INGRESS_CLOUD_");
5345 emit(
5346 &mut d,
5347 source,
5348 var,
5349 &["serve", "s3_ingress_cloud", field.as_str()],
5350 );
5351 }
5352
5353 // --- secrets (+ nested vault) -------------------------------------------
5354 for var in SECRETS_ENV_VARS {
5355 if let Some(rest) = var.strip_prefix("BOATRAMP_SECRETS_VAULT_") {
5356 emit(
5357 &mut d,
5358 source,
5359 var,
5360 &["secrets", "vault", rest.to_ascii_lowercase().as_str()],
5361 );
5362 } else {
5363 let field = field_of(var, "BOATRAMP_SECRETS_");
5364 emit(&mut d, source, var, &["secrets", field.as_str()]);
5365 }
5366 }
5367
5368 // --- cluster (+ nested mesh) --------------------------------------------
5369 // The overlay always emits a cluster field when set; the `listen`
5370 // requirement (ClusterConfig has no Default) is enforced LOUDLY at extract,
5371 // rather than silently dropped as `apply_env_overrides` did for an env-only
5372 // cluster without a listen. See the plan's parity notes.
5373 for var in CLUSTER_ENV_VARS {
5374 if let Some(rest) = var.strip_prefix("BOATRAMP_CLUSTER_MESH_") {
5375 emit(
5376 &mut d,
5377 source,
5378 var,
5379 &["cluster", "mesh", rest.to_ascii_lowercase().as_str()],
5380 );
5381 } else {
5382 let field = field_of(var, "BOATRAMP_CLUSTER_");
5383 emit(&mut d, source, var, &["cluster", field.as_str()]);
5384 }
5385 }
5386
5387 // --- dynamic maps (P0: the generic Env provider cannot do these) --------
5388 blob_backends_overlay(&mut d, source);
5389 sql_databases_overlay(&mut d, source);
5390 listeners_overlay(&mut d, source);
5391
5392 d
5393 }
5394
5395 /// `[serve.blob_backends.<project>]` — keyed by project, member names scanned
5396 /// from the environment (there is no file to enumerate them). Mirrors the
5397 /// `apply_env_overrides` block, flattening the sealed credential's two public
5398 /// refs under `s3_credential`.
5399 fn blob_backends_overlay(d: &mut Dict, source: &EnvSource) {
5400 for name in source.blob_backend_projects() {
5401 let prefix = format!("{BLOB_BACKEND_ENV_PREFIX}{name}_");
5402 let n = name.as_str();
5403 if let Some(v) = source.get(&format!("{prefix}KIND")) {
5404 put(
5405 d,
5406 &["serve", "blob_backends", n, "blobs"],
5407 Value::from(v.trim().to_ascii_lowercase()),
5408 );
5409 }
5410 for (suffix, field) in [
5411 ("S3_BUCKET", "s3_bucket"),
5412 ("S3_ENDPOINT", "s3_endpoint"),
5413 ("S3_REGION", "s3_region"),
5414 ("S3_PATH_STYLE", "s3_path_style"),
5415 ] {
5416 if let Some(v) = source.get(&format!("{prefix}{suffix}")) {
5417 put(d, &["serve", "blob_backends", n, field], Value::from(v));
5418 }
5419 }
5420 if let Some(v) = source.get(&format!("{prefix}S3_ACCESS_KEY_ID")) {
5421 put(
5422 d,
5423 &[
5424 "serve",
5425 "blob_backends",
5426 name.as_str(),
5427 "s3_credential",
5428 "access_key_id",
5429 ],
5430 Value::from(v),
5431 );
5432 }
5433 if let Some(v) = source.get(&format!("{prefix}S3_SECRET_ACCESS_KEY")) {
5434 put(
5435 d,
5436 &[
5437 "serve",
5438 "blob_backends",
5439 name.as_str(),
5440 "s3_credential",
5441 "secret_access_key",
5442 ],
5443 Value::from(v),
5444 );
5445 }
5446 }
5447 }
5448
5449 /// `handlers.bindings.sql.databases.<name>` — keyed external-DB map. The
5450 /// reserved `DEFAULT` env token maps to the real key `"default"`
5451 /// (`DEFAULT_DB_NAME`); every other name is used verbatim.
5452 fn sql_databases_overlay(d: &mut Dict, source: &EnvSource) {
5453 for name in source.sql_database_names() {
5454 let key = if name == "DEFAULT" {
5455 boatramp_core::project::DEFAULT_DB_NAME.to_string()
5456 } else {
5457 name.clone()
5458 };
5459 let prefix = format!("{SQL_DB_ENV_PREFIX}{name}_");
5460 let k = key.as_str();
5461 // scalar string fields
5462 for (suffix, field) in [
5463 ("KIND", "kind"),
5464 ("URL_ENV", "url_env"),
5465 ("READ_URL_ENV", "read_url_env"),
5466 ("COMPUTE", "compute"),
5467 ("DATABASE", "database"),
5468 ("USER", "user"),
5469 ("PASSWORD_ENV", "password_env"),
5470 ("POOL_MAX", "pool_max"),
5471 ("READ_ONLY", "read_only"),
5472 ("ALLOW_PREVIEW", "allow_preview"),
5473 ("CONNECT_TIMEOUT_SECS", "connect_timeout_secs"),
5474 ("IMAGE", "image"),
5475 ("VOLUME_SIZE_MIB", "volume_size_mib"),
5476 ("STARTUP_GRACE_SECS", "startup_grace_secs"),
5477 ("RLS_SESSION", "rls_session"),
5478 ("TENANT_GUC", "tenant_guc"),
5479 ("SESSION_GUC", "session_guc"),
5480 ("TENANT_ALL_MARKER", "tenant_all_marker"),
5481 ] {
5482 if let Some(v) = source.get(&format!("{prefix}{suffix}")) {
5483 put(
5484 d,
5485 &["handlers", "bindings", "sql", "databases", k, field],
5486 Value::from(v),
5487 );
5488 }
5489 }
5490 // enum fields (lowercased token)
5491 for (suffix, field) in [("TENANT", "tenant"), ("TENANT_SCOPE", "tenant_scope")] {
5492 if let Some(v) = source.get(&format!("{prefix}{suffix}")) {
5493 put(
5494 d,
5495 &["handlers", "bindings", "sql", "databases", k, field],
5496 Value::from(v.trim().to_ascii_lowercase()),
5497 );
5498 }
5499 }
5500 }
5501 }
5502
5503 /// `[serve.listeners.<name>]` — keyed inbound-TCP listeners. Only the SCALAR +
5504 /// `imports` (list) fields are env-settable; structured fields (tenancy/env/tls)
5505 /// are file-only.
5506 fn listeners_overlay(d: &mut Dict, source: &EnvSource) {
5507 for name in source.listener_names() {
5508 let prefix = format!("{LISTENER_ENV_PREFIX}{name}_");
5509 let n = name.as_str();
5510 for (suffix, field) in [
5511 ("BIND", "bind"),
5512 ("COMPONENT", "component"),
5513 ("PROJECT", "project"),
5514 ("SITE", "site"),
5515 ("MAX_CONNS", "max_conns"),
5516 ("IDLE_TIMEOUT_MS", "idle_timeout_ms"),
5517 ("MAX_CONN_DURATION_MS", "max_conn_duration_ms"),
5518 ] {
5519 if let Some(v) = source.get(&format!("{prefix}{suffix}")) {
5520 put(d, &["serve", "listeners", n, field], Value::from(v));
5521 }
5522 }
5523 if let Some(items) = source.parse_list(&format!("{prefix}IMPORTS")) {
5524 put(d, &["serve", "listeners", n, "imports"], Value::from(items));
5525 }
5526 }
5527 }
5528
5529 /// A figment [`Provider`] carrying the `BOATRAMP_*` environment overlay. Merged
5530 /// into the pipeline ABOVE the file layer (env overrides file) and BELOW the
5531 /// explicit-flag layer.
5532 pub(crate) struct BoatrampEnv(Dict);
5533
5534 impl BoatrampEnv {
5535 pub(crate) fn new(source: &EnvSource) -> Self {
5536 Self(env_overlay_dict(source))
5537 }
5538 }
5539
5540 impl Provider for BoatrampEnv {
5541 fn metadata(&self) -> Metadata {
5542 Metadata::named("BOATRAMP_* environment")
5543 }
5544
5545 fn data(&self) -> Result<FigMap<Profile, Dict>, Error> {
5546 let mut map = FigMap::new();
5547 map.insert(Profile::Default, self.0.clone());
5548 Ok(map)
5549 }
5550 }
5551
5552 /// A figment [`Provider`] wrapping a prebuilt `Dict` at the default profile — used
5553 /// for the base-seed, file, and flag layers.
5554 struct DictLayer {
5555 name: &'static str,
5556 dict: Dict,
5557 }
5558
5559 impl Provider for DictLayer {
5560 fn metadata(&self) -> Metadata {
5561 Metadata::named(self.name)
5562 }
5563 fn data(&self) -> Result<FigMap<Profile, Dict>, Error> {
5564 let mut map = FigMap::new();
5565 map.insert(Profile::Default, self.dict.clone());
5566 Ok(map)
5567 }
5568 }
5569
5570 /// Recursively drop `Empty` (figment's serialized `None`) entries from a dict, so the
5571 /// file layer never clobbers a lower layer's value with a null (figment merge replaces
5572 /// a dict with a non-dict). This is what lets the base-seed layer (decision 2) survive
5573 /// under a file that simply omits the section.
5574 fn prune_empty(dict: Dict) -> Dict {
5575 dict.into_iter()
5576 .filter_map(|(k, v)| match v {
5577 Value::Empty(..) => None,
5578 Value::Dict(t, inner) => Some((k, Value::Dict(t, prune_empty(inner)))),
5579 other => Some((k, other)),
5580 })
5581 .collect()
5582 }
5583
5584 /// Serialize `value` to a figment `Dict` via figment's OWN serializer (decision 1 — no
5585 /// serde_json bridge). The error is boxed because `figment::Error` is large
5586 /// (`clippy::result_large_err`).
5587 fn to_dict(value: &impl Serialize) -> Result<Dict, Box<Error>> {
5588 let mut data = Serialized::defaults(value).data().map_err(Box::new)?;
5589 Ok(data
5590 .remove(&Profile::Default)
5591 .or_else(|| data.into_values().next())
5592 .unwrap_or_default())
5593 }
5594
5595 /// The parsed config file as a pruned figment layer (decision 1). Absent `Option`
5596 /// sections serialize to `Empty` and are pruned so they don't clobber the base-seed.
5597 fn file_layer(cfg: &ServerConfig) -> Result<Dict, Box<Error>> {
5598 Ok(prune_empty(to_dict(cfg)?))
5599 }
5600
5601 /// Decision 2: the two `deny_unknown_fields` sub-structs with a REQUIRED field
5602 /// (`VaultSecretsConfig` has `addr`/`key`; `S3CredentialConfig` has
5603 /// `access_key_id`/`secret_access_key`) cannot deserialize from a partial env sub-dict.
5604 /// Seed their COMPLETE defaults in a layer BELOW the file, so file + env field overrides
5605 /// layer on top without a partial ever reaching extract — and WITHOUT clobbering a
5606 /// file-provided field (the file layer, merged above this, wins per-key; env wins above
5607 /// that). Seeded only when env actually references the sub-struct (so an unset section
5608 /// stays absent, matching `apply_env_overrides`' lazy materialization).
5609 fn base_seed(source: &EnvSource) -> Result<Dict, Box<Error>> {
5610 let mut d = Dict::new();
5611 if source.any(SECRETS_VAULT_ENV_VARS) {
5612 put(
5613 &mut d,
5614 &["secrets", "vault"],
5615 Value::Dict(Tag::Default, to_dict(&VaultSecretsConfig::default())?),
5616 );
5617 }
5618 for name in source.blob_backend_projects() {
5619 let prefix = format!("{BLOB_BACKEND_ENV_PREFIX}{name}_");
5620 let has_cred = source.get(&format!("{prefix}S3_ACCESS_KEY_ID")).is_some()
5621 || source
5622 .get(&format!("{prefix}S3_SECRET_ACCESS_KEY"))
5623 .is_some();
5624 if has_cred {
5625 put(
5626 &mut d,
5627 &["serve", "blob_backends", name.as_str(), "s3_credential"],
5628 Value::Dict(Tag::Default, to_dict(&S3CredentialConfig::default())?),
5629 );
5630 }
5631 }
5632 Ok(d)
5633 }
5634
5635 /// The single layered config resolution — `base-seed → file → env → explicit flags` —
5636 /// used by `ServerConfig::load` (serve + every offline op). `flags` is the caller's
5637 /// explicit-CLI layer (empty for the offline ops; the serve binary passes its
5638 /// `ValueSource::CommandLine` args, which is what keeps a defaulted `--blobs fs` from
5639 /// clobbering file/env — risk P3#14). Replaces `apply_env_overrides` + the serve clap
5640 /// `#[arg(env)]` + ad-hoc `std::env::var` loaders (the parity battery asserts the SAME
5641 /// result as `apply_env_overrides` across the whole surface).
5642 pub(crate) fn load_with_figment(
5643 path: &Path,
5644 override_: Option<ConfigFormat>,
5645 source: &EnvSource,
5646 flags: Dict,
5647 ) -> Result<ServerConfig, ConfigError> {
5648 // File: parsed with the existing RON/JSON decoder + its own validation (a file-only
5649 // config still fails at parse exactly as today). Decision 3 re-validates the MERGED
5650 // result below.
5651 let fmt = resolve_format(path, override_);
5652 let file_cfg = match std::fs::read_to_string(path) {
5653 Ok(contents) => ServerConfig::parse_with_format(&contents, fmt).map_err(|err| {
5654 ConfigError::File {
5655 path: path.display().to_string(),
5656 source: Box::new(err),
5657 }
5658 })?,
5659 Err(err) if err.kind() == std::io::ErrorKind::NotFound => ServerConfig::default(),
5660 Err(err) => return Err(err.into()),
5661 };
5662
5663 let base = base_seed(source).map_err(|e| ConfigError::Resolve(e.to_string()))?;
5664 let file = file_layer(&file_cfg).map_err(|e| ConfigError::Resolve(e.to_string()))?;
5665
5666 // Decision 4: a `[cluster]` missing its required `listen` has no `ClusterConfig`
5667 // default, so extract fails LOUDLY here (we do not preserve the old silent-drop).
5668 let cfg: ServerConfig = Figment::new()
5669 .merge(DictLayer {
5670 name: "base defaults",
5671 dict: base,
5672 })
5673 .merge(DictLayer {
5674 name: "config file",
5675 dict: file,
5676 })
5677 .merge(BoatrampEnv::new(source))
5678 .merge(DictLayer {
5679 name: "cli flags",
5680 dict: flags,
5681 })
5682 .extract_lossy()
5683 .map_err(|e| ConfigError::Resolve(e.to_string()))?;
5684
5685 // Decision 3: run the fail-closed validators on the fully merged (file + env + flags)
5686 // result — stricter than `apply_env_overrides`, which only re-validated the db-name /
5687 // blob-project / listener maps (this also validates a file-introduced entry).
5688 cfg.validate_sql_db_names()?;
5689 cfg.validate_blob_backend_projects()?;
5690 cfg.validate_listeners()?;
5691 Ok(cfg)
5692 }
5693
5694 /// Resolve the `BOATRAMP_*` env overlay OVER an already-parsed base config (the base
5695 /// standing in for the file layer): `base-seed → base → env`. Equivalent to
5696 /// [`load_with_figment`] with the file already read into `base` and no flags. Test-only —
5697 /// it backs the `#[cfg(test)]` `apply_env_overrides` adapter so the pre-figment env tests
5698 /// (which layer env over a parsed `boatramp.cfg` struct) run THROUGH the real pipeline.
5699 #[cfg(test)]
5700 pub(crate) fn resolve_env_over(
5701 base: &ServerConfig,
5702 source: &EnvSource,
5703 ) -> Result<ServerConfig, ConfigError> {
5704 let seed = base_seed(source).map_err(|e| ConfigError::Resolve(e.to_string()))?;
5705 let file = file_layer(base).map_err(|e| ConfigError::Resolve(e.to_string()))?;
5706 let cfg: ServerConfig = Figment::new()
5707 .merge(DictLayer {
5708 name: "base defaults",
5709 dict: seed,
5710 })
5711 .merge(DictLayer {
5712 name: "base config",
5713 dict: file,
5714 })
5715 .merge(BoatrampEnv::new(source))
5716 .extract_lossy()
5717 .map_err(|e| ConfigError::Resolve(e.to_string()))?;
5718 cfg.validate_sql_db_names()?;
5719 cfg.validate_blob_backend_projects()?;
5720 cfg.validate_listeners()?;
5721 Ok(cfg)
5722 }
5723
5724 /// Build the explicit-CLI-**flag** figment layer from a `{BOATRAMP_<NAME>: value}` map
5725 /// of the args the operator set on the command line. Reuses [`env_overlay_dict`] (a
5726 /// flag's name→path mapping is the SAME as its env var's), so only recognised config
5727 /// knobs produce entries and the runtime/selector flags (`--tls`, cluster-actions, …)
5728 /// are ignored. This dict is merged as the TOP layer (above the Process env), so an
5729 /// explicit flag wins over env + file — matching clap's `flag > env` precedence today.
5730 pub(crate) fn flag_overlay_dict(cli_flags: &BTreeMap<String, String>) -> Dict {
5731 env_overlay_dict(&EnvSource::Map(cli_flags.clone()))
5732 }
5733
5734 /// Config-tree field names whose VALUES are raw secret material — redacted by
5735 /// [`dump_redacted`]. Secret *references* and env-var-NAME fields (`token_env`,
5736 /// `url_env`, `pin_env`, `password_env`, `access_token_env`) are NOT secrets and are
5737 /// left intact; only the fields that can hold raw key/secret bytes are masked.
5738 const SECRET_FIELDS: &[&str] = &[
5739 "auth_root_private_key",
5740 "bootstrap_secret",
5741 "azure_access_key",
5742 "secret_access_key",
5743 // The external token signer's in-process root key (`[serve.signer] Local { private_key }`)
5744 // is raw key material in the config — mask it (Security MEDIUM).
5745 "private_key",
5746 // `[cluster] join_token` is a secret REFERENCE by convention (`env:`/`path:`), but the
5747 // schema allows a raw-inlined token, so mask it to be safe (Security MEDIUM).
5748 "join_token",
5749 ];
5750
5751 fn redact(value: &mut serde_json::Value) {
5752 match value {
5753 serde_json::Value::Object(map) => {
5754 for (k, v) in map.iter_mut() {
5755 if SECRET_FIELDS.contains(&k.as_str()) && !v.is_null() {
5756 *v = serde_json::Value::String("<redacted>".to_string());
5757 } else {
5758 redact(v);
5759 }
5760 }
5761 }
5762 serde_json::Value::Array(items) => items.iter_mut().for_each(redact),
5763 _ => {}
5764 }
5765 }
5766
5767 /// Serialize the resolved [`ServerConfig`] for `boatramp config dump`, REDACTING the
5768 /// secret-bearing fields ([`SECRET_FIELDS`]). The config is `Serialize` for the figment
5769 /// file layer, which would otherwise expose the control-plane root key / bootstrap
5770 /// secret / azure access key / sealed-cred ref in a dump. Pretty JSON (also a valid
5771 /// config input).
5772 pub(crate) fn dump_redacted(cfg: &ServerConfig) -> Result<String, ConfigError> {
5773 let mut v = serde_json::to_value(cfg).map_err(ConfigError::Json)?;
5774 redact(&mut v);
5775 serde_json::to_string_pretty(&v).map_err(ConfigError::Json)
5776 }
5777
5778 /// Resolve a [`ServerConfig`] from the environment overlay ALONE (no file, no
5779 /// flags) — a thin test helper for the sections that deserialize from a partial env
5780 /// dict. Sections needing the base-seed (decision 2) are tested through
5781 /// [`load_with_figment`] instead.
5782 #[cfg(test)]
5783 pub(crate) fn resolve_from_env(source: &EnvSource) -> Result<ServerConfig, Box<Error>> {
5784 Figment::new()
5785 .merge(BoatrampEnv::new(source))
5786 .extract_lossy()
5787 .map_err(Box::new)
5788 }
5789
5790 #[cfg(test)]
5791 mod tests {
5792 use super::*;
5793
5794 fn map(pairs: &[(&str, &str)]) -> EnvSource {
5795 EnvSource::Map(
5796 pairs
5797 .iter()
5798 .map(|(k, v)| ((*k).to_string(), (*v).to_string()))
5799 .collect(),
5800 )
5801 }
5802
5803 /// The keystone drift guard: EVERY fixed `BOATRAMP_*` var the old loader
5804 /// (`apply_env_overrides`) honors must also be produced by the new overlay.
5805 /// Because the overlay iterates the same `*_ENV_VARS` const tables, this
5806 /// holds by construction — the test is the regression guard that a future
5807 /// edit can't quietly drop a section's table from the overlay loop, and
5808 /// that no const var escapes classification. (The forgot-a-knob guards in
5809 /// the parent module already prove every struct FIELD has a const-table
5810 /// var; together they chain field → var → overlay entry.)
5811 #[test]
5812 fn overlay_honors_every_loader_b_fixed_var() {
5813 let all: Vec<&str> = COMPUTE_ENV_VARS
5814 .iter()
5815 .chain(SECURITY_ENV_VARS)
5816 .chain(SQL_ENV_VARS)
5817 .chain(JWKS_ENV_VARS)
5818 .chain(HANDLER_CONCURRENCY_ENV_VARS)
5819 .chain(HANDLER_BLOB_HEDGE_ENV_VARS)
5820 .chain(HANDLER_COLDSTART_ENV_VARS)
5821 .chain(S3_INGRESS_CLOUD_ENV_VARS)
5822 .chain(SECRETS_ENV_VARS)
5823 .chain(CLUSTER_ENV_VARS)
5824 .copied()
5825 .collect();
5826 let mut unhandled = Vec::new();
5827 for var in all {
5828 // A socket-addr-ish sample keeps the value non-empty; the overlay
5829 // emits strings (no parse), so any non-empty value exercises it.
5830 let dict = env_overlay_dict(&map(&[(var, "x")]));
5831 if dict.is_empty() {
5832 unhandled.push(var);
5833 }
5834 }
5835 assert!(
5836 unhandled.is_empty(),
5837 "overlay produced nothing for these registered Loader-B vars \
5838 (a drift gap — wire them into env_overlay_dict): {unhandled:?}"
5839 );
5840 }
5841
5842 /// P4: the overlay's bool spellings match `parse_bool` end-to-end, via
5843 /// figment's `to_bool_lossy` at `extract_lossy`.
5844 #[test]
5845 fn bool_spellings_round_trip_like_parse_bool() {
5846 for (raw, expect) in [
5847 ("on", true),
5848 ("1", true),
5849 ("yes", true),
5850 ("TRUE", true),
5851 ("off", false),
5852 ("0", false),
5853 ("no", false),
5854 ] {
5855 let cfg = resolve_from_env(&map(&[(
5856 "BOATRAMP_SECURITY_ALLOW_SHARED_KERNEL_COMPUTE",
5857 raw,
5858 )]))
5859 .expect("extract");
5860 assert_eq!(
5861 cfg.security
5862 .expect("security materialised")
5863 .overrides
5864 .allow_shared_kernel_compute,
5865 Some(expect),
5866 "bool spelling {raw:?} must parse like parse_bool"
5867 );
5868 }
5869 }
5870
5871 /// Empty env value = UNSET (never clobbers to `""`), matching `EnvSource::get`.
5872 #[test]
5873 fn empty_value_is_unset() {
5874 let dict = env_overlay_dict(&map(&[("BOATRAMP_S3_BUCKET", "")]));
5875 assert!(dict.is_empty(), "an empty value must be treated as unset");
5876 }
5877
5878 /// `[compute]` resolves from env across str / int / list / enum / bool field kinds
5879 /// (`ComputeConfig` is `#[serde(default)]`, so a partial env dict fills the rest).
5880 #[test]
5881 fn compute_resolves_from_env() {
5882 let c = resolve_from_env(&map(&[
5883 ("BOATRAMP_COMPUTE_VCPUS", "4"),
5884 ("BOATRAMP_COMPUTE_MEM_MIB", "2048"),
5885 ("BOATRAMP_COMPUTE_REGION", "ams"),
5886 (
5887 "BOATRAMP_COMPUTE_KERNEL_SIGNING_PUBKEYS",
5888 "es256:aa, es256:bb",
5889 ),
5890 ("BOATRAMP_COMPUTE_MANAGED_DB_PRIVILEGE", "rootless"),
5891 ("BOATRAMP_COMPUTE_INTERNAL_DNS", "on"),
5892 ]))
5893 .expect("figment extract")
5894 .compute
5895 .expect("compute materialised from env");
5896 assert_eq!(c.vcpus, 4);
5897 assert_eq!(c.mem_mib, 2048);
5898 assert_eq!(c.region.as_deref(), Some("ams"));
5899 assert_eq!(
5900 c.kernel_signing_pubkeys,
5901 vec!["es256:aa".to_string(), "es256:bb".to_string()],
5902 "comma-list trimmed + split"
5903 );
5904 assert_eq!(c.managed_db_privilege, ManagedDbPrivilege::Rootless);
5905 assert!(c.internal_dns, "bool coerced from \"on\"");
5906 }
5907
5908 /// The serve S3 scalars (the construens finalize concern) resolve from env —
5909 /// `ServeConfig` is `#[serde(default)]`. Asserts ALL FIVE top-level `[serve]` S3-backend
5910 /// levers (`blobs`/`s3_bucket`/`s3_endpoint`/`s3_region`/`s3_path_style`) resolve — the
5911 /// enum, three strings, and the bool. This resolves through the pipeline with NO flag layer
5912 /// (`resolve_from_env`), i.e. exactly the way the OFFLINE ops (`migrate`/`blob rehome`) see
5913 /// the object store from the environment — the parity that v0.34.0's hand-added Loader-B
5914 /// `SERVE_S3_BACKEND_ENV_VARS` arm provided and the figment overlay (`SERVE_SCALARS`) now
5915 /// subsumes. So a file-less fleet (the Tigris-only construens deployment) needs no
5916 /// `boatramp.cfg` for its object store.
5917 #[test]
5918 fn serve_s3_scalars_extract() {
5919 let cfg = resolve_from_env(&map(&[
5920 ("BOATRAMP_BLOBS", "s3"),
5921 ("BOATRAMP_S3_BUCKET", "construens-blobs"),
5922 ("BOATRAMP_S3_ENDPOINT", "https://fly.storage.tigris.dev"),
5923 ("BOATRAMP_S3_REGION", "auto"),
5924 ("BOATRAMP_S3_PATH_STYLE", "true"),
5925 ]))
5926 .expect("extract");
5927 let serve = cfg.serve.expect("serve materialised from env");
5928 assert_eq!(serve.blobs, Some(crate::backends::BlobBackend::S3));
5929 assert_eq!(serve.s3_bucket.as_deref(), Some("construens-blobs"));
5930 assert_eq!(
5931 serve.s3_endpoint.as_deref(),
5932 Some("https://fly.storage.tigris.dev")
5933 );
5934 assert_eq!(serve.s3_region.as_deref(), Some("auto"));
5935 assert!(serve.s3_path_style, "s3_path_style coerced from \"true\"");
5936 }
5937
5938 /// P0#2: the dynamic blob-backends map populates at the right nested path,
5939 /// including the flattened sealed-credential public ref.
5940 #[test]
5941 fn blob_backends_dynamic_map_shape() {
5942 let dict = env_overlay_dict(&map(&[
5943 ("BOATRAMP_SERVE_BLOB_BACKEND_myproj_KIND", "s3"),
5944 ("BOATRAMP_SERVE_BLOB_BACKEND_myproj_S3_BUCKET", "p-blobs"),
5945 (
5946 "BOATRAMP_SERVE_BLOB_BACKEND_myproj_S3_ACCESS_KEY_ID",
5947 "AKIA",
5948 ),
5949 ]));
5950 let serve = match dict.get("serve") {
5951 Some(Value::Dict(_, s)) => s,
5952 _ => panic!("serve dict present"),
5953 };
5954 let backends = match serve.get("blob_backends") {
5955 Some(Value::Dict(_, b)) => b,
5956 _ => panic!("blob_backends dict present"),
5957 };
5958 let myproj = match backends.get("myproj") {
5959 Some(Value::Dict(_, p)) => p,
5960 _ => panic!("myproj backend present"),
5961 };
5962 assert!(matches!(myproj.get("blobs"), Some(Value::String(_, s)) if s == "s3"));
5963 assert!(matches!(myproj.get("s3_bucket"), Some(Value::String(_, s)) if s == "p-blobs"));
5964 match myproj.get("s3_credential") {
5965 Some(Value::Dict(_, cred)) => assert!(
5966 matches!(cred.get("access_key_id"), Some(Value::String(_, s)) if s == "AKIA")
5967 ),
5968 _ => panic!("s3_credential flattened under the backend"),
5969 }
5970 }
5971
5972 /// P0#1: the SQL `databases` map resolves the reserved `DEFAULT` token to
5973 /// the real key `"default"`.
5974 #[test]
5975 fn sql_db_default_token_maps_to_default_key() {
5976 let dict = env_overlay_dict(&map(&[(
5977 "BOATRAMP_HANDLERS_SQL_DB_DEFAULT_KIND",
5978 "postgres",
5979 )]));
5980 // handlers.bindings.sql.databases.default.kind == "postgres"
5981 let mut cur = &dict;
5982 for seg in ["handlers", "bindings", "sql", "databases", "default"] {
5983 cur = match cur.get(seg) {
5984 Some(Value::Dict(_, inner)) => inner,
5985 _ => panic!("missing dict segment {seg}"),
5986 };
5987 }
5988 assert!(matches!(cur.get("kind"), Some(Value::String(_, s)) if s == "postgres"));
5989 }
5990
5991 // The figment pipeline resolves an offline op's config (base-seed + env, no file, no
5992 // flags) — `figment_env` — used by the direct section/serve tests below. (The old
5993 // full-surface parity battery, which compared this to `apply_env_overrides`, retired
5994 // with Loader B; its equivalence was proven green at the cutover, and the direct
5995 // per-section tests — here + the `env_wires_*` tests in `config::tests`, which now run
5996 // THROUGH the pipeline via the test adapter — are the spec going forward.)
5997
5998 /// The figment pipeline an offline op takes: base-seed + env, no file, no flags.
5999 fn figment_env(pairs: &[(&str, &str)]) -> ServerConfig {
6000 load_with_figment(
6001 std::path::Path::new("/nonexistent/boatramp.cfg"),
6002 None,
6003 &map(pairs),
6004 Dict::new(),
6005 )
6006 .expect("figment load_with_figment")
6007 }
6008
6009 // --- serve.* scalars + serve.kv.* (former Loader A / C) -------------------
6010 // The pipeline resolves these (the serve-only clap `#[arg(env)]` + ad-hoc env reads
6011 // the rewrite subsumed) into their ServeConfig fields, asserted directly below.
6012
6013 /// Env-only figment resolution via the full pipeline (base-seed + env), so the
6014 /// serve-scalar secrets' deny-unknown neighbours aren't an issue (serve is
6015 /// `#[serde(default)]`).
6016 fn serve_from_env(pairs: &[(&str, &str)]) -> ServeConfig {
6017 figment_env(pairs)
6018 .serve
6019 .expect("serve materialised from env")
6020 }
6021
6022 #[test]
6023 fn serve_scalars_full_extract() {
6024 let s = serve_from_env(&[
6025 ("BOATRAMP_ADDR", "0.0.0.0:8080"),
6026 ("BOATRAMP_DATA_DIR", "/data"),
6027 ("BOATRAMP_BLOBS", "s3"),
6028 ("BOATRAMP_S3_BUCKET", "b"),
6029 ("BOATRAMP_S3_PATH_STYLE", "true"),
6030 ("BOATRAMP_GCS_BUCKET", "gb"),
6031 ("BOATRAMP_GCS_ENDPOINT", "http://gcs"),
6032 ("BOATRAMP_GCS_ANONYMOUS", "yes"),
6033 ("BOATRAMP_AZURE_ACCOUNT", "acct"),
6034 ("BOATRAMP_AZURE_CONTAINER", "cont"),
6035 ("BOATRAMP_AZURE_ACCESS_KEY", "secret-key"),
6036 ("BOATRAMP_AZURE_EMULATOR", "true"),
6037 ("BOATRAMP_AUTH_ROOT_PRIVATE_KEY", "deadbeef"),
6038 ("BOATRAMP_AUTH_ROOT_PUBLIC_KEY", "cafe"),
6039 ("BOATRAMP_BOOTSTRAP_SECRET", "boot"),
6040 ("BOATRAMP_MAX_UPLOAD_BYTES", "1048576"),
6041 ("BOATRAMP_UPLOAD_IDLE_TIMEOUT", "30"),
6042 ("BOATRAMP_MAX_CONCURRENT_UPLOADS", "16"),
6043 ("BOATRAMP_HTTP_REDIRECT_ADDR", "0.0.0.0:80"),
6044 ("BOATRAMP_DEFAULT_SITE", "construens"),
6045 ("BOATRAMP_POP_ORIGIN", "https://cp.example.com"),
6046 ("BOATRAMP_PROTECT_PREVIEWS", "true"),
6047 ("BOATRAMP_CLUSTER_RATE_LIMIT", "true"),
6048 ("BOATRAMP_SHARED_CACHE_COHERENCE", "true"),
6049 ]);
6050 assert_eq!(s.addr, Some("0.0.0.0:8080".parse().unwrap()));
6051 assert_eq!(s.data_dir.as_deref(), Some(std::path::Path::new("/data")));
6052 assert!(matches!(s.blobs, Some(crate::backends::BlobBackend::S3)));
6053 assert_eq!(s.s3_bucket.as_deref(), Some("b"));
6054 assert!(s.s3_path_style);
6055 assert_eq!(s.gcs_bucket.as_deref(), Some("gb"));
6056 assert!(s.gcs_anonymous, "GCS anonymous coerced from \"yes\"");
6057 assert_eq!(s.azure_account.as_deref(), Some("acct"));
6058 assert_eq!(s.azure_access_key.as_deref(), Some("secret-key"));
6059 assert!(s.azure_emulator);
6060 assert_eq!(s.auth_root_private_key.as_deref(), Some("deadbeef"));
6061 assert_eq!(s.auth_root_public_key.as_deref(), Some("cafe"));
6062 assert_eq!(s.bootstrap_secret.as_deref(), Some("boot"));
6063 assert_eq!(s.max_upload_bytes, Some(1_048_576));
6064 // The field-name mismatch: env UPLOAD_IDLE_TIMEOUT → field upload_idle_timeout_secs.
6065 assert_eq!(s.upload_idle_timeout_secs, Some(30));
6066 assert_eq!(s.max_concurrent_uploads, Some(16));
6067 assert_eq!(s.http_redirect_addr, Some("0.0.0.0:80".parse().unwrap()));
6068 assert_eq!(s.default_site.as_deref(), Some("construens"));
6069 assert_eq!(s.pop_origin.as_deref(), Some("https://cp.example.com"));
6070 assert!(s.protect_previews);
6071 assert!(s.cluster_rate_limit);
6072 assert!(s.shared_cache_coherence);
6073 }
6074
6075 #[test]
6076 fn serve_kv_knobs_full_extract() {
6077 let s = serve_from_env(&[
6078 ("BOATRAMP_KV_CHECKPOINT_INTERVAL", "0"),
6079 ("BOATRAMP_KV_CLOSE_DEADLINE", "30"),
6080 ("BOATRAMP_KV_GC_INTERVAL", "600"),
6081 ("BOATRAMP_KV_GC_MIN_AGE", "3600"),
6082 ("BOATRAMP_KV_SQL_KIND", "sqlite"),
6083 ("BOATRAMP_KV_SQL_PATH", "/data/kv.db"),
6084 ("BOATRAMP_KV_SQL_URL_ENV", "KV_URL"),
6085 ("BOATRAMP_KV_SQL_POOL_MAX", "8"),
6086 ]);
6087 let kv = s.kv.expect("serve.kv materialised");
6088 // `0` round-trips as Some(0) (the meaningful "disable cadence" value — KvConfig
6089 // maps Some(0) → None at resolve time, preserving Loader-C semantics). Checked on
6090 // the resolver BEFORE moving the sub-structs out.
6091 assert_eq!(
6092 kv.checkpoint_interval(),
6093 None,
6094 "Some(0) disables the cadence"
6095 );
6096 let slate = kv.slatedb.clone().expect("serve.kv.slatedb materialised");
6097 assert_eq!(slate.checkpoint_interval, Some(0));
6098 assert_eq!(slate.close_deadline, Some(30));
6099 assert_eq!(slate.gc_interval, Some(600));
6100 assert_eq!(slate.gc_min_age, Some(3600));
6101 let sql = kv.sql.expect("serve.kv.sql materialised");
6102 assert_eq!(sql.kind, "sqlite");
6103 assert_eq!(sql.path.as_deref(), Some("/data/kv.db"));
6104 assert_eq!(sql.url_env.as_deref(), Some("KV_URL"));
6105 assert_eq!(sql.pool_max, Some(8));
6106 }
6107
6108 /// Drift guard for the serve surface: every SERVE_SCALARS + SERVE_KV var produces
6109 /// an overlay entry (the Loader-A/C analog of `overlay_honors_every_loader_b_fixed_var`).
6110 #[test]
6111 fn overlay_honors_every_serve_var() {
6112 let mut unhandled = Vec::new();
6113 for (var, _) in SERVE_SCALARS.iter().chain(SERVE_KV) {
6114 if env_overlay_dict(&map(&[(var, "x")])).is_empty() {
6115 unhandled.push(*var);
6116 }
6117 }
6118 assert!(
6119 unhandled.is_empty(),
6120 "overlay produced nothing for these serve vars: {unhandled:?}"
6121 );
6122 }
6123
6124 // --- the flag layer: precedence + the config dump redaction ---------------
6125
6126 /// `flag > env > file` precedence (matching clap's `flag > env` + the file fallback),
6127 /// resolved through the full pipeline.
6128 #[test]
6129 fn flag_env_file_precedence() {
6130 let path = std::env::temp_dir().join(format!(
6131 "brtest-figment-{}-{:?}.cfg",
6132 std::process::id(),
6133 std::thread::current().id()
6134 ));
6135 std::fs::write(
6136 &path,
6137 r#"( serve: ( s3_bucket: "from-file", s3_region: "file-region", s3_endpoint: "file-endpoint" ) )"#,
6138 )
6139 .unwrap();
6140
6141 let env = map(&[
6142 ("BOATRAMP_S3_BUCKET", "from-env"),
6143 ("BOATRAMP_S3_ENDPOINT", "from-env-endpoint"),
6144 ]);
6145 let flags: BTreeMap<String, String> =
6146 [("BOATRAMP_S3_BUCKET".to_string(), "from-flag".to_string())]
6147 .into_iter()
6148 .collect();
6149 let cfg =
6150 load_with_figment(&path, None, &env, flag_overlay_dict(&flags)).expect("resolve");
6151 let serve = cfg.serve.expect("serve");
6152 assert_eq!(
6153 serve.s3_bucket.as_deref(),
6154 Some("from-flag"),
6155 "flag beats env+file"
6156 );
6157 assert_eq!(
6158 serve.s3_endpoint.as_deref(),
6159 Some("from-env-endpoint"),
6160 "env beats file when no flag"
6161 );
6162 assert_eq!(
6163 serve.s3_region.as_deref(),
6164 Some("file-region"),
6165 "file survives when neither env nor flag set it"
6166 );
6167 std::fs::remove_file(&path).ok();
6168 }
6169
6170 /// `config dump` must redact the raw-secret fields (the control-plane root key,
6171 /// bootstrap secret, azure access key, sealed-cred ref) — never emit their values.
6172 #[test]
6173 fn dump_redacts_secrets() {
6174 let cfg = figment_env(&[
6175 ("BOATRAMP_AUTH_ROOT_PRIVATE_KEY", "deadbeefsecret"),
6176 ("BOATRAMP_BOOTSTRAP_SECRET", "topsecretboot"),
6177 ("BOATRAMP_AZURE_ACCESS_KEY", "azuresecretkey"),
6178 ("BOATRAMP_DEFAULT_SITE", "construens"),
6179 ]);
6180 let dump = dump_redacted(&cfg).expect("dump");
6181 for leaked in ["deadbeefsecret", "topsecretboot", "azuresecretkey"] {
6182 assert!(
6183 !dump.contains(leaked),
6184 "config dump leaked a secret value: {leaked}\n{dump}"
6185 );
6186 }
6187 assert!(dump.contains("<redacted>"), "secrets shown as <redacted>");
6188 // A non-secret field is still shown in full.
6189 assert!(dump.contains("construens"), "non-secret values are shown");
6190 }
6191
6192 /// Security MEDIUM: the external signer's in-process `private_key` and a raw-inlined
6193 /// `cluster.join_token` must be redacted in a dump (the config is `Serialize`, so a raw
6194 /// dump would otherwise print the signing key / join secret in cleartext).
6195 #[test]
6196 fn dump_redacts_signer_key_and_join_token() {
6197 let file = r#"(
6198 serve: ( signer: Local( private_key: "SIGNERPRIVKEYSECRET" ) ),
6199 cluster: ( listen: "10.0.0.2:7000", join_token: "RAWJOINTOKENSECRET" ),
6200 )"#;
6201 let cfg = ServerConfig::parse_with_format(file, ConfigFormat::Ron).expect("parse");
6202 let dump = cfg.dump_redacted().expect("dump");
6203 assert!(
6204 !dump.contains("SIGNERPRIVKEYSECRET"),
6205 "signer private_key leaked:\n{dump}"
6206 );
6207 assert!(
6208 !dump.contains("RAWJOINTOKENSECRET"),
6209 "cluster join_token leaked:\n{dump}"
6210 );
6211 assert!(dump.contains("<redacted>"));
6212 }
6213
6214 /// Security LOW (bool trim): a templated env value with trailing whitespace
6215 /// (`"true\n"` from a fly.toml / k8s block scalar) must still coerce — the overlay
6216 /// trims scalar values so figment's non-trimming `to_bool_lossy` sees `true`. Also
6217 /// covers an enum with surrounding whitespace.
6218 #[test]
6219 fn trailing_whitespace_on_bool_and_enum_still_parses() {
6220 let cfg = resolve_from_env(&map(&[
6221 ("BOATRAMP_SECURITY_REQUIRE_TENANCY_DECLARATION", "true\n"),
6222 ("BOATRAMP_COMPUTE_MANAGED_DB_PRIVILEGE", " rootless \n"),
6223 ]))
6224 .expect("extract despite trailing whitespace");
6225 assert_eq!(
6226 cfg.security
6227 .expect("security")
6228 .overrides
6229 .require_tenancy_declaration,
6230 Some(true),
6231 "a trailing-newline bool must parse as true"
6232 );
6233 assert_eq!(
6234 cfg.compute.expect("compute").managed_db_privilege,
6235 ManagedDbPrivilege::Rootless,
6236 "a whitespace-padded enum must parse"
6237 );
6238 }
6239
6240 /// Security LOW (file round-trip): the file-only, isolation-bearing structured fields
6241 /// must survive the file → derived-`Serialize` → `extract_lossy` path intact — the
6242 /// riskiest being a listener `tenancy: Scoped{…}` (custom `de_opt_tenancy` + an
6243 /// internally-tagged enum), plus a `security.profiles` and a `security.projects` entry.
6244 #[test]
6245 fn file_only_structured_fields_round_trip() {
6246 let file = r#"(
6247 serve: ( listeners: {
6248 "edge": (
6249 component: "tcp-echo", project: "proj", site: "site",
6250 bind: "0.0.0.0:7100",
6251 tenancy: (mode: "scoped", column: "tenant_id"),
6252 ),
6253 } ),
6254 security: (
6255 profile: "multi-tenant",
6256 profiles: { "preview": ( allow_guest_email: true ) },
6257 projects: { "proj": ( allow_cross_tenant_db: true ) },
6258 ),
6259 )"#;
6260 // The pipeline path a file-configured serve takes (file → figment → extract), no env.
6261 let cfg = load_with_figment(
6262 write_temp_cfg(file).as_path(),
6263 None,
6264 &EnvSource::Map(BTreeMap::new()),
6265 Dict::new(),
6266 )
6267 .expect("resolve file through the pipeline");
6268 let serve = cfg.serve.expect("serve");
6269 let l = serve.listeners.get("edge").expect("listener edge survived");
6270 assert_eq!(l.component, "tcp-echo");
6271 match l.tenancy.as_ref().expect("tenancy survived (Some)") {
6272 boatramp_core::tenancy::Tenancy::Scoped { column, .. } => {
6273 assert_eq!(column, "tenant_id");
6274 }
6275 other => panic!("tenancy did not round-trip as Scoped: {other:?}"),
6276 }
6277 let sec = cfg.security.expect("security");
6278 assert!(
6279 sec.profiles
6280 .get("preview")
6281 .expect("profile survived")
6282 .allow_guest_email
6283 == Some(true)
6284 );
6285 assert!(
6286 sec.projects
6287 .get("proj")
6288 .expect("project override survived")
6289 .allow_cross_tenant_db
6290 == Some(true)
6291 );
6292 }
6293
6294 /// Write `text` to a unique temp `.cfg` and return its path (leaked into the temp dir;
6295 /// fine for a test process). Used by the file round-trip test.
6296 fn write_temp_cfg(text: &str) -> std::path::PathBuf {
6297 use std::sync::atomic::{AtomicU32, Ordering};
6298 static N: AtomicU32 = AtomicU32::new(0);
6299 let path = std::env::temp_dir().join(format!(
6300 "brtest-rt-{}-{}.cfg",
6301 std::process::id(),
6302 N.fetch_add(1, Ordering::Relaxed)
6303 ));
6304 std::fs::write(&path, text).expect("write temp cfg");
6305 path
6306 }
6307 }
6308}