feat: JSON-Logging mit Correlation-ID, Anfrage-Log und Audit (M2.4)
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
162
crates/nexus-api/src/access.rs
Normal file
162
crates/nexus-api/src/access.rs
Normal file
@ -0,0 +1,162 @@
|
||||
//! Zustand und Protokollierung je Anfrage: Correlation-ID, Zugriffsprotokoll
|
||||
//! und Anfrage-Log.
|
||||
//!
|
||||
//! Protokolliert werden nur Metadaten (Methode, Pfad ohne Query, Status,
|
||||
//! Zeiten, Name des Keys, Modellname). **Nie** protokolliert werden Header,
|
||||
//! Bodys (Prompts, Antworten, Bilder), Keys und Fehlertexte der Engine.
|
||||
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::time::Instant;
|
||||
|
||||
use axum::extract::{Request, State};
|
||||
use axum::http::HeaderValue;
|
||||
use axum::middleware::Next;
|
||||
use axum::response::Response;
|
||||
use nexus_store::RequestLogEntry;
|
||||
use tracing::Instrument;
|
||||
|
||||
use crate::state::AppState;
|
||||
|
||||
/// Correlation-ID der Anfrage (`x-request-id`).
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct RequestId(pub String);
|
||||
|
||||
/// Was die Handler über eine Anfrage herausfinden; die Middleware schreibt
|
||||
/// es nach der Antwort ins Log.
|
||||
#[derive(Debug, Default, Clone)]
|
||||
pub struct AccessInfo {
|
||||
pub key_id: Option<i64>,
|
||||
pub key_name: Option<String>,
|
||||
pub model: Option<String>,
|
||||
pub wait_ms: Option<u64>,
|
||||
}
|
||||
|
||||
pub type AccessSlot = Arc<Mutex<AccessInfo>>;
|
||||
|
||||
/// Längste Zeichenzahl eines Modellnamens im Log.
|
||||
const MAX_LOGGED_MODEL_CHARS: usize = 100;
|
||||
|
||||
/// Kürzt Texte, die vom Client stammen, bevor sie ins Log gehen.
|
||||
pub fn clip(text: &str) -> String {
|
||||
text.chars().take(MAX_LOGGED_MODEL_CHARS).collect()
|
||||
}
|
||||
|
||||
/// Übernimmt eine vom Client mitgeschickte ID nur, wenn sie harmlos aussieht
|
||||
/// (Buchstaben, Ziffern, `-`, `_`, `.`; höchstens 64 Zeichen).
|
||||
fn accept_incoming(value: &str) -> bool {
|
||||
!value.is_empty()
|
||||
&& value.len() <= 64
|
||||
&& value
|
||||
.chars()
|
||||
.all(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '_' | '.'))
|
||||
}
|
||||
|
||||
fn new_id() -> String {
|
||||
nexus_core::random_hex(8)
|
||||
.map(|h| format!("req_{h}"))
|
||||
.unwrap_or_else(|_| "req_unbekannt".to_string())
|
||||
}
|
||||
|
||||
pub async fn observe(
|
||||
State(state): State<Arc<AppState>>,
|
||||
mut request: Request,
|
||||
next: Next,
|
||||
) -> Response {
|
||||
let started = Instant::now();
|
||||
let correlation = request
|
||||
.headers()
|
||||
.get("x-request-id")
|
||||
.and_then(|v| v.to_str().ok())
|
||||
.filter(|v| accept_incoming(v))
|
||||
.map(str::to_string)
|
||||
.unwrap_or_else(new_id);
|
||||
let method = request.method().to_string();
|
||||
let path = request.uri().path().to_string();
|
||||
let slot = AccessSlot::default();
|
||||
request
|
||||
.extensions_mut()
|
||||
.insert(RequestId(correlation.clone()));
|
||||
request.extensions_mut().insert(slot.clone());
|
||||
|
||||
let span = tracing::info_span!("request", korrelation = %correlation);
|
||||
let mut response = next.run(request).instrument(span.clone()).await;
|
||||
let latency_ms = started.elapsed().as_millis() as u64;
|
||||
let status = response.status().as_u16();
|
||||
if let Ok(value) = HeaderValue::from_str(&correlation) {
|
||||
response.headers_mut().insert("x-request-id", value);
|
||||
}
|
||||
|
||||
let info = slot.lock().unwrap_or_else(|e| e.into_inner()).clone();
|
||||
span.in_scope(|| {
|
||||
let key = info.key_name.as_deref();
|
||||
let model = info.model.as_deref();
|
||||
if status >= 500 {
|
||||
tracing::error!(
|
||||
method,
|
||||
path,
|
||||
status,
|
||||
latency_ms,
|
||||
key,
|
||||
model,
|
||||
wait_ms = info.wait_ms,
|
||||
"Anfrage beantwortet"
|
||||
);
|
||||
} else if status >= 400 {
|
||||
tracing::warn!(
|
||||
method,
|
||||
path,
|
||||
status,
|
||||
latency_ms,
|
||||
key,
|
||||
model,
|
||||
wait_ms = info.wait_ms,
|
||||
"Anfrage beantwortet"
|
||||
);
|
||||
} else {
|
||||
tracing::info!(
|
||||
method,
|
||||
path,
|
||||
status,
|
||||
latency_ms,
|
||||
key,
|
||||
model,
|
||||
wait_ms = info.wait_ms,
|
||||
"Anfrage beantwortet"
|
||||
);
|
||||
}
|
||||
if info.key_id.is_some() {
|
||||
let entry = RequestLogEntry {
|
||||
correlation: correlation.clone(),
|
||||
api_key_id: info.key_id,
|
||||
model: info.model.clone(),
|
||||
status,
|
||||
wait_ms: info.wait_ms,
|
||||
latency_ms: Some(latency_ms),
|
||||
};
|
||||
if let Err(e) = state.store().log_request(&entry) {
|
||||
tracing::error!(fehler = %e, "Anfrage-Log konnte nicht geschrieben werden");
|
||||
}
|
||||
}
|
||||
});
|
||||
response
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn nur_harmlose_ids_werden_uebernommen() {
|
||||
assert!(accept_incoming("abc-123_x.y"));
|
||||
assert!(!accept_incoming(""));
|
||||
assert!(!accept_incoming("mit leerzeichen"));
|
||||
assert!(!accept_incoming("zeile\nzwei"));
|
||||
assert!(!accept_incoming(&"a".repeat(65)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn clip_kuerzt_lange_namen() {
|
||||
assert_eq!(clip(&"x".repeat(500)).chars().count(), 100);
|
||||
assert_eq!(clip("kurz"), "kurz");
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user