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