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