Files
leleka/control-plane/src/auth.rs
T
Pavlo RatushnyiandClaude Sonnet 5.5 392037d83e feat(serving): port the operational HTTP surface of the Python server
control-plane serves /props, /slots, /v1/status, /api/health, /settings, /load, /unload,
/v1/load, /v1/unload, model aliases, CORS with the preflight ahead of authentication and the
own-page guard; replayed scenario by scenario against the real Python handlers. The worker
supervisor gains load/unload, lazy start, idle unload, reload gates (before_load, min free VRAM),
an outside stall watchdog and the reasoning-budget wrap-up (budget tracker golden-tested against
the Python Detokenizer/OutputParser loop). leleka-serving-policy adds CORS, idle, stall watchdog,
logits stride (golden vs the C++ header), request timings and alias rules.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-14 15:35:08 +02:00

239 lines
7.8 KiB
Rust

//! Optional single-operator bearer authentication. Never format the credential.
use std::{fs::OpenOptions, io::Read, path::Path, sync::Arc};
use axum::{
Json,
extract::{Request, State},
http::{HeaderMap, StatusCode, header},
middleware::Next,
response::{IntoResponse, Response},
};
use serde_json::json;
use sha2::{Digest, Sha256};
use subtle::ConstantTimeEq;
pub struct ApiKey([u8; 32]);
impl ApiKey {
pub fn from_file(path: &Path) -> Result<Self, Box<dyn std::error::Error>> {
Self::from_token(&read_token(path)?).map_err(Into::into)
}
fn from_token(value: &str) -> Result<Self, &'static str> {
if !(32..=512).contains(&value.len()) || !value.bytes().all(|b| b.is_ascii_graphic()) {
return Err("API key requires 32..512 printable ASCII bytes without whitespace");
}
Ok(Self(Sha256::digest(value.as_bytes()).into()))
}
fn accepts_messages(&self, headers: &HeaderMap) -> bool {
let mut values = headers.get_all("x-api-key").iter();
let Some(value) = values.next() else {
return self.accepts(headers);
};
if values.next().is_some() || headers.contains_key(header::AUTHORIZATION) {
return false;
}
let Ok(value) = value.to_str() else {
return false;
};
let Ok(candidate) = Self::from_token(value) else {
return false;
};
bool::from(self.0.ct_eq(&candidate.0))
}
fn accepts(&self, headers: &HeaderMap) -> bool {
let mut values = headers.get_all(header::AUTHORIZATION).iter();
let Some(value) = values.next() else {
return false;
};
if values.next().is_some() {
return false;
}
let Ok(value) = value.to_str() else {
return false;
};
let Some((scheme, token)) = value.split_once(' ') else {
return false;
};
if !scheme.eq_ignore_ascii_case("Bearer") {
return false;
}
let Ok(candidate) = Self::from_token(token) else {
return false;
};
bool::from(self.0.ct_eq(&candidate.0))
}
}
// Client code needs the original token; keep file and syntax policy identical to serving.
pub(crate) fn read_token(path: &Path) -> Result<String, Box<dyn std::error::Error>> {
let mut options = OpenOptions::new();
options.read(true);
#[cfg(unix)]
{
use std::os::unix::fs::OpenOptionsExt;
options.custom_flags(libc::O_NONBLOCK);
}
let file = options.open(path)?;
let metadata = file.metadata()?;
if !metadata.is_file() {
return Err("API key source must be a regular file".into());
}
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
if metadata.permissions().mode() & 0o077 != 0 {
return Err(
"API key file must not grant group/other permissions (use chmod 600)".into(),
);
}
}
let mut bytes = Vec::new();
file.take(515).read_to_end(&mut bytes)?;
parse_token(&bytes)
}
pub(crate) fn parse_token(bytes: &[u8]) -> Result<String, Box<dyn std::error::Error>> {
if bytes.len() > 514 {
return Err("API key file exceeds 514 bytes".into());
}
let value = std::str::from_utf8(bytes)
.map_err(|_| "API key must contain printable ASCII")?
.trim_end_matches(['\r', '\n']);
ApiKey::from_token(value)?;
Ok(value.to_owned())
}
pub async fn authorize(
State(key): State<Option<Arc<ApiKey>>>,
request: Request,
next: Next,
) -> Response {
let messages = matches!(
request.uri().path(),
"/v1/messages" | "/v1/messages/count_tokens"
);
if !matches!(request.uri().path(), "/health" | "/api/health")
&& key.as_ref().is_some_and(|key| {
if messages {
!key.accepts_messages(request.headers())
} else {
!key.accepts(request.headers())
}
})
{
return (
StatusCode::UNAUTHORIZED,
[(header::WWW_AUTHENTICATE, "Bearer")],
Json(if messages { crate::messages::error_value(StatusCode::UNAUTHORIZED, "Invalid API key") } else { json!({"error":{"message":"Invalid API key","type":"authentication_error","code":"invalid_api_key"}}) }),
).into_response();
}
next.run(request).await
}
#[cfg(test)]
mod tests {
use super::*;
const KEY: &str = "fixture-only-not-a-real-secret-0001";
#[test]
fn header_contract_rejects_ambiguous_or_invalid_credentials() {
let key = ApiKey::from_token(KEY).unwrap();
let mut headers = HeaderMap::new();
for value in [format!("Bearer {KEY}"), format!("bearer {KEY}")] {
headers.insert(header::AUTHORIZATION, value.parse().unwrap());
assert!(key.accepts(&headers));
}
for value in [
format!("Basic {KEY}"),
format!("Bearer {KEY} "),
format!("Bearer {KEY}"),
"Bearer wrong".into(),
"Bearer fixture-only-not-a-real-secret-0002".into(),
] {
headers.insert(header::AUTHORIZATION, value.parse().unwrap());
assert!(!key.accepts(&headers));
}
headers.insert(
header::AUTHORIZATION,
format!("Bearer {KEY}").parse().unwrap(),
);
headers.append(
header::AUTHORIZATION,
format!("Bearer {KEY}").parse().unwrap(),
);
assert!(!key.accepts(&headers));
}
#[tokio::test]
async fn protected_routes_fail_before_body_parsing_and_health_stays_public() {
let state = crate::app::AppState {
api_key: Some(Arc::new(ApiKey::from_token(KEY).unwrap())),
..Default::default()
};
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let url = format!("http://{}", listener.local_addr().unwrap());
let server =
tokio::spawn(async move { axum::serve(listener, crate::app::router(state)).await });
let client = reqwest::Client::new();
for path in [
"/status",
"/metrics",
"/ready",
"/v1/responses",
"/admin/drain",
"/admin/resume",
"/admin/lifecycle",
"/unknown",
] {
let response = client
.post(format!("{url}{path}"))
.body("not json")
.send()
.await
.unwrap();
assert_eq!(response.status(), StatusCode::UNAUTHORIZED);
assert_eq!(response.headers()[header::WWW_AUTHENTICATE], "Bearer");
assert!(!response.text().await.unwrap().contains(KEY));
}
assert_eq!(
client
.get(format!("{url}/health"))
.send()
.await
.unwrap()
.status(),
StatusCode::OK
);
let response = client
.get(format!("{url}/status"))
.bearer_auth(KEY)
.send()
.await
.unwrap();
assert_eq!(response.status(), StatusCode::OK);
assert!(!response.text().await.unwrap().contains(KEY));
let response = client
.post(format!("{url}/v1/responses"))
.bearer_auth(KEY)
.header(header::CONTENT_TYPE, "application/json")
.body("not json")
.send()
.await
.unwrap();
assert_eq!(response.status(), StatusCode::BAD_REQUEST);
server.abort();
}
#[test]
fn malformed_token_is_rejected_without_echoing_it() {
for token in ["short".to_owned(), "X".repeat(513), "X".repeat(32) + "\nY"] {
let error = ApiKey::from_token(&token).err().unwrap();
assert!(!error.contains(&token));
}
}
}