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