Skip to main content

aion_server/api/http/
router.rs

1//! Public HTTP router construction.
2
3use axum::{
4    Router,
5    extract::DefaultBodyLimit,
6    http::{HeaderName, HeaderValue, Method, StatusCode, header},
7    routing::{any, get, post},
8};
9use tower_http::cors::CorsLayer;
10
11use super::assistant::{assistant_descriptor, assistant_document};
12use super::authoring::compile_source;
13use super::awl::{
14    bind_run, check, create_document, deploy_authoring, edit, emit, format, get_document,
15    get_layout, get_revision, get_run_status, list_documents, put_document, put_layout, scaffold,
16    worker_availability,
17};
18use super::awl_deployed::{get_deployed_document, list_deployed};
19use super::build::build_identity;
20use super::changelog::changelog;
21use super::cluster_command::cluster_command;
22use super::deploy::{list_versions, route_version, unload_version, upload_package};
23use super::describe_live::describe_live;
24use super::dev_ui::{dev_register_mock, dev_replay_run, dev_trigger_run};
25use super::events::subscribe_events_socket;
26use super::history::{fetch_event, fetch_history};
27use super::intervene::{intervene, list_attempts};
28use super::managed_workers::{
29    list_managed_workers, restart_managed_worker, start_managed_worker, stop_managed_worker,
30};
31use super::outbox::list_dead_letters;
32use super::queues::list_unserved_queues;
33use super::schedules::{
34    create_schedule, delete_schedule, describe_schedule, list_schedules, pause_schedule,
35    resume_schedule, update_schedule,
36};
37use super::transcripts::{fetch_transcript, list_transcript_streams};
38use super::unrecoverable::list_unrecoverable_runs;
39use super::update_status::update_status;
40use super::whoami::whoami;
41use super::worker_deployments::{
42    delete_worker_deployment, get_worker_deployment, list_worker_deployments,
43    put_worker_deployment, set_worker_deployment_desired_state,
44};
45use super::workers::{drain_worker, stop_worker};
46use super::workflows::{
47    cancel_workflow, count_workflows, describe_workflow, get_workflows, list_namespace_records,
48    list_namespaces, post_list_workflows, post_namespace, query_workflow, reopen_workflow,
49    set_namespace_placement, signal_workflow, start_workflow,
50};
51use crate::mcp::{McpRuntime, mcp_disabled_router, mcp_router};
52use crate::{ServerError, ServerState, observability, ops_console::assets};
53
54/// Build the public HTTP application: workflow-management routes first, then
55/// the ops-console static asset fallback. The ops console adds no data API.
56///
57/// # Errors
58///
59/// Returns [`ServerError::Config`] when ops-console assets are misconfigured, or
60/// when the MCP surface is enabled and its published tool catalog cannot be
61/// constructed.
62pub fn http_router(state: ServerState) -> Result<Router, ServerError> {
63    let ops_console = assets::ops_console_router(&state.runtime_config().ops_console)?;
64    let cors = cors_layer(&state.runtime_config().cors_allowed_origins)?;
65    let metrics = state.metrics().cloned();
66    let health = state.health().cloned();
67    let mut router = workflow_router(state.clone());
68    // The MCP endpoint is another route on THIS listener: one port, one
69    // process. It is merged here rather than inside `workflow_router` because
70    // it is a top-level protocol surface alongside `/metrics` and `/health/*`,
71    // not a workflow-management route.
72    router = router.merge(mcp_family(&state)?.with_state(state));
73    if let Some(metrics) = metrics {
74        router = router.merge(Router::new().route(
75            "/metrics",
76            get(observability::metrics::metrics_handler).with_state(metrics),
77        ));
78    }
79    if let Some(health) = health {
80        router = router.merge(
81            Router::new()
82                .route("/health/live", get(observability::health::live))
83                .route(
84                    "/health/ready",
85                    get(observability::health::ready).with_state(health),
86                ),
87        );
88    }
89    let router = router.merge(ops_console);
90    // CORS is applied last so it wraps every public route the browser ops console
91    // calls (the workflow API, /metrics, /health/*, the ops-console fallback).
92    // With no configured origins `cors_layer` returns None and the router is
93    // byte-identical to before — no cross-origin request is allowed (the secure
94    // default). With origins set the layer also answers OPTIONS preflight.
95    Ok(match cors {
96        Some(cors) => router.layer(cors),
97        None => router,
98    })
99}
100
101/// Build the CORS layer for the public HTTP router from the operator-configured
102/// allowed origins.
103///
104/// Returns `Ok(None)` when no origins are configured — the secure default:
105/// the layer is not installed and no cross-origin request is permitted. When
106/// origins are configured the layer is scoped to exactly those origins (never
107/// `Any`, so it is safe to pair with credentialed requests), permits the
108/// methods the ops console uses (GET, POST, PUT, DELETE, and OPTIONS preflight), and allows
109/// exactly the request headers the API consumes.
110///
111/// # Errors
112///
113/// Returns [`ServerError::Config`] when a configured origin is not a valid HTTP
114/// header value. Startup validation already rejects malformed origins, so this
115/// is defense in depth.
116fn cors_layer(allowed_origins: &[String]) -> Result<Option<CorsLayer>, ServerError> {
117    if allowed_origins.is_empty() {
118        return Ok(None);
119    }
120    let mut origins = Vec::with_capacity(allowed_origins.len());
121    for origin in allowed_origins {
122        let value = origin
123            .parse::<HeaderValue>()
124            .map_err(|source| ServerError::Config {
125                message: format!("invalid CORS origin `{origin}`: {source}"),
126            })?;
127        origins.push(value);
128    }
129    let layer = CorsLayer::new()
130        .allow_origin(origins)
131        .allow_methods([
132            Method::GET,
133            Method::POST,
134            Method::PUT,
135            Method::DELETE,
136            Method::OPTIONS,
137        ])
138        .allow_headers([
139            header::CONTENT_TYPE,
140            header::AUTHORIZATION,
141            HeaderName::from_static("x-aion-namespaces"),
142            HeaderName::from_static("x-aion-subject"),
143        ]);
144    Ok(Some(layer))
145}
146
147/// Disabled deploy surface: a plain 404 with no body, indistinguishable
148/// from an unmounted route family.
149async fn deploy_disabled() -> StatusCode {
150    StatusCode::NOT_FOUND
151}
152
153/// Disabled authoring surface: a plain 404 with no body, indistinguishable
154/// from an unmounted route family. When `[authoring].gleam_path` is absent the
155/// server compiles no Gleam and deploys pre-built `.aion` files only (CN7).
156async fn authoring_disabled() -> StatusCode {
157    StatusCode::NOT_FOUND
158}
159
160/// Disabled dev surface: a plain 404 with no body, indistinguishable from an
161/// unmounted route family. When `[dev].enabled` is false the server mounts no
162/// dev endpoints and installs no activity-mock decorator (CN4).
163async fn dev_disabled() -> StatusCode {
164    StatusCode::NOT_FOUND
165}
166
167/// Disabled deployment surfaces: a plain 404 with no body for the deployed-AWL
168/// reader, worker-deployment management, and managed-worker lifecycle
169/// families. All follow the deploy surface's switch and stay dark when the
170/// operator closes it.
171async fn deploy_surface_disabled() -> StatusCode {
172    StatusCode::NOT_FOUND
173}
174
175/// The read-only deployed-AWL route family.
176///
177/// GET only: both routes carry a single `get`, so every other method is a 405
178/// the router answers — there is no mutation handler on this family to reach,
179/// guarded or otherwise. With the deploy surface off the family is a plain 404,
180/// covering the bare path and everything under it (a `{*rest}` wildcard does
181/// not match the bare path).
182fn deployed_awl_router(deploy_enabled: bool) -> Router<ServerState> {
183    if deploy_enabled {
184        Router::new()
185            .route("/awl/deployed", get(list_deployed))
186            .route(
187                "/awl/deployed/{workflow_type}/{content_hash}",
188                get(get_deployed_document),
189            )
190    } else {
191        Router::new()
192            .route("/awl/deployed", any(deploy_surface_disabled))
193            .route("/awl/deployed/{*rest}", any(deploy_surface_disabled))
194    }
195}
196
197fn worker_deployment_router(deploy_enabled: bool) -> Router<ServerState> {
198    if deploy_enabled {
199        Router::new()
200            .route("/worker-deployments", get(list_worker_deployments))
201            .route(
202                "/worker-deployments/{name}",
203                get(get_worker_deployment)
204                    .put(put_worker_deployment)
205                    .delete(delete_worker_deployment),
206            )
207            .route(
208                "/worker-deployments/{name}/desired-state",
209                post(set_worker_deployment_desired_state),
210            )
211    } else {
212        Router::new()
213            .route("/worker-deployments", any(deploy_surface_disabled))
214            .route("/worker-deployments/{*rest}", any(deploy_surface_disabled))
215    }
216}
217
218/// The managed-worker route family: the always-mounted status join, and the
219/// three lifecycle commands mounted only when `[deploy].enabled` is set.
220///
221/// The mount condition matches the surfaces these commands belong to: their
222/// gRPC counterparts live on `DeployService`, which joins the listener only
223/// under `[deploy].enabled` (`crate::run`), and the sibling
224/// `/worker-deployments/*` family follows the same switch. With deploy off,
225/// every path under `/workers/managed/` is a plain 404 — a server that is not
226/// a deploy target exposes no lifecycle mutation on any transport. Within a
227/// mounted route, authorization is the handlers' deploy-grant check (decided
228/// per caller; with auth disabled the single-tenant operator holds the grant
229/// server-side). The read stays mounted regardless, exactly as it always has
230/// been: reporting the fleet is not a deploy-surface mutation.
231fn managed_worker_router(deploy_enabled: bool) -> Router<ServerState> {
232    let read = Router::new().route("/workers/managed", get(list_managed_workers));
233    if deploy_enabled {
234        read.route("/workers/managed/{name}/start", post(start_managed_worker))
235            .route("/workers/managed/{name}/stop", post(stop_managed_worker))
236            .route(
237                "/workers/managed/{name}/restart",
238                post(restart_managed_worker),
239            )
240    } else {
241        read.route("/workers/managed/{*rest}", any(deploy_surface_disabled))
242    }
243}
244
245/// The MCP route family, mounted on the SERVER'S OWN listener.
246///
247/// One port, one process: the MCP endpoint is another route on the same HTTP
248/// surface the console and the workflow API are served from, not a second
249/// listener. It is dark unless `[mcp].enabled` is set, and a dark surface is a
250/// plain 404 — indistinguishable from a build that never had the route.
251///
252/// A construction failure (a published tool schema that will not compile) is
253/// NOT downgraded to a dark surface: it is a server defect, and an operator who
254/// asked for the endpoint would otherwise get a 404 and no idea why.
255///
256/// Each call builds one runtime, and a runtime owns one task store. That is
257/// correct because a task is reachable only through the identifier its creator
258/// was handed: two routers are two disjoint sets of handles, never a split view
259/// of one set. The serving path builds the router exactly once.
260fn mcp_family(state: &ServerState) -> Result<Router<ServerState>, ServerError> {
261    if !state.runtime_config().mcp.enabled {
262        return Ok(mcp_disabled_router());
263    }
264    let runtime = McpRuntime::build(state.clone(), &state.runtime_config().mcp)?;
265    Ok(mcp_router(std::sync::Arc::new(runtime)))
266}
267
268/// Build the public workflow-management HTTP router.
269pub fn workflow_router(state: ServerState) -> Router {
270    // The deploy surface is dark by default: when `[deploy].enabled` is
271    // false the routes are not mounted and every `/deploy/*` path is a
272    // plain 404 (the explicit catch-all keeps the ops-console SPA fallback
273    // from answering for the deploy namespace). The archive upload route
274    // disables the default body limit because `read_archive_body` enforces
275    // the operator-configured `deploy.max_archive_bytes` ceiling while
276    // streaming.
277    let deploy = if state.runtime_config().deploy.enabled {
278        Router::new()
279            .route(
280                "/deploy/packages",
281                post(upload_package).layer(DefaultBodyLimit::disable()),
282            )
283            .route("/deploy/versions", get(list_versions))
284            .route("/deploy/route", post(route_version))
285            .route("/deploy/unload", post(unload_version))
286    } else {
287        Router::new().route("/deploy/{*rest}", any(deploy_disabled))
288    };
289    // The authoring surface is dark by default, gated on
290    // `[authoring].gleam_path`: when it is unset the routes are not mounted and
291    // every `/authoring/*` path is a plain 404 (the explicit catch-all keeps
292    // the ops-console SPA fallback from answering for the authoring namespace).
293    // With it absent the server compiles no Gleam and deploys pre-built `.aion`
294    // files only (CN7).
295    let authoring = if state.runtime_config().authoring.gleam_path.is_some() {
296        Router::new().route("/authoring/compile", post(compile_source))
297    } else {
298        Router::new().route("/authoring/{*rest}", any(authoring_disabled))
299    };
300    // The full AWL studio is always mounted. Stock config supplies the
301    // `aion-authoring` workspace; the typed unconfigured refusal remains for
302    // manually constructed runtime configs that explicitly omit it.
303    let awl_documents = Router::new()
304        .route("/awl/documents", get(list_documents).post(create_document))
305        .route(
306            "/awl/documents/{*path}",
307            get(get_document).put(put_document),
308        )
309        .route("/awl/layout/{*path}", get(get_layout).put(put_layout));
310    let awl_deployed = deployed_awl_router(state.runtime_config().deploy.enabled);
311    let awl = Router::new()
312        .route("/awl/check", post(check))
313        .route("/awl/emit", post(emit))
314        .route("/awl/deploy", post(deploy_authoring))
315        .route("/awl/revisions/{hash}", get(get_revision))
316        .route("/awl/workers/availability", post(worker_availability))
317        .route("/awl/runs/{deployment_id}", get(get_run_status))
318        .route("/awl/runs/{deployment_id}/binding", post(bind_run))
319        .route("/awl/edit", post(edit))
320        .route("/awl/fmt", post(format))
321        .route("/awl/scaffold", post(scaffold))
322        .merge(awl_documents)
323        .merge(awl_deployed);
324    // The dev surface is dark by default, gated on `[dev].enabled`: when off the
325    // routes are not mounted and every `/dev/*` path is a plain 404 (the
326    // explicit catch-all keeps the ops-console SPA fallback from answering for
327    // the dev namespace), and the engine runs the bare production dispatcher.
328    let dev = if state.runtime_config().dev.enabled {
329        Router::new()
330            .route("/dev/runs", post(dev_trigger_run))
331            .route("/dev/mocks", post(dev_register_mock))
332            .route("/dev/replay", post(dev_replay_run))
333    } else {
334        Router::new().route("/dev/{*rest}", any(dev_disabled))
335    };
336    deploy
337        .merge(authoring)
338        .merge(awl)
339        .merge(dev)
340        .merge(worker_deployment_router(
341            state.runtime_config().deploy.enabled,
342        ))
343        .route("/whoami", get(whoami))
344        .route("/build", get(build_identity))
345        // The installed version joined with the last completed manual update
346        // check — the ops console's update pill reads this. Serving it never
347        // touches the network.
348        .route("/update-status", get(update_status))
349        // What changed in the version this server runs — embedded in the
350        // binary, consumed by the console's "What's new" panel.
351        .route("/changelog", get(changelog))
352        // The built-in assistant, always mounted: it ships in the binary like
353        // the ops console, so there is no configuration under which this server
354        // has one and does not say so.
355        .route("/assistant", get(assistant_descriptor))
356        .route("/assistant/document", get(assistant_document))
357        .route("/namespaces", get(list_namespaces).post(post_namespace))
358        .route("/namespaces/records", get(list_namespace_records))
359        .route(
360            "/namespaces/{name}/placement",
361            axum::routing::put(set_namespace_placement),
362        )
363        .route("/workflows", get(get_workflows))
364        .route("/workflows/count", get(count_workflows))
365        .route("/workflows/start", post(start_workflow))
366        .route("/workflows/signal", post(signal_workflow))
367        .route("/workflows/query", post(query_workflow))
368        .route("/workflows/cancel", post(cancel_workflow))
369        .route("/workflows/reopen", post(reopen_workflow))
370        .route("/workflows/list", post(post_list_workflows))
371        .route("/workflows/describe", post(describe_workflow))
372        .route("/workflows/describe-live", post(describe_live))
373        .route("/workflows/history", post(fetch_history))
374        .route("/workflows/event", post(fetch_event))
375        .route("/workflows/intervene", post(intervene))
376        .route("/workflows/attempts", post(list_attempts))
377        .route("/workflows/transcript", post(fetch_transcript))
378        .route("/workflows/transcripts", post(list_transcript_streams))
379        .route("/workflows/unrecoverable", get(list_unrecoverable_runs))
380        .route("/events/stream", get(subscribe_events_socket))
381        .route("/cluster/command", post(cluster_command))
382        .route("/outbox/dead-letters", post(list_dead_letters))
383        .route("/queues/unserved", get(list_unserved_queues))
384        .merge(managed_worker_router(state.runtime_config().deploy.enabled))
385        .route("/workers/{worker_id}/drain", post(drain_worker))
386        .route("/workers/{worker_id}/stop", post(stop_worker))
387        .route("/schedules", post(create_schedule).get(list_schedules))
388        .route(
389            "/schedules/{id}",
390            get(describe_schedule)
391                .put(update_schedule)
392                .delete(delete_schedule),
393        )
394        .route("/schedules/{id}/pause", post(pause_schedule))
395        .route("/schedules/{id}/resume", post(resume_schedule))
396        .with_state(state)
397}
398
399#[cfg(test)]
400mod tests {
401    use std::{fs, sync::Arc};
402
403    use aion::EngineBuilder;
404    use aion_store::{EventStore, InMemoryStore};
405    use axum::{body, http::Request, http::StatusCode};
406    use tower::ServiceExt;
407
408    use super::super::test_support::{
409        NAMESPACE, json_request, read_json, read_text, runtime_config, server_state,
410    };
411    use super::*;
412    use crate::{
413        NamespaceResolver, StaticScheduleNamespaces, StaticWorkflowNamespaces,
414        config::{NamespaceConfig, NamespaceMode, OpsConsoleAssetSource, OpsConsoleConfig},
415    };
416
417    #[tokio::test]
418    async fn ops_console_assets_serve_index_asset_and_do_not_shadow_public_api()
419    -> Result<(), Box<dyn std::error::Error>> {
420        let bundle = crate::test_support::private_tempdir()?;
421        fs::write(
422            bundle.path().join("index.html"),
423            "<!doctype html><title>Aion</title><script src=\"/app.js\"></script>",
424        )?;
425        fs::write(bundle.path().join("app.js"), "window.AION = true;")?;
426
427        let store: Arc<dyn EventStore> = Arc::new(InMemoryStore::default());
428        let engine = Arc::new(
429            EngineBuilder::new()
430                .store_arc(Arc::clone(&store))
431                .in_memory_visibility()
432                .scheduler_threads(1)
433                .build()
434                .await?,
435        );
436        let resolver = NamespaceResolver::from_parts(
437            NamespaceMode::SharedEngine,
438            Some(engine),
439            Arc::new(StaticWorkflowNamespaces::default()),
440            Arc::new(StaticScheduleNamespaces::default()),
441        );
442        let mut config = runtime_config();
443        config.ops_console = OpsConsoleConfig {
444            source: OpsConsoleAssetSource::FileSystem {
445                asset_path: bundle.path().to_path_buf(),
446            },
447        };
448        let router = http_router(server_state(resolver, config).await?)?;
449
450        let root = router
451            .clone()
452            .oneshot(Request::builder().uri("/").body(body::Body::empty())?)
453            .await?;
454        assert_eq!(root.status(), StatusCode::OK);
455        assert!(read_text(root).await?.contains("<title>Aion</title>"));
456
457        let asset = router
458            .clone()
459            .oneshot(
460                Request::builder()
461                    .uri("/app.js")
462                    .body(body::Body::empty())?,
463            )
464            .await?;
465        assert_eq!(asset.status(), StatusCode::OK);
466        assert_eq!(read_text(asset).await?, "window.AION = true;");
467
468        let spa = router
469            .clone()
470            .oneshot(
471                Request::builder()
472                    .uri("/ops-console/workflows/demo")
473                    .body(body::Body::empty())?,
474            )
475            .await?;
476        assert_eq!(spa.status(), StatusCode::OK);
477        assert!(read_text(spa).await?.contains("<title>Aion</title>"));
478
479        let list = serde_json::json!({
480            "namespace": NAMESPACE,
481            "filter": { "workflow_type": "nonexistent" },
482        });
483        let list_response = router
484            .oneshot(json_request("/workflows/list", &list)?)
485            .await?;
486        assert_eq!(list_response.status(), StatusCode::OK);
487        let list_body: serde_json::Value = read_json(list_response).await?;
488        assert!(
489            list_body["summaries"]
490                .as_array()
491                .ok_or("summaries missing")?
492                .is_empty()
493        );
494        Ok(())
495    }
496
497    #[tokio::test]
498    async fn cors_preflight_and_actual_request_carry_allow_headers_for_configured_origin()
499    -> Result<(), Box<dyn std::error::Error>> {
500        let store: Arc<dyn EventStore> = Arc::new(InMemoryStore::default());
501        let engine = Arc::new(
502            EngineBuilder::new()
503                .store_arc(Arc::clone(&store))
504                .in_memory_visibility()
505                .scheduler_threads(1)
506                .build()
507                .await?,
508        );
509        let resolver = NamespaceResolver::from_parts(
510            NamespaceMode::SharedEngine,
511            Some(engine),
512            Arc::new(StaticWorkflowNamespaces::default()),
513            Arc::new(StaticScheduleNamespaces::default()),
514        );
515        let mut config = runtime_config();
516        config.cors_allowed_origins = vec!["http://localhost:5173".to_owned()];
517        let router = http_router(server_state(resolver, config).await?)?;
518
519        // Preflight: the browser sends OPTIONS with the requested method/header;
520        // the layer must answer with the matching allow-origin and allow-methods.
521        let preflight = router
522            .clone()
523            .oneshot(
524                Request::builder()
525                    .method("OPTIONS")
526                    .uri("/workflows/list")
527                    .header("origin", "http://localhost:5173")
528                    .header("access-control-request-method", "POST")
529                    .header("access-control-request-headers", "x-aion-namespaces")
530                    .body(body::Body::empty())?,
531            )
532            .await?;
533        assert_eq!(
534            preflight
535                .headers()
536                .get("access-control-allow-origin")
537                .and_then(|value| value.to_str().ok()),
538            Some("http://localhost:5173")
539        );
540
541        // Actual request from the allowed origin echoes the allow-origin header.
542        let actual = router
543            .oneshot(
544                Request::builder()
545                    .uri("/health/live")
546                    .header("origin", "http://localhost:5173")
547                    .body(body::Body::empty())?,
548            )
549            .await?;
550        assert_eq!(actual.status(), StatusCode::OK);
551        assert_eq!(
552            actual
553                .headers()
554                .get("access-control-allow-origin")
555                .and_then(|value| value.to_str().ok()),
556            Some("http://localhost:5173")
557        );
558        Ok(())
559    }
560
561    #[tokio::test]
562    async fn cors_absent_origins_install_no_layer() -> Result<(), Box<dyn std::error::Error>> {
563        let store: Arc<dyn EventStore> = Arc::new(InMemoryStore::default());
564        let engine = Arc::new(
565            EngineBuilder::new()
566                .store_arc(Arc::clone(&store))
567                .in_memory_visibility()
568                .scheduler_threads(1)
569                .build()
570                .await?,
571        );
572        let resolver = NamespaceResolver::from_parts(
573            NamespaceMode::SharedEngine,
574            Some(engine),
575            Arc::new(StaticWorkflowNamespaces::default()),
576            Arc::new(StaticScheduleNamespaces::default()),
577        );
578        // runtime_config() leaves cors_allowed_origins empty (the secure default).
579        let router = http_router(server_state(resolver, runtime_config()).await?)?;
580
581        let response = router
582            .oneshot(
583                Request::builder()
584                    .uri("/health/live")
585                    .header("origin", "http://localhost:5173")
586                    .body(body::Body::empty())?,
587            )
588            .await?;
589        assert_eq!(response.status(), StatusCode::OK);
590        assert!(
591            response
592                .headers()
593                .get("access-control-allow-origin")
594                .is_none(),
595            "no CorsLayer must be installed when no origins are configured"
596        );
597        Ok(())
598    }
599
600    #[cfg(feature = "auth")]
601    #[tokio::test]
602    async fn worker_availability_allows_granted_jwt_namespace_and_denies_foreign_namespace()
603    -> Result<(), Box<dyn std::error::Error>> {
604        let (engine, _, _) = super::super::test_support::shared_engine().await?;
605        let resolver = NamespaceResolver::from_config(
606            NamespaceConfig {
607                mode: NamespaceMode::SharedEngine,
608            },
609            engine,
610        );
611        let router = http_router(server_state(resolver, runtime_config()).await?)?;
612
613        let allowed = router
614            .clone()
615            .oneshot(json_request(
616                "/awl/workers/availability",
617                &serde_json::json!({
618                    "namespace": NAMESPACE,
619                    "task_queue": "orders",
620                }),
621            )?)
622            .await?;
623        assert_eq!(allowed.status(), StatusCode::OK);
624
625        let foreign = router
626            .oneshot(json_request(
627                "/awl/workers/availability",
628                &serde_json::json!({
629                    "namespace": "tenant-b",
630                    "task_queue": "orders",
631                }),
632            )?)
633            .await?;
634        assert_eq!(foreign.status(), StatusCode::FORBIDDEN);
635        let body: serde_json::Value = read_json(foreign).await?;
636        assert_eq!(body["code"], "namespace_denied");
637        Ok(())
638    }
639
640    #[tokio::test]
641    async fn worker_availability_keeps_auth_off_operator_access()
642    -> Result<(), Box<dyn std::error::Error>> {
643        let (engine, _, _) = super::super::test_support::shared_engine().await?;
644        let resolver = NamespaceResolver::from_config(
645            NamespaceConfig {
646                mode: NamespaceMode::SharedEngine,
647            },
648            engine,
649        );
650        let mut config = runtime_config();
651        config.auth.enabled = false;
652        config.auth.jwks_url = None;
653        let router = http_router(crate::ServerState::from_parts(resolver, config))?;
654        let request = Request::builder()
655            .method("POST")
656            .uri("/awl/workers/availability")
657            .header("content-type", "application/json")
658            .body(body::Body::from(serde_json::to_vec(&serde_json::json!({
659                "namespace": "operator-selected-namespace",
660                "task_queue": "orders",
661            }))?))?;
662
663        let response = router.oneshot(request).await?;
664        assert_eq!(response.status(), StatusCode::OK);
665        let body: serde_json::Value = read_json(response).await?;
666        assert_eq!(body["connected_workers"], 0);
667        Ok(())
668    }
669
670    #[tokio::test]
671    async fn observability_routes_are_public_and_expose_expected_payloads()
672    -> Result<(), Box<dyn std::error::Error>> {
673        // This test rides the production `build_with_store` startup path, so
674        // under `feature = "auth"` the configured jwks_url must be a live
675        // endpoint for the initial JWKS fetch.
676        #[cfg(feature = "auth")]
677        let config = {
678            let mut config = runtime_config();
679            config.auth.jwks_url = Some(crate::auth::test_support::serve_jwks()?);
680            config
681        };
682        #[cfg(not(feature = "auth"))]
683        let config = runtime_config();
684        let router = http_router(
685            crate::ServerState::build_with_store(InMemoryStore::default(), config).await?,
686        )?;
687
688        let metrics_response = router
689            .clone()
690            .oneshot(
691                Request::builder()
692                    .uri("/metrics")
693                    .body(body::Body::empty())?,
694            )
695            .await?;
696        assert_eq!(metrics_response.status(), StatusCode::OK);
697        assert_eq!(
698            metrics_response
699                .headers()
700                .get(axum::http::header::CONTENT_TYPE)
701                .and_then(|value| value.to_str().ok()),
702            Some("text/plain; version=0.0.4; charset=utf-8")
703        );
704        let metrics_body = read_text(metrics_response).await?;
705        assert!(metrics_body.contains("# HELP aion_workflows_started_total"));
706        assert!(metrics_body.contains("# TYPE aion_workflows_started_total counter"));
707        assert!(metrics_body.contains("# HELP aion_activity_duration_seconds"));
708        assert!(metrics_body.contains("# TYPE aion_activity_duration_seconds histogram"));
709        assert!(metrics_body.contains("aion_activity_duration_seconds_bucket"));
710        assert!(metrics_body.contains("aion_store_operation_duration_seconds_bucket"));
711
712        let live_response = router
713            .clone()
714            .oneshot(
715                Request::builder()
716                    .uri("/health/live")
717                    .body(body::Body::empty())?,
718            )
719            .await?;
720        assert_eq!(live_response.status(), StatusCode::OK);
721
722        let ready_response = router
723            .oneshot(
724                Request::builder()
725                    .uri("/health/ready")
726                    .body(body::Body::empty())?,
727            )
728            .await?;
729        assert_eq!(ready_response.status(), StatusCode::OK);
730        Ok(())
731    }
732}