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