Files
leleka/control-plane/src/auth.rs
T
Pavlo Ratushnyi 3530208024 STRA-338 S7: AppState in four groups, app/ routes split by role, main.rs becomes a dispatcher plus the composition root
AppState (app/state.rs) is now lifecycle + EngineLink (client port, control channel, worker status, pool,
queue timeout) + HttpPolicy (api key, CORS, trusted origins) + ModelView (name, aliases, tokenizer, template,
vision port, prefix-cache and memory views) + Services (response store, monitor, MCP port, settings, clock,
started_at). Field uses were rewritten mechanically (state.worker -> state.engine.worker, ...); no handler logic
changed. The old impl_default_for_appstate.rs, which held the route table and the admin handlers, is app/routes.rs,
app/admin_routes.rs and app/readiness.rs.

main.rs (1156 lines: an 840-line argument match, the serve function, two helpers) is now 8 lines. The argument match
is split into command groups under src/cli/ (operations, model_fetch, model_inspect, model_ensure, model_prepare,
kar_inspect, kar_verify, kar_overlay, model_text; each owns its arms in their old order and answers Ok(false) for a
line it does not own), serve() and shutdown_signal() are src/serve.rs (the composition root), the usage text is
cli/usage.rs. The binary name and every command line are unchanged.

Architecture gate: control-plane/src/main.rs leaves the oversize list (1156 -> 8). --allow-increase was used because
the type change forces the AppState struct literals in seven already-oversize test/example files to nest by group:
cp_replay.rs +7, responses/tests.rs +11, backend_worker_http.rs +14, mcp_hub.rs +3, memory_gate_http.rs +7,
vision_http.rs +6, desktop-core api_over_runtime.rs +6 (55 lines in all, against 1148 lines removed from main.rs).
Test outcomes are unchanged (597 ok / 2 ignored before and after, 14 new tests from S16).
2026-11-05 20:22:10 +01:00

245 lines
8.1 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");
}
// Only a digest is kept for comparison; the log layer is told the value so that no line can ever carry it.
leleka_obs::register_secret(value);
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 {
http: crate::app::HttpPolicy {
api_key: Some(Arc::new(ApiKey::from_token(KEY).unwrap())),
..Default::default()
},
..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",
"/api/requests",
"/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));
}
}
}