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