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