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