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