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