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