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