boatramp_node/node.rs
1//! The node-graph assembly: given a built store (blobs + KV), a configured
2//! [`Auth`](boatramp_server::Auth), and resolved
3//! [`ServerOptions`](boatramp_server::ServerOptions), wire the deploy store,
4//! handler runtime, compute reconcile loop, and domain-verify reconcile loop
5//! into a [`RunningNode`] ready to hand to a transport (`serve_with` & friends).
6//!
7//! This is the headline extraction of `PLAN-node-library`: the binary's
8//! `serve::run` used to inline this wiring, so no embedder or in-process test
9//! could exercise the same graph the `boatramp serve` binary runs. `run` now
10//! resolves the *environment* (args -> backends -> store, signal handlers,
11//! migration, auth) and calls [`assemble`]; the cluster path keeps its own inline
12//! copy until a later step converges it here.
13
14use std::path::Path;
15use std::sync::Arc;
16
17use boatramp_core::Storage;
18use boatramp_core::deploy::DeployStore;
19use boatramp_core::kv::KvStore;
20
21use crate::config::ServerConfig;
22use crate::error::{Error, Result};
23
24/// How often the compute reconcile loop converges desired vs actual workloads.
25/// Defaults to 30s; override with `BOATRAMP_COMPUTE_RECONCILE_TICK_MS` (milliseconds)
26/// so compute-backed tests can converge in a fraction of a second instead of
27/// waiting a full tick for the launch/scale reconcile.
28pub fn compute_reconcile_tick() -> std::time::Duration {
29 std::env::var("BOATRAMP_COMPUTE_RECONCILE_TICK_MS")
30 .ok()
31 .and_then(|s| s.parse::<u64>().ok())
32 .filter(|&ms| ms > 0)
33 .map(std::time::Duration::from_millis)
34 .unwrap_or(std::time::Duration::from_secs(30))
35}
36/// How often the domain-verify reconcile loop re-checks pending challenges.
37pub const DOMAIN_VERIFY_RECONCILE_TICK: std::time::Duration = std::time::Duration::from_secs(60);
38/// How long a compute workload may be idle before scale-to-zero sleeps it.
39pub const COMPUTE_IDLE_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(300);
40
41/// The built store + resolved config handed to [`assemble`]. Owns the blob/KV
42/// backends and the auth/options the caller already resolved; borrows the parsed
43/// config and data directory.
44pub struct NodeInput<'a> {
45 /// The full parsed server config (the handler + compute sections are read here).
46 pub config: &'a ServerConfig,
47 /// The node data directory (per-site SQL, handler state).
48 pub data_dir: &'a Path,
49 /// The object store built by [`crate::blobs::build_blobs`].
50 pub storage: Arc<dyn Storage>,
51 /// Per-project blob backends (PLAN-per-project-blob-backend): a `project → RAW backend` map the
52 /// serve wiring built (each with its own sealed S3 credential, fail-closed on an unresolvable one).
53 /// RAW (undecorated) — the handler runtime wraps each in the SAME MarkerHeadCache + opt-in
54 /// HedgedStorage decorator stack as the global `storage` and assembles a `CompositeBlobBackends`
55 /// over the global default. Empty ⇒ no overrides (every project resolves the global; an all-global
56 /// deployment is byte-for-byte unchanged). The project a backend binds to is host-resolved at serve
57 /// time, never guest input (invariant 1).
58 pub per_project_blob_backends: std::collections::HashMap<String, Arc<dyn Storage>>,
59 /// The metadata KV, already cache-fronted, built by [`crate::backends::build_kv`].
60 pub kv: Arc<dyn KvStore>,
61 /// The control-plane auth built by [`crate::auth::configure_auth`].
62 pub auth: boatramp_server::Auth,
63 /// Server options, already carrying the resolved posture, daemon runtime, and
64 /// (post-`configure_auth`/`configure_oidc`) issuer / OIDC verifier.
65 pub options: boatramp_server::ServerOptions,
66 /// The public HTTP serve bind address, if known — used (under
67 /// `allow_guest_self_egress`) to let a handler guest's `wasi:http` reach this
68 /// instance's own front door over loopback. `None` (an in-process embedder with no
69 /// listener) disables self-egress.
70 pub serve_addr: Option<std::net::SocketAddr>,
71 /// The cloud blob-change watch provider (FA-5b2), if the backend is a cloud one.
72 pub watch_provider: Option<Arc<dyn boatramp_core::blob_provision::WatchProvider>>,
73 /// The provisioning tier for the watch provider.
74 pub provision_tier: boatramp_core::blob_notify::ProvisionTier,
75 /// The `wasi:messaging` substrate override for the handler runtime. `None` uses
76 /// the single-node default (`LogMessaging` over the same backends); the cluster
77 /// path passes its Raft-backed coordinator.
78 pub messaging: Option<Arc<dyn boatramp_core::messaging::Messaging>>,
79 /// The single leader gate for cron firing + the compute / domain-verify reconcile
80 /// loops. Single-node passes an always-true gate (there is one node); the cluster
81 /// passes its Raft `is_leader` check so a single node drives each sweep.
82 pub is_leader: boatramp_server::CronLeaderGate,
83 /// This node's compute scheduler id (`0` single-node; the cluster node id in a
84 /// fleet, so replicas are tagged to the right node).
85 pub node_id: u64,
86 /// The binary the re-exec'd compute workers run as — the container backend's
87 /// `__sandbox` jailer and the microVM backends' `__vmm-run`/`__vz-run` VM hosts.
88 /// `None` uses this process's own executable (`current_exe`), which is what
89 /// `boatramp serve` wants (the child *is* boatramp). An **embedding harness**
90 /// whose own binary doesn't implement those subcommands should point this at a
91 /// built `boatramp` binary, so it can drive the real container/microVM backends
92 /// in-process (only the per-workload worker re-execs; the serving plane stays
93 /// embedded). The docker backend needs neither — it talks to a daemon.
94 pub worker_exe: Option<std::path::PathBuf>,
95}
96
97/// A fully wired node: the deploy store, handler runtime, auth, and options a
98/// transport consumes, plus the detached reconcile loops kept alive for the
99/// node's serving life. Destructure it and hold `reconcile` across the serve
100/// await so the loops outlive assembly.
101pub struct RunningNode {
102 /// The deploy store (blob + KV) the router serves from.
103 pub deploy: DeployStore,
104 /// The handler runtime for wasm handlers (a disabled build ⇒ a no-op runtime).
105 pub handlers: boatramp_server::HandlerRuntime,
106 /// The control-plane auth.
107 pub auth: boatramp_server::Auth,
108 /// The resolved server options.
109 pub options: boatramp_server::ServerOptions,
110 /// The detached reconcile loops (compute + domain-verify). Tokio `JoinHandle`s
111 /// do not abort on drop, so the loops run for the process life regardless; the
112 /// handles are retained so an embedder can join/abort them on shutdown.
113 pub reconcile: Vec<tokio::task::JoinHandle<()>>,
114}
115
116/// The instance's own serve socket(s) a guest self-call may reach, given the bind `addr` and
117/// whether the posture (`allow_guest_self_egress`) permits it. A wildcard bind
118/// (`0.0.0.0`/`::`) is reachable over loopback, so it normalizes to `127.0.0.1` **and** `::1`
119/// on the serve port; a specific bind is reachable at itself. Empty when disabled or no
120/// listener.
121fn self_egress_addrs(
122 addr: Option<std::net::SocketAddr>,
123 enabled: bool,
124) -> Vec<std::net::SocketAddr> {
125 use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr};
126 let Some(addr) = addr.filter(|_| enabled) else {
127 return Vec::new();
128 };
129 if addr.ip().is_unspecified() {
130 let port = addr.port();
131 vec![
132 SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), port),
133 SocketAddr::new(IpAddr::V6(Ipv6Addr::LOCALHOST), port),
134 ]
135 } else {
136 vec![addr]
137 }
138}
139
140/// Whether a node with **no configured control-plane issuer** should auto-provision an ephemeral
141/// in-memory fleet signer (for host session cookies + delegable capabilities) from its serve bind.
142///
143/// The fleet signer is a distinct trust domain from control-plane admin auth, so a DEV / loopback
144/// node with auth disabled should still be able to sign/verify session cookies and capabilities. It
145/// is gated **strictly to a loopback bind** (`127.0.0.1`/`::1`) or an in-process embedder with no
146/// bind address (`None`): NEVER a public or wildcard (`0.0.0.0`/`::`, reachable off-host) bind,
147/// where an ephemeral key would silently invalidate live capabilities across a restart — a
148/// public node that wants guest capabilities without control-plane auth must supply a persistent
149/// key. (`is_loopback()` is already `false` for a wildcard/unspecified address, so a `0.0.0.0` bind
150/// correctly does NOT auto-provision.)
151#[cfg(feature = "handlers")]
152fn should_autoprovision_fleet_signer(serve_addr: Option<std::net::SocketAddr>) -> bool {
153 serve_addr.is_none_or(|a| a.ip().is_loopback())
154}
155
156/// Wire [`NodeInput`] into a [`RunningNode`]: build the handler runtime, the
157/// deploy store (materializing the reserved `default` project), the compute
158/// backends + reconcile loop, and the domain-verify reconcile loop.
159///
160/// The caller has already built the store and configured auth/OIDC on `options`;
161/// this is the pure node-graph wiring, identical to what `boatramp serve` runs.
162pub async fn assemble(input: NodeInput<'_>) -> Result<RunningNode> {
163 let NodeInput {
164 config,
165 data_dir,
166 storage,
167 per_project_blob_backends,
168 kv,
169 auth,
170 options,
171 serve_addr,
172 watch_provider,
173 provision_tier,
174 messaging,
175 is_leader,
176 node_id,
177 worker_exe,
178 } = input;
179 // Copy out the posture scalars up front so `options` can be moved into the
180 // returned `RunningNode` without a lingering borrow.
181 let max_handler_blob_bytes = options.posture.max_handler_blob_bytes;
182 let max_component_bytes = options.posture.max_component_bytes;
183 let allow_guest_private_egress = options.posture.allow_guest_private_egress;
184 let allow_guest_tcp_egress = options.posture.allow_guest_tcp_egress;
185 let allow_guest_tcp_listener = options.posture.allow_guest_tcp_listener;
186 let allow_env_secret_refs = options.posture.allow_env_secret_refs;
187 let allow_guest_email = options.posture.allow_guest_email;
188 // The instance's own serve socket(s) a guest self-call may reach, when the posture allows
189 // it: a wildcard bind (`0.0.0.0`/`::`) is reachable on loopback, so normalize to
190 // `127.0.0.1`/`::1`; a specific bind is itself.
191 let self_egress_addrs = self_egress_addrs(serve_addr, options.posture.allow_guest_self_egress);
192 let allow_shared_kernel = options.posture.allow_shared_kernel_compute;
193 let domain_verify_allow_private = options.posture.domain_verify_allow_private;
194
195 // The deploy store the router serves from — built up front so the handler
196 // runtime's managed compute-backed `sql` binding can resolve DB endpoints from
197 // the same store the reconcile writes.
198 let compute_storage = storage.clone();
199 let deploy = DeployStore::new(storage, kv.clone());
200 // **Crown-jewel frontier-sync (v0.9.0 KV-recovery, C2).** The sealed-secret / sealed-credential
201 // stores below hold IRREPLACEABLE data (a dropped write = a lost secret with no client copy), so
202 // rather than rely on per-call-site discipline we route them ALL through a `CheckpointKv`: every
203 // write advances the durable frontier before it acks, so a crash's self-heal-on-open trailing-
204 // tail quarantine can never drop one. Wrapping ONCE here is the can't-miss guarantee. (On the
205 // cluster `RaftKv` / `MemoryKv` the added checkpoint is a no-op, so this is inert there.) The
206 // mixed `DeployStore` above keeps the RAW `kv` and selects the frontier-sync per method instead
207 // (its `current/*` pointers, history, invocation records and metering stay async).
208 let secrets_kv: Arc<dyn KvStore> = Arc::new(boatramp_core::kv::CheckpointKv::new(kv.clone()));
209 // The `[secrets]` envelope (local KEK / Vault) that seals a managed SQL
210 // credential at rest. `None` ⇒ no wrapping (a managed DB then fails closed).
211 let secrets_envelope = build_secrets_envelope(config.secrets.as_ref(), data_dir)?;
212 // The project-scoped internal secret store, built from the same KV + `[secrets]`
213 // envelope that seal managed-DB credentials. Backs both the `boatramp:<name>`
214 // resolver (wired into the handler runtime below, when that feature is present)
215 // and the admin secrets API (threaded into `ServerOptions` unconditionally, so it
216 // works on a lean node too). `None` when no envelope is configured — the admin
217 // endpoints then fail closed with a clear 501, never a panic.
218 let secret_store = secrets_envelope.clone().map(|envelope| {
219 Arc::new(boatramp_core::secret_store::SecretStore::new(
220 secrets_kv.clone(),
221 envelope,
222 ))
223 });
224 // The per-TENANT sealed secret store (task #493), sealed with the SAME `[secrets]` envelope.
225 // Backs both the control-plane CRUD (threaded into `ServerOptions` below) and — when the
226 // `tenant-secrets` feature is compiled — the runtime guest binding (the SAME `Arc` handed to
227 // `set_tenant_secret_store`). `None` when no envelope is configured, so the endpoints fail
228 // closed with a clear 501 and the guest binding is not built.
229 let tenant_secret_store = secrets_envelope.clone().map(|envelope| {
230 Arc::new(boatramp_core::secret_store::TenantSecretStore::new(
231 secrets_kv.clone(),
232 envelope,
233 ))
234 });
235 // The project-scoped SMTP email-profile store, built from the same KV + envelope
236 // (the password is sealed at rest). Backs the admin API (`options` below,
237 // unconditionally, so it works on a lean node) and — when the `email` feature +
238 // `allow_guest_email` posture permit — the runtime's host-side profile
239 // resolution (wired inside `build_handler_runtime`). `None` with no envelope, so
240 // the admin email endpoints fail closed with a clear 501.
241 let email_profile_store = secrets_envelope.clone().map(|envelope| {
242 Arc::new(boatramp_core::email_config::EmailProfileStore::new(
243 secrets_kv.clone(),
244 envelope,
245 ))
246 });
247
248 // Dev-posture guest-egress extra CA(s): when the posture permits (off/refused under
249 // multi-tenant) AND the operator pointed `BOATRAMP_GUEST_EGRESS_EXTRA_CA_FILE` at a PEM, parse
250 // it into trust anchors the guest's outbound `wasi:http` TLS client trusts on TOP of the webpki
251 // roots (for a hermetic HTTPS test double). Empty otherwise. A configured-but-unreadable/
252 // unparsable file is a hard config error (fail closed), never a silent no-trust.
253 let guest_egress_extra_roots =
254 load_guest_egress_extra_roots(options.posture.allow_guest_egress_extra_ca)?;
255
256 // The handler runtime reuses the same blob/KV backends (per-site prefixed)
257 // for its wasi:blobstore/keyvalue bindings; the sql binding is selected by
258 // `[handlers.bindings.sql]` (default: per-site libsql files under <data-dir>).
259 let handlers = crate::handlers::build_handler_runtime(
260 kv.clone(),
261 compute_storage.clone(),
262 per_project_blob_backends,
263 data_dir,
264 config.handlers.as_ref(),
265 messaging,
266 max_handler_blob_bytes,
267 max_component_bytes,
268 allow_guest_private_egress,
269 allow_guest_tcp_egress,
270 allow_guest_tcp_listener,
271 self_egress_addrs,
272 guest_egress_extra_roots,
273 allow_env_secret_refs,
274 allow_guest_email,
275 options.posture.require_tenancy_declaration,
276 options.posture.allow_cross_tenant_db,
277 &deploy,
278 secrets_envelope.clone(),
279 )
280 .await?;
281 // JWKS pre-warm (federated-gateway overhead fix): fetch the configured first-party (`own`-tier)
282 // JWKS up front so even the FIRST request per first-party issuer is instant, not a cold fetch.
283 // Best-effort + spawned (a slow/unreachable IdP must never delay node readiness); the token
284 // cache's single-flight lock dedups a pre-warm fetch against a concurrent first request.
285 // `prewarm_own_jwks` internally honors the `[handlers] jwks_prewarm` flag (no-op when off).
286 // Sites deployed AFTER startup simply warm lazily on first request (today's behavior).
287 #[cfg(feature = "handlers")]
288 {
289 let prewarm_deploy = deploy.clone();
290 tokio::spawn(async move {
291 let entries = collect_own_jwks_prewarm(&prewarm_deploy).await;
292 if !entries.is_empty() {
293 boatramp_server::prewarm_own_jwks(&entries).await;
294 }
295 });
296 }
297 // Hand the runtime the SAME per-tenant secret store `Arc` the control-plane routes hold (task
298 // #493), so a guest `tenant-secrets` `get` and a control-plane `PUT` seal/unseal against ONE
299 // store. Unset when no `[secrets]` envelope, so the guest binding is not built (fail-closed).
300 // Handlers-gated: `set_tenant_secret_store` lives on the handler runtime, so a lean (no-handlers)
301 // node has no guest binding to wire (the control-plane routes still work via `ServerOptions`).
302 #[cfg(feature = "handlers")]
303 if let Some(store) = tenant_secret_store.clone() {
304 handlers.set_tenant_secret_store(store);
305 }
306 // Record the node data directory so the node-health endpoint can report `/data` filesystem
307 // headroom (construens node-health-alerting — the disk-full incident signal).
308 #[cfg(feature = "handlers")]
309 handlers.set_data_dir(data_dir.to_path_buf());
310 // Wire the fleet session-cookie signer (R3, PLAN-tenancy-principal): the same issuer that mints
311 // control-plane tokens signs + verifies the host-issued anonymous session cookie AND the
312 // delegable capabilities (PLAN-delegable-capabilities). Handlers-gated: the session-cookie
313 // machinery lives on the handler runtime, so a lean (no-handlers) build has nothing to wire.
314 //
315 // The fleet signer is a DIFFERENT trust domain from control-plane admin auth (signing a
316 // customer's session cookie / an embed capability is not the authority to admit an operator to
317 // the control plane), but production derives it from the control-plane issuer for convenience.
318 // For a DEV / loopback node with control-plane auth disabled (`options.issuer` is `None`),
319 // auto-provision an EPHEMERAL in-memory Ed25519 fleet key so the guest-facing signer just works
320 // — session cookies + capability mint/verify — WITHOUT turning on control-plane auth. Strictly
321 // gated to a loopback bind (or an in-process embedder with no bind address): never on a public
322 // bind, where an ephemeral key would silently invalidate live capabilities across a restart (a
323 // public node that wants guest capabilities without control-plane auth must supply a persistent
324 // key). Ephemeral = issue + verify within one process run; nothing persisted, no cross-process
325 // or cross-deploy trust. Production is byte-identical: a real deploy supplies a control-plane key
326 // ⇒ `issuer` is `Some` ⇒ this fallback is never taken.
327 #[cfg(feature = "handlers")]
328 {
329 let fleet_signer = options.issuer.clone().or_else(|| {
330 should_autoprovision_fleet_signer(serve_addr).then(|| {
331 tracing::warn!(
332 "control-plane auth is disabled and no signer is configured; auto-provisioning \
333 an EPHEMERAL in-memory fleet signer (Ed25519) for host session cookies + \
334 delegable capabilities on this loopback/dev node — regenerated each start, \
335 never persisted. Configure a control-plane key (or a dedicated signer) for \
336 production."
337 );
338 Arc::new(boatramp_core::cose::LocalSigner::generate(
339 boatramp_core::cose::TokenAlg::Ed25519,
340 )) as Arc<dyn boatramp_core::cose::Signer>
341 })
342 });
343 if let Some(issuer) = fleet_signer {
344 handlers.set_session_signer(issuer);
345 }
346 }
347 // Enable guest capability minting (`boatramp:handlers/capability`, PLAN-delegable-capabilities)
348 // when the operator posture allows it. A minted capability is verified against the same fleet
349 // signer as the session cookie (wired just above), so this only enables the mint path + the TTL
350 // ceiling; posture-off (or a zero ceiling) ⇒ not offered (a guest `mint` is access-denied).
351 #[cfg(feature = "capability")]
352 if options.posture.allow_guest_mint_capability {
353 handlers.set_capability_minting(options.posture.max_guest_capability_ttl_secs);
354 }
355 // Per-project tenancy/capability posture overrides (Gap 4a): resolve each
356 // `[security.projects.<p>]` override against the fleet base so one serve process can run a
357 // strict-isolation project beside a looser one on a shared, multi-project machine. Empty ⇒
358 // every project uses the node base wired just above. Only these four in-project knobs are
359 // per-project; cross-project isolation stays structural (project = database).
360 #[cfg(feature = "handlers")]
361 {
362 let base = &options.posture;
363 let overrides: std::collections::BTreeMap<
364 String,
365 boatramp_core::security::ResolvedProjectTenancy,
366 > = config
367 .security
368 .as_ref()
369 .map(|s| {
370 s.projects
371 .iter()
372 .map(|(project, ovr)| (project.clone(), base.project_tenancy(ovr)))
373 .collect()
374 })
375 .unwrap_or_default();
376 handlers.set_project_tenancy_overrides(overrides);
377 }
378 // Wire the guest project self-config capability (`boatramp:handlers/admin`) when the
379 // operator posture enables at least one surface. The controller reuses the same in-process
380 // domain-verify / email-profile / secret / site-config subsystems + the real domain probe;
381 // it's project-scoped per grant and rate-limited + audited. Posture-off ⇒ not offered.
382 #[cfg(feature = "admin")]
383 {
384 use boatramp_handlers::AdminSurface;
385 let p = &options.posture;
386 let mut surfaces = std::collections::BTreeSet::new();
387 if p.allow_guest_admin_domains {
388 surfaces.insert(AdminSurface::Domains);
389 }
390 if p.allow_guest_admin_email {
391 surfaces.insert(AdminSurface::Email);
392 }
393 if p.allow_guest_admin_site {
394 surfaces.insert(AdminSurface::Site);
395 }
396 if p.allow_guest_admin_secrets {
397 surfaces.insert(AdminSurface::Secrets);
398 }
399 if !surfaces.is_empty() {
400 let controller = Arc::new(boatramp_server::ServerAdminController::with_server_probe(
401 deploy.clone(),
402 email_profile_store.clone(),
403 secret_store.clone(),
404 p.domain_verify_allow_private,
405 ));
406 handlers.set_admin(controller, surfaces);
407 }
408 }
409 // Leader-gate cron firing (cluster: only the Raft leader fires; single-node: an
410 // always-true gate, equivalent to the unset default). The same gate drives the
411 // reconcile loops below, so all three converge on one leader per fleet. Only the
412 // handler runtime has a scheduler, so this is a no-op without the `handlers` feature.
413 #[cfg(feature = "handlers")]
414 handlers.set_cron_leader_gate(is_leader.clone());
415 // FA-5b2: on a cloud backend, wire the blob-change notification provisioner +
416 // its tier so adding a `blob` trigger provisions (and removing it retracts).
417 #[cfg(feature = "handlers")]
418 if let Some(provider) = watch_provider {
419 handlers.set_watch_provider(provider);
420 handlers.set_provision_tier(provision_tier);
421 }
422 #[cfg(not(feature = "handlers"))]
423 let _ = (watch_provider, provision_tier);
424
425 // Materialize the reserved `default` project so `project ls` / `project show
426 // default` reflect it on a fresh install, not only after a migration. Best
427 // effort: the reader backstop keeps listings correct even if this write can't
428 // land, so a transient failure must never block serving.
429 match deploy.ensure_default_project().await {
430 Ok(true) => tracing::info!("materialized the reserved `default` project record"),
431 Ok(false) => {}
432 Err(e) => tracing::warn!(
433 error = %e,
434 "could not materialize the `default` project record; readers use the synthesized default"
435 ),
436 }
437 // Wire the function-to-function invoke resolver now the deploy store exists,
438 // so a function granted `invoke` can call a sibling in-process (FI).
439 #[cfg(feature = "handlers")]
440 handlers.set_invoker(deploy.clone());
441
442 // Compute reconcile loop. Single-node is always the "leader". Backends are
443 // built from the `[compute]` config + capability detection; a no-op when none
444 // are registered. Detached for the server's life.
445 let (compute_backends, compute_node) = crate::compute::build_compute(
446 config.compute.as_ref(),
447 compute_storage,
448 data_dir,
449 node_id,
450 !allow_shared_kernel,
451 options.daemon_runtime.clone(),
452 worker_exe.as_deref(),
453 )
454 .await;
455 // Adopt the IPs of already-running replicas into each backend's fresh-on-boot
456 // IP pool BEFORE the reconcile loop starts allocating. A backend with a per-node
457 // pool (the native container backend) rebuilds it empty each process start; without
458 // this the boot reconcile could re-hand a live address to a different workload —
459 // the container-IP collision — or move a replica's endpoint on relaunch. Feeds
460 // every persisted replica's `(workload, replica, endpoint-ip)`; each backend keeps
461 // only the IPs in its own subnet (a cheap no-op for docker/cloudflare/VMM).
462 crate::compute::adopt_running_replica_ips(&deploy, &compute_backends).await;
463 // Per-project internal DNS (service discovery): start the resolver on the bridge
464 // gateway so a guest resolves peers by name within its project. On by default;
465 // starts only when the container backend + bridge are up (Linux). Detached for
466 // the node's serving life (pushed into `reconcile` below). Started before the
467 // reconcile loop consumes `compute_backends` — it borrows the registry to check
468 // the container backend is present.
469 let internal_dns =
470 crate::compute::spawn_internal_dns(config.compute.as_ref(), &compute_backends, &deploy);
471 // Activate the compute sql-shim (PLAN-compute-bindings): bind its listener +
472 // build the resolver when a sql provider and `compute.sql_shim_url` are both present.
473 #[cfg(feature = "handlers")]
474 let sql_resolver = boatramp_server::sql_shim::spawn_sql_shim(
475 handlers.sql_backends(),
476 config.compute.as_ref().and_then(|c| c.sql_shim_url.clone()),
477 )
478 .await;
479 #[cfg(not(feature = "handlers"))]
480 let sql_resolver: Option<Arc<dyn boatramp_core::compute::ComputeBindingResolver>> = None;
481
482 // Activate the compute blob-shim (PLAN-compute-bindings): the symmetric sibling of the
483 // sql-shim — bind its listener + build the resolver when a blob provider and
484 // `compute.blob_shim_url` are both present, so a workload's `--bind blob` reaches the
485 // SAME per-site `hblob/{qualified-site}/…` namespace a `wasi:blobstore` handler sees.
486 #[cfg(feature = "handlers")]
487 let blob_resolver = boatramp_server::blob_shim::spawn_blob_shim(
488 handlers.blob_backends(),
489 config
490 .compute
491 .as_ref()
492 .and_then(|c| c.blob_shim_url.clone()),
493 config
494 .compute
495 .as_ref()
496 .and_then(|c| c.blob_shim_max_object_bytes),
497 )
498 .await;
499 #[cfg(not(feature = "handlers"))]
500 let blob_resolver: Option<Arc<dyn boatramp_core::compute::ComputeBindingResolver>> = None;
501
502 // One resolver for the reconcile: each shim filters to its own binding kind, so chaining
503 // them lets a workload declaring both `sql` and `blob` bindings be served by both from a
504 // single `resolve` call.
505 let binding_resolver =
506 boatramp_core::compute::ChainedBindingResolver::chain([sql_resolver, blob_resolver]);
507
508 // Managed compute-backed SQL (PLAN-managed-compute-sql P2-b): if the handler
509 // `sql` config declares any managed database, inject its `POSTGRES_*`/`MYSQL_*`
510 // server-init env into the DB workload at launch from the sealed credential.
511 // Reaching here with a managed DB implies an envelope (build_handler_runtime
512 // fails closed otherwise), so the credential store always has one to seal with.
513 // Keep a clone of the secrets envelope for the operator-SQL capability below
514 // (the managed_db_resolver match moves the original).
515 #[cfg(any(feature = "sql-postgres", feature = "sql-mysql"))]
516 let operator_envelope = secrets_envelope.clone();
517 // …and a second clone for the tenant-deprovision capability (drops a deleted
518 // tenant's managed DB/role/credential on project/site delete). It needs a real
519 // envelope to seal/unseal + delete per-tenant credentials, so it is wired only
520 // when one is present (same fail-closed gating as the managed-DB paths).
521 #[cfg(any(feature = "sql-postgres", feature = "sql-mysql"))]
522 let deprovision_envelope = secrets_envelope.clone();
523 // …and a clone for the provisioning drift-repair capability (owner-model retrofit /
524 // reconcile). Like the migrate path it connects as the sealed owner role and re-seals
525 // credentials, so it needs a real envelope; wired only when one is present.
526 #[cfg(any(feature = "sql-postgres", feature = "sql-mysql"))]
527 let repair_envelope = secrets_envelope.clone();
528 // …and a third clone for the soft-delete tombstone reaper (the leader-gated task
529 // that hard-drops a Shared-Postgres tenant once its grace window elapses). It, too,
530 // needs a real envelope to unseal the superuser credential + delete the per-tenant
531 // one on hard-drop.
532 #[cfg(any(feature = "sql-postgres", feature = "sql-mysql"))]
533 let reaper_envelope = secrets_envelope.clone();
534 // …and a clone for the declarative managed-database capability (#501 Stage B): it
535 // provisions the declared DB + seals its credential server-side, so it needs a real
536 // envelope; wired only when one is present (fail-closed like every managed-DB path).
537 #[cfg(any(feature = "sql-postgres", feature = "sql-mysql"))]
538 let declare_envelope = secrets_envelope.clone();
539 #[cfg(any(feature = "sql-postgres", feature = "sql-mysql"))]
540 let managed_db_resolver: Option<Arc<dyn boatramp_core::compute::ManagedDbEnvResolver>> = match (
541 config
542 .handlers
543 .as_ref()
544 .and_then(|h| h.bindings.sql.as_ref()),
545 secrets_envelope,
546 ) {
547 (Some(sql), Some(envelope)) if !sql.databases.is_empty() => {
548 // Crown-jewel (C2): sealed managed-DB credentials go through the frontier-syncing
549 // `secrets_kv`, so a freshly-minted DB credential is past the durable frontier before
550 // the workload sees it — never droppable by the self-heal-on-open trailing-tail quarantine.
551 let creds =
552 crate::managed_sql::ManagedSqlCredentials::new(secrets_kv.clone(), envelope);
553 let privilege = config
554 .compute
555 .as_ref()
556 .map(|c| c.managed_db_privilege)
557 .unwrap_or_default();
558 let env =
559 crate::managed_sql::ManagedDbEnv::from_config(&sql.databases, creds, privilege);
560 (!env.is_empty()).then(|| Arc::new(env) as Arc<_>)
561 }
562 _ => None,
563 };
564 #[cfg(not(any(feature = "sql-postgres", feature = "sql-mysql")))]
565 let managed_db_resolver: Option<Arc<dyn boatramp_core::compute::ManagedDbEnvResolver>> = None;
566
567 // Turnkey managed DB: auto-register the compute workload(s) backing each managed
568 // co-located database that has none yet, so declaring the `databases` binding is
569 // enough to boot the DB (no separate `compute set` / apply). Tenant-aware — a
570 // `Shared` binding registers its one shared server; a `Single` binding registers
571 // nothing at boot (its per-tenant `<compute>-<ident>` is created durably by the lazy
572 // resolve on first `sql` use and relaunched by the reconcile, so a project that never
573 // uses `sql` — e.g. a static-only site — never gets a spurious DB). Non-clobbering +
574 // idempotent; runs before the reconcile loop so its first tick can launch what it
575 // registered.
576 #[cfg(any(feature = "sql-postgres", feature = "sql-mysql"))]
577 if let Some(sql) = config
578 .handlers
579 .as_ref()
580 .and_then(|h| h.bindings.sql.as_ref())
581 .filter(|sql| !sql.databases.is_empty())
582 {
583 crate::managed_sql::auto_register_managed_db_workloads(&deploy, &sql.databases).await;
584 }
585
586 // Operator SQL capability (managed-DB migrations/queries via the sealed credential, resolved
587 // server-side) — backs `POST /api/sql/{db}/{exec,query}`. The SAME concrete NodeOperatorSql
588 // also backs the owner-gated schema-migration runner (which reuses its owner + superuser
589 // backends), so build it ONCE and share it.
590 // Build the SAME concrete NodeOperatorSql once (when a managed DB is configured) and share it:
591 // it backs both `operator_sql` (the sql exec/query cap) and the migration runner (which reuses
592 // its owner + superuser backends). Two separate bindings so neither annotation is a complex type.
593 // The migration substrate is a single dispatcher (crate::managed_sql::DispatchMigrationRunner)
594 // routing each `(project, db)` to its engine's substrate: the sqlx NodeMigrationRunner for a
595 // Postgres/MySQL binding, the LibsqlMigrationRunner for a `libsql` binding. It compiles whenever a
596 // sqlx engine OR `migrate` (⇒ libsql) is on, so the embedded-libsql default can migrate even on a
597 // node with no external sqlx engine. `operator_sql` (the `POST /api/sql/{db}/{exec,query}` cap)
598 // stays sqlx-only — a libsql file has no operator-SQL/credential seam.
599 #[cfg(any(feature = "sql-postgres", feature = "sql-mysql"))]
600 let operator_sql: Option<Arc<dyn boatramp_core::sql::OperatorSql>>;
601 // Late-init: the match arms assign it (and, under sqlx, `operator_sql` in the same block), and the
602 // arms differ by feature-cfg — so a direct `let … = match {…}` would need cfg'd arm bodies. The
603 // late-init keeps that readable; the value is always assigned before use.
604 #[cfg(any(feature = "sql-postgres", feature = "sql-mysql", feature = "migrate"))]
605 #[allow(clippy::needless_late_init)]
606 let migration_substrate: Option<Arc<dyn boatramp_core::sql::MigrationSubstrate>>;
607 #[cfg(any(feature = "sql-postgres", feature = "sql-mysql", feature = "migrate"))]
608 match config
609 .handlers
610 .as_ref()
611 .and_then(|h| h.bindings.sql.as_ref())
612 .filter(|sql| !sql.databases.is_empty())
613 {
614 Some(sql) => {
615 // The sqlx (Postgres/MySQL) arm — the shared NodeOperatorSql backs both the operator-SQL
616 // cap and the sqlx migration runner. Only built when a sqlx engine is compiled in.
617 #[cfg(any(feature = "sql-postgres", feature = "sql-mysql"))]
618 let node_op = Arc::new(crate::managed_sql::NodeOperatorSql::new(
619 sql.databases.clone(),
620 kv.clone(),
621 operator_envelope,
622 deploy.clone(),
623 ));
624 // The operator's trusted-extension allowlist — the only extensions a migration may
625 // enable (empty ⇒ none). See ExternalSqlConfig::migrate_trusted_extensions.
626 #[cfg(any(feature = "sql-postgres", feature = "sql-mysql"))]
627 let trusted: std::collections::BTreeSet<String> = sql
628 .migrate_trusted_extensions
629 .clone()
630 .unwrap_or_default()
631 .into_iter()
632 .collect();
633 migration_substrate = Some(Arc::new(crate::managed_sql::DispatchMigrationRunner::new(
634 #[cfg(any(feature = "sql-postgres", feature = "sql-mysql"))]
635 node_op.clone(),
636 #[cfg(any(feature = "sql-postgres", feature = "sql-mysql"))]
637 trusted,
638 #[cfg(feature = "migrate")]
639 sql.databases.clone(),
640 ))
641 as Arc<dyn boatramp_core::sql::MigrationSubstrate>);
642 #[cfg(any(feature = "sql-postgres", feature = "sql-mysql"))]
643 {
644 operator_sql = Some(node_op as Arc<dyn boatramp_core::sql::OperatorSql>);
645 }
646 }
647 None => {
648 #[cfg(any(feature = "sql-postgres", feature = "sql-mysql"))]
649 {
650 operator_sql = None;
651 }
652 migration_substrate = None;
653 }
654 }
655 // When only `migrate` (no sqlx) is compiled, the operator-SQL cap does not exist.
656 #[cfg(all(
657 not(any(feature = "sql-postgres", feature = "sql-mysql")),
658 feature = "migrate"
659 ))]
660 let operator_sql: Option<Arc<dyn boatramp_core::sql::OperatorSql>> = None;
661 #[cfg(not(any(feature = "sql-postgres", feature = "sql-mysql", feature = "migrate")))]
662 let migration_substrate: Option<Arc<dyn boatramp_core::sql::MigrationSubstrate>> = None;
663 #[cfg(not(any(feature = "sql-postgres", feature = "sql-mysql", feature = "migrate")))]
664 let operator_sql: Option<Arc<dyn boatramp_core::sql::OperatorSql>> = None;
665
666 // Tenant-deprovision capability (drop a deleted tenant's managed DB/role/sealed
667 // credential on project/site delete). Wired only when a compute-backed managed
668 // database + a secrets envelope are both present — same gating as operator_sql,
669 // plus the envelope requirement (it must seal/unseal per-tenant credentials).
670 // The soft-delete grace window for a Shared-Postgres managed tenant
671 // (`handlers.bindings.sql.deprovision_grace_secs`, env-settable). Default 7 days;
672 // `0` disables the soft path (immediate hard drop). Threaded to the deprovisioner
673 // (which soft-deletes) and implicitly honored by the reaper (which only ever finds
674 // tombstones a >0 grace produced).
675 #[cfg(any(feature = "sql-postgres", feature = "sql-mysql"))]
676 let deprovision_grace_secs = config
677 .handlers
678 .as_ref()
679 .and_then(|h| h.bindings.sql.as_ref())
680 .and_then(|sql| sql.deprovision_grace_secs)
681 .unwrap_or(crate::tenant_sql::DEFAULT_DEPROVISION_GRACE_SECS);
682 #[cfg(any(feature = "sql-postgres", feature = "sql-mysql"))]
683 let tenant_deprovisioner: Option<Arc<dyn boatramp_core::sql::TenantDeprovisioner>> = config
684 .handlers
685 .as_ref()
686 .and_then(|h| h.bindings.sql.as_ref())
687 .filter(|sql| !sql.databases.is_empty())
688 .zip(deprovision_envelope)
689 .map(|(sql, envelope)| {
690 Arc::new(crate::tenant_sql::NodeTenantDeprovisioner::new(
691 deploy.clone(),
692 kv.clone(),
693 envelope,
694 sql.databases.clone(),
695 deprovision_grace_secs,
696 )) as Arc<_>
697 });
698 #[cfg(not(any(feature = "sql-postgres", feature = "sql-mysql")))]
699 let tenant_deprovisioner: Option<Arc<dyn boatramp_core::sql::TenantDeprovisioner>> = None;
700
701 // Provisioning drift-repair capability (owner-model retrofit / reconcile) — backs the
702 // `Project·Admin`-gated `/api/repair/{db}` + `/dry-run`. Same gating as operator_sql plus
703 // the envelope requirement (it re-seals the owner credential + connects as it). The
704 // envelope is threaded as `Some(_)` so a lean-but-managed node still gets a clear
705 // per-check error rather than a panic if none is configured.
706 #[cfg(any(feature = "sql-postgres", feature = "sql-mysql"))]
707 let tenant_repair: Option<Arc<dyn boatramp_core::sql::TenantRepair>> = config
708 .handlers
709 .as_ref()
710 .and_then(|h| h.bindings.sql.as_ref())
711 .filter(|sql| !sql.databases.is_empty())
712 .map(|sql| {
713 Arc::new(crate::repair::NodeTenantRepair::new(
714 sql.databases.clone(),
715 deploy.clone(),
716 kv.clone(),
717 repair_envelope.clone(),
718 )) as Arc<_>
719 });
720 #[cfg(not(any(feature = "sql-postgres", feature = "sql-mysql")))]
721 let tenant_repair: Option<Arc<dyn boatramp_core::sql::TenantRepair>> = None;
722
723 // Declarative managed-database capability (#501 Stage B) — backs the `Project·Admin`-gated
724 // `PUT /api/projects/{proj}/databases/{name}` + `POST …/ensure`. It persists a manifest
725 // `databases:` entry to `project/{project}/database/{name}`, enforces daemon-config-wins at
726 // the merge point (against the node-static `sql.databases`), refuses an identity change,
727 // binds provisioning to the caller's project, and eagerly provisions via `provision_tenant`.
728 // Requires a sqlx engine (it provisions a Postgres/MySQL server) AND a `[secrets]` envelope
729 // (a managed DB seals its credential). UNLIKE repair/operator_sql it is NOT gated on
730 // `!sql.databases.is_empty()` — a node with NO node-static databases can still accept a
731 // project declaration (the whole point of the declarative front door). The node-static map
732 // (possibly empty) is threaded so the daemon-wins conflict check has both sources.
733 #[cfg(any(feature = "sql-postgres", feature = "sql-mysql"))]
734 let managed_db_declare: Option<Arc<dyn boatramp_core::sql::ManagedDbDeclare>> =
735 declare_envelope.map(|envelope| {
736 let sql_cfg = config
737 .handlers
738 .as_ref()
739 .and_then(|h| h.bindings.sql.as_ref());
740 let static_dbs = sql_cfg.map(|sql| sql.databases.clone()).unwrap_or_default();
741 // Per-project declaration ceilings (#501 Stage B MEDIUM-1 — the disk-exhaustion
742 // guard): the operator's `max_declared_databases`/`max_declared_volume_mib`, or
743 // the built-in `apply_db_caps` defaults (16 DBs / 512 GiB) when unset.
744 let quota = crate::managed_db_declare::DeclareQuota::from_config(
745 sql_cfg.and_then(|sql| sql.max_declared_databases),
746 sql_cfg.and_then(|sql| sql.max_declared_volume_mib),
747 );
748 Arc::new(crate::managed_db_declare::NodeManagedDbDeclare::new(
749 static_dbs,
750 deploy.clone(),
751 kv.clone(),
752 envelope,
753 quota,
754 )) as Arc<_>
755 });
756 #[cfg(not(any(feature = "sql-postgres", feature = "sql-mysql")))]
757 let managed_db_declare: Option<Arc<dyn boatramp_core::sql::ManagedDbDeclare>> = None;
758
759 // Operator compute-exec capability (run a command inside a running workload) —
760 // backs `POST /api/compute/{name}/exec`, gated by the `allow_compute_exec`
761 // posture. Clone the backend registry before the reconcile loop consumes it.
762 let compute_exec: Option<Arc<dyn boatramp_core::compute::ComputeExec>> = Some(Arc::new(
763 crate::compute::NodeComputeExec::new(compute_backends.clone(), deploy.clone()),
764 ) as Arc<_>);
765
766 // Operator volume-reclamation capability (list + remove persistent volumes) —
767 // backs `GET /api/compute/volumes` + `DELETE /api/compute/volumes/{name}`.
768 // Same admin-scoped `/api/compute/*` gate; clone the registry before the
769 // reconcile loop consumes the original below.
770 let compute_volumes: Option<Arc<dyn boatramp_core::compute::ComputeVolumes>> = Some(Arc::new(
771 crate::compute::NodeComputeVolumes::new(compute_backends.clone(), deploy.clone()),
772 )
773 as Arc<_>);
774
775 // Operator reconcile-plane control capability (restart a replica) — backs
776 // `POST /api/compute/maintenance/restart` (admin-scoped). Clone the registry
777 // before the reconcile loop consumes the original below.
778 let compute_control: Option<Arc<dyn boatramp_core::compute::ComputeControl>> = Some(Arc::new(
779 crate::compute::NodeComputeControl::new(compute_backends.clone(), deploy.clone()),
780 )
781 as Arc<_>);
782
783 let compute_reconcile = boatramp_server::spawn_compute_reconcile(
784 deploy.clone(),
785 compute_backends,
786 vec![compute_node],
787 boatramp_core::compute::BackendPolicy::from_shared_kernel_allowed(allow_shared_kernel),
788 is_leader.clone(),
789 compute_reconcile_tick(),
790 COMPUTE_IDLE_TIMEOUT,
791 binding_resolver,
792 managed_db_resolver,
793 );
794
795 // Tenant tombstone reaper: leader-gated hard-drop of soft-deleted Shared-Postgres
796 // tenants past their grace window (safe deprovision — see `tenant_sql`). Wired only
797 // when a compute-backed managed database + a secrets envelope are both present
798 // (same gating as the deprovisioner); each tombstone carries its own server +
799 // superuser, so the reaper needs no per-binding config. A `0` grace never writes a
800 // tombstone, so the sweep is simply inert then.
801 #[cfg(any(feature = "sql-postgres", feature = "sql-mysql"))]
802 let tombstone_reaper: Option<tokio::task::JoinHandle<()>> = config
803 .handlers
804 .as_ref()
805 .and_then(|h| h.bindings.sql.as_ref())
806 .filter(|sql| !sql.databases.is_empty())
807 .zip(reaper_envelope)
808 .map(|(_sql, envelope)| {
809 crate::tenant_sql::spawn_tenant_tombstone_reaper(
810 deploy.clone(),
811 kv.clone(),
812 envelope,
813 is_leader.clone(),
814 crate::tenant_sql::TOMBSTONE_REAPER_TICK,
815 )
816 });
817 #[cfg(not(any(feature = "sql-postgres", feature = "sql-mysql")))]
818 let tombstone_reaper: Option<tokio::task::JoinHandle<()>> = None;
819
820 // Domain-verify auto-complete: periodically re-check every site's pending
821 // ownership challenges and attach any that now pass — a published token (e.g.
822 // via `domain add --provider`) converges without a manual `domain verify`.
823 let dv_reconcile = boatramp_server::spawn_domain_verify_reconcile(
824 deploy.clone(),
825 domain_verify_allow_private,
826 is_leader,
827 DOMAIN_VERIFY_RECONCILE_TICK,
828 );
829
830 // Wire the operator capabilities onto the options the router is built from.
831 let mut options = options;
832 options.operator_sql = operator_sql;
833 options.migration_substrate = migration_substrate;
834 options.tenant_repair = tenant_repair;
835 options.managed_db_declare = managed_db_declare;
836 options.tenant_deprovisioner = tenant_deprovisioner;
837 options.compute_exec = compute_exec;
838 options.compute_volumes = compute_volumes;
839 options.compute_control = compute_control;
840 // The internal secret store backs the admin secrets API (set/list/delete). Not
841 // handlers-gated — it must be reachable even on a lean node.
842 options.secret_store = secret_store;
843 // The per-tenant sealed secret store backs the control-plane CRUD (task #493). Like the secret
844 // store it is not handlers-gated, so the endpoints work on a lean node.
845 options.tenant_secret_store = tenant_secret_store;
846 // The email-profile store backs the admin API (`/api/email/profiles`); like the
847 // secret store it is not handlers-gated, so it works on a lean node.
848 options.email_profile_store = email_profile_store;
849
850 // The detached reconcile loops: the always-present compute + domain-verify ones,
851 // plus the optional tenant-tombstone reaper (only when a managed DB is configured).
852 let mut reconcile = vec![compute_reconcile, dv_reconcile];
853 if let Some(reaper) = tombstone_reaper {
854 reconcile.push(reaper);
855 }
856 if let Some(dns) = internal_dns {
857 reconcile.push(dns);
858 }
859
860 Ok(RunningNode {
861 deploy,
862 handlers,
863 auth,
864 options,
865 reconcile,
866 })
867}
868
869/// Build the `[secrets]` envelope (secrets-at-rest wrapping) from `boatramp.cfg`'s
870/// `[secrets]` section: `local` (a machine-local AES-256-GCM KEK) or `vault` (Vault
871/// Env var an operator points at a PEM file of extra CA(s) the guest's outbound `wasi:http` TLS
872/// client should trust on top of the webpki roots — honored only under the
873/// `allow_guest_egress_extra_ca` posture (a hermetic HTTPS test double lever).
874const GUEST_EGRESS_EXTRA_CA_ENV: &str = "BOATRAMP_GUEST_EGRESS_EXTRA_CA_FILE";
875
876/// Parse the operator's guest-egress extra-CA PEM ([`GUEST_EGRESS_EXTRA_CA_ENV`]) into rustls trust
877/// Collect the first-party (`own`-tier) JWKS URLs to pre-warm at startup: every site's gateway-level
878/// `[handlers.graphql.data].claims_from_token` that is single-issuer (`jwks_url` set) and NOT
879/// multi-issuer (`issuer_trust` unset) — foreign/multi-issuer issuers can't be pre-warmed (unknown
880/// until a token arrives), and `jwks_env` is an env var, not a fetch. Returns deduped
881/// `(url, issuer, audience)` tuples. Best-effort: a per-site read error is logged and skipped, never
882/// propagated (pre-warm must not fail node startup). Per-route `HandlerConfig`/consumer/session/
883/// function `token_claims` live in content-addressed deployment manifests not enumerated here; those
884/// warm lazily on first request (today's behavior).
885#[cfg(feature = "handlers")]
886async fn collect_own_jwks_prewarm(deploy: &DeployStore) -> Vec<(String, String, Option<String>)> {
887 use boatramp_core::project::ProjectRef;
888 let sites = match deploy.list_sites_all().await {
889 Ok(s) => s,
890 Err(e) => {
891 tracing::warn!(error = %e, "JWKS pre-warm: could not list sites; skipping pre-warm");
892 return Vec::new();
893 }
894 };
895 let mut seen = std::collections::HashSet::new();
896 let mut out = Vec::new();
897 for (project, site) in sites {
898 let sc = match deploy
899 .get_site_config(ProjectRef::new(&project), &site)
900 .await
901 {
902 Ok(Some(sc)) => sc,
903 Ok(None) => continue,
904 Err(e) => {
905 tracing::warn!(project = %project, site = %site, error = %e,
906 "JWKS pre-warm: could not load site config; skipping");
907 continue;
908 }
909 };
910 let Some(claims) = sc
911 .handlers
912 .as_ref()
913 .and_then(|h| h.graphql.as_ref())
914 .and_then(|g| g.data.as_ref())
915 .and_then(|d| d.claims_from_token.as_ref())
916 else {
917 continue;
918 };
919 // OWN tier only: operator-fixed single-issuer `jwks_url`, never multi-issuer discovery.
920 if claims.issuer_trust.is_some() {
921 continue;
922 }
923 if let Some(url) = claims.jwks_url.as_ref() {
924 let entry = (url.clone(), claims.issuer.clone(), claims.audience.clone());
925 if seen.insert(entry.clone()) {
926 out.push(entry);
927 }
928 }
929 }
930 out
931}
932
933/// anchors, gated by the `allow_guest_egress_extra_ca` posture (`allow`). No env set ⇒ empty (the
934/// default). `allow == false` (e.g. multi-tenant) with a file set ⇒ empty + a warning (the posture
935/// refuses it). Set + readable + ≥1 cert ⇒ those certs. Set-but-unreadable / no valid cert ⇒ a hard
936/// error (fail closed — a configured-but-broken CA must not silently degrade to no-trust).
937fn load_guest_egress_extra_roots(
938 allow: bool,
939) -> Result<Vec<rustls::pki_types::CertificateDer<'static>>> {
940 let path = match std::env::var(GUEST_EGRESS_EXTRA_CA_ENV) {
941 Ok(p) if !p.is_empty() => p,
942 _ => return Ok(Vec::new()),
943 };
944 if !allow {
945 tracing::warn!(
946 env = GUEST_EGRESS_EXTRA_CA_ENV,
947 "ignoring a guest-egress extra CA: the security posture forbids it \
948 (allow_guest_egress_extra_ca is off — e.g. under multi-tenant)"
949 );
950 return Ok(Vec::new());
951 }
952 let pem =
953 std::fs::read(&path).map_err(|e| Error::GuestEgressCa(format!("reading {path:?}: {e}")))?;
954 let certs = rustls_pemfile::certs(&mut std::io::BufReader::new(&pem[..]))
955 .collect::<std::result::Result<Vec<_>, _>>()
956 .map_err(|e| Error::GuestEgressCa(format!("parsing {path:?}: {e}")))?;
957 if certs.is_empty() {
958 return Err(Error::GuestEgressCa(format!(
959 "{path:?} contained no PEM certificate"
960 )));
961 }
962 tracing::info!(
963 env = GUEST_EGRESS_EXTRA_CA_ENV,
964 count = certs.len(),
965 path = %path,
966 "guest egress trusts operator extra CA(s) (dev-posture; webpki roots still apply)"
967 );
968 Ok(certs)
969}
970
971/// Transit). `None`/empty ⇒ no wrapping. The Vault token is read from the
972/// environment (`token_env`), never a file. This seals a managed SQL credential at
973/// rest; a managed database fails closed without it.
974fn build_secrets_envelope(
975 secrets: Option<&crate::config::SecretsConfig>,
976 data_dir: &Path,
977) -> Result<Option<Arc<dyn boatramp_core::envelope::KeyEnvelope>>> {
978 use boatramp_server::envelope::{EnvelopeSpec, build_envelope};
979 let Some(cfg) = secrets else {
980 return Ok(None);
981 };
982 let spec = match cfg.envelope.as_str() {
983 "" => EnvelopeSpec::None,
984 "local" => EnvelopeSpec::Local {
985 kek_file: cfg
986 .kek_file
987 .clone()
988 .unwrap_or_else(|| data_dir.join("secrets/kek")),
989 },
990 "vault" => {
991 let v = cfg.vault.as_ref().ok_or_else(|| {
992 Error::Envelope(
993 "secrets.envelope = \"vault\" needs a [secrets.vault] section".into(),
994 )
995 })?;
996 let token = std::env::var(&v.token_env).map_err(|_| {
997 Error::Envelope(format!("Vault token env `{}` is not set", v.token_env))
998 })?;
999 EnvelopeSpec::Vault {
1000 addr: v.addr.clone(),
1001 key: v.key.clone(),
1002 token,
1003 }
1004 }
1005 other => {
1006 return Err(Error::Envelope(format!(
1007 "unknown secrets.envelope {other:?} (want \"local\" or \"vault\")"
1008 )));
1009 }
1010 };
1011 build_envelope(spec).map_err(|e| Error::Envelope(e.to_string()))
1012}
1013
1014#[cfg(all(test, feature = "fs"))]
1015mod tests {
1016 use super::*;
1017 use boatramp_core::kv::MemoryKv;
1018 use boatramp_core::security::SecurityProfile;
1019
1020 /// The dev/loopback ephemeral fleet-signer auto-provision is gated STRICTLY to a loopback bind
1021 /// (or an in-process embedder with no bind): a public / wildcard / private-network bind must
1022 /// NOT silently provision an ephemeral signing key (it would invalidate live capabilities on a
1023 /// restart — such a node must supply a persistent key). This is the security-critical boundary.
1024 #[cfg(feature = "handlers")]
1025 #[test]
1026 fn ephemeral_fleet_signer_auto_provisions_only_on_loopback_or_in_process() {
1027 use std::net::SocketAddr;
1028 let sa = |s: &str| s.parse::<SocketAddr>().unwrap();
1029 // In-process (no listener) and loopback → auto-provision the dev fleet signer.
1030 assert!(should_autoprovision_fleet_signer(None));
1031 assert!(should_autoprovision_fleet_signer(Some(sa(
1032 "127.0.0.1:8080"
1033 ))));
1034 assert!(should_autoprovision_fleet_signer(Some(sa("[::1]:8080"))));
1035 // Off-host-reachable binds MUST NOT auto-provision an ephemeral key: a public IP, a
1036 // private-network IP, and a wildcard bind (`0.0.0.0`/`::`, reachable off-host).
1037 assert!(!should_autoprovision_fleet_signer(Some(sa(
1038 "203.0.113.5:8080"
1039 ))));
1040 assert!(!should_autoprovision_fleet_signer(Some(sa(
1041 "10.0.0.4:8080"
1042 ))));
1043 assert!(!should_autoprovision_fleet_signer(Some(sa("0.0.0.0:8080"))));
1044 assert!(!should_autoprovision_fleet_signer(Some(sa("[::]:8080"))));
1045 }
1046
1047 /// The headline in-process fidelity check (PLAN-node-library N2b.3): `assemble`
1048 /// over a temp `FsStorage` + `MemoryKv` produces a `RunningNode` whose deploy
1049 /// store is live (the reserved `default` project was materialized during
1050 /// assembly) and whose router — the exact one `boatramp serve` builds — answers
1051 /// `/healthz`. No listener is bound: the request is driven through the router
1052 /// via `tower::oneshot`, so the whole assembly runs in-process.
1053 #[tokio::test]
1054 async fn assemble_produces_a_serving_node_over_a_temp_store() {
1055 use axum::body::Body;
1056 use axum::http::{Request, StatusCode};
1057 use tower::ServiceExt;
1058
1059 let tmp = tempfile::tempdir().unwrap();
1060 let storage: Arc<dyn Storage> = Arc::new(boatramp_storage::FsStorage::new(tmp.path()));
1061 let kv: Arc<dyn KvStore> = Arc::new(MemoryKv::new());
1062 let config = ServerConfig::default();
1063 let options = boatramp_server::ServerOptions {
1064 // The strict `multi-tenant` posture, as an unconfigured `serve` resolves.
1065 posture: SecurityProfile::MultiTenant.preset(),
1066 ..Default::default()
1067 };
1068
1069 let node = assemble(NodeInput {
1070 config: &config,
1071 data_dir: tmp.path(),
1072 storage,
1073 per_project_blob_backends: std::collections::HashMap::new(),
1074 kv,
1075 auth: boatramp_server::Auth::disabled(),
1076 options,
1077 serve_addr: None,
1078 watch_provider: None,
1079 provision_tier: boatramp_core::blob_notify::ProvisionTier::default(),
1080 messaging: None,
1081 is_leader: Arc::new(|| true),
1082 node_id: 0,
1083 worker_exe: None,
1084 })
1085 .await
1086 .expect("assemble a node over a temp store");
1087
1088 // The deploy store is live: `assemble` already materialized the reserved
1089 // `default` project, so a second ensure reports "already present" (`false`).
1090 assert!(
1091 !node
1092 .deploy
1093 .ensure_default_project()
1094 .await
1095 .expect("read the default project"),
1096 "assemble should have materialized the default project"
1097 );
1098
1099 // The assembled router (the same wiring `serve` binds) answers /healthz.
1100 let router =
1101 boatramp_server::router_with(node.deploy, node.auth, node.handlers, node.options);
1102 let response = router
1103 .oneshot(
1104 Request::builder()
1105 .uri("/healthz")
1106 .body(Body::empty())
1107 .unwrap(),
1108 )
1109 .await
1110 .expect("route /healthz");
1111 assert_eq!(response.status(), StatusCode::OK);
1112 }
1113}