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 // Keep a clone of the node blob storage for the project-export driver (it copies the
180 // project's blob prefix in/out via `blob_migrate`), captured before `storage` is
181 // moved into the handler runtime below.
182 #[cfg(feature = "project-export")]
183 let export_blobs = storage.clone();
184 // Copy out the posture scalars up front so `options` can be moved into the
185 // returned `RunningNode` without a lingering borrow.
186 let max_handler_blob_bytes = options.posture.max_handler_blob_bytes;
187 let max_component_bytes = options.posture.max_component_bytes;
188 let allow_guest_private_egress = options.posture.allow_guest_private_egress;
189 let allow_guest_tcp_egress = options.posture.allow_guest_tcp_egress;
190 let allow_guest_tcp_listener = options.posture.allow_guest_tcp_listener;
191 let allow_env_secret_refs = options.posture.allow_env_secret_refs;
192 let allow_guest_email = options.posture.allow_guest_email;
193 // The instance's own serve socket(s) a guest self-call may reach, when the posture allows
194 // it: a wildcard bind (`0.0.0.0`/`::`) is reachable on loopback, so normalize to
195 // `127.0.0.1`/`::1`; a specific bind is itself.
196 let self_egress_addrs = self_egress_addrs(serve_addr, options.posture.allow_guest_self_egress);
197 let allow_shared_kernel = options.posture.allow_shared_kernel_compute;
198 let domain_verify_allow_private = options.posture.domain_verify_allow_private;
199
200 // The deploy store the router serves from — built up front so the handler
201 // runtime's managed compute-backed `sql` binding can resolve DB endpoints from
202 // the same store the reconcile writes.
203 let compute_storage = storage.clone();
204 let deploy = DeployStore::new(storage, kv.clone());
205 // **Crown-jewel frontier-sync (v0.9.0 KV-recovery, C2).** The sealed-secret / sealed-credential
206 // stores below hold IRREPLACEABLE data (a dropped write = a lost secret with no client copy), so
207 // rather than rely on per-call-site discipline we route them ALL through a `CheckpointKv`: every
208 // write advances the durable frontier before it acks, so a crash's self-heal-on-open trailing-
209 // tail quarantine can never drop one. Wrapping ONCE here is the can't-miss guarantee. (On the
210 // cluster `RaftKv` / `MemoryKv` the added checkpoint is a no-op, so this is inert there.) The
211 // mixed `DeployStore` above keeps the RAW `kv` and selects the frontier-sync per method instead
212 // (its `current/*` pointers, history, invocation records and metering stay async).
213 let secrets_kv: Arc<dyn KvStore> = Arc::new(boatramp_core::kv::CheckpointKv::new(kv.clone()));
214 // The `[secrets]` envelope (local KEK / Vault) that seals a managed SQL
215 // credential at rest. `None` ⇒ no wrapping (a managed DB then fails closed).
216 let secrets_envelope = build_secrets_envelope(config.secrets.as_ref(), data_dir)?;
217 // The project-scoped internal secret store, built from the same KV + `[secrets]`
218 // envelope that seal managed-DB credentials. Backs both the `boatramp:<name>`
219 // resolver (wired into the handler runtime below, when that feature is present)
220 // and the admin secrets API (threaded into `ServerOptions` unconditionally, so it
221 // works on a lean node too). `None` when no envelope is configured — the admin
222 // endpoints then fail closed with a clear 501, never a panic.
223 let secret_store = secrets_envelope.clone().map(|envelope| {
224 Arc::new(boatramp_core::secret_store::SecretStore::new(
225 secrets_kv.clone(),
226 envelope,
227 ))
228 });
229 // The per-TENANT sealed secret store (task #493), sealed with the SAME `[secrets]` envelope.
230 // Backs both the control-plane CRUD (threaded into `ServerOptions` below) and — when the
231 // `tenant-secrets` feature is compiled — the runtime guest binding (the SAME `Arc` handed to
232 // `set_tenant_secret_store`). `None` when no envelope is configured, so the endpoints fail
233 // closed with a clear 501 and the guest binding is not built.
234 let tenant_secret_store = secrets_envelope.clone().map(|envelope| {
235 Arc::new(boatramp_core::secret_store::TenantSecretStore::new(
236 secrets_kv.clone(),
237 envelope,
238 ))
239 });
240 // The project-scoped SMTP email-profile store, built from the same KV + envelope
241 // (the password is sealed at rest). Backs the admin API (`options` below,
242 // unconditionally, so it works on a lean node) and — when the `email` feature +
243 // `allow_guest_email` posture permit — the runtime's host-side profile
244 // resolution (wired inside `build_handler_runtime`). `None` with no envelope, so
245 // the admin email endpoints fail closed with a clear 501.
246 let email_profile_store = secrets_envelope.clone().map(|envelope| {
247 Arc::new(boatramp_core::email_config::EmailProfileStore::new(
248 secrets_kv.clone(),
249 envelope,
250 ))
251 });
252
253 // Dev-posture guest-egress extra CA(s): when the posture permits (off/refused under
254 // multi-tenant) AND the operator pointed `BOATRAMP_GUEST_EGRESS_EXTRA_CA_FILE` at a PEM, parse
255 // it into trust anchors the guest's outbound `wasi:http` TLS client trusts on TOP of the webpki
256 // roots (for a hermetic HTTPS test double). Empty otherwise. A configured-but-unreadable/
257 // unparsable file is a hard config error (fail closed), never a silent no-trust.
258 let guest_egress_extra_roots =
259 load_guest_egress_extra_roots(options.posture.allow_guest_egress_extra_ca)?;
260
261 // The handler runtime reuses the same blob/KV backends (per-site prefixed)
262 // for its wasi:blobstore/keyvalue bindings; the sql binding is selected by
263 // `[handlers.bindings.sql]` (default: per-site libsql files under <data-dir>).
264 let handlers = crate::handlers::build_handler_runtime(
265 kv.clone(),
266 compute_storage.clone(),
267 per_project_blob_backends,
268 data_dir,
269 config.handlers.as_ref(),
270 messaging,
271 max_handler_blob_bytes,
272 max_component_bytes,
273 allow_guest_private_egress,
274 allow_guest_tcp_egress,
275 allow_guest_tcp_listener,
276 self_egress_addrs,
277 guest_egress_extra_roots,
278 allow_env_secret_refs,
279 allow_guest_email,
280 options.posture.require_tenancy_declaration,
281 options.posture.allow_cross_tenant_db,
282 &deploy,
283 secrets_envelope.clone(),
284 )
285 .await?;
286 // JWKS pre-warm (federated-gateway overhead fix): fetch the configured first-party (`own`-tier)
287 // JWKS up front so even the FIRST request per first-party issuer is instant, not a cold fetch.
288 // Best-effort + spawned (a slow/unreachable IdP must never delay node readiness); the token
289 // cache's single-flight lock dedups a pre-warm fetch against a concurrent first request.
290 // `prewarm_own_jwks` internally honors the `[handlers] jwks_prewarm` flag (no-op when off).
291 // Sites deployed AFTER startup simply warm lazily on first request (today's behavior).
292 #[cfg(feature = "handlers")]
293 {
294 let prewarm_deploy = deploy.clone();
295 tokio::spawn(async move {
296 let entries = collect_own_jwks_prewarm(&prewarm_deploy).await;
297 if !entries.is_empty() {
298 boatramp_server::prewarm_own_jwks(&entries).await;
299 }
300 });
301 }
302 // Hand the runtime the SAME per-tenant secret store `Arc` the control-plane routes hold (task
303 // #493), so a guest `tenant-secrets` `get` and a control-plane `PUT` seal/unseal against ONE
304 // store. Unset when no `[secrets]` envelope, so the guest binding is not built (fail-closed).
305 // Handlers-gated: `set_tenant_secret_store` lives on the handler runtime, so a lean (no-handlers)
306 // node has no guest binding to wire (the control-plane routes still work via `ServerOptions`).
307 #[cfg(feature = "handlers")]
308 if let Some(store) = tenant_secret_store.clone() {
309 handlers.set_tenant_secret_store(store);
310 }
311 // Record the node data directory so the node-health endpoint can report `/data` filesystem
312 // headroom (a node-health-alerting request — the disk-full incident signal).
313 #[cfg(feature = "handlers")]
314 handlers.set_data_dir(data_dir.to_path_buf());
315 // Wire the fleet session-cookie signer (R3, PLAN-tenancy-principal): the same issuer that mints
316 // control-plane tokens signs + verifies the host-issued anonymous session cookie AND the
317 // delegable capabilities (PLAN-delegable-capabilities). Handlers-gated: the session-cookie
318 // machinery lives on the handler runtime, so a lean (no-handlers) build has nothing to wire.
319 //
320 // The fleet signer is a DIFFERENT trust domain from control-plane admin auth (signing a
321 // customer's session cookie / an embed capability is not the authority to admit an operator to
322 // the control plane), but production derives it from the control-plane issuer for convenience.
323 // For a DEV / loopback node with control-plane auth disabled (`options.issuer` is `None`),
324 // auto-provision an EPHEMERAL in-memory Ed25519 fleet key so the guest-facing signer just works
325 // — session cookies + capability mint/verify — WITHOUT turning on control-plane auth. Strictly
326 // gated to a loopback bind (or an in-process embedder with no bind address): never on a public
327 // bind, where an ephemeral key would silently invalidate live capabilities across a restart (a
328 // public node that wants guest capabilities without control-plane auth must supply a persistent
329 // key). Ephemeral = issue + verify within one process run; nothing persisted, no cross-process
330 // or cross-deploy trust. Production is byte-identical: a real deploy supplies a control-plane key
331 // ⇒ `issuer` is `Some` ⇒ this fallback is never taken.
332 #[cfg(feature = "handlers")]
333 {
334 let fleet_signer = options.issuer.clone().or_else(|| {
335 should_autoprovision_fleet_signer(serve_addr).then(|| {
336 tracing::warn!(
337 "control-plane auth is disabled and no signer is configured; auto-provisioning \
338 an EPHEMERAL in-memory fleet signer (Ed25519) for host session cookies + \
339 delegable capabilities on this loopback/dev node — regenerated each start, \
340 never persisted. Configure a control-plane key (or a dedicated signer) for \
341 production."
342 );
343 Arc::new(boatramp_core::cose::LocalSigner::generate(
344 boatramp_core::cose::TokenAlg::Ed25519,
345 )) as Arc<dyn boatramp_core::cose::Signer>
346 })
347 });
348 if let Some(issuer) = fleet_signer {
349 handlers.set_session_signer(issuer);
350 }
351 }
352 // Enable guest capability minting (`boatramp:handlers/capability`, PLAN-delegable-capabilities)
353 // when the operator posture allows it. A minted capability is verified against the same fleet
354 // signer as the session cookie (wired just above), so this only enables the mint path + the TTL
355 // ceiling; posture-off (or a zero ceiling) ⇒ not offered (a guest `mint` is access-denied).
356 #[cfg(feature = "capability")]
357 if options.posture.allow_guest_mint_capability {
358 handlers.set_capability_minting(options.posture.max_guest_capability_ttl_secs);
359 }
360 // Per-project tenancy/capability posture overrides (Gap 4a): resolve each
361 // `[security.projects.<p>]` override against the fleet base so one serve process can run a
362 // strict-isolation project beside a looser one on a shared, multi-project machine. Empty ⇒
363 // every project uses the node base wired just above. Only these four in-project knobs are
364 // per-project; cross-project isolation stays structural (project = database).
365 #[cfg(feature = "handlers")]
366 {
367 let base = &options.posture;
368 let overrides: std::collections::BTreeMap<
369 String,
370 boatramp_core::security::ResolvedProjectTenancy,
371 > = config
372 .security
373 .as_ref()
374 .map(|s| {
375 s.projects
376 .iter()
377 .map(|(project, ovr)| (project.clone(), base.project_tenancy(ovr)))
378 .collect()
379 })
380 .unwrap_or_default();
381 handlers.set_project_tenancy_overrides(overrides);
382 }
383 // Wire the guest project self-config capability (`boatramp:handlers/admin`) when the
384 // operator posture enables at least one surface. The controller reuses the same in-process
385 // domain-verify / email-profile / secret / site-config subsystems + the real domain probe;
386 // it's project-scoped per grant and rate-limited + audited. Posture-off ⇒ not offered.
387 #[cfg(feature = "admin")]
388 {
389 use boatramp_handlers::AdminSurface;
390 let p = &options.posture;
391 let mut surfaces = std::collections::BTreeSet::new();
392 if p.allow_guest_admin_domains {
393 surfaces.insert(AdminSurface::Domains);
394 }
395 if p.allow_guest_admin_email {
396 surfaces.insert(AdminSurface::Email);
397 }
398 if p.allow_guest_admin_site {
399 surfaces.insert(AdminSurface::Site);
400 }
401 if p.allow_guest_admin_secrets {
402 surfaces.insert(AdminSurface::Secrets);
403 }
404 if !surfaces.is_empty() {
405 let controller = Arc::new(boatramp_server::ServerAdminController::with_server_probe(
406 deploy.clone(),
407 email_profile_store.clone(),
408 secret_store.clone(),
409 p.domain_verify_allow_private,
410 ));
411 handlers.set_admin(controller, surfaces);
412 }
413 }
414 // Leader-gate cron firing (cluster: only the Raft leader fires; single-node: an
415 // always-true gate, equivalent to the unset default). The same gate drives the
416 // reconcile loops below, so all three converge on one leader per fleet. Only the
417 // handler runtime has a scheduler, so this is a no-op without the `handlers` feature.
418 #[cfg(feature = "handlers")]
419 handlers.set_cron_leader_gate(is_leader.clone());
420 // FA-5b2: on a cloud backend, wire the blob-change notification provisioner +
421 // its tier so adding a `blob` trigger provisions (and removing it retracts).
422 #[cfg(feature = "handlers")]
423 if let Some(provider) = watch_provider {
424 handlers.set_watch_provider(provider);
425 handlers.set_provision_tier(provision_tier);
426 }
427 #[cfg(not(feature = "handlers"))]
428 let _ = (watch_provider, provision_tier);
429
430 // Materialize the reserved `default` project so `project ls` / `project show
431 // default` reflect it on a fresh install, not only after a migration. Best
432 // effort: the reader backstop keeps listings correct even if this write can't
433 // land, so a transient failure must never block serving.
434 match deploy.ensure_default_project().await {
435 Ok(true) => tracing::info!("materialized the reserved `default` project record"),
436 Ok(false) => {}
437 Err(e) => tracing::warn!(
438 error = %e,
439 "could not materialize the `default` project record; readers use the synthesized default"
440 ),
441 }
442 // Wire the function-to-function invoke resolver now the deploy store exists,
443 // so a function granted `invoke` can call a sibling in-process (FI).
444 #[cfg(feature = "handlers")]
445 handlers.set_invoker(deploy.clone());
446
447 // Compute reconcile loop. Single-node is always the "leader". Backends are
448 // built from the `[compute]` config + capability detection; a no-op when none
449 // are registered. Detached for the server's life.
450 // Decide which single workload (if any) may adopt the pre-v0.46 shared legacy `data`
451 // volume on this node, from the `databases` config — so the container backend migrates a
452 // reused deployment's managed-DB data into the per-(project, workload) scoped layout
453 // safely and a non-owner fails closed. `None` when there is no managed DB or ownership is
454 // ambiguous (≥2 co-located managed DBs, none designated via `adopt_legacy_data_volume`).
455 // The node-trusted legacy-`data` claimant (+ a credential probe reused by the F4 migration
456 // below). Computed from the node's OWN config + control-plane records (the deploy store),
457 // NEVER a workload spec — so it recognizes the node-default (turnkey) managed pg as the owner
458 // of the bare `<volumes>/data` cluster even when the `databases` config is EMPTY (the common
459 // ENV-configured turnkey deployment). Needs the `[secrets]` envelope that seals managed-DB
460 // credentials; without it there are no managed DBs, so the claimant is `None`.
461 #[cfg(any(feature = "sql-postgres", feature = "sql-mysql"))]
462 let (legacy_data_claimant, f4_creds) = match secrets_envelope.clone() {
463 Some(envelope) => {
464 let creds =
465 crate::managed_sql::ManagedSqlCredentials::new(secrets_kv.clone(), envelope);
466 let empty = std::collections::BTreeMap::new();
467 let databases = config
468 .handlers
469 .as_ref()
470 .and_then(|h| h.bindings.sql.as_ref())
471 .map(|sql| &sql.databases)
472 .unwrap_or(&empty);
473 let claimant =
474 crate::managed_sql::legacy_data_volume_claimant(databases, &deploy, &creds).await;
475 (claimant, Some(creds))
476 }
477 None => (None, None),
478 };
479 #[cfg(not(any(feature = "sql-postgres", feature = "sql-mysql")))]
480 let legacy_data_claimant: Option<(String, String)> = None;
481 let (compute_backends, compute_node) = crate::compute::build_compute(
482 config.compute.as_ref(),
483 compute_storage,
484 data_dir,
485 node_id,
486 !allow_shared_kernel,
487 options.daemon_runtime.clone(),
488 worker_exe.as_deref(),
489 legacy_data_claimant.clone(),
490 )
491 .await;
492 // Adopt the IPs of already-running replicas into each backend's fresh-on-boot
493 // IP pool BEFORE the reconcile loop starts allocating. A backend with a per-node
494 // pool (the native container backend) rebuilds it empty each process start; without
495 // this the boot reconcile could re-hand a live address to a different workload —
496 // the container-IP collision — or move a replica's endpoint on relaunch. Feeds
497 // every persisted replica's `(workload, replica, endpoint-ip)`; each backend keeps
498 // only the IPs in its own subnet (a cheap no-op for docker/cloudflare/VMM).
499 crate::compute::adopt_running_replica_ips(&deploy, &compute_backends).await;
500 // F4 — node-side BULK migration of managed-tenant legacy volume dirs into the per-(project,
501 // workload) scoped layout, BEFORE the reconcile loop launches anything. Authorized ENTIRELY
502 // from node-trusted state (the deploy store + node-minted sealed credentials + the legacy-
503 // `data` claimant), never a workload spec. This proactively prevents the launch-time
504 // fail-closed for node-provisioned managed tenants on upgrade — the node-default pg adopts its
505 // `<volumes>/data` cluster, and each per-tenant Single dir moves to its scoped path — while the
506 // launch-time adoption remains the safety backstop for anything not covered here. Idempotent.
507 #[cfg(any(feature = "sql-postgres", feature = "sql-mysql"))]
508 if let Some(creds) = &f4_creds {
509 crate::managed_sql::migrate_managed_tenant_legacy_volumes(
510 &deploy,
511 creds,
512 &legacy_data_claimant,
513 &compute_backends,
514 )
515 .await;
516 }
517 // Capture a run_ephemeral-capable compute backend for the project-export/import + `sql exec`
518 // managed-SQL seam BEFORE `compute_backends` is consumed by the reconcile loop below (a cheap
519 // `Arc` clone). Prefer the Docker-daemon backend, but FALL BACK to the native `container`
520 // backend — both implement `run_ephemeral` (the native one since v0.32.0), so the seam wires on
521 // a fly/firecracker (container-only) node too, not only a Docker host. `None` ⇒ neither backend
522 // is present, so the managed-SQL export seam is not wired (the `501 operator-SQL seam not
523 // configured`). This was the gap: it previously required `"docker"` and silently no-op'd on every
524 // container node.
525 #[cfg(feature = "project-export")]
526 let export_sql_backend: Option<Arc<dyn boatramp_core::compute::ComputeBackend>> =
527 compute_backends
528 .get("docker")
529 .or_else(|| compute_backends.get("container"))
530 .cloned();
531 // Per-project internal DNS (service discovery): start the resolver on the bridge
532 // gateway so a guest resolves peers by name within its project. On by default;
533 // starts only when the container backend + bridge are up (Linux). Detached for
534 // the node's serving life (pushed into `reconcile` below). Started before the
535 // reconcile loop consumes `compute_backends` — it borrows the registry to check
536 // the container backend is present.
537 let internal_dns =
538 crate::compute::spawn_internal_dns(config.compute.as_ref(), &compute_backends, &deploy);
539 // Activate the compute sql-shim (PLAN-compute-bindings): bind its listener +
540 // build the resolver when a sql provider and `compute.sql_shim_url` are both present.
541 #[cfg(feature = "handlers")]
542 let sql_resolver = boatramp_server::sql_shim::spawn_sql_shim(
543 handlers.sql_backends(),
544 config.compute.as_ref().and_then(|c| c.sql_shim_url.clone()),
545 )
546 .await;
547 #[cfg(not(feature = "handlers"))]
548 let sql_resolver: Option<Arc<dyn boatramp_core::compute::ComputeBindingResolver>> = None;
549
550 // Activate the compute blob-shim (PLAN-compute-bindings): the symmetric sibling of the
551 // sql-shim — bind its listener + build the resolver when a blob provider and
552 // `compute.blob_shim_url` are both present, so a workload's `--bind blob` reaches the
553 // SAME per-site `hblob/{qualified-site}/…` namespace a `wasi:blobstore` handler sees.
554 #[cfg(feature = "handlers")]
555 let blob_resolver = boatramp_server::blob_shim::spawn_blob_shim(
556 handlers.blob_backends(),
557 config
558 .compute
559 .as_ref()
560 .and_then(|c| c.blob_shim_url.clone()),
561 config
562 .compute
563 .as_ref()
564 .and_then(|c| c.blob_shim_max_object_bytes),
565 )
566 .await;
567 #[cfg(not(feature = "handlers"))]
568 let blob_resolver: Option<Arc<dyn boatramp_core::compute::ComputeBindingResolver>> = None;
569
570 // Activate the compute messaging-shim (PLAN-compute-bindings): the symmetric sibling of the
571 // sql/blob shims — bind its listener + build the resolver when a messaging substrate and
572 // `compute.messaging_shim_url` are both present, so a workload's `--bind messaging` publishes
573 // to the SAME `{project}/bus/<topic>` project bus a `wasi:messaging` producer's `bus:` publish
574 // reaches (the native-MX-edge → `bus:deliver` → consumer-function round-trip, M28 28b).
575 #[cfg(feature = "handlers")]
576 let messaging_resolver = boatramp_server::messaging_shim::spawn_messaging_shim(
577 handlers.messaging(),
578 config
579 .compute
580 .as_ref()
581 .and_then(|c| c.messaging_shim_url.clone()),
582 )
583 .await;
584 #[cfg(not(feature = "handlers"))]
585 let messaging_resolver: Option<Arc<dyn boatramp_core::compute::ComputeBindingResolver>> = None;
586
587 // Retain a clone of the blob resolver (before it is moved into the reconcile chain) so
588 // the dev/CI affordance `POST /api/compute/dev-bind-blob` can mint + register a blob
589 // credential for a non-managed local process through the EXACT managed `resolve` path.
590 // `None` when the blob-shim is inactive ⇒ that endpoint returns `501`.
591 let dev_blob_bind_resolver = blob_resolver.clone();
592 // The symmetric clone for `POST /api/compute/dev-bind-messaging` (the messaging dev-bind
593 // affordance). `None` when the messaging-shim is inactive ⇒ that endpoint returns `501`.
594 let dev_messaging_bind_resolver = messaging_resolver.clone();
595
596 // One resolver for the reconcile: each shim filters to its own binding kind, so chaining
597 // them lets a workload declaring `sql`, `blob`, and/or `messaging` bindings be served by all
598 // three from a single `resolve` call.
599 let binding_resolver = boatramp_core::compute::ChainedBindingResolver::chain([
600 sql_resolver,
601 blob_resolver,
602 messaging_resolver,
603 ]);
604
605 // Managed compute-backed SQL (PLAN-managed-compute-sql P2-b): if the handler
606 // `sql` config declares any managed database, inject its `POSTGRES_*`/`MYSQL_*`
607 // server-init env into the DB workload at launch from the sealed credential.
608 // Reaching here with a managed DB implies an envelope (build_handler_runtime
609 // fails closed otherwise), so the credential store always has one to seal with.
610 // Keep a clone of the secrets envelope for the operator-SQL capability below
611 // (the managed_db_resolver match moves the original).
612 #[cfg(any(feature = "sql-postgres", feature = "sql-mysql"))]
613 let operator_envelope = secrets_envelope.clone();
614 // …and a second clone for the tenant-deprovision capability (drops a deleted
615 // tenant's managed DB/role/credential on project/site delete). It needs a real
616 // envelope to seal/unseal + delete per-tenant credentials, so it is wired only
617 // when one is present (same fail-closed gating as the managed-DB paths).
618 #[cfg(any(feature = "sql-postgres", feature = "sql-mysql"))]
619 let deprovision_envelope = secrets_envelope.clone();
620 // …and a clone for the provisioning drift-repair capability (owner-model retrofit /
621 // reconcile). Like the migrate path it connects as the sealed owner role and re-seals
622 // credentials, so it needs a real envelope; wired only when one is present.
623 #[cfg(any(feature = "sql-postgres", feature = "sql-mysql"))]
624 let repair_envelope = secrets_envelope.clone();
625 // …and a third clone for the soft-delete tombstone reaper (the leader-gated task
626 // that hard-drops a Shared-Postgres tenant once its grace window elapses). It, too,
627 // needs a real envelope to unseal the superuser credential + delete the per-tenant
628 // one on hard-drop.
629 #[cfg(any(feature = "sql-postgres", feature = "sql-mysql"))]
630 let reaper_envelope = secrets_envelope.clone();
631 // …and a clone for the declarative managed-database capability (#501 Stage B): it
632 // provisions the declared DB + seals its credential server-side, so it needs a real
633 // envelope; wired only when one is present (fail-closed like every managed-DB path).
634 #[cfg(any(feature = "sql-postgres", feature = "sql-mysql"))]
635 let declare_envelope = secrets_envelope.clone();
636 // …and a clone for the project-export driver (it unseals managed-DB credentials to
637 // assemble the dump/restore connection). Captured here before the resolver match
638 // moves the original.
639 #[cfg(feature = "project-export")]
640 let export_envelope = secrets_envelope.clone();
641 // Build the managed-DB server-init credential injector whenever a secrets envelope is
642 // present — NOT only when the node-static `[databases]` map is non-empty. A turnkey,
643 // ENV-configured node with EMPTY node-static `[databases]` still has APPLIED managed dbs
644 // (declared via `boatramp apply`, stored in the deploy store, launched as a derived
645 // `bramp-db-<digest>` workload); the resolver resolves those from the deploy store at launch
646 // (`ManagedDbEnv::resolve_spec`), so without this the fresh applied db would launch with no
647 // `POSTGRES_*`/`MYSQL_*` env and the stock image would refuse to `initdb`. The resolver is a
648 // no-op for every non-managed workload, so building it unconditionally (given an envelope) is
649 // safe. (Same relaxation the declarative capability already applies — a node with no
650 // node-static databases can still serve a project declaration.) No envelope ⇒ `None`: a
651 // managed DB requires one to seal its credential, so there is nothing to inject.
652 #[cfg(any(feature = "sql-postgres", feature = "sql-mysql"))]
653 let managed_db_resolver: Option<Arc<dyn boatramp_core::compute::ManagedDbEnvResolver>> =
654 match secrets_envelope {
655 Some(envelope) => {
656 let static_dbs = config
657 .handlers
658 .as_ref()
659 .and_then(|h| h.bindings.sql.as_ref())
660 .map(|sql| sql.databases.clone())
661 .unwrap_or_default();
662 // Crown-jewel (C2): sealed managed-DB credentials go through the frontier-syncing
663 // `secrets_kv`, so a freshly-minted DB credential is past the durable frontier before
664 // the workload sees it — never droppable by the self-heal-on-open trailing-tail quarantine.
665 let creds =
666 crate::managed_sql::ManagedSqlCredentials::new(secrets_kv.clone(), envelope);
667 let privilege = config
668 .compute
669 .as_ref()
670 .map(|c| c.managed_db_privilege)
671 .unwrap_or_default();
672 let env = crate::managed_sql::ManagedDbEnv::from_config(
673 &static_dbs,
674 creds,
675 privilege,
676 deploy.clone(),
677 );
678 Some(Arc::new(env) as Arc<_>)
679 }
680 None => None,
681 };
682 #[cfg(not(any(feature = "sql-postgres", feature = "sql-mysql")))]
683 let managed_db_resolver: Option<Arc<dyn boatramp_core::compute::ManagedDbEnvResolver>> = None;
684
685 // Turnkey managed DB: auto-register the compute workload(s) backing each managed
686 // co-located database that has none yet, so declaring the `databases` binding is
687 // enough to boot the DB (no separate `compute set` / apply). Tenant-aware — a
688 // `Shared` binding registers its one shared server; a `Single` binding registers
689 // nothing at boot (its per-tenant `<compute>-<ident>` is created durably by the lazy
690 // resolve on first `sql` use and relaunched by the reconcile, so a project that never
691 // uses `sql` — e.g. a static-only site — never gets a spurious DB). Non-clobbering +
692 // idempotent; runs before the reconcile loop so its first tick can launch what it
693 // registered.
694 #[cfg(any(feature = "sql-postgres", feature = "sql-mysql"))]
695 if let Some(sql) = config
696 .handlers
697 .as_ref()
698 .and_then(|h| h.bindings.sql.as_ref())
699 .filter(|sql| !sql.databases.is_empty())
700 {
701 crate::managed_sql::auto_register_managed_db_workloads(&deploy, &sql.databases).await;
702 }
703
704 // Operator SQL capability (managed-DB migrations/queries via the sealed credential, resolved
705 // server-side) — backs `POST /api/sql/{db}/{exec,query}`. The SAME concrete NodeOperatorSql
706 // also backs the owner-gated schema-migration runner (which reuses its owner + superuser
707 // backends), so build it ONCE and share it.
708 // Build the SAME concrete NodeOperatorSql once (when a managed DB is configured) and share it:
709 // it backs both `operator_sql` (the sql exec/query cap) and the migration runner (which reuses
710 // its owner + superuser backends). Two separate bindings so neither annotation is a complex type.
711 // The migration substrate is a single dispatcher (crate::managed_sql::DispatchMigrationRunner)
712 // routing each `(project, db)` to its engine's substrate: the sqlx NodeMigrationRunner for a
713 // Postgres/MySQL binding, the LibsqlMigrationRunner for a `libsql` binding. It compiles whenever a
714 // sqlx engine OR `migrate` (⇒ libsql) is on, so the embedded-libsql default can migrate even on a
715 // node with no external sqlx engine. `operator_sql` (the `POST /api/sql/{db}/{exec,query}` cap)
716 // stays sqlx-only — a libsql file has no operator-SQL/credential seam.
717 #[cfg(any(feature = "sql-postgres", feature = "sql-mysql"))]
718 let operator_sql: Option<Arc<dyn boatramp_core::sql::OperatorSql>>;
719 // Late-init: the `if want_sql_substrate` branches below assign it (and, under sqlx,
720 // `operator_sql` in the same block), and the bodies differ by feature-cfg — so a direct
721 // `let … = if {…}` would need cfg'd branch bodies. The late-init keeps that readable; the
722 // value is always assigned before use.
723 #[cfg(any(feature = "sql-postgres", feature = "sql-mysql", feature = "migrate"))]
724 #[allow(clippy::needless_late_init)]
725 let migration_substrate: Option<Arc<dyn boatramp_core::sql::MigrationSubstrate>>;
726 // Build the operator-SQL / migration substrate when the node has a node-static `databases`
727 // map OR — under a sqlx engine — a secrets envelope. The envelope case is the turnkey,
728 // ENV-configured node with EMPTY node-static `[databases]`: it can still have APPLIED managed
729 // dbs (declared via `boatramp apply`, in the deploy store) that `sql exec/query` must reach,
730 // and `NodeOperatorSql` resolves those through the SAME merge point the declare capability
731 // uses. (A `migrate`-only node has no managed-credential seam, so it still builds the libsql
732 // substrate only when a `libsql` binding is actually declared in the static config.)
733 #[cfg(any(feature = "sql-postgres", feature = "sql-mysql", feature = "migrate"))]
734 let sql_static_dbs = config
735 .handlers
736 .as_ref()
737 .and_then(|h| h.bindings.sql.as_ref())
738 .map(|sql| sql.databases.clone())
739 .unwrap_or_default();
740 #[cfg(any(feature = "sql-postgres", feature = "sql-mysql"))]
741 let want_sql_substrate = !sql_static_dbs.is_empty() || operator_envelope.is_some();
742 #[cfg(all(
743 not(any(feature = "sql-postgres", feature = "sql-mysql")),
744 feature = "migrate"
745 ))]
746 let want_sql_substrate = !sql_static_dbs.is_empty();
747 #[cfg(any(feature = "sql-postgres", feature = "sql-mysql", feature = "migrate"))]
748 if want_sql_substrate {
749 // The sqlx (Postgres/MySQL) arm — the shared NodeOperatorSql backs both the operator-SQL
750 // cap and the sqlx migration runner. Only built when a sqlx engine is compiled in.
751 #[cfg(any(feature = "sql-postgres", feature = "sql-mysql"))]
752 let node_op = Arc::new(crate::managed_sql::NodeOperatorSql::new(
753 sql_static_dbs.clone(),
754 kv.clone(),
755 operator_envelope,
756 deploy.clone(),
757 ));
758 // The operator's trusted-extension allowlist — the only extensions a migration may
759 // enable (empty ⇒ none). See ExternalSqlConfig::migrate_trusted_extensions.
760 #[cfg(any(feature = "sql-postgres", feature = "sql-mysql"))]
761 let trusted: std::collections::BTreeSet<String> = config
762 .handlers
763 .as_ref()
764 .and_then(|h| h.bindings.sql.as_ref())
765 .and_then(|sql| sql.migrate_trusted_extensions.clone())
766 .unwrap_or_default()
767 .into_iter()
768 .collect();
769 migration_substrate = Some(Arc::new(crate::managed_sql::DispatchMigrationRunner::new(
770 #[cfg(any(feature = "sql-postgres", feature = "sql-mysql"))]
771 node_op.clone(),
772 #[cfg(any(feature = "sql-postgres", feature = "sql-mysql"))]
773 trusted,
774 #[cfg(feature = "migrate")]
775 sql_static_dbs.clone(),
776 ))
777 as Arc<dyn boatramp_core::sql::MigrationSubstrate>);
778 #[cfg(any(feature = "sql-postgres", feature = "sql-mysql"))]
779 {
780 operator_sql = Some(node_op as Arc<dyn boatramp_core::sql::OperatorSql>);
781 }
782 } else {
783 #[cfg(any(feature = "sql-postgres", feature = "sql-mysql"))]
784 {
785 operator_sql = None;
786 }
787 migration_substrate = None;
788 }
789 // When only `migrate` (no sqlx) is compiled, the operator-SQL cap does not exist.
790 #[cfg(all(
791 not(any(feature = "sql-postgres", feature = "sql-mysql")),
792 feature = "migrate"
793 ))]
794 let operator_sql: Option<Arc<dyn boatramp_core::sql::OperatorSql>> = None;
795 #[cfg(not(any(feature = "sql-postgres", feature = "sql-mysql", feature = "migrate")))]
796 let migration_substrate: Option<Arc<dyn boatramp_core::sql::MigrationSubstrate>> = None;
797 #[cfg(not(any(feature = "sql-postgres", feature = "sql-mysql", feature = "migrate")))]
798 let operator_sql: Option<Arc<dyn boatramp_core::sql::OperatorSql>> = None;
799
800 // Tenant-deprovision capability (drop a deleted tenant's managed DB/role/sealed
801 // credential on project/site delete). Wired only when a compute-backed managed
802 // database + a secrets envelope are both present — same gating as operator_sql,
803 // plus the envelope requirement (it must seal/unseal per-tenant credentials).
804 // The soft-delete grace window for a Shared-Postgres managed tenant
805 // (`handlers.bindings.sql.deprovision_grace_secs`, env-settable). Default 7 days;
806 // `0` disables the soft path (immediate hard drop). Threaded to the deprovisioner
807 // (which soft-deletes) and implicitly honored by the reaper (which only ever finds
808 // tombstones a >0 grace produced).
809 #[cfg(any(feature = "sql-postgres", feature = "sql-mysql"))]
810 let deprovision_grace_secs = config
811 .handlers
812 .as_ref()
813 .and_then(|h| h.bindings.sql.as_ref())
814 .and_then(|sql| sql.deprovision_grace_secs)
815 .unwrap_or(crate::tenant_sql::DEFAULT_DEPROVISION_GRACE_SECS);
816 #[cfg(any(feature = "sql-postgres", feature = "sql-mysql"))]
817 let tenant_deprovisioner: Option<Arc<dyn boatramp_core::sql::TenantDeprovisioner>> = config
818 .handlers
819 .as_ref()
820 .and_then(|h| h.bindings.sql.as_ref())
821 .filter(|sql| !sql.databases.is_empty())
822 .zip(deprovision_envelope)
823 .map(|(sql, envelope)| {
824 Arc::new(crate::tenant_sql::NodeTenantDeprovisioner::new(
825 deploy.clone(),
826 kv.clone(),
827 envelope,
828 sql.databases.clone(),
829 deprovision_grace_secs,
830 )) as Arc<_>
831 });
832 #[cfg(not(any(feature = "sql-postgres", feature = "sql-mysql")))]
833 let tenant_deprovisioner: Option<Arc<dyn boatramp_core::sql::TenantDeprovisioner>> = None;
834
835 // Provisioning drift-repair capability (owner-model retrofit / reconcile) — backs the
836 // `Project·Admin`-gated `/api/repair/{db}` + `/dry-run`. Same gating as operator_sql plus
837 // the envelope requirement (it re-seals the owner credential + connects as it). The
838 // envelope is threaded as `Some(_)` so a lean-but-managed node still gets a clear
839 // per-check error rather than a panic if none is configured.
840 #[cfg(any(feature = "sql-postgres", feature = "sql-mysql"))]
841 let tenant_repair: Option<Arc<dyn boatramp_core::sql::TenantRepair>> = config
842 .handlers
843 .as_ref()
844 .and_then(|h| h.bindings.sql.as_ref())
845 .filter(|sql| !sql.databases.is_empty())
846 .map(|sql| {
847 Arc::new(crate::repair::NodeTenantRepair::new(
848 sql.databases.clone(),
849 deploy.clone(),
850 kv.clone(),
851 repair_envelope.clone(),
852 )) as Arc<_>
853 });
854 #[cfg(not(any(feature = "sql-postgres", feature = "sql-mysql")))]
855 let tenant_repair: Option<Arc<dyn boatramp_core::sql::TenantRepair>> = None;
856
857 // Declarative managed-database capability (#501 Stage B) — backs the `Project·Admin`-gated
858 // `PUT /api/projects/{proj}/databases/{name}` + `POST …/ensure`. It persists a manifest
859 // `databases:` entry to `project/{project}/database/{name}`, enforces daemon-config-wins at
860 // the merge point (against the node-static `sql.databases`), refuses an identity change,
861 // binds provisioning to the caller's project, and eagerly provisions via `provision_tenant`.
862 // Requires a sqlx engine (it provisions a Postgres/MySQL server) AND a `[secrets]` envelope
863 // (a managed DB seals its credential). UNLIKE repair/operator_sql it is NOT gated on
864 // `!sql.databases.is_empty()` — a node with NO node-static databases can still accept a
865 // project declaration (the whole point of the declarative front door). The node-static map
866 // (possibly empty) is threaded so the daemon-wins conflict check has both sources.
867 #[cfg(any(feature = "sql-postgres", feature = "sql-mysql"))]
868 let managed_db_declare: Option<Arc<dyn boatramp_core::sql::ManagedDbDeclare>> =
869 declare_envelope.map(|envelope| {
870 let sql_cfg = config
871 .handlers
872 .as_ref()
873 .and_then(|h| h.bindings.sql.as_ref());
874 let static_dbs = sql_cfg.map(|sql| sql.databases.clone()).unwrap_or_default();
875 // Per-project declaration ceilings (#501 Stage B MEDIUM-1 — the disk-exhaustion
876 // guard): the operator's `max_declared_databases`/`max_declared_volume_mib`, or
877 // the built-in `apply_db_caps` defaults (16 DBs / 512 GiB) when unset.
878 let quota = crate::managed_db_declare::DeclareQuota::from_config(
879 sql_cfg.and_then(|sql| sql.max_declared_databases),
880 sql_cfg.and_then(|sql| sql.max_declared_volume_mib),
881 );
882 Arc::new(crate::managed_db_declare::NodeManagedDbDeclare::new(
883 static_dbs,
884 deploy.clone(),
885 kv.clone(),
886 envelope,
887 quota,
888 compute_backends.clone(),
889 )) as Arc<_>
890 });
891 #[cfg(not(any(feature = "sql-postgres", feature = "sql-mysql")))]
892 let managed_db_declare: Option<Arc<dyn boatramp_core::sql::ManagedDbDeclare>> = None;
893
894 // Operator compute-exec capability (run a command inside a running workload) —
895 // backs `POST /api/compute/{name}/exec`, gated by the `allow_compute_exec`
896 // posture. Clone the backend registry before the reconcile loop consumes it.
897 let compute_exec: Option<Arc<dyn boatramp_core::compute::ComputeExec>> = Some(Arc::new(
898 crate::compute::NodeComputeExec::new(compute_backends.clone(), deploy.clone()),
899 ) as Arc<_>);
900
901 // Operator volume-reclamation capability (list + remove persistent volumes) —
902 // backs `GET /api/compute/volumes` + `DELETE /api/compute/volumes/{name}`.
903 // Same admin-scoped `/api/compute/*` gate; clone the registry before the
904 // reconcile loop consumes the original below.
905 let compute_volumes: Option<Arc<dyn boatramp_core::compute::ComputeVolumes>> = Some(Arc::new(
906 crate::compute::NodeComputeVolumes::new(compute_backends.clone(), deploy.clone()),
907 )
908 as Arc<_>);
909
910 // Operator reconcile-plane control capability (restart a replica) — backs
911 // `POST /api/compute/maintenance/restart` (admin-scoped). Clone the registry
912 // before the reconcile loop consumes the original below.
913 let compute_control: Option<Arc<dyn boatramp_core::compute::ComputeControl>> = Some(Arc::new(
914 crate::compute::NodeComputeControl::new(compute_backends.clone(), deploy.clone()),
915 )
916 as Arc<_>);
917
918 let compute_reconcile = boatramp_server::spawn_compute_reconcile(
919 deploy.clone(),
920 compute_backends,
921 vec![compute_node],
922 boatramp_core::compute::BackendPolicy::from_shared_kernel_allowed(allow_shared_kernel),
923 is_leader.clone(),
924 compute_reconcile_tick(),
925 COMPUTE_IDLE_TIMEOUT,
926 binding_resolver,
927 managed_db_resolver,
928 );
929
930 // Tenant tombstone reaper: leader-gated hard-drop of soft-deleted Shared-Postgres
931 // tenants past their grace window (safe deprovision — see `tenant_sql`). Wired only
932 // when a compute-backed managed database + a secrets envelope are both present
933 // (same gating as the deprovisioner); each tombstone carries its own server +
934 // superuser, so the reaper needs no per-binding config. A `0` grace never writes a
935 // tombstone, so the sweep is simply inert then.
936 #[cfg(any(feature = "sql-postgres", feature = "sql-mysql"))]
937 let tombstone_reaper: Option<tokio::task::JoinHandle<()>> = config
938 .handlers
939 .as_ref()
940 .and_then(|h| h.bindings.sql.as_ref())
941 .filter(|sql| !sql.databases.is_empty())
942 .zip(reaper_envelope)
943 .map(|(_sql, envelope)| {
944 crate::tenant_sql::spawn_tenant_tombstone_reaper(
945 deploy.clone(),
946 kv.clone(),
947 envelope,
948 is_leader.clone(),
949 crate::tenant_sql::TOMBSTONE_REAPER_TICK,
950 )
951 });
952 #[cfg(not(any(feature = "sql-postgres", feature = "sql-mysql")))]
953 let tombstone_reaper: Option<tokio::task::JoinHandle<()>> = None;
954
955 // Domain-verify auto-complete: periodically re-check every site's pending
956 // ownership challenges and attach any that now pass — a published token (e.g.
957 // via `domain add --provider`) converges without a manual `domain verify`.
958 let dv_reconcile = boatramp_server::spawn_domain_verify_reconcile(
959 deploy.clone(),
960 domain_verify_allow_private,
961 is_leader,
962 DOMAIN_VERIFY_RECONCILE_TICK,
963 );
964
965 // Native project export/import capability (env-clone). The node ALWAYS has the
966 // deploy + KV + blob deps, so the driver is always wired (a node with no SQL still
967 // exports its KV slice + blobs); the engine contexts attach optionally — the managed
968 // pg/mysql ephemeral-dump context when a docker backend + envelope + operator-SQL are
969 // present, and the LOCAL libsql backend when the `sql` binding is embedded libsql
970 // (not remote sqld).
971 #[cfg(feature = "project-export")]
972 let project_export_cap: Option<Arc<dyn boatramp_core::project_export::ProjectExport>> = {
973 let sql_cfg = config
974 .handlers
975 .as_ref()
976 .and_then(|h| h.bindings.sql.as_ref());
977 let databases = sql_cfg.map(|s| s.databases.clone()).unwrap_or_default();
978 // The operator trusted-extension allowlist the superuser pre-creates in a pg shadow before
979 // the NON-superuser apply, so a legit `CREATE EXTENSION IF NOT EXISTS <ext>` (pgvector) in an
980 // untrusted dump no-ops instead of failing under the non-superuser apply (HIGH-1 pgvector
981 // wrinkle). Same operator-controlled allowlist the owner-gated migration surface uses.
982 let trusted_extensions = sql_cfg
983 .and_then(|s| s.migrate_trusted_extensions.clone())
984 .unwrap_or_default();
985 let mut driver = crate::project_export::NodeProjectExport::new(
986 databases,
987 deploy.clone(),
988 kv.clone(),
989 export_blobs,
990 data_dir.join("project-export"),
991 )
992 .with_trusted_extensions(trusted_extensions)
993 // T3: the configured base for resumable export/import dirs (None ⇒ surface disabled).
994 .with_resumable_base(
995 config
996 .serve
997 .as_ref()
998 .and_then(|s| s.resumable_export_dir.clone()),
999 );
1000 // Operator digest-pin / override for the ephemeral SQL-client images (the `pg_dump`/
1001 // `mysqldump`/`psql` one-shots), so a `pgvector/pgvector:pg16@sha256:<hex>` ref can be
1002 // supplied by env and accepted under the multi-tenant posture without rootfs staging. `None`
1003 // ⇒ the version-computed tag.
1004 if let Some(c) = config.compute.as_ref() {
1005 driver =
1006 driver.with_client_images(c.pg_client_image.clone(), c.mysql_client_image.clone());
1007 }
1008 if let (Some(backend), Some(envelope), Some(op)) =
1009 (export_sql_backend, export_envelope, operator_sql.clone())
1010 {
1011 let published = config
1012 .compute
1013 .as_ref()
1014 .map(|c| {
1015 matches!(
1016 c.docker_endpoint,
1017 boatramp_docker::DockerEndpoint::Published
1018 )
1019 })
1020 .unwrap_or(true);
1021 driver = driver.with_managed_pg(backend, envelope, op, published);
1022 }
1023 // Local libsql backend (embedded per-site DBs) — skipped for a remote-sqld project
1024 // (no local file to snapshot). Mirrors `build_sql_backends`' dir derivation.
1025 if sql_cfg.map(|c| c.url.is_none()).unwrap_or(true) {
1026 let dir = sql_cfg
1027 .and_then(|c| c.dir.clone())
1028 .unwrap_or_else(|| data_dir.join("handlers-sql"));
1029 let libsql_backends = boatramp_storage::LibsqlSqlBackends::local(dir);
1030 // inc2: sweep any stale `*.shadow_*` left by a crash mid-import — the atomic
1031 // shadow-restore's RAII drop-guard only fires in-process, so a crash would otherwise
1032 // orphan the in-flight shadow DB. Safe at startup (no import is in flight yet).
1033 match libsql_backends.sweep_stale_shadows() {
1034 Ok(n) if n > 0 => {
1035 tracing::info!(
1036 swept = n,
1037 "project-export: removed stale libsql import shadows"
1038 )
1039 }
1040 Ok(_) => {}
1041 Err(e) => tracing::warn!(error = %e, "project-export: stale-shadow sweep failed"),
1042 }
1043 driver = driver.with_libsql(std::sync::Arc::new(libsql_backends));
1044 }
1045 let driver = Arc::new(driver);
1046 // inc2 Stage C/D: best-effort startup sweep of stale `*__shadow_*` / `*__old_*` managed
1047 // pg/mysql databases left by a crash mid-import (the in-process RAII drop-on-abort only
1048 // fires in-process). DETACHED so a not-yet-ready / unreachable managed server never blocks
1049 // or fails node boot; it covers a Shared server's whole fleet via the default-project
1050 // maintenance connection (a non-default Single instance relies on the in-process guard).
1051 {
1052 let sweeper = driver.clone();
1053 tokio::spawn(async move {
1054 let n = sweeper
1055 .sweep_stale_sql_shadows(boatramp_core::project::DEFAULT_PROJECT)
1056 .await;
1057 if n > 0 {
1058 tracing::info!(
1059 swept = n,
1060 "project-export: removed stale managed-SQL import shadow databases"
1061 );
1062 }
1063 });
1064 }
1065 Some(driver as Arc<dyn boatramp_core::project_export::ProjectExport>)
1066 };
1067 #[cfg(not(feature = "project-export"))]
1068 let project_export_cap: Option<Arc<dyn boatramp_core::project_export::ProjectExport>> = None;
1069
1070 // Wire the operator capabilities onto the options the router is built from.
1071 let mut options = options;
1072 options.operator_sql = operator_sql;
1073 options.project_export = project_export_cap;
1074 options.migration_substrate = migration_substrate;
1075 options.tenant_repair = tenant_repair;
1076 options.managed_db_declare = managed_db_declare;
1077 options.tenant_deprovisioner = tenant_deprovisioner;
1078 options.compute_exec = compute_exec;
1079 options.dev_blob_bind = dev_blob_bind_resolver;
1080 options.dev_messaging_bind = dev_messaging_bind_resolver;
1081 options.compute_volumes = compute_volumes;
1082 options.compute_control = compute_control;
1083 // The internal secret store backs the admin secrets API (set/list/delete). Not
1084 // handlers-gated — it must be reachable even on a lean node.
1085 options.secret_store = secret_store;
1086 // The per-tenant sealed secret store backs the control-plane CRUD (task #493). Like the secret
1087 // store it is not handlers-gated, so the endpoints work on a lean node.
1088 options.tenant_secret_store = tenant_secret_store;
1089 // The email-profile store backs the admin API (`/api/email/profiles`); like the
1090 // secret store it is not handlers-gated, so it works on a lean node.
1091 options.email_profile_store = email_profile_store;
1092
1093 // The detached reconcile loops: the always-present compute + domain-verify ones,
1094 // plus the optional tenant-tombstone reaper (only when a managed DB is configured).
1095 let mut reconcile = vec![compute_reconcile, dv_reconcile];
1096 if let Some(reaper) = tombstone_reaper {
1097 reconcile.push(reaper);
1098 }
1099 if let Some(dns) = internal_dns {
1100 reconcile.push(dns);
1101 }
1102
1103 Ok(RunningNode {
1104 deploy,
1105 handlers,
1106 auth,
1107 options,
1108 reconcile,
1109 })
1110}
1111
1112/// Build the `[secrets]` envelope (secrets-at-rest wrapping) from `boatramp.cfg`'s
1113/// `[secrets]` section: `local` (a machine-local AES-256-GCM KEK) or `vault` (Vault
1114/// Env var an operator points at a PEM file of extra CA(s) the guest's outbound `wasi:http` TLS
1115/// client should trust on top of the webpki roots — honored only under the
1116/// `allow_guest_egress_extra_ca` posture (a hermetic HTTPS test double lever).
1117const GUEST_EGRESS_EXTRA_CA_ENV: &str = "BOATRAMP_GUEST_EGRESS_EXTRA_CA_FILE";
1118
1119/// Parse the operator's guest-egress extra-CA PEM ([`GUEST_EGRESS_EXTRA_CA_ENV`]) into rustls trust
1120/// Collect the first-party (`own`-tier) JWKS URLs to pre-warm at startup: every site's gateway-level
1121/// `[handlers.graphql.data].claims_from_token` that is single-issuer (`jwks_url` set) and NOT
1122/// multi-issuer (`issuer_trust` unset) — foreign/multi-issuer issuers can't be pre-warmed (unknown
1123/// until a token arrives), and `jwks_env` is an env var, not a fetch. Returns deduped
1124/// `(url, issuer, audience)` tuples. Best-effort: a per-site read error is logged and skipped, never
1125/// propagated (pre-warm must not fail node startup). Per-route `HandlerConfig`/consumer/session/
1126/// function `token_claims` live in content-addressed deployment manifests not enumerated here; those
1127/// warm lazily on first request (today's behavior).
1128#[cfg(feature = "handlers")]
1129async fn collect_own_jwks_prewarm(deploy: &DeployStore) -> Vec<(String, String, Option<String>)> {
1130 use boatramp_core::project::ProjectRef;
1131 let sites = match deploy.list_sites_all().await {
1132 Ok(s) => s,
1133 Err(e) => {
1134 tracing::warn!(error = %e, "JWKS pre-warm: could not list sites; skipping pre-warm");
1135 return Vec::new();
1136 }
1137 };
1138 let mut seen = std::collections::HashSet::new();
1139 let mut out = Vec::new();
1140 for (project, site) in sites {
1141 let sc = match deploy
1142 .get_site_config(ProjectRef::new(&project), &site)
1143 .await
1144 {
1145 Ok(Some(sc)) => sc,
1146 Ok(None) => continue,
1147 Err(e) => {
1148 tracing::warn!(project = %project, site = %site, error = %e,
1149 "JWKS pre-warm: could not load site config; skipping");
1150 continue;
1151 }
1152 };
1153 let Some(claims) = sc
1154 .handlers
1155 .as_ref()
1156 .and_then(|h| h.graphql.as_ref())
1157 .and_then(|g| g.data.as_ref())
1158 .and_then(|d| d.claims_from_token.as_ref())
1159 else {
1160 continue;
1161 };
1162 // OWN tier only: operator-fixed single-issuer `jwks_url`, never multi-issuer discovery.
1163 if claims.issuer_trust.is_some() {
1164 continue;
1165 }
1166 if let Some(url) = claims.jwks_url.as_ref() {
1167 let entry = (url.clone(), claims.issuer.clone(), claims.audience.clone());
1168 if seen.insert(entry.clone()) {
1169 out.push(entry);
1170 }
1171 }
1172 }
1173 out
1174}
1175
1176/// anchors, gated by the `allow_guest_egress_extra_ca` posture (`allow`). No env set ⇒ empty (the
1177/// default). `allow == false` (e.g. multi-tenant) with a file set ⇒ empty + a warning (the posture
1178/// refuses it). Set + readable + ≥1 cert ⇒ those certs. Set-but-unreadable / no valid cert ⇒ a hard
1179/// error (fail closed — a configured-but-broken CA must not silently degrade to no-trust).
1180fn load_guest_egress_extra_roots(
1181 allow: bool,
1182) -> Result<Vec<rustls::pki_types::CertificateDer<'static>>> {
1183 let path = match std::env::var(GUEST_EGRESS_EXTRA_CA_ENV) {
1184 Ok(p) if !p.is_empty() => p,
1185 _ => return Ok(Vec::new()),
1186 };
1187 if !allow {
1188 tracing::warn!(
1189 env = GUEST_EGRESS_EXTRA_CA_ENV,
1190 "ignoring a guest-egress extra CA: the security posture forbids it \
1191 (allow_guest_egress_extra_ca is off — e.g. under multi-tenant)"
1192 );
1193 return Ok(Vec::new());
1194 }
1195 let pem =
1196 std::fs::read(&path).map_err(|e| Error::GuestEgressCa(format!("reading {path:?}: {e}")))?;
1197 let certs = rustls_pemfile::certs(&mut std::io::BufReader::new(&pem[..]))
1198 .collect::<std::result::Result<Vec<_>, _>>()
1199 .map_err(|e| Error::GuestEgressCa(format!("parsing {path:?}: {e}")))?;
1200 if certs.is_empty() {
1201 return Err(Error::GuestEgressCa(format!(
1202 "{path:?} contained no PEM certificate"
1203 )));
1204 }
1205 tracing::info!(
1206 env = GUEST_EGRESS_EXTRA_CA_ENV,
1207 count = certs.len(),
1208 path = %path,
1209 "guest egress trusts operator extra CA(s) (dev-posture; webpki roots still apply)"
1210 );
1211 Ok(certs)
1212}
1213
1214/// Transit). `None`/empty ⇒ no wrapping. The Vault token is read from the
1215/// environment (`token_env`), never a file. This seals a managed SQL credential at
1216/// rest; a managed database fails closed without it.
1217fn build_secrets_envelope(
1218 secrets: Option<&crate::config::SecretsConfig>,
1219 data_dir: &Path,
1220) -> Result<Option<Arc<dyn boatramp_core::envelope::KeyEnvelope>>> {
1221 use boatramp_server::envelope::{EnvelopeSpec, build_envelope};
1222 let Some(cfg) = secrets else {
1223 return Ok(None);
1224 };
1225 let spec = match cfg.envelope.as_str() {
1226 "" => EnvelopeSpec::None,
1227 "local" => EnvelopeSpec::Local {
1228 kek_file: cfg
1229 .kek_file
1230 .clone()
1231 .unwrap_or_else(|| data_dir.join("secrets/kek")),
1232 },
1233 "vault" => {
1234 let v = cfg.vault.as_ref().ok_or_else(|| {
1235 Error::Envelope(
1236 "secrets.envelope = \"vault\" needs a [secrets.vault] section".into(),
1237 )
1238 })?;
1239 let token = std::env::var(&v.token_env).map_err(|_| {
1240 Error::Envelope(format!("Vault token env `{}` is not set", v.token_env))
1241 })?;
1242 EnvelopeSpec::Vault {
1243 addr: v.addr.clone(),
1244 key: v.key.clone(),
1245 token,
1246 }
1247 }
1248 other => {
1249 return Err(Error::Envelope(format!(
1250 "unknown secrets.envelope {other:?} (want \"local\" or \"vault\")"
1251 )));
1252 }
1253 };
1254 build_envelope(spec).map_err(|e| Error::Envelope(e.to_string()))
1255}
1256
1257#[cfg(all(test, feature = "fs"))]
1258mod tests {
1259 use super::*;
1260 use boatramp_core::kv::MemoryKv;
1261 use boatramp_core::security::SecurityProfile;
1262
1263 /// The dev/loopback ephemeral fleet-signer auto-provision is gated STRICTLY to a loopback bind
1264 /// (or an in-process embedder with no bind): a public / wildcard / private-network bind must
1265 /// NOT silently provision an ephemeral signing key (it would invalidate live capabilities on a
1266 /// restart — such a node must supply a persistent key). This is the security-critical boundary.
1267 #[cfg(feature = "handlers")]
1268 #[test]
1269 fn ephemeral_fleet_signer_auto_provisions_only_on_loopback_or_in_process() {
1270 use std::net::SocketAddr;
1271 let sa = |s: &str| s.parse::<SocketAddr>().unwrap();
1272 // In-process (no listener) and loopback → auto-provision the dev fleet signer.
1273 assert!(should_autoprovision_fleet_signer(None));
1274 assert!(should_autoprovision_fleet_signer(Some(sa(
1275 "127.0.0.1:8080"
1276 ))));
1277 assert!(should_autoprovision_fleet_signer(Some(sa("[::1]:8080"))));
1278 // Off-host-reachable binds MUST NOT auto-provision an ephemeral key: a public IP, a
1279 // private-network IP, and a wildcard bind (`0.0.0.0`/`::`, reachable off-host).
1280 assert!(!should_autoprovision_fleet_signer(Some(sa(
1281 "203.0.113.5:8080"
1282 ))));
1283 assert!(!should_autoprovision_fleet_signer(Some(sa(
1284 "10.0.0.4:8080"
1285 ))));
1286 assert!(!should_autoprovision_fleet_signer(Some(sa("0.0.0.0:8080"))));
1287 assert!(!should_autoprovision_fleet_signer(Some(sa("[::]:8080"))));
1288 }
1289
1290 /// The headline in-process fidelity check (PLAN-node-library N2b.3): `assemble`
1291 /// over a temp `FsStorage` + `MemoryKv` produces a `RunningNode` whose deploy
1292 /// store is live (the reserved `default` project was materialized during
1293 /// assembly) and whose router — the exact one `boatramp serve` builds — answers
1294 /// `/healthz`. No listener is bound: the request is driven through the router
1295 /// via `tower::oneshot`, so the whole assembly runs in-process.
1296 #[tokio::test]
1297 async fn assemble_produces_a_serving_node_over_a_temp_store() {
1298 use axum::body::Body;
1299 use axum::http::{Request, StatusCode};
1300 use tower::ServiceExt;
1301
1302 let tmp = tempfile::tempdir().unwrap();
1303 let storage: Arc<dyn Storage> = Arc::new(boatramp_storage::FsStorage::new(tmp.path()));
1304 let kv: Arc<dyn KvStore> = Arc::new(MemoryKv::new());
1305 let config = ServerConfig::default();
1306 let options = boatramp_server::ServerOptions {
1307 // The strict `multi-tenant` posture, as an unconfigured `serve` resolves.
1308 posture: SecurityProfile::MultiTenant.preset(),
1309 ..Default::default()
1310 };
1311
1312 let node = assemble(NodeInput {
1313 config: &config,
1314 data_dir: tmp.path(),
1315 storage,
1316 per_project_blob_backends: std::collections::HashMap::new(),
1317 kv,
1318 auth: boatramp_server::Auth::disabled(),
1319 options,
1320 serve_addr: None,
1321 watch_provider: None,
1322 provision_tier: boatramp_core::blob_notify::ProvisionTier::default(),
1323 messaging: None,
1324 is_leader: Arc::new(|| true),
1325 node_id: 0,
1326 worker_exe: None,
1327 })
1328 .await
1329 .expect("assemble a node over a temp store");
1330
1331 // The deploy store is live: `assemble` already materialized the reserved
1332 // `default` project, so a second ensure reports "already present" (`false`).
1333 assert!(
1334 !node
1335 .deploy
1336 .ensure_default_project()
1337 .await
1338 .expect("read the default project"),
1339 "assemble should have materialized the default project"
1340 );
1341
1342 // The assembled router (the same wiring `serve` binds) answers /healthz.
1343 let router =
1344 boatramp_server::router_with(node.deploy, node.auth, node.handlers, node.options);
1345 let response = router
1346 .oneshot(
1347 Request::builder()
1348 .uri("/healthz")
1349 .body(Body::empty())
1350 .unwrap(),
1351 )
1352 .await
1353 .expect("route /healthz");
1354 assert_eq!(response.status(), StatusCode::OK);
1355 }
1356}