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