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

+84
View File
@@ -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 <key>` or `x-api-key: <key>`.
pub api_key: Option<String>,
/// Host-header allowlist. Empty or `["*"]` allows any host; otherwise the
/// request `Host` must match one of these (DNS-rebinding protection).
pub allowed_hosts: Vec<String>,
}
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<AuthConfig>,
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)]