Skip to main content

assay_engine/
server.rs

1//! HTTP server wiring — composes the workflow API + dashboard + auth
2//! routers into one axum `Router`. URL surface:
3//!
4//! - `/auth/*`                   OIDC spec (discovery, authorize, token, …)
5//! - `/api/v1/engine/core/*`     engine-core admin
6//! - `/api/v1/engine/workflow/*` workflow API (auth-gated below)
7//! - `/api/v1/engine/auth/*`     engine-internal auth + admin
8//! - `/healthz`                  redirect to `/api/v1/engine/core/health`
9
10use axum::Router;
11use axum::response::Redirect;
12use axum::routing::get;
13use std::sync::Arc;
14use tracing::info;
15
16use assay_domain::events::EngineEventBus;
17use assay_workflow::events::WorkflowEventBus;
18use assay_workflow::{WorkflowCtx, WorkflowStore};
19
20use crate::state::EngineState;
21
22/// Always-public paths under `/api/v1/engine/workflow/*` that bypass
23/// the engine's auth gate (k8s probes, version banners, OpenAPI docs).
24const WORKFLOW_PUBLIC_PATHS: &[&str] = &[
25    "/api/v1/engine/workflow/health",
26    "/api/v1/engine/workflow/version",
27    "/api/v1/engine/workflow/openapi.json",
28    "/api/v1/engine/workflow/docs",
29];
30
31/// Compose the full `axum::Router` for the engine.
32///
33/// The workflow crate returns a `Router` that already embeds its state,
34/// and the dashboard crate returns a `Router<Arc<DashboardCtx>>` that we
35/// `.with_state()` here. Both are merged into a single stateless `Router`
36/// ready for `axum::serve`. When the `auth` feature is on AND the
37/// engine boot constructed an `AuthCtx`, the OIDC spec router (mounted
38/// at `/auth/`) and the engine-internal auth router (mounted under
39/// `/api/v1/engine/auth/`) join the composition.
40pub fn build_app<S: WorkflowStore + Clone + 'static>(state: EngineState<S>) -> Router {
41    // Workflow router carries no auth of its own — slice 2 lifted that
42    // to the engine layer. When `auth` is on AND an `AuthCtx` is
43    // composed, wrap the workflow router with the gate middleware that
44    // enforces `workflow:<namespace>#access` via `assay_auth::gate`.
45    let workflow_router = assay_workflow::api::router(Arc::clone(&state.workflow));
46    let workflow_router = if state.auth.is_some() {
47        workflow_router.layer(axum::middleware::from_fn_with_state(
48            state.clone(),
49            workflow_gate_middleware::<S>,
50        ))
51    } else {
52        workflow_router
53    };
54
55    let dashboard_router =
56        assay_dashboard::workflow_router().with_state(Arc::clone(&state.dashboard));
57
58    // `/healthz` is kept as a 1-line redirect to the new engine-core
59    // health endpoint for backward-compatible k8s probes. The real
60    // health response is served by the engine-core router under
61    // `/api/v1/engine/core/health` (see `engine_api.rs`).
62    let healthz = Router::new().route(
63        "/healthz",
64        get(|| async { Redirect::permanent("/api/v1/engine/core/health") }),
65    );
66
67    // Engine-core admin API + console SPA. Always present (engine-core
68    // is always running, regardless of which functional modules are
69    // enabled). The admin handlers require a configured api-key —
70    // when `admin_api_keys` is empty every admin route returns 401, so
71    // mounting unconditionally is safe for no-auth builds. The
72    // engine-core router carries `/api/v1/engine/core/info` (public),
73    // `/api/v1/engine/core/health`, `/api/v1/engine/core/active-modules`,
74    // and the admin endpoints.
75    let engine_api_router = crate::engine_api::router::<S>().with_state(state.clone());
76    let engine_console_router = assay_dashboard::engine_router();
77
78    let mut app = workflow_router
79        .merge(dashboard_router)
80        .merge(healthz)
81        .merge(engine_api_router)
82        .merge(engine_console_router);
83
84    // Mount the auth routers when AuthCtx is present. We bind state to
85    // each router *before* nesting so the merged tree remains
86    // `Router<()>` (every other sub-router has its state baked in
87    // similarly). This avoids the axum requirement that all merged
88    // routers share a common state parameter.
89    //
90    // The routers are generic over a parent state from which both
91    // `AuthCtx` and `AdminApiKeys` are extractable via `FromRef`;
92    // `EngineState<S>` implements both impls (see `state.rs`), so the
93    // engine threads its full state in once and the auth handlers
94    // pluck what they need.
95    if state.auth.is_some() {
96        // OIDC spec endpoints — mounted at `/auth/...`. Discovery doc,
97        // JWKS, authorize/token/userinfo/revoke/introspect/logout,
98        // federation upstream callbacks. Stable surface that downstream
99        // OIDC clients depend on.
100        let spec_router =
101            assay_auth::oidc_spec_router::<EngineState<S>>().with_state(state.clone());
102        app = app.nest("/auth", spec_router);
103
104        // Engine-internal auth — login, logout (DELETE), whoami,
105        // passkey ceremonies, admin (users/sessions/biscuit/jwks/
106        // zanzibar/audit + OIDC clients/upstream CRUD). Mounted under
107        // `/api/v1/engine/auth/...` so the operator-facing surface
108        // sits beside the engine-core + workflow APIs.
109        let engine_auth_router =
110            assay_auth::engine_auth_router::<EngineState<S>>().with_state(state.clone());
111        app = app.nest("/api/v1/engine/auth", engine_auth_router);
112
113        // Mount the auth-console SPA assets at root (so the same
114        // `/auth/...` path namespace serves both the OIDC spec and the
115        // dashboard asset bundle — `/auth/console` for the SPA,
116        // `/api/v1/engine/auth/admin/*` for the admin JSON API).
117        let asset_router = assay_dashboard::auth_router();
118        app = app.merge(asset_router);
119    }
120
121    // Vault module — plan 17 / v0.3.0. Mounted under /api/v1/vault when
122    // both the Cargo feature is on AND a VaultCtx was composed at boot
123    // (i.e. engine.modules.vault.enabled was TRUE). Phase 1 routes are
124    // admin-key-gated; Phase 3+ adds biscuit-share and Phase 7 the
125    // BW-compat shim's per-user session auth.
126    #[cfg(feature = "vault")]
127    if state.vault.is_some() {
128        let vault = assay_vault::router::vault_router::<EngineState<S>>().with_state(state.clone());
129        app = app.nest("/api/v1/vault", vault);
130    }
131
132    // BW-compat shim (Phase 7). Stock BW mobile / browser / CLI
133    // clients hardcode /identity/* and /api/* — mount the compat
134    // router at root so those clients work without a reverse-proxy
135    // rewrite. Only reachable when both vault + bitwarden-compat
136    // features are on AND VaultCtx + AuthCtx are composed.
137    #[cfg(all(feature = "vault", feature = "vault-bitwarden-compat"))]
138    if state.vault.is_some() && state.auth.is_some() {
139        let bw =
140            assay_vault::bitwarden_compat::router::<EngineState<S>>().with_state(state.clone());
141        app = app.merge(bw);
142    }
143
144    // Vault console assets (plan 17 §S10). Always mounted when the
145    // vault feature is on; runtime visibility is gated by
146    // engine.modules.vault.enabled like every other console.
147    #[cfg(feature = "vault")]
148    {
149        app = app.merge(assay_dashboard::vault_router());
150    }
151
152    app
153}
154
155/// Workflow-API auth gate. The engine is the auth boundary for every
156/// module — the workflow router carries no gate of its own.
157/// [`WORKFLOW_PUBLIC_PATHS`] bypass; everything else goes through
158/// [`assay_auth::gate::require_role_for`] keyed on the
159/// `?namespace=<X>` query param (default `main`).
160async fn workflow_gate_middleware<S: WorkflowStore + Clone + 'static>(
161    axum::extract::State(state): axum::extract::State<EngineState<S>>,
162    request: axum::extract::Request,
163    next: axum::middleware::Next,
164) -> axum::response::Response {
165    let path = request.uri().path();
166    if WORKFLOW_PUBLIC_PATHS
167        .iter()
168        .any(|p| path == *p || path.starts_with(&format!("{p}/")))
169    {
170        return next.run(request).await;
171    }
172
173    // Auth is on but no `AuthCtx` was composed at boot — this can
174    // happen for tests that build a no-auth engine. Fail closed; the
175    // engine binary's boot path always composes an AuthCtx when the
176    // auth module is enabled.
177    let Some(auth) = state.auth.as_ref() else {
178        return (
179            axum::http::StatusCode::SERVICE_UNAVAILABLE,
180            axum::Json(serde_json::json!({
181                "error": "service_unavailable",
182                "error_description": "auth not configured on this engine instance",
183            })),
184        )
185            .into_response();
186    };
187
188    let namespace = request
189        .uri()
190        .query()
191        .and_then(|q| {
192            url::form_urlencoded::parse(q.as_bytes())
193                .find(|(k, _)| k == "namespace")
194                .map(|(_, v)| v.into_owned())
195        })
196        .unwrap_or_else(|| "main".to_string());
197
198    let keys = crate::state::AdminApiKeys(Arc::clone(&state.admin_api_keys));
199    let headers = request.headers().clone();
200    if let Err(r) =
201        assay_auth::gate::require_role_for(&headers, auth, &keys, "workflow", &namespace, "access")
202            .await
203    {
204        return *r;
205    }
206
207    next.run(request).await
208}
209
210use axum::response::IntoResponse;
211
212/// Bind a TCP listener on `bind_addr` and serve the composed app.
213///
214/// Convenience wrapper that composes [`EngineState`] into an
215/// [`axum::Router`] via [`build_app`] and hands off to
216/// [`bind_and_serve`]. Used by the standalone `assay-engine` binary.
217pub async fn serve<S: WorkflowStore + Clone + 'static>(
218    bind_addr: &str,
219    state: EngineState<S>,
220) -> anyhow::Result<()> {
221    let app = build_app(state);
222    bind_and_serve(bind_addr, app).await
223}
224
225/// Bind a TCP listener on `bind_addr` and serve a pre-built
226/// [`axum::Router`].
227///
228/// Used by [`crate::run`] (after `embedded::build` returns the
229/// composed router) and by downstream embedders who want to add
230/// their own middleware / merge with their own router before
231/// serving.
232pub async fn bind_and_serve(bind_addr: &str, app: axum::Router) -> anyhow::Result<()> {
233    let listener = tokio::net::TcpListener::bind(bind_addr)
234        .await
235        .map_err(|e| anyhow::anyhow!("bind {bind_addr}: {e}"))?;
236    let actual = listener.local_addr()?;
237    info!(target: "assay-engine", %actual, "listening");
238    axum::serve(listener, app).await?;
239    Ok(())
240}
241
242/// Start a `WorkflowCtx` around the given store. Authentication +
243/// authorization are no longer the workflow's concern — the engine
244/// wraps the workflow router with a gate middleware ([`build_app`])
245/// that handles all of that.
246pub fn build_workflow_ctx<S: WorkflowStore + 'static>(store: S) -> Arc<WorkflowCtx<S>> {
247    let ctx = WorkflowCtx::start(Arc::new(store)).with_binary_version(env!("CARGO_PKG_VERSION"));
248    Arc::new(ctx)
249}
250
251/// Like [`build_workflow_ctx`] but also wires the engine-wide event
252/// bus into the workflow context so SSE + the dispatch-wakeup loop see
253/// state transitions.
254pub fn build_workflow_ctx_with_bus<S: WorkflowStore + 'static>(
255    store: S,
256    bus: Arc<dyn EngineEventBus>,
257) -> Arc<WorkflowCtx<S>> {
258    let ctx = WorkflowCtx::start(Arc::new(store))
259        .with_binary_version(env!("CARGO_PKG_VERSION"))
260        .with_event_bus(WorkflowEventBus::new(bus));
261    Arc::new(ctx)
262}