feat: OpenAI-kompatible API mit Keys, Registry und serve-Befehl (M2.3)
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
65
crates/nexus-api/src/auth.rs
Normal file
65
crates/nexus-api/src/auth.rs
Normal file
@ -0,0 +1,65 @@
|
||||
//! API-Key-Prüfung über den Header `Authorization: Bearer <key>`.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use axum::extract::FromRequestParts;
|
||||
use axum::http::header::AUTHORIZATION;
|
||||
use axum::http::request::Parts;
|
||||
use nexus_core::Priority;
|
||||
use nexus_store::ApiKeyRecord;
|
||||
|
||||
use crate::error::ApiError;
|
||||
use crate::state::AppState;
|
||||
|
||||
/// Ein erfolgreich geprüfter Key.
|
||||
pub struct Authed(pub ApiKeyRecord);
|
||||
|
||||
impl FromRequestParts<Arc<AppState>> for Authed {
|
||||
type Rejection = ApiError;
|
||||
|
||||
async fn from_request_parts(
|
||||
parts: &mut Parts,
|
||||
state: &Arc<AppState>,
|
||||
) -> Result<Self, Self::Rejection> {
|
||||
let token = parts
|
||||
.headers
|
||||
.get(AUTHORIZATION)
|
||||
.and_then(|v| v.to_str().ok())
|
||||
.and_then(|v| v.strip_prefix("Bearer "))
|
||||
.map(str::trim)
|
||||
.filter(|t| !t.is_empty())
|
||||
.ok_or_else(ApiError::invalid_key)?;
|
||||
match state.store().find_api_key(token) {
|
||||
Ok(Some(key)) => Ok(Authed(key)),
|
||||
Ok(None) => Err(ApiError::invalid_key()),
|
||||
Err(e) => {
|
||||
eprintln!("FEHLER Key-Prüfung: {e}");
|
||||
Err(ApiError::internal())
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Liest den optionalen Header `X-Gateway-Priority` und prüft ihn gegen die
|
||||
/// Höchstpriorität des Keys. Ohne Header gilt die Standardpriorität.
|
||||
pub fn requested_priority(
|
||||
headers: &axum::http::HeaderMap,
|
||||
key: &ApiKeyRecord,
|
||||
) -> Result<Priority, ApiError> {
|
||||
let Some(raw) = headers.get("x-gateway-priority") else {
|
||||
return Ok(key.default_priority);
|
||||
};
|
||||
let text = raw
|
||||
.to_str()
|
||||
.map_err(|_| ApiError::bad_request("X-Gateway-Priority ist kein Text."))?;
|
||||
let priority = Priority::parse(text).ok_or_else(|| {
|
||||
ApiError::bad_request("X-Gateway-Priority muss \"low\", \"normal\" oder \"high\" sein.")
|
||||
})?;
|
||||
if priority > key.max_priority {
|
||||
return Err(ApiError::priority_not_permitted(
|
||||
priority.as_str(),
|
||||
key.max_priority.as_str(),
|
||||
));
|
||||
}
|
||||
Ok(priority)
|
||||
}
|
||||
Reference in New Issue
Block a user