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