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