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 (admin-bearer-gated)
6//! - `/api/v1/engine/workflow/*` workflow API (admin-bearer-gated)
7//! - `/api/v1/engine/auth/*`     engine-internal auth + admin
8//! - `/api/v1/vault/*`           vault module (admin-bearer-gated)
9//! - `/healthz`                  redirect to `/api/v1/engine/core/health`
10//!
11//! Per the decoupled-modules architecture: each module accepts ONLY
12//! an admin bearer token at its HTTP boundary. Per-user authentication
13//! and policy decisions live upstream of the engine — typically in a
14//! dashboard / BFF / API gateway that validates the user session, asks
15//! zanzibar if they're allowed, and then forwards the call to the
16//! engine using its own admin bearer. The engine itself does not
17//! resolve sessions or check zanzibar at request time.
18//!
19//! Share-redeem (`GET /api/v1/vault/share/{token}`) is the one route
20//! that bypasses admin bearer — the biscuit token in the URL is its
21//! own auth, verified inside the handler.
22
23use axum::Router;
24use axum::http::{HeaderMap, StatusCode, header};
25use axum::response::{IntoResponse, Redirect, Response};
26use axum::routing::get;
27use std::sync::Arc;
28use tracing::info;
29
30use assay_domain::events::EngineEventBus;
31use assay_workflow::events::WorkflowEventBus;
32use assay_workflow::{WorkflowCtx, WorkflowStore};
33
34use crate::state::EngineState;
35
36/// Compose the full `axum::Router` for the engine.
37///
38/// The workflow crate returns a `Router` that already embeds its state,
39/// and the dashboard crate returns a `Router<Arc<DashboardCtx>>` that we
40/// `.with_state()` here. Both are merged into a single stateless `Router`
41/// ready for `axum::serve`. When the `auth` feature is on AND the
42/// engine boot constructed an `AuthCtx`, the OIDC spec router (mounted
43/// at `/auth/`) and the engine-internal auth router (mounted under
44/// `/api/v1/engine/auth/`) join the composition.
45pub fn build_app<S: WorkflowStore + Clone + 'static>(state: EngineState<S>) -> Router {
46    let operator_ui_enabled = state.engine_config.dashboard.operator_enabled();
47    let auth_ui_enabled = state.engine_config.dashboard.auth_ui_enabled();
48    // Workflow router takes a non-optional gate closure (typechecked).
49    // We supply admin_bearer_middleware as the gate; the workflow
50    // crate applies it to only the authed portion of the router so
51    // /health, /version, /openapi.json, /docs stay public for probes.
52    let state_for_workflow = state.clone();
53    let workflow_router = assay_workflow::api::router(Arc::clone(&state.workflow), |r| {
54        r.layer(axum::middleware::from_fn_with_state(
55            state_for_workflow,
56            admin_bearer_middleware::<S>,
57        ))
58    });
59
60    // `/healthz` is kept as a 1-line redirect to the new engine-core
61    // health endpoint for backward-compatible k8s probes. The real
62    // health response is served by the engine-core router under
63    // `/api/v1/engine/core/health` (see `engine_api.rs`).
64    let healthz = Router::new().route(
65        "/healthz",
66        get(|| async { Redirect::permanent("/api/v1/engine/core/health") }),
67    );
68
69    // Engine-core admin API. The handlers require an admin api-key
70    // bearer; when `admin_api_keys` is empty every admin route returns
71    // 401, so mounting unconditionally is safe for no-auth builds.
72    let engine_api_router = crate::engine_api::router::<S>().with_state(state.clone());
73
74    let mut app = workflow_router.merge(healthz).merge(engine_api_router);
75
76    // Built-in operator SPAs. The engine ships its own browser UI —
77    // auth console, vault console, workflow dashboard, engine console —
78    // so a stand-alone deployment (no sysops in front) is usable from
79    // a browser. SPAs prompt for an admin api-key and store it in
80    // localStorage, then call the engine API with that bearer.
81    // Deployments fronting the engine with sysops/gondor (or any
82    // other dashboard) toggle this off at runtime with
83    // `[dashboard] enabled = false` in engine.toml.
84    if operator_ui_enabled {
85        let dashboard_router =
86            assay_dashboard::workflow_router().with_state(Arc::clone(&state.dashboard));
87        let engine_console_router = assay_dashboard::engine_router();
88        app = app.merge(dashboard_router).merge(engine_console_router);
89    }
90
91    // Mount the auth routers when AuthCtx is present. We bind state to
92    // each router *before* nesting so the merged tree remains
93    // `Router<()>` (every other sub-router has its state baked in
94    // similarly). This avoids the axum requirement that all merged
95    // routers share a common state parameter.
96    //
97    // The routers are generic over a parent state from which both
98    // `AuthCtx` and `AdminApiKeys` are extractable via `FromRef`;
99    // `EngineState<S>` implements both impls (see `state.rs`), so the
100    // engine threads its full state in once and the auth handlers
101    // pluck what they need.
102    if state.auth.is_some() {
103        // OIDC spec endpoints — mounted at `/auth/...`. Discovery doc,
104        // JWKS, authorize/token/userinfo/revoke/introspect/logout,
105        // federation upstream callbacks. Stable surface that downstream
106        // OIDC clients depend on.
107        let spec_router =
108            assay_auth::oidc_spec_router::<EngineState<S>>().with_state(state.clone());
109        app = app.nest("/auth", spec_router);
110
111        // Engine-internal auth — login, logout (DELETE), whoami,
112        // passkey ceremonies, admin (users/sessions/biscuit/jwks/
113        // zanzibar/audit + OIDC clients/upstream CRUD). Mounted under
114        // `/api/v1/engine/auth/...` so the operator-facing surface
115        // sits beside the engine-core + workflow APIs.
116        let engine_auth_router =
117            assay_auth::engine_auth_router::<EngineState<S>>().with_state(state.clone());
118        app = app.nest("/api/v1/engine/auth", engine_auth_router);
119
120        // Browser sign-in/recovery and the operator auth console are
121        // independently gated so a public issuer does not need to expose
122        // administrative HTML.
123        if auth_ui_enabled {
124            app = app.merge(assay_dashboard::auth_public_router());
125        }
126        if operator_ui_enabled {
127            app = app.merge(assay_dashboard::auth_console_router());
128        }
129    }
130
131    // Vault module — plan 17 / v0.3.0. Mounted under /api/v1/vault when
132    // both the Cargo feature is on AND a VaultCtx was composed at boot
133    // (i.e. engine.modules.vault.enabled was TRUE). Phase 1 routes are
134    // admin-key-gated; Phase 3+ adds biscuit-share and Phase 7 the
135    // BW-compat shim's per-user session auth.
136    #[cfg(feature = "vault")]
137    if state.vault.is_some() {
138        // Vault router requires a non-optional gate closure
139        // (typechecked). We supply admin_bearer_middleware, which has
140        // the share-redeem path bypass built in so /share/{token}
141        // stays public (biscuit verifies in the handler).
142        let state_for_vault = state.clone();
143        let vault = assay_vault::router::vault_router::<EngineState<S>, _>(|r| {
144            r.layer(axum::middleware::from_fn_with_state(
145                state_for_vault,
146                admin_bearer_middleware::<S>,
147            ))
148        })
149        .with_state(state.clone());
150        app = app.nest("/api/v1/vault", vault);
151
152        // Vault console SPA at /vault, /vault/console, /vault/console/*.
153        // Runtime-gated on the dashboard flag, same as the other SPAs.
154        if operator_ui_enabled {
155            app = app.merge(assay_dashboard::vault_router());
156        }
157    }
158
159    // BW-compat shim (Phase 7). Stock BW mobile / browser / CLI
160    // clients hardcode /identity/* and /api/* — mount the compat
161    // router at root so those clients work without a reverse-proxy
162    // rewrite. Only reachable when both vault + bitwarden-compat
163    // features are on AND VaultCtx + AuthCtx are composed.
164    #[cfg(all(feature = "vault", feature = "vault-bitwarden-compat"))]
165    if state.vault.is_some() && state.auth.is_some() {
166        let bw =
167            assay_vault::bitwarden_compat::router::<EngineState<S>>().with_state(state.clone());
168        app = app.merge(bw);
169    }
170
171    if auth_ui_enabled && !operator_ui_enabled {
172        let auth_url = state
173            .engine_config
174            .auth
175            .public_url
176            .as_deref()
177            .unwrap_or(&state.engine_config.server.public_url);
178        let auth_host = url::Url::parse(auth_url)
179            .ok()
180            .and_then(|url| url.host_str().map(str::to_owned));
181        let root = Router::new()
182            .route("/", get(auth_origin_root))
183            .with_state(auth_host);
184        app = app.merge(root);
185    }
186
187    if !state.engine_config.server.allowed_hosts.is_empty() {
188        app = app.layer(axum::middleware::from_fn_with_state(
189            state,
190            allowed_host_middleware::<S>,
191        ));
192    }
193
194    app
195}
196
197async fn auth_origin_root(
198    axum::extract::State(auth_host): axum::extract::State<Option<String>>,
199    headers: HeaderMap,
200) -> Response {
201    let request_host = request_host(&headers);
202    if auth_host
203        .as_deref()
204        .zip(request_host.as_deref())
205        .is_some_and(|(expected, actual)| expected.eq_ignore_ascii_case(actual))
206    {
207        return Redirect::temporary("/auth/landing").into_response();
208    }
209    StatusCode::NOT_FOUND.into_response()
210}
211
212async fn allowed_host_middleware<S: WorkflowStore + Clone + 'static>(
213    axum::extract::State(state): axum::extract::State<EngineState<S>>,
214    request: axum::extract::Request,
215    next: axum::middleware::Next,
216) -> Response {
217    if request.uri().path() == "/api/v1/engine/core/health"
218        || host_is_allowed(request.headers(), &state.engine_config.server.allowed_hosts)
219    {
220        return next.run(request).await;
221    }
222    StatusCode::MISDIRECTED_REQUEST.into_response()
223}
224
225fn host_is_allowed(headers: &HeaderMap, allowed_hosts: &[String]) -> bool {
226    if allowed_hosts.is_empty() {
227        return true;
228    }
229    let Some(host) = request_host(headers) else {
230        return false;
231    };
232    allowed_hosts
233        .iter()
234        .any(|allowed| allowed.eq_ignore_ascii_case(&host))
235}
236
237fn request_host(headers: &HeaderMap) -> Option<String> {
238    let value = headers.get(header::HOST)?.to_str().ok()?;
239    value
240        .parse::<axum::http::uri::Authority>()
241        .ok()
242        .map(|authority| authority.host().to_owned())
243}
244
245/// Resource-server middleware applied to every engine module router.
246/// Accepts EITHER the operator admin api-key (service-to-service /
247/// break-glass) OR a JWT from a configured trusted issuer (per-user
248/// resource-server pattern). No session, no zanzibar — policy lives
249/// upstream.
250///
251/// The one bypass: vault share-redeem (`GET /share/{token}` —
252/// path-relative because this middleware runs INSIDE the nested
253/// `/api/v1/vault` router, after axum has stripped the prefix).
254/// `/share/revoke` is excluded — it's an admin operation that mints
255/// or revokes tokens. The biscuit token in the share-redeem URL is
256/// its own authentication.
257async fn admin_bearer_middleware<S: WorkflowStore + Clone + 'static>(
258    axum::extract::State(state): axum::extract::State<EngineState<S>>,
259    request: axum::extract::Request,
260    next: axum::middleware::Next,
261) -> axum::response::Response {
262    let path = request.uri().path();
263    if (path.starts_with("/share/") && path != "/share/revoke")
264        || (path.starts_with("/api/v1/vault/share/") && path != "/api/v1/vault/share/revoke")
265    {
266        return next.run(request).await;
267    }
268    let keys = crate::state::AdminApiKeys(Arc::clone(&state.admin_api_keys));
269    // If auth is configured, accept admin bearer OR trusted JWT.
270    // If auth is not configured at all (no AuthCtx), only the admin
271    // bearer path is available — fall back to the strict check.
272    let outcome = match state.auth.as_ref() {
273        Some(auth) => assay_auth::gate::require_admin_or_jwt(request.headers(), auth, &keys)
274            .await
275            .map(|_| ()),
276        None => assay_auth::gate::require_admin_bearer(request.headers(), &keys),
277    };
278    if let Err(r) = outcome {
279        return *r;
280    }
281    next.run(request).await
282}
283
284/// Bind a TCP listener on `bind_addr` and serve the composed app.
285///
286/// Convenience wrapper that composes [`EngineState`] into an
287/// [`axum::Router`] via [`build_app`] and hands off to
288/// [`bind_and_serve`]. Used by the standalone `assay-engine` binary.
289pub async fn serve<S: WorkflowStore + Clone + 'static>(
290    bind_addr: &str,
291    state: EngineState<S>,
292) -> anyhow::Result<()> {
293    let app = build_app(state);
294    bind_and_serve(bind_addr, app).await
295}
296
297/// Bind a TCP listener on `bind_addr` and serve a pre-built
298/// [`axum::Router`].
299///
300/// Used by [`crate::run`] (after `embedded::build` returns the
301/// composed router) and by downstream embedders who want to add
302/// their own middleware / merge with their own router before
303/// serving.
304pub async fn bind_and_serve(bind_addr: &str, app: axum::Router) -> anyhow::Result<()> {
305    let listener = tokio::net::TcpListener::bind(bind_addr)
306        .await
307        .map_err(|e| anyhow::anyhow!("bind {bind_addr}: {e}"))?;
308    let actual = listener.local_addr()?;
309    info!(target: "assay-engine", %actual, "listening");
310    axum::serve(listener, app).await?;
311    Ok(())
312}
313
314/// Start a `WorkflowCtx` around the given store. Authentication +
315/// authorization are no longer the workflow's concern — the engine
316/// wraps the workflow router with a gate middleware ([`build_app`])
317/// that handles all of that.
318pub fn build_workflow_ctx<S: WorkflowStore + 'static>(store: S) -> Arc<WorkflowCtx<S>> {
319    let ctx = WorkflowCtx::start(Arc::new(store)).with_binary_version(env!("CARGO_PKG_VERSION"));
320    Arc::new(ctx)
321}
322
323/// Like [`build_workflow_ctx`] but also wires the engine-wide event
324/// bus into the workflow context so SSE + the dispatch-wakeup loop see
325/// state transitions.
326pub fn build_workflow_ctx_with_bus<S: WorkflowStore + 'static>(
327    store: S,
328    bus: Arc<dyn EngineEventBus>,
329) -> Arc<WorkflowCtx<S>> {
330    let ctx = WorkflowCtx::start(Arc::new(store))
331        .with_binary_version(env!("CARGO_PKG_VERSION"))
332        .with_event_bus(WorkflowEventBus::new(bus));
333    Arc::new(ctx)
334}
335
336#[cfg(test)]
337mod host_boundary_tests {
338    use axum::extract::State;
339    use axum::http::{HeaderMap, HeaderValue, StatusCode, header};
340
341    use super::{auth_origin_root, host_is_allowed};
342
343    #[tokio::test]
344    async fn auth_origin_root_enters_public_auth_while_engine_root_stays_hidden() {
345        let mut auth_headers = HeaderMap::new();
346        auth_headers.insert(header::HOST, HeaderValue::from_static("auth.assay.rs"));
347        let auth = auth_origin_root(State(Some("auth.assay.rs".to_string())), auth_headers).await;
348        assert_eq!(auth.status(), StatusCode::TEMPORARY_REDIRECT);
349        assert_eq!(auth.headers()[header::LOCATION], "/auth/landing");
350
351        let mut engine_headers = HeaderMap::new();
352        engine_headers.insert(header::HOST, HeaderValue::from_static("engine.assay.rs"));
353        let engine =
354            auth_origin_root(State(Some("auth.assay.rs".to_string())), engine_headers).await;
355        assert_eq!(engine.status(), StatusCode::NOT_FOUND);
356    }
357
358    #[test]
359    fn configured_hosts_are_case_insensitive_and_port_agnostic() {
360        let allowed = vec!["auth.assay.rs".to_string(), "engine.assay.rs".to_string()];
361        let mut headers = HeaderMap::new();
362        headers.insert(header::HOST, HeaderValue::from_static("AUTH.ASSAY.RS:443"));
363
364        assert!(host_is_allowed(&headers, &allowed));
365    }
366
367    #[test]
368    fn unknown_and_missing_hosts_are_rejected_when_the_allowlist_is_configured() {
369        let allowed = vec!["auth.assay.rs".to_string(), "engine.assay.rs".to_string()];
370        let mut headers = HeaderMap::new();
371        headers.insert(header::HOST, HeaderValue::from_static("assay-auth.fly.dev"));
372
373        assert!(!host_is_allowed(&headers, &allowed));
374        assert!(!host_is_allowed(&HeaderMap::new(), &allowed));
375    }
376
377    #[test]
378    fn an_empty_allowlist_preserves_embedded_and_local_callers() {
379        assert!(host_is_allowed(&HeaderMap::new(), &[]));
380    }
381}