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