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/// Wire [`NodeInput`] into a [`RunningNode`]: build the handler runtime, the
133/// deploy store (materializing the reserved `default` project), the compute
134/// backends + reconcile loop, and the domain-verify reconcile loop.
135///
136/// The caller has already built the store and configured auth/OIDC on `options`;
137/// this is the pure node-graph wiring, identical to what `boatramp serve` runs.
138pub async fn assemble(input: NodeInput<'_>) -> Result<RunningNode> {
139 let NodeInput {
140 config,
141 data_dir,
142 storage,
143 kv,
144 auth,
145 options,
146 serve_addr,
147 watch_provider,
148 provision_tier,
149 messaging,
150 is_leader,
151 node_id,
152 worker_exe,
153 } = input;
154 // Copy out the posture scalars up front so `options` can be moved into the
155 // returned `RunningNode` without a lingering borrow.
156 let max_handler_blob_bytes = options.posture.max_handler_blob_bytes;
157 let max_component_bytes = options.posture.max_component_bytes;
158 let allow_guest_private_egress = options.posture.allow_guest_private_egress;
159 let allow_env_secret_refs = options.posture.allow_env_secret_refs;
160 let allow_guest_email = options.posture.allow_guest_email;
161 // The instance's own serve socket(s) a guest self-call may reach, when the posture allows
162 // it: a wildcard bind (`0.0.0.0`/`::`) is reachable on loopback, so normalize to
163 // `127.0.0.1`/`::1`; a specific bind is itself.
164 let self_egress_addrs = self_egress_addrs(serve_addr, options.posture.allow_guest_self_egress);
165 let allow_shared_kernel = options.posture.allow_shared_kernel_compute;
166 let domain_verify_allow_private = options.posture.domain_verify_allow_private;
167
168 // The deploy store the router serves from — built up front so the handler
169 // runtime's managed compute-backed `sql` binding can resolve DB endpoints from
170 // the same store the reconcile writes.
171 let compute_storage = storage.clone();
172 let deploy = DeployStore::new(storage, kv.clone());
173 // The `[secrets]` envelope (local KEK / Vault) that seals a managed SQL
174 // credential at rest. `None` ⇒ no wrapping (a managed DB then fails closed).
175 let secrets_envelope = build_secrets_envelope(config.secrets.as_ref(), data_dir)?;
176 // The project-scoped internal secret store, built from the same KV + `[secrets]`
177 // envelope that seal managed-DB credentials. Backs both the `boatramp:<name>`
178 // resolver (wired into the handler runtime below, when that feature is present)
179 // and the admin secrets API (threaded into `ServerOptions` unconditionally, so it
180 // works on a lean node too). `None` when no envelope is configured — the admin
181 // endpoints then fail closed with a clear 501, never a panic.
182 let secret_store = secrets_envelope.clone().map(|envelope| {
183 Arc::new(boatramp_core::secret_store::SecretStore::new(
184 kv.clone(),
185 envelope,
186 ))
187 });
188 // The project-scoped SMTP email-profile store, built from the same KV + envelope
189 // (the password is sealed at rest). Backs the admin API (`options` below,
190 // unconditionally, so it works on a lean node) and — when the `email` feature +
191 // `allow_guest_email` posture permit — the runtime's host-side profile
192 // resolution (wired inside `build_handler_runtime`). `None` with no envelope, so
193 // the admin email endpoints fail closed with a clear 501.
194 let email_profile_store = secrets_envelope.clone().map(|envelope| {
195 Arc::new(boatramp_core::email_config::EmailProfileStore::new(
196 kv.clone(),
197 envelope,
198 ))
199 });
200
201 // The handler runtime reuses the same blob/KV backends (per-site prefixed)
202 // for its wasi:blobstore/keyvalue bindings; the sql binding is selected by
203 // `[handlers.bindings.sql]` (default: per-site libsql files under <data-dir>).
204 let handlers = crate::handlers::build_handler_runtime(
205 kv.clone(),
206 compute_storage.clone(),
207 data_dir,
208 config.handlers.as_ref(),
209 messaging,
210 max_handler_blob_bytes,
211 max_component_bytes,
212 allow_guest_private_egress,
213 self_egress_addrs,
214 allow_env_secret_refs,
215 allow_guest_email,
216 &deploy,
217 secrets_envelope.clone(),
218 )
219 .await?;
220 // Wire the guest project self-config capability (`boatramp:handlers/admin`) when the
221 // operator posture enables at least one surface. The controller reuses the same in-process
222 // domain-verify / email-profile / secret / site-config subsystems + the real domain probe;
223 // it's project-scoped per grant and rate-limited + audited. Posture-off ⇒ not offered.
224 #[cfg(feature = "admin")]
225 {
226 use boatramp_handlers::AdminSurface;
227 let p = &options.posture;
228 let mut surfaces = std::collections::BTreeSet::new();
229 if p.allow_guest_admin_domains {
230 surfaces.insert(AdminSurface::Domains);
231 }
232 if p.allow_guest_admin_email {
233 surfaces.insert(AdminSurface::Email);
234 }
235 if p.allow_guest_admin_site {
236 surfaces.insert(AdminSurface::Site);
237 }
238 if p.allow_guest_admin_secrets {
239 surfaces.insert(AdminSurface::Secrets);
240 }
241 if !surfaces.is_empty() {
242 let controller = Arc::new(boatramp_server::ServerAdminController::with_server_probe(
243 deploy.clone(),
244 email_profile_store.clone(),
245 secret_store.clone(),
246 p.domain_verify_allow_private,
247 ));
248 handlers.set_admin(controller, surfaces);
249 }
250 }
251 // Leader-gate cron firing (cluster: only the Raft leader fires; single-node: an
252 // always-true gate, equivalent to the unset default). The same gate drives the
253 // reconcile loops below, so all three converge on one leader per fleet. Only the
254 // handler runtime has a scheduler, so this is a no-op without the `handlers` feature.
255 #[cfg(feature = "handlers")]
256 handlers.set_cron_leader_gate(is_leader.clone());
257 // FA-5b2: on a cloud backend, wire the blob-change notification provisioner +
258 // its tier so adding a `blob` trigger provisions (and removing it retracts).
259 #[cfg(feature = "handlers")]
260 if let Some(provider) = watch_provider {
261 handlers.set_watch_provider(provider);
262 handlers.set_provision_tier(provision_tier);
263 }
264 #[cfg(not(feature = "handlers"))]
265 let _ = (watch_provider, provision_tier);
266
267 // Materialize the reserved `default` project so `project ls` / `project show
268 // default` reflect it on a fresh install, not only after a migration. Best
269 // effort: the reader backstop keeps listings correct even if this write can't
270 // land, so a transient failure must never block serving.
271 match deploy.ensure_default_project().await {
272 Ok(true) => tracing::info!("materialized the reserved `default` project record"),
273 Ok(false) => {}
274 Err(e) => tracing::warn!(
275 error = %e,
276 "could not materialize the `default` project record; readers use the synthesized default"
277 ),
278 }
279 // Wire the function-to-function invoke resolver now the deploy store exists,
280 // so a function granted `invoke` can call a sibling in-process (FI).
281 #[cfg(feature = "handlers")]
282 handlers.set_invoker(deploy.clone());
283
284 // Compute reconcile loop. Single-node is always the "leader". Backends are
285 // built from the `[compute]` config + capability detection; a no-op when none
286 // are registered. Detached for the server's life.
287 let (compute_backends, compute_node) = crate::compute::build_compute(
288 config.compute.as_ref(),
289 compute_storage,
290 data_dir,
291 node_id,
292 !allow_shared_kernel,
293 options.daemon_runtime.clone(),
294 worker_exe.as_deref(),
295 )
296 .await;
297 // Adopt the IPs of already-running replicas into each backend's fresh-on-boot
298 // IP pool BEFORE the reconcile loop starts allocating. A backend with a per-node
299 // pool (the native container backend) rebuilds it empty each process start; without
300 // this the boot reconcile could re-hand a live address to a different workload —
301 // the container-IP collision — or move a replica's endpoint on relaunch. Feeds
302 // every persisted replica's `(workload, replica, endpoint-ip)`; each backend keeps
303 // only the IPs in its own subnet (a cheap no-op for docker/cloudflare/VMM).
304 crate::compute::adopt_running_replica_ips(&deploy, &compute_backends).await;
305 // Per-project internal DNS (service discovery): start the resolver on the bridge
306 // gateway so a guest resolves peers by name within its project. On by default;
307 // starts only when the container backend + bridge are up (Linux). Detached for
308 // the node's serving life (pushed into `reconcile` below). Started before the
309 // reconcile loop consumes `compute_backends` — it borrows the registry to check
310 // the container backend is present.
311 let internal_dns =
312 crate::compute::spawn_internal_dns(config.compute.as_ref(), &compute_backends, &deploy);
313 // Activate the compute sql-shim (PLAN-compute-bindings): bind its listener +
314 // build the resolver when a sql provider and `compute.sql_shim_url` are both present.
315 #[cfg(feature = "handlers")]
316 let sql_resolver = boatramp_server::sql_shim::spawn_sql_shim(
317 handlers.sql_backends(),
318 config.compute.as_ref().and_then(|c| c.sql_shim_url.clone()),
319 )
320 .await;
321 #[cfg(not(feature = "handlers"))]
322 let sql_resolver: Option<Arc<dyn boatramp_core::compute::ComputeBindingResolver>> = None;
323
324 // Managed compute-backed SQL (PLAN-managed-compute-sql P2-b): if the handler
325 // `sql` config declares any managed database, inject its `POSTGRES_*`/`MYSQL_*`
326 // server-init env into the DB workload at launch from the sealed credential.
327 // Reaching here with a managed DB implies an envelope (build_handler_runtime
328 // fails closed otherwise), so the credential store always has one to seal with.
329 // Keep a clone of the secrets envelope for the operator-SQL capability below
330 // (the managed_db_resolver match moves the original).
331 #[cfg(any(feature = "sql-postgres", feature = "sql-mysql"))]
332 let operator_envelope = secrets_envelope.clone();
333 // …and a second clone for the tenant-deprovision capability (drops a deleted
334 // tenant's managed DB/role/credential on project/site delete). It needs a real
335 // envelope to seal/unseal + delete per-tenant credentials, so it is wired only
336 // when one is present (same fail-closed gating as the managed-DB paths).
337 #[cfg(any(feature = "sql-postgres", feature = "sql-mysql"))]
338 let deprovision_envelope = secrets_envelope.clone();
339 // …and a third clone for the soft-delete tombstone reaper (the leader-gated task
340 // that hard-drops a Shared-Postgres tenant once its grace window elapses). It, too,
341 // needs a real envelope to unseal the superuser credential + delete the per-tenant
342 // one on hard-drop.
343 #[cfg(any(feature = "sql-postgres", feature = "sql-mysql"))]
344 let reaper_envelope = secrets_envelope.clone();
345 #[cfg(any(feature = "sql-postgres", feature = "sql-mysql"))]
346 let managed_db_resolver: Option<Arc<dyn boatramp_core::compute::ManagedDbEnvResolver>> = match (
347 config
348 .handlers
349 .as_ref()
350 .and_then(|h| h.bindings.sql.as_ref()),
351 secrets_envelope,
352 ) {
353 (Some(sql), Some(envelope)) if !sql.databases.is_empty() => {
354 let creds = crate::managed_sql::ManagedSqlCredentials::new(kv.clone(), envelope);
355 let privilege = config
356 .compute
357 .as_ref()
358 .map(|c| c.managed_db_privilege)
359 .unwrap_or_default();
360 let env =
361 crate::managed_sql::ManagedDbEnv::from_config(&sql.databases, creds, privilege);
362 (!env.is_empty()).then(|| Arc::new(env) as Arc<_>)
363 }
364 _ => None,
365 };
366 #[cfg(not(any(feature = "sql-postgres", feature = "sql-mysql")))]
367 let managed_db_resolver: Option<Arc<dyn boatramp_core::compute::ManagedDbEnvResolver>> = None;
368
369 // Turnkey managed DB: auto-register the compute workload(s) backing each managed
370 // co-located database that has none yet, so declaring the `databases` binding is
371 // enough to boot the DB (no separate `compute set` / apply). Tenant-aware — a
372 // `Shared` binding registers its one shared server; a `Single` binding registers
373 // nothing at boot (its per-tenant `<compute>-<ident>` is created durably by the lazy
374 // resolve on first `sql` use and relaunched by the reconcile, so a project that never
375 // uses `sql` — e.g. a static-only site — never gets a spurious DB). Non-clobbering +
376 // idempotent; runs before the reconcile loop so its first tick can launch what it
377 // registered.
378 #[cfg(any(feature = "sql-postgres", feature = "sql-mysql"))]
379 if let Some(sql) = config
380 .handlers
381 .as_ref()
382 .and_then(|h| h.bindings.sql.as_ref())
383 .filter(|sql| !sql.databases.is_empty())
384 {
385 crate::managed_sql::auto_register_managed_db_workloads(&deploy, &sql.databases).await;
386 }
387
388 // Operator SQL capability (managed-DB migrations/queries via the sealed
389 // credential, resolved server-side) — backs `POST /api/sql/{db}/{exec,query}`.
390 #[cfg(any(feature = "sql-postgres", feature = "sql-mysql"))]
391 let operator_sql: Option<Arc<dyn boatramp_core::sql::OperatorSql>> = config
392 .handlers
393 .as_ref()
394 .and_then(|h| h.bindings.sql.as_ref())
395 .filter(|sql| !sql.databases.is_empty())
396 .map(|sql| {
397 Arc::new(crate::managed_sql::NodeOperatorSql::new(
398 sql.databases.clone(),
399 kv.clone(),
400 operator_envelope,
401 deploy.clone(),
402 )) as Arc<_>
403 });
404 #[cfg(not(any(feature = "sql-postgres", feature = "sql-mysql")))]
405 let operator_sql: Option<Arc<dyn boatramp_core::sql::OperatorSql>> = None;
406
407 // Tenant-deprovision capability (drop a deleted tenant's managed DB/role/sealed
408 // credential on project/site delete). Wired only when a compute-backed managed
409 // database + a secrets envelope are both present — same gating as operator_sql,
410 // plus the envelope requirement (it must seal/unseal per-tenant credentials).
411 // The soft-delete grace window for a Shared-Postgres managed tenant
412 // (`handlers.bindings.sql.deprovision_grace_secs`, env-settable). Default 7 days;
413 // `0` disables the soft path (immediate hard drop). Threaded to the deprovisioner
414 // (which soft-deletes) and implicitly honored by the reaper (which only ever finds
415 // tombstones a >0 grace produced).
416 #[cfg(any(feature = "sql-postgres", feature = "sql-mysql"))]
417 let deprovision_grace_secs = config
418 .handlers
419 .as_ref()
420 .and_then(|h| h.bindings.sql.as_ref())
421 .and_then(|sql| sql.deprovision_grace_secs)
422 .unwrap_or(crate::tenant_sql::DEFAULT_DEPROVISION_GRACE_SECS);
423 #[cfg(any(feature = "sql-postgres", feature = "sql-mysql"))]
424 let tenant_deprovisioner: Option<Arc<dyn boatramp_core::sql::TenantDeprovisioner>> = config
425 .handlers
426 .as_ref()
427 .and_then(|h| h.bindings.sql.as_ref())
428 .filter(|sql| !sql.databases.is_empty())
429 .zip(deprovision_envelope)
430 .map(|(sql, envelope)| {
431 Arc::new(crate::tenant_sql::NodeTenantDeprovisioner::new(
432 deploy.clone(),
433 kv.clone(),
434 envelope,
435 sql.databases.clone(),
436 deprovision_grace_secs,
437 )) as Arc<_>
438 });
439 #[cfg(not(any(feature = "sql-postgres", feature = "sql-mysql")))]
440 let tenant_deprovisioner: Option<Arc<dyn boatramp_core::sql::TenantDeprovisioner>> = None;
441
442 // Operator compute-exec capability (run a command inside a running workload) —
443 // backs `POST /api/compute/{name}/exec`, gated by the `allow_compute_exec`
444 // posture. Clone the backend registry before the reconcile loop consumes it.
445 let compute_exec: Option<Arc<dyn boatramp_core::compute::ComputeExec>> = Some(Arc::new(
446 crate::compute::NodeComputeExec::new(compute_backends.clone(), deploy.clone()),
447 ) as Arc<_>);
448
449 // Operator volume-reclamation capability (list + remove persistent volumes) —
450 // backs `GET /api/compute/volumes` + `DELETE /api/compute/volumes/{name}`.
451 // Same admin-scoped `/api/compute/*` gate; clone the registry before the
452 // reconcile loop consumes the original below.
453 let compute_volumes: Option<Arc<dyn boatramp_core::compute::ComputeVolumes>> = Some(Arc::new(
454 crate::compute::NodeComputeVolumes::new(compute_backends.clone(), deploy.clone()),
455 )
456 as Arc<_>);
457
458 // Operator reconcile-plane control capability (restart a replica) — backs
459 // `POST /api/compute/maintenance/restart` (admin-scoped). Clone the registry
460 // before the reconcile loop consumes the original below.
461 let compute_control: Option<Arc<dyn boatramp_core::compute::ComputeControl>> = Some(Arc::new(
462 crate::compute::NodeComputeControl::new(compute_backends.clone(), deploy.clone()),
463 )
464 as Arc<_>);
465
466 let compute_reconcile = boatramp_server::spawn_compute_reconcile(
467 deploy.clone(),
468 compute_backends,
469 vec![compute_node],
470 boatramp_core::compute::BackendPolicy::from_shared_kernel_allowed(allow_shared_kernel),
471 is_leader.clone(),
472 compute_reconcile_tick(),
473 COMPUTE_IDLE_TIMEOUT,
474 sql_resolver,
475 managed_db_resolver,
476 );
477
478 // Tenant tombstone reaper: leader-gated hard-drop of soft-deleted Shared-Postgres
479 // tenants past their grace window (safe deprovision — see `tenant_sql`). Wired only
480 // when a compute-backed managed database + a secrets envelope are both present
481 // (same gating as the deprovisioner); each tombstone carries its own server +
482 // superuser, so the reaper needs no per-binding config. A `0` grace never writes a
483 // tombstone, so the sweep is simply inert then.
484 #[cfg(any(feature = "sql-postgres", feature = "sql-mysql"))]
485 let tombstone_reaper: Option<tokio::task::JoinHandle<()>> = config
486 .handlers
487 .as_ref()
488 .and_then(|h| h.bindings.sql.as_ref())
489 .filter(|sql| !sql.databases.is_empty())
490 .zip(reaper_envelope)
491 .map(|(_sql, envelope)| {
492 crate::tenant_sql::spawn_tenant_tombstone_reaper(
493 deploy.clone(),
494 kv.clone(),
495 envelope,
496 is_leader.clone(),
497 crate::tenant_sql::TOMBSTONE_REAPER_TICK,
498 )
499 });
500 #[cfg(not(any(feature = "sql-postgres", feature = "sql-mysql")))]
501 let tombstone_reaper: Option<tokio::task::JoinHandle<()>> = None;
502
503 // Domain-verify auto-complete: periodically re-check every site's pending
504 // ownership challenges and attach any that now pass — a published token (e.g.
505 // via `domain add --provider`) converges without a manual `domain verify`.
506 let dv_reconcile = boatramp_server::spawn_domain_verify_reconcile(
507 deploy.clone(),
508 domain_verify_allow_private,
509 is_leader,
510 DOMAIN_VERIFY_RECONCILE_TICK,
511 );
512
513 // Wire the operator capabilities onto the options the router is built from.
514 let mut options = options;
515 options.operator_sql = operator_sql;
516 options.tenant_deprovisioner = tenant_deprovisioner;
517 options.compute_exec = compute_exec;
518 options.compute_volumes = compute_volumes;
519 options.compute_control = compute_control;
520 // The internal secret store backs the admin secrets API (set/list/delete). Not
521 // handlers-gated — it must be reachable even on a lean node.
522 options.secret_store = secret_store;
523 // The email-profile store backs the admin API (`/api/email/profiles`); like the
524 // secret store it is not handlers-gated, so it works on a lean node.
525 options.email_profile_store = email_profile_store;
526
527 // The detached reconcile loops: the always-present compute + domain-verify ones,
528 // plus the optional tenant-tombstone reaper (only when a managed DB is configured).
529 let mut reconcile = vec![compute_reconcile, dv_reconcile];
530 if let Some(reaper) = tombstone_reaper {
531 reconcile.push(reaper);
532 }
533 if let Some(dns) = internal_dns {
534 reconcile.push(dns);
535 }
536
537 Ok(RunningNode {
538 deploy,
539 handlers,
540 auth,
541 options,
542 reconcile,
543 })
544}
545
546/// Build the `[secrets]` envelope (secrets-at-rest wrapping) from `boatramp.cfg`'s
547/// `[secrets]` section: `local` (a machine-local AES-256-GCM KEK) or `vault` (Vault
548/// Transit). `None`/empty ⇒ no wrapping. The Vault token is read from the
549/// environment (`token_env`), never a file. This seals a managed SQL credential at
550/// rest; a managed database fails closed without it.
551fn build_secrets_envelope(
552 secrets: Option<&crate::config::SecretsConfig>,
553 data_dir: &Path,
554) -> Result<Option<Arc<dyn boatramp_core::envelope::KeyEnvelope>>> {
555 use boatramp_server::envelope::{build_envelope, EnvelopeSpec};
556 let Some(cfg) = secrets else {
557 return Ok(None);
558 };
559 let spec = match cfg.envelope.as_str() {
560 "" => EnvelopeSpec::None,
561 "local" => EnvelopeSpec::Local {
562 kek_file: cfg
563 .kek_file
564 .clone()
565 .unwrap_or_else(|| data_dir.join("secrets/kek")),
566 },
567 "vault" => {
568 let v = cfg.vault.as_ref().ok_or_else(|| {
569 Error::Envelope(
570 "secrets.envelope = \"vault\" needs a [secrets.vault] section".into(),
571 )
572 })?;
573 let token = std::env::var(&v.token_env).map_err(|_| {
574 Error::Envelope(format!("Vault token env `{}` is not set", v.token_env))
575 })?;
576 EnvelopeSpec::Vault {
577 addr: v.addr.clone(),
578 key: v.key.clone(),
579 token,
580 }
581 }
582 other => {
583 return Err(Error::Envelope(format!(
584 "unknown secrets.envelope {other:?} (want \"local\" or \"vault\")"
585 )))
586 }
587 };
588 build_envelope(spec).map_err(|e| Error::Envelope(e.to_string()))
589}
590
591#[cfg(all(test, feature = "fs"))]
592mod tests {
593 use super::*;
594 use boatramp_core::kv::MemoryKv;
595 use boatramp_core::security::SecurityProfile;
596
597 /// The headline in-process fidelity check (PLAN-node-library N2b.3): `assemble`
598 /// over a temp `FsStorage` + `MemoryKv` produces a `RunningNode` whose deploy
599 /// store is live (the reserved `default` project was materialized during
600 /// assembly) and whose router — the exact one `boatramp serve` builds — answers
601 /// `/healthz`. No listener is bound: the request is driven through the router
602 /// via `tower::oneshot`, so the whole assembly runs in-process.
603 #[tokio::test]
604 async fn assemble_produces_a_serving_node_over_a_temp_store() {
605 use axum::body::Body;
606 use axum::http::{Request, StatusCode};
607 use tower::ServiceExt;
608
609 let tmp = tempfile::tempdir().unwrap();
610 let storage: Arc<dyn Storage> = Arc::new(boatramp_storage::FsStorage::new(tmp.path()));
611 let kv: Arc<dyn KvStore> = Arc::new(MemoryKv::new());
612 let config = ServerConfig::default();
613 let options = boatramp_server::ServerOptions {
614 // The strict `multi-tenant` posture, as an unconfigured `serve` resolves.
615 posture: SecurityProfile::MultiTenant.preset(),
616 ..Default::default()
617 };
618
619 let node = assemble(NodeInput {
620 config: &config,
621 data_dir: tmp.path(),
622 storage,
623 kv,
624 auth: boatramp_server::Auth::disabled(),
625 options,
626 serve_addr: None,
627 watch_provider: None,
628 provision_tier: boatramp_core::blob_notify::ProvisionTier::default(),
629 messaging: None,
630 is_leader: Arc::new(|| true),
631 node_id: 0,
632 worker_exe: None,
633 })
634 .await
635 .expect("assemble a node over a temp store");
636
637 // The deploy store is live: `assemble` already materialized the reserved
638 // `default` project, so a second ensure reports "already present" (`false`).
639 assert!(
640 !node
641 .deploy
642 .ensure_default_project()
643 .await
644 .expect("read the default project"),
645 "assemble should have materialized the default project"
646 );
647
648 // The assembled router (the same wiring `serve` binds) answers /healthz.
649 let router =
650 boatramp_server::router_with(node.deploy, node.auth, node.handlers, node.options);
651 let response = router
652 .oneshot(
653 Request::builder()
654 .uri("/healthz")
655 .body(Body::empty())
656 .unwrap(),
657 )
658 .await
659 .expect("route /healthz");
660 assert_eq!(response.status(), StatusCode::OK);
661 }
662}