//! The HTTP surface: routing, request extraction, and OpenAI-shaped errors. //! //! `POST /v1/chat/completions` (stream and non-stream) and `GET /v1/models`, //! plus a tiny `/health`. The handlers are thin: they delegate all behaviour //! to [`ChatService`] and only decide status codes and envelopes. use axum::extract::State; use axum::http::StatusCode; use axum::response::{sse::Event, sse::Sse, IntoResponse, Json}; use axum::routing::{get, post}; use axum::Router; use serde::de::DeserializeOwned; use std::sync::Arc; use super::anthropic::{self, AnthropicRequest, AnthropicStream}; use super::service::ChatService; use super::types::{ApiErrorEnvelope, ChatRequest, ModelCard, ModelList}; use super::{files, mcp, sessions, uploads, web}; use crate::store::Store; /// Build the router. Mount this inside any axum `Router` or serve it directly. pub fn router(service: ChatService) -> Router { router_with_auth(service, AuthConfig::default()) } /// Build the router with optional API-key auth and a Host allowlist (no GUI store). pub fn router_with_auth(service: ChatService, auth: AuthConfig) -> Router { build_router( AppState { service, store: None, workspace_root: default_workspace_root(), }, auth, ) } /// Build the router with the session store + web GUI enabled, plus auth. /// `workspace_root` is the parent of the per-session personal folders. pub fn router_with_store( service: ChatService, store: Arc, auth: AuthConfig, workspace_root: std::path::PathBuf, ) -> Router { build_router( AppState { service, store: Some(store), workspace_root, }, auth, ) } /// Default parent of the per-session workspace folders: `~/.strata-ctl`. fn default_workspace_root() -> std::path::PathBuf { let home = std::env::var("HOME").unwrap_or_default(); std::path::PathBuf::from(home).join(".strata-ctl") } fn build_router(state: AppState, auth: AuthConfig) -> Router { let mut r = Router::new() .route("/health", get(health)) .route("/v1/models", get(models)) .route("/v1/chat/completions", post(chat_completions)) .route("/v1/messages", post(messages)); // The session-aware API and the web GUI exist only when a store is configured. if state.store.is_some() { r = r .route( "/api/sessions", get(sessions::list_sessions).post(sessions::create_session), ) .route( "/api/sessions/{id}", get(sessions::get_session) .delete(sessions::delete_session) .patch(sessions::patch_session), ) .route("/api/sessions/{id}/messages", get(sessions::get_messages)) .route("/api/sessions/{id}/notepad", get(sessions::get_notepad)) .route("/api/sessions/{id}/chat", post(sessions::session_chat)) .route("/api/sessions/{id}/download", get(files::download)) .route( "/api/uploads", // Uploads arrive as base64 JSON: a 32 MiB decoded file becomes // ~43 MiB on the wire, well over axum's 2 MiB default body limit // (which silently 413-rejected images/PDFs/exes). Allow 64 MiB so // the handler runs and applies its own decoded-size cap. post(uploads::upload).layer(axum::extract::DefaultBodyLimit::max(64 * 1024 * 1024)), ) .route( "/api/settings/defaults", get(sessions::get_defaults).put(sessions::put_defaults), ) .route("/api/stats", get(sessions::stats)) .route("/api/mcp/connectors", get(mcp::list_connectors)) .route( "/api/mcp/connectors/{name}", axum::routing::put(mcp::upsert_connector).delete(mcp::delete_connector), ) .route("/api/mcp/connectors/{name}/tools", post(mcp::list_tools)) .route("/", get(web::index)) .route("/assets/{*path}", get(web::asset)); } r.with_state(state) .layer(axum::middleware::from_fn_with_state(auth, auth_middleware)) } /// Optional access control, read from the shared config. Default = open (no /// key, any host), matching a loopback-only deployment. #[derive(Clone, Default)] pub struct AuthConfig { /// When set, every request except `/health` must carry this key, either as /// `Authorization: Bearer ` or `x-api-key: `. pub api_key: Option, /// Host-header allowlist. Empty or `["*"]` allows any host; otherwise the /// request `Host` must match one of these (DNS-rebinding protection). pub allowed_hosts: Vec, } impl AuthConfig { fn host_allowed(&self, headers: &axum::http::HeaderMap) -> bool { if self.allowed_hosts.is_empty() || self.allowed_hosts.iter().any(|h| h == "*") { return true; } let host = headers .get(axum::http::header::HOST) .and_then(|h| h.to_str().ok()) .unwrap_or(""); // Strip the port. A bracketed IPv6 Host (`[::1]:8095` or `[::1]`) must // yield `::1`, not `[:` — rsplit_once(':') alone mangles it. let host = match host.strip_prefix('[') { Some(v6) => v6.split(']').next().unwrap_or(v6), None => host.rsplit_once(':').map(|(h, _)| h).unwrap_or(host), }; self.allowed_hosts.iter().any(|h| { let h = h .strip_prefix('[') .and_then(|s| s.strip_suffix(']')) .unwrap_or(h); h.eq_ignore_ascii_case(host) }) } fn key_ok(&self, headers: &axum::http::HeaderMap) -> bool { // An empty/whitespace key is a misconfiguration, not "accept an empty // header": treat it as no key rather than letting `Bearer ` pass. let Some(key) = self.api_key.as_deref().filter(|k| !k.trim().is_empty()) else { return true; }; if let Some(auth) = headers .get(axum::http::header::AUTHORIZATION) .and_then(|v| v.to_str().ok()) { // The auth scheme is case-insensitive (RFC 9110); the token is not. if auth .get(..7) .is_some_and(|p| p.eq_ignore_ascii_case("Bearer ")) && ct_eq(&auth.as_bytes()[7..], key.as_bytes()) { return true; } } headers .get("x-api-key") .and_then(|v| v.to_str().ok()) .is_some_and(|k| ct_eq(k.as_bytes(), key.as_bytes())) } } /// Constant-time byte equality (no timing side-channel on the API key), std-only. /// The length XOR is folded into the accumulator so unequal lengths still fail. fn ct_eq(a: &[u8], b: &[u8]) -> bool { let mut diff = a.len() ^ b.len(); for (x, y) in a.iter().zip(b.iter()) { diff |= usize::from(*x ^ *y); } diff == 0 } /// Enforces the Host allowlist and (except on `/health`) the API key before any /// handler runs. async fn auth_middleware( State(auth): State, req: axum::extract::Request, next: axum::middleware::Next, ) -> axum::response::Response { if !auth.host_allowed(req.headers()) { return Error::new( StatusCode::FORBIDDEN, ApiErrorEnvelope::new( "request Host is not in allowed_hosts", "invalid_request_error", Some("host_not_allowed".to_string()), ), ) .into_response(); } if req.uri().path() != "/health" && !auth.key_ok(req.headers()) { return Error::new( StatusCode::UNAUTHORIZED, ApiErrorEnvelope::new( "missing or invalid API key", "invalid_request_error", Some("invalid_api_key".to_string()), ), ) .into_response(); } next.run(req).await } #[derive(Clone)] pub(crate) struct AppState { pub(crate) service: ChatService, pub(crate) store: Option>, pub(crate) workspace_root: std::path::PathBuf, } /// An OpenAI error with the HTTP status the code implies. #[derive(Debug)] pub struct Error { status: StatusCode, body: ApiErrorEnvelope, } impl Error { pub(crate) fn new(status: StatusCode, body: ApiErrorEnvelope) -> Self { Self { status, body } } /// Choose a status from the error's `code`; unknown codes are client 400s. pub(crate) fn from_envelope(env: ApiErrorEnvelope) -> Self { let status = match env.error.code.as_deref() { Some("engine_unavailable") | Some("engine_startup") => StatusCode::SERVICE_UNAVAILABLE, Some("engine_silent") => StatusCode::GATEWAY_TIMEOUT, // engine_refused, and any client/parse error, is a 400 _ => StatusCode::BAD_REQUEST, }; Self::new(status, env) } pub(crate) fn bad_request(msg: impl Into) -> Self { Self::new( StatusCode::BAD_REQUEST, ApiErrorEnvelope::new(msg, "invalid_request_error", None), ) } pub(crate) fn not_found(msg: impl Into) -> Self { Self::new( StatusCode::NOT_FOUND, ApiErrorEnvelope::new(msg, "invalid_request_error", Some("not_found".to_string())), ) } pub(crate) fn internal(msg: impl Into) -> Self { Self::new( StatusCode::INTERNAL_SERVER_ERROR, ApiErrorEnvelope::new(msg, "server_error", None), ) } } impl IntoResponse for Error { fn into_response(self) -> axum::response::Response { (self.status, Json(self.body)).into_response() } } async fn health() -> &'static str { "ok" } async fn models(State(st): State) -> Json { Json(ModelList { object: "list", data: vec![ModelCard { id: st.service.model_name().to_string(), object: "model", created: super::types::now_unix(), owned_by: "strata-ctl".to_string(), }], }) } async fn chat_completions( State(st): State, raw: axum::extract::Request, ) -> axum::response::Response { // Parse manually so a malformed body yields an OpenAI-shaped 400 rather // than axum's default plain-text rejection. let req: ChatRequest = match json_body(raw).await { Ok(r) => r, Err(e) => return e.into_response(), }; if req.messages.is_empty() { return Error::bad_request("`messages` must not be empty").into_response(); } if req.stream { match st.service.stream(&req).await { Ok((stream, _prompt_len)) => { use futures::StreamExt; // Serialize each semantic chunk to an SSE event, then append the // terminal [DONE] the OpenAI wire expects. let events = stream .map(|chunk| match Event::default().json_data(&chunk) { Ok(ev) => Ok::<_, std::convert::Infallible>(ev), Err(e) => { tracing::error!(error = %e, "failed to serialize SSE chunk"); Ok(Event::default().data("{}")) } }) .chain(futures::stream::once(async { Ok::<_, std::convert::Infallible>(Event::default().data("[DONE]")) })); Sse::new(events) .keep_alive( axum::response::sse::KeepAlive::new() .interval(std::time::Duration::from_secs(10)) .text("ping"), ) .into_response() } Err(env) => Error::from_envelope(env).into_response(), } } else { match st.service.complete(&req).await { Ok(resp) => Json(resp).into_response(), Err(env) => Error::from_envelope(env).into_response(), } } } /// `POST /v1/messages` — the Anthropic Messages surface, translated onto the /// same service. Non-streaming returns one message; streaming emits the /// Anthropic event sequence. async fn messages( State(st): State, raw: axum::extract::Request, ) -> axum::response::Response { let areq: AnthropicRequest = match json_body(raw).await { Ok(r) => r, Err(e) => return e.into_response(), }; let req = match areq.to_chat_request() { Ok(r) => r, Err(env) => return Error::from_envelope(env).into_response(), }; if req.messages.is_empty() { return Error::bad_request("`messages` must not be empty").into_response(); } if req.stream { match st.service.stream(&req).await { Ok((stream, prompt_len)) => { use futures::StreamExt; let mut tr = AnthropicStream::new(req.model.clone(), prompt_len); let start = tr.start(); let events = futures::stream::once(async move { Ok::<_, std::convert::Infallible>(start) }) .chain(stream.flat_map(move |chunk| { let evs = tr.on_chunk(&chunk); futures::stream::iter( evs.into_iter().map(Ok::<_, std::convert::Infallible>), ) })); Sse::new(events) .keep_alive( axum::response::sse::KeepAlive::new() .interval(std::time::Duration::from_secs(10)) .text("ping"), ) .into_response() } Err(env) => Error::from_envelope(env).into_response(), } } else { match st.service.complete(&req).await { Ok(resp) => Json(anthropic::from_chat_response(&resp)).into_response(), Err(env) => Error::from_envelope(env).into_response(), } } } /// Read and deserialize a JSON body, mapping any failure to our error type. async fn json_body(req: axum::extract::Request) -> Result { let bytes = axum::body::to_bytes(req.into_body(), 32 * 1024 * 1024) .await .map_err(|e| Error::bad_request(format!("failed to read body: {e}")))?; serde_json::from_slice::(&bytes) .map_err(|e| Error::bad_request(format!("invalid JSON body: {e}"))) } #[cfg(test)] mod tests { use super::*; use axum::http::{HeaderMap, HeaderName}; fn host_header(value: &str) -> HeaderMap { let mut h = HeaderMap::new(); h.insert(axum::http::header::HOST, value.parse().unwrap()); h } #[test] fn host_allowlist_parses_ipv6_and_ports() { let auth = AuthConfig { api_key: None, allowed_hosts: vec!["localhost".into(), "127.0.0.1".into(), "::1".into()], }; assert!(auth.host_allowed(&host_header("localhost:8095"))); assert!(auth.host_allowed(&host_header("127.0.0.1:8095"))); assert!(auth.host_allowed(&host_header("[::1]:8095"))); assert!(auth.host_allowed(&host_header("[::1]"))); assert!(!auth.host_allowed(&host_header("evil.com:8095"))); let open = AuthConfig { api_key: None, allowed_hosts: vec!["*".into()], }; assert!(open.host_allowed(&host_header("anything.example"))); } #[test] fn key_check_bearer_case_and_empty_key() { let auth = AuthConfig { api_key: Some("secret".into()), allowed_hosts: vec![], }; let bearer = |v: &str| { let mut h = HeaderMap::new(); h.insert(axum::http::header::AUTHORIZATION, v.parse().unwrap()); h }; assert!(auth.key_ok(&bearer("Bearer secret"))); // RFC 9110: the auth scheme is case-insensitive. assert!(auth.key_ok(&bearer("bearer secret"))); assert!(auth.key_ok(&bearer("BEARER secret"))); assert!(!auth.key_ok(&bearer("Bearer nope"))); let mut x = HeaderMap::new(); x.insert( HeaderName::from_static("x-api-key"), "secret".parse().unwrap(), ); assert!(auth.key_ok(&x)); // An empty configured key is a misconfiguration -> treated as no auth, // never "accept an empty Bearer/x-api-key header". let empty = AuthConfig { api_key: Some("".into()), allowed_hosts: vec![], }; assert!(empty.key_ok(&HeaderMap::new())); assert!(empty.key_ok(&bearer("Bearer "))); } #[test] fn ct_eq_compares_bytes_without_early_exit() { assert!(ct_eq(b"secret", b"secret")); assert!(ct_eq(b"", b"")); assert!(!ct_eq(b"secret", b"secreu")); assert!(!ct_eq(b"secret", b"secret2")); assert!(!ct_eq(b"", b"x")); } }