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 <key> 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.
This commit is contained in:
adm committed 2026-11-24 18:48:05 +01:00
1 parent 5bafd000c8
commit b6619d30de
6 files changed
+227 -20

No files matched your search

+93
View File
@@ -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);
}