80 lines
2.6 KiB
Rust
80 lines
2.6 KiB
Rust
//! 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::access::AccessSlot;
|
|
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(|| {
|
|
tracing::warn!("Anfrage ohne API-Key");
|
|
ApiError::invalid_key()
|
|
})?;
|
|
match state.store().find_api_key(token) {
|
|
Ok(Some(key)) => {
|
|
if let Some(slot) = parts.extensions.get::<AccessSlot>() {
|
|
let mut info = slot.lock().unwrap_or_else(|e| e.into_inner());
|
|
info.key_id = Some(key.id);
|
|
info.key_name = Some(key.name.clone());
|
|
}
|
|
Ok(Authed(key))
|
|
}
|
|
Ok(None) => {
|
|
tracing::warn!("Ungültiger oder gesperrter API-Key");
|
|
Err(ApiError::invalid_key())
|
|
}
|
|
Err(e) => {
|
|
tracing::error!(fehler = %e, "Key-Prüfung fehlgeschlagen");
|
|
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)
|
|
}
|