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