From b6619d30defc91d8d0c58988bc285c7005e15e05 Mon Sep 17 00:00:00 2001 From: iz0eyj Date: Tue, 24 Nov 2026 18:48:05 +0100 Subject: [PATCH] Add optional API key auth and allowed_hosts enforcement - AuthConfig (api_key, allowed_hosts) read from the shared config; router_with_auth applies an axum middleware before any handler. - Host not in allowlist -> 403 host_not_allowed; missing/wrong key -> 401 invalid_api_key (accepts Authorization: Bearer or x-api-key); /health open. - router() stays the open default: backward compatible (no key, wildcard hosts). - The non-loopback bind warning now fires only when no api_key is configured. - README updated (auth is a feature, no longer a gap). 4 new tests; 80 green + 2 real-file ignored; clippy clean; cargo fmt applied. --- README.md | 16 ++++---- src/api/mod.rs | 2 +- src/api/routes.rs | 84 ++++++++++++++++++++++++++++++++++++++++ src/config.rs | 38 ++++++++++++++---- src/main.rs | 14 ++++--- tests/api_openai.rs | 93 +++++++++++++++++++++++++++++++++++++++++++++ 6 files changed, 227 insertions(+), 20 deletions(-) diff --git a/README.md b/README.md index 99e1264..78bbeb4 100644 --- a/README.md +++ b/README.md @@ -70,7 +70,9 @@ Operational hardening: - Graceful shutdown on **SIGINT and SIGTERM**; the engine is signalled without blocking on an in-flight request. - Configurable startup and silence-watchdog timeouts. -- A warning when binding a non-loopback address (the API has no authentication). +- Optional **API key** auth (`Authorization: Bearer ` or `x-api-key`) and a + **Host allowlist** (`allowed_hosts`, DNS-rebinding protection); `/health` stays + open. A warning is logged when binding a non-loopback address with no key set. - Blocking image I/O runs off the async event loop; temp files are cleaned on every exit path; image fetches have a timeout, a size cap and a basic SSRF guard. @@ -113,20 +115,20 @@ uses `tracing`; set `RUST_LOG` to control verbosity (default `info`). The config is the same JSON the other Strata tools use. Keys acted on here include `exe`, `args`, `cwd`, `tokenizer`, `model_name`, `host`, `port`, `reasoning_effort`, -`sampling`, and the optional `startup_timeout_secs` / `silence_timeout_secs`. -Everything else (`arch`, `mcp_servers`, `cors_origins`, `allowed_hosts`, …) is -preserved untouched and reported as ignored — unknown keys never break startup. +`sampling`, `api_key`, `allowed_hosts`, and the optional `startup_timeout_secs` / +`silence_timeout_secs`. Everything else (`arch`, `mcp_servers`, `cors_origins`, …) +is preserved untouched and reported as ignored — unknown keys never break startup. ## Status -Working and tested (76 tests, plus 2 real-file tests run on demand). Text, images +Working and tested (80 tests, plus 2 real-file tests run on demand). Text, images and the full client-side tool loop have been validated live against the real Inkling engine. Not yet implemented (honest gaps): forced `tool_choice` (`required` / named function returns a clear 400), multi-slot batching, logprobs / structured output, automatic -engine restart after a crash, an API key / `allowed_hosts` enforcement, a full -SSRF guard against DNS rebinding, and the Anthropic / Responses native endpoints. +engine restart after a crash, a full SSRF guard against DNS rebinding, and the +Anthropic / Responses native endpoints. ## License and credits diff --git a/src/api/mod.rs b/src/api/mod.rs index c38790e..e268695 100644 --- a/src/api/mod.rs +++ b/src/api/mod.rs @@ -11,6 +11,6 @@ pub mod stop; pub mod types; pub use formatter::{Decoder, Formatter, Piece, Prompt}; -pub use routes::router; +pub use routes::{router, router_with_auth, AuthConfig}; pub use service::ChatService; pub use types::{ChatMessage, ChatRequest, ChatResponse, ModelList, Role}; diff --git a/src/api/routes.rs b/src/api/routes.rs index 55a3780..4b0cf57 100644 --- a/src/api/routes.rs +++ b/src/api/routes.rs @@ -16,11 +16,95 @@ use super::types::{ApiErrorEnvelope, ChatRequest, ModelCard, ModelList}; /// 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. +pub fn router_with_auth(service: ChatService, auth: AuthConfig) -> Router { Router::new() .route("/health", get(health)) .route("/v1/models", get(models)) .route("/v1/chat/completions", post(chat_completions)) .with_state(AppState { service }) + .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(""); + let host = host.rsplit_once(':').map(|(h, _)| h).unwrap_or(host); + self.allowed_hosts + .iter() + .any(|h| h.eq_ignore_ascii_case(host)) + } + + fn key_ok(&self, headers: &axum::http::HeaderMap) -> bool { + let Some(key) = self.api_key.as_deref() else { + return true; + }; + if let Some(auth) = headers + .get(axum::http::header::AUTHORIZATION) + .and_then(|v| v.to_str().ok()) + { + if auth.strip_prefix("Bearer ").is_some_and(|t| t == key) { + return true; + } + } + headers + .get("x-api-key") + .and_then(|v| v.to_str().ok()) + .is_some_and(|k| k == key) + } +} + +/// 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)] diff --git a/src/config.rs b/src/config.rs index fe31629..626aaef 100644 --- a/src/config.rs +++ b/src/config.rs @@ -87,6 +87,15 @@ pub struct Config { #[serde(default)] pub silence_timeout_secs: Option, + /// Optional bearer API key. When set, every request except `/health` must + /// carry it (`Authorization: Bearer ...` or `x-api-key`). + #[serde(default)] + pub api_key: Option, + /// Host-header allowlist. Absent/empty or `["*"]` allows any host; otherwise + /// the request `Host` must match one of these (DNS-rebinding protection). + #[serde(default)] + pub allowed_hosts: Option>, + /// Keys we understand but don't act on yet are NOT listed above, so they /// arrive here untouched — the "ignore what isn't ours" guarantee. #[serde(flatten)] @@ -247,17 +256,32 @@ mod tests { fn known_but_unused_fields_report_as_ignored() { let cfg = Config::parse(REAL, "test").unwrap(); // we don't act on these yet, so they must not be lost or cause errors - for k in [ - "arch", - "cors_origins", - "allowed_hosts", - "drafting", - "mcp_servers", - ] { + for k in ["arch", "cors_origins", "drafting", "mcp_servers"] { assert!(cfg.extra.contains_key(k), "{k} should be in ignored extras"); } } + #[test] + fn auth_fields_are_read() { + let cfg = Config::parse( + r#"{"exe":"/x/e","api_key":"secret","allowed_hosts":["a.com","b.com"]}"#, + "test", + ) + .unwrap(); + assert_eq!(cfg.api_key.as_deref(), Some("secret")); + assert_eq!( + cfg.allowed_hosts.as_deref(), + Some(["a.com".to_string(), "b.com".to_string()].as_slice()) + ); + // the real config: no key, wildcard hosts (open) + let real = Config::parse(REAL, "test").unwrap(); + assert!(real.api_key.is_none()); + assert_eq!( + real.allowed_hosts.as_deref(), + Some(["*".to_string()].as_slice()) + ); + } + #[test] fn engine_argv_adds_serve_once() { // REAL args already contain --serve -> no duplicate diff --git a/src/main.rs b/src/main.rs index 57fb100..0bdb582 100644 --- a/src/main.rs +++ b/src/main.rs @@ -8,7 +8,7 @@ use std::path::Path; use std::process::ExitCode; use std::sync::Arc; -use strata_ctl::api::{router, ChatService}; +use strata_ctl::api::{router_with_auth, AuthConfig, ChatService}; use strata_ctl::config::{Config, ConfigError}; use strata_ctl::engine::Engine; use strata_ctl::inkling::{ChatTemplate, InklingFormatter, InklingTokenizer}; @@ -171,14 +171,18 @@ async fn serve(cfg: &Config, cli_host: Option<&str>, cli_port: Option) -> E ); let svc = ChatService::new(engine.clone(), fmt); - let app = router(svc); + let auth = AuthConfig { + api_key: cfg.api_key.clone(), + allowed_hosts: cfg.allowed_hosts.clone().unwrap_or_default(), + }; + let app = router_with_auth(svc, auth); let host = cfg.bind_host(cli_host); let port = cfg.bind_port(cli_port); - if !is_loopback_host(&host) { + if !is_loopback_host(&host) && cfg.api_key.is_none() { tracing::warn!( host = %host, - "binding a non-loopback address: the API has NO authentication and \ - `allowed_hosts` is not enforced — anyone on the network can use it" + "binding a non-loopback address with NO API key: anyone on the network \ + can use the API (set `api_key` in the config to require authentication)" ); } let addr = format!("{host}:{port}"); diff --git a/tests/api_openai.rs b/tests/api_openai.rs index 4aeeaac..887d378 100644 --- a/tests/api_openai.rs +++ b/tests/api_openai.rs @@ -338,3 +338,96 @@ async fn stop_sequence_truncates_stream() { assert_eq!(content, "ef"); assert_eq!(finish.as_deref(), Some("stop")); } + +async fn build_app_auth(auth: strata_ctl::api::AuthConfig) -> axum::Router { + let engine = Arc::new( + Engine::start( + "python3", + &[MOCK.to_string()], + None, + Duration::from_secs(10), + ) + .await + .expect("mock engine starts"), + ); + let svc = ChatService::new(engine, Arc::new(ByteFormatter)); + strata_ctl::api::router_with_auth(svc, auth) +} + +/// POST a completion with extra headers; returns (status, body). +async fn post_with_headers(app: &axum::Router, headers: &[(&str, &str)]) -> (StatusCode, String) { + let mut builder = Request::builder() + .method(Method::POST) + .uri("/v1/chat/completions") + .header(CONTENT_TYPE, "application/json"); + for (k, v) in headers { + builder = builder.header(*k, *v); + } + let req = builder + .body(Body::from( + serde_json::json!({"model":"test-model","messages":[{"role":"user","content":"hi"}]}) + .to_string(), + )) + .unwrap(); + let resp = app.clone().oneshot(req).await.unwrap(); + let status = resp.status(); + let bytes = axum::body::to_bytes(resp.into_body(), usize::MAX) + .await + .unwrap(); + (status, String::from_utf8_lossy(&bytes).into_owned()) +} + +#[tokio::test] +async fn api_key_is_enforced_when_configured() { + let auth = strata_ctl::api::AuthConfig { + api_key: Some("secret".into()), + allowed_hosts: vec![], + }; + let app = build_app_auth(auth).await; + // no key -> 401 + let (status, _) = post_with_headers(&app, &[]).await; + assert_eq!(status, StatusCode::UNAUTHORIZED); + // wrong key -> 401 + let (status, _) = post_with_headers(&app, &[("authorization", "Bearer wrong")]).await; + assert_eq!(status, StatusCode::UNAUTHORIZED); + // correct bearer -> 200 + let (status, text) = post_with_headers(&app, &[("authorization", "Bearer secret")]).await; + assert_eq!(status, StatusCode::OK, "body: {text}"); + // x-api-key (Anthropic style) also accepted + let (status, _) = post_with_headers(&app, &[("x-api-key", "secret")]).await; + assert_eq!(status, StatusCode::OK); +} + +#[tokio::test] +async fn health_is_open_even_with_api_key() { + let auth = strata_ctl::api::AuthConfig { + api_key: Some("secret".into()), + allowed_hosts: vec![], + }; + let app = build_app_auth(auth).await; + let resp = app + .oneshot( + Request::builder() + .uri("/health") + .body(Body::empty()) + .unwrap(), + ) + .await + .unwrap(); + assert_eq!(resp.status(), StatusCode::OK); +} + +#[tokio::test] +async fn allowed_hosts_is_enforced() { + let auth = strata_ctl::api::AuthConfig { + api_key: None, + allowed_hosts: vec!["good.example".into()], + }; + let app = build_app_auth(auth).await; + // matching Host (port stripped) -> 200 + let (status, text) = post_with_headers(&app, &[("host", "good.example:8095")]).await; + assert_eq!(status, StatusCode::OK, "body: {text}"); + // wrong Host -> 403 + let (status, _) = post_with_headers(&app, &[("host", "evil.example")]).await; + assert_eq!(status, StatusCode::FORBIDDEN); +}