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