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