diff --git a/Cargo.lock b/Cargo.lock index 7e11024..1e1d890 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -636,6 +636,7 @@ dependencies = [ "nexus-core", "nexus-store", "reqwest", + "serde", "serde_json", "thiserror", "tokio", diff --git a/crates/nexus-api/Cargo.toml b/crates/nexus-api/Cargo.toml index 93a7a45..a861922 100644 --- a/crates/nexus-api/Cargo.toml +++ b/crates/nexus-api/Cargo.toml @@ -12,6 +12,7 @@ nexus-adapter.workspace = true nexus-core.workspace = true nexus-store.workspace = true reqwest.workspace = true +serde.workspace = true serde_json.workspace = true thiserror.workspace = true tokio.workspace = true diff --git a/crates/nexus-api/src/lib.rs b/crates/nexus-api/src/lib.rs index c76fc32..b094787 100644 --- a/crates/nexus-api/src/lib.rs +++ b/crates/nexus-api/src/lib.rs @@ -18,6 +18,7 @@ mod models; mod runtime; mod state; mod tap; +mod ui; mod usage; use std::sync::Arc; @@ -45,6 +46,8 @@ pub fn router(state: Arc) -> Router { .route("/v1/chat/completions", post(chat::completions)) .route("/gateway/v1/health", get(health)) .route("/gateway/v1/metrics", get(metrics_endpoint)) + .route("/gateway/v1/status", get(status_endpoint)) + .merge(ui::routes()) .fallback(not_found) .layer(DefaultBodyLimit::max(MAX_BODY_BYTES)) .layer(middleware::from_fn_with_state( @@ -76,6 +79,50 @@ async fn metrics_endpoint( )) } +/// Zustand des Gateways als JSON (für die Oberfläche und Skripte); für Keys +/// mit dem Recht `metrics` oder `ui`. +async fn status_endpoint( + axum::extract::State(state): axum::extract::State>, + auth::Authed(key): auth::Authed, +) -> Result { + if !key.rights.metrics && !key.rights.ui { + return Err(ApiError::new( + StatusCode::FORBIDDEN, + "invalid_request_error", + "permission_denied", + "Dieser Key hat weder das Recht \"metrics\" noch \"ui\".", + )); + } + let instances = state.runtime.metrics.instances(); + let models: Vec = { + let store = state.store(); + store + .list_models(false) + .unwrap_or_default() + .into_iter() + .map(|m| { + let plan = store.start_plan(&m.name).ok().flatten(); + serde_json::json!({ + "name": m.name, + "enabled": m.enabled, + "engine": plan.as_ref().map(|p| p.engine_name.clone()), + "gpus": plan.as_ref().map(|p| p.gpus.clone()), + "context": plan.as_ref().and_then(|p| p.context), + "loaded": instances.iter().any(|i| i.model == m.name), + }) + }) + .collect() + }; + Ok(axum::Json(serde_json::json!({ + "version": nexus_core::VERSION, + "uptime_s": state.started.elapsed().as_secs(), + "totals": state.runtime.metrics.totals(), + "instances": instances, + "gpus": state.runtime.metrics.gpus(), + "models": models, + }))) +} + async fn health() -> impl IntoResponse { axum::Json(serde_json::json!({ "status": "ok", "version": nexus_core::VERSION })) } diff --git a/crates/nexus-api/src/metrics.rs b/crates/nexus-api/src/metrics.rs index bd3fb11..aeaa4bc 100644 --- a/crates/nexus-api/src/metrics.rs +++ b/crates/nexus-api/src/metrics.rs @@ -35,7 +35,7 @@ impl Histogram { } /// Eine laufende Instanz mit gemessenem Verbrauch. -#[derive(Debug, Clone, PartialEq, Eq)] +#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)] pub struct InstanceSample { pub model: String, pub engine: String, @@ -45,7 +45,7 @@ pub struct InstanceSample { } /// Gesamtwerte einer GPU (aus `nvidia-smi`). -#[derive(Debug, Clone, PartialEq)] +#[derive(Debug, Clone, PartialEq, serde::Serialize)] pub struct GpuSample { pub index: u32, pub memory_used_mb: u64, @@ -54,6 +54,17 @@ pub struct GpuSample { pub temperature_c: Option, } +/// Summen seit dem Start des Gateways. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, serde::Serialize)] +pub struct Totals { + pub requests: u64, + pub server_errors: u64, + pub aborted: u64, + pub tokens_in: u64, + pub tokens_out: u64, + pub start_failures: u64, +} + #[derive(Default)] struct Inner { /// (Modell, Status) -> Anzahl @@ -142,6 +153,34 @@ impl Metrics { self.lock().gpus = gpus; } + /// Letzte Messung der laufenden Instanzen. + pub fn instances(&self) -> Vec { + self.lock().instances.clone() + } + + /// Letzte Messung der GPUs. + pub fn gpus(&self) -> Vec { + self.lock().gpus.clone() + } + + /// Summen seit dem Start (für die Übersicht). + pub fn totals(&self) -> Totals { + let m = self.lock(); + Totals { + requests: m.requests.values().sum(), + server_errors: m + .requests + .iter() + .filter(|((_, status), _)| *status >= 500) + .map(|(_, n)| n) + .sum(), + aborted: m.aborted.values().sum(), + tokens_in: m.tokens_in.values().sum(), + tokens_out: m.tokens_out.values().sum(), + start_failures: m.start_failures.values().sum(), + } + } + /// Ausgabe im Prometheus-Textformat. pub fn render(&self) -> String { let m = self.lock(); diff --git a/crates/nexus-api/src/state.rs b/crates/nexus-api/src/state.rs index 3b2d022..ddc31fa 100644 --- a/crates/nexus-api/src/state.rs +++ b/crates/nexus-api/src/state.rs @@ -1,14 +1,21 @@ +use std::collections::HashMap; use std::sync::{Arc, Mutex, MutexGuard}; +use std::time::Instant; use nexus_store::Store; use crate::runtime::Runtime; +use crate::ui::Session; /// Gemeinsamer Zustand aller Anfragen. pub struct AppState { store: Mutex, pub runtime: Runtime, pub http: reqwest::Client, + /// Start des Gateways (für die Laufzeit in der Übersicht). + pub started: Instant, + /// Sitzungen der Weboberfläche (nur im Speicher; ein Neustart meldet ab). + pub sessions: Mutex>, } impl AppState { @@ -21,6 +28,8 @@ impl AppState { store: Mutex::new(store), runtime, http, + started: Instant::now(), + sessions: Mutex::new(HashMap::new()), }) } diff --git a/crates/nexus-api/src/ui.rs b/crates/nexus-api/src/ui.rs new file mode 100644 index 0000000..40a7eab --- /dev/null +++ b/crates/nexus-api/src/ui.rs @@ -0,0 +1,685 @@ +//! Erste Weboberfläche (nur lesend): Übersicht, Modelle, Anfragen, Audit. +//! +//! Anmeldung mit einem API-Key, der das Recht `ui` hat (Entscheidung #1049). +//! Nach der Anmeldung gilt ein zufälliges Sitzungs-Token im Cookie +//! `nexus_ui` (`HttpOnly`, `SameSite=Strict`, Pfad `/ui`, 12 Stunden). Die +//! Sitzungen stehen nur im Speicher: Ein Neustart des Gateways meldet alle ab. +//! +//! Schutz: Alle Werte werden für HTML maskiert; jede Seite schickt eine +//! strenge Content-Security-Policy (nur eigene Skripte und Stile, kein +//! Einbetten in fremde Seiten) und `Cache-Control: no-store`. POST-Anfragen +//! mit fremdem `Origin` werden abgelehnt. Eine falsche Anmeldung kostet eine +//! Sekunde Wartezeit. Über HTTP ohne TLS kann das Cookie nicht `Secure` sein; +//! die Oberfläche ist wie das Gateway nur für das interne Netz oder Tailscale +//! gedacht. +//! +//! Statt der Bibliothek HTMX steckt das eine benötigte Muster (Teil der Seite +//! regelmäßig neu laden) in wenigen Zeilen eigenem JavaScript; so muss keine +//! fremde Datei eingebettet werden. + +use std::sync::Arc; +use std::time::{Duration, Instant}; + +use axum::Router; +use axum::body::{Body, Bytes}; +use axum::extract::State; +use axum::http::header::{CACHE_CONTROL, CONTENT_TYPE, COOKIE, HOST, LOCATION, ORIGIN, SET_COOKIE}; +use axum::http::{HeaderMap, HeaderValue, StatusCode}; +use axum::response::Response; +use axum::routing::{get, post}; + +use crate::metrics::{GpuSample, InstanceSample}; +use crate::state::AppState; + +const COOKIE_NAME: &str = "nexus_ui"; +const SESSION_SECS: u64 = 12 * 3600; +const MAX_SESSIONS: usize = 100; +const ROWS: u32 = 100; + +/// Eine angemeldete Sitzung. +#[derive(Debug, Clone)] +pub struct Session { + pub key_name: String, + pub expires: Instant, +} + +pub fn routes() -> Router> { + Router::new() + .route("/ui", get(overview)) + .route("/ui/", get(overview)) + .route("/ui/login", get(login_form).post(login)) + .route("/ui/logout", post(logout)) + .route("/ui/modelle", get(models_page)) + .route("/ui/anfragen", get(requests_page)) + .route("/ui/audit", get(audit_page)) + .route("/ui/teil/uebersicht", get(overview_fragment)) + .route("/ui/app.js", get(app_js)) + .route("/ui/app.css", get(app_css)) +} + +// --- Sitzungen --------------------------------------------------------------- + +fn cookie_token(headers: &HeaderMap) -> Option { + headers + .get_all(COOKIE) + .iter() + .filter_map(|v| v.to_str().ok()) + .flat_map(|v| v.split(';')) + .filter_map(|pair| pair.trim().split_once('=')) + .find(|(name, _)| *name == COOKIE_NAME) + .map(|(_, value)| value.to_string()) +} + +/// Name des Keys der gültigen Sitzung, falls es eine gibt. +fn session(state: &AppState, headers: &HeaderMap) -> Option { + let token = cookie_token(headers)?; + let mut sessions = state.sessions.lock().unwrap_or_else(|e| e.into_inner()); + match sessions.get(&token) { + Some(s) if s.expires > Instant::now() => Some(s.key_name.clone()), + Some(_) => { + sessions.remove(&token); + None + } + None => None, + } +} + +fn new_session(state: &AppState, key_name: &str) -> Option { + let token = nexus_core::random_hex(32).ok()?; + let mut sessions = state.sessions.lock().unwrap_or_else(|e| e.into_inner()); + let now = Instant::now(); + sessions.retain(|_, s| s.expires > now); + while sessions.len() >= MAX_SESSIONS { + let oldest = sessions + .iter() + .min_by_key(|(_, s)| s.expires) + .map(|(t, _)| t.clone())?; + sessions.remove(&oldest); + } + sessions.insert( + token.clone(), + Session { + key_name: key_name.to_string(), + expires: now + Duration::from_secs(SESSION_SECS), + }, + ); + Some(token) +} + +/// Ein POST mit `Origin` muss von derselben Adresse kommen wie die Seite. +fn same_origin(headers: &HeaderMap) -> bool { + let Some(origin) = headers.get(ORIGIN).and_then(|v| v.to_str().ok()) else { + return true; + }; + let Some(host) = headers.get(HOST).and_then(|v| v.to_str().ok()) else { + return false; + }; + let origin_host = origin + .strip_prefix("http://") + .or_else(|| origin.strip_prefix("https://")) + .unwrap_or(""); + origin_host == host +} + +// --- Antworten --------------------------------------------------------------- + +fn secure(builder: axum::http::response::Builder) -> axum::http::response::Builder { + builder + .header( + "content-security-policy", + "default-src 'none'; script-src 'self'; style-src 'self'; img-src 'self'; \ + connect-src 'self'; form-action 'self'; frame-ancestors 'none'; base-uri 'none'", + ) + .header("x-content-type-options", "nosniff") + .header("x-frame-options", "DENY") + .header("referrer-policy", "no-referrer") + .header(CACHE_CONTROL, "no-store") +} + +fn html(status: StatusCode, body: String) -> Response { + secure(Response::builder().status(status)) + .header(CONTENT_TYPE, "text/html; charset=utf-8") + .body(Body::from(body)) + .unwrap_or_default() +} + +fn redirect(to: &str) -> Response { + secure(Response::builder().status(StatusCode::SEE_OTHER)) + .header(LOCATION, to) + .body(Body::empty()) + .unwrap_or_default() +} + +/// Maskiert Text für HTML. +pub(crate) fn esc(text: &str) -> String { + let mut out = String::with_capacity(text.len()); + for c in text.chars() { + match c { + '&' => out.push_str("&"), + '<' => out.push_str("<"), + '>' => out.push_str(">"), + '"' => out.push_str("""), + '\'' => out.push_str("'"), + c => out.push(c), + } + } + out +} + +fn opt(v: Option) -> String { + v.map(|v| v.to_string()).unwrap_or_else(|| "–".to_string()) +} + +fn mb(v: Option) -> String { + match v { + Some(v) if v >= 1024 => format!("{:.1} GB", v as f64 / 1024.0).replace('.', ","), + Some(v) => format!("{v} MB"), + None => "–".to_string(), + } +} + +fn layout(title: &str, active: &str, key_name: &str, body: &str) -> String { + let nav: String = [ + ("/ui", "Übersicht"), + ("/ui/modelle", "Modelle"), + ("/ui/anfragen", "Anfragen"), + ("/ui/audit", "Audit"), + ] + .iter() + .map(|(href, label)| { + let current = if *href == active { + " aria-current=\"page\"" + } else { + "" + }; + format!("{label}") + }) + .collect(); + format!( + "\ + \ + {title} · Nexus\ +
Nexus\ +
{key}\ +
\ +

{title}

{body}
\ +
Nexus {version} · nur lesend · Zeiten in UTC
\ + ", + title = esc(title), + key = esc(key_name), + version = esc(nexus_core::VERSION), + ) +} + +// --- Anmeldung --------------------------------------------------------------- + +fn login_page(message: Option<&str>) -> String { + let note = message + .map(|m| format!("

{}

", esc(m))) + .unwrap_or_default(); + format!( + "\ + \ + Anmelden · Nexus\ +

Nexus

\ +

Anmelden mit einem API-Key, der das Recht ui hat \ + (nexus key create --name … --ui).

{note}\ +
\ + \ + \ +
" + ) +} + +async fn login_form(State(state): State>, headers: HeaderMap) -> Response { + if session(&state, &headers).is_some() { + return redirect("/ui"); + } + html(StatusCode::OK, login_page(None)) +} + +/// Liest ein Feld aus einem `application/x-www-form-urlencoded`-Body. +pub(crate) fn form_field(body: &[u8], name: &str) -> Option { + let text = std::str::from_utf8(body).ok()?; + text.split('&').find_map(|pair| { + let (k, v) = pair.split_once('=')?; + (k == name).then(|| percent_decode(v)) + }) +} + +fn percent_decode(text: &str) -> String { + let bytes = text.as_bytes(); + let mut out = Vec::with_capacity(bytes.len()); + let mut i = 0; + while i < bytes.len() { + match bytes[i] { + b'+' => out.push(b' '), + b'%' if i + 2 < bytes.len() => { + match u8::from_str_radix( + std::str::from_utf8(&bytes[i + 1..i + 3]).unwrap_or(""), + 16, + ) { + Ok(b) => { + out.push(b); + i += 2; + } + Err(_) => out.push(b'%'), + } + } + b => out.push(b), + } + i += 1; + } + String::from_utf8_lossy(&out).into_owned() +} + +async fn login(State(state): State>, headers: HeaderMap, body: Bytes) -> Response { + if !same_origin(&headers) { + return html(StatusCode::FORBIDDEN, login_page(Some("Fremde Herkunft."))); + } + let key = form_field(&body, "key").unwrap_or_default(); + let found = if key.trim().is_empty() { + None + } else { + state.store().find_api_key(key.trim()).ok().flatten() + }; + match found { + Some(record) if record.rights.ui => { + let Some(token) = new_session(&state, &record.name) else { + return html( + StatusCode::INTERNAL_SERVER_ERROR, + login_page(Some("Sitzung konnte nicht angelegt werden.")), + ); + }; + if let Err(e) = state.store().audit("ui", "ui.login", Some(&record.name)) { + tracing::error!(fehler = %e, "Audit der Anmeldung fehlgeschlagen"); + } + tracing::info!(key = %record.name, "Anmeldung an der Oberfläche"); + let cookie = format!( + "{COOKIE_NAME}={token}; Path=/ui; HttpOnly; SameSite=Strict; Max-Age={SESSION_SECS}" + ); + let mut response = redirect("/ui"); + if let Ok(value) = HeaderValue::from_str(&cookie) { + response.headers_mut().insert(SET_COOKIE, value); + } + response + } + _ => { + // Gleiche Antwort für falsche Keys und Keys ohne Recht `ui`. + tracing::warn!("Anmeldung an der Oberfläche abgelehnt"); + tokio::time::sleep(Duration::from_secs(1)).await; + html( + StatusCode::UNAUTHORIZED, + login_page(Some( + "Anmeldung abgelehnt: Key unbekannt, gesperrt oder ohne Recht „ui“.", + )), + ) + } + } +} + +async fn logout(State(state): State>, headers: HeaderMap) -> Response { + if !same_origin(&headers) { + return html(StatusCode::FORBIDDEN, login_page(Some("Fremde Herkunft."))); + } + if let Some(token) = cookie_token(&headers) { + let removed = state + .sessions + .lock() + .unwrap_or_else(|e| e.into_inner()) + .remove(&token); + if let Some(s) = removed { + let _ = state.store().audit("ui", "ui.logout", Some(&s.key_name)); + } + } + let mut response = redirect("/ui/login"); + response.headers_mut().insert( + SET_COOKIE, + HeaderValue::from_static("nexus_ui=; Path=/ui; HttpOnly; SameSite=Strict; Max-Age=0"), + ); + response +} + +// --- Seiten ------------------------------------------------------------------ + +async fn overview(State(state): State>, headers: HeaderMap) -> Response { + let Some(key) = session(&state, &headers) else { + return redirect("/ui/login"); + }; + let body = format!( + "
{}
", + overview_html(&state) + ); + html(StatusCode::OK, layout("Übersicht", "/ui", &key, &body)) +} + +async fn overview_fragment(State(state): State>, headers: HeaderMap) -> Response { + if session(&state, &headers).is_none() { + return html(StatusCode::UNAUTHORIZED, String::new()); + } + html(StatusCode::OK, overview_html(&state)) +} + +fn uptime(secs: u64) -> String { + let (d, h, m) = (secs / 86_400, secs % 86_400 / 3600, secs % 3600 / 60); + if d > 0 { + format!("{d} d {h} h") + } else if h > 0 { + format!("{h} h {m} min") + } else { + format!("{m} min") + } +} + +fn overview_html(state: &AppState) -> String { + let t = state.runtime.metrics.totals(); + let gpus = state.runtime.metrics.gpus(); + let instances = state.runtime.metrics.instances(); + format!( + "
\ +
Laufzeit{uptime}
\ +
Anfragen{req}
\ +
Serverfehler{err}
\ +
Abgebrochen{ab}
\ +
Tokens rein / raus{ti} / {to}
\ +
Fehlstarts{fs}
\ +

GPUs

{gpus}

Geladene Modelle

{inst}\ +

Zähler seit dem Start des Gateways. Stand {now} UTC, wird alle 5 s erneuert.

", + uptime = uptime(state.started.elapsed().as_secs()), + req = t.requests, + err = t.server_errors, + ab = t.aborted, + ti = t.tokens_in, + to = t.tokens_out, + fs = t.start_failures, + gpus = gpu_table(&gpus), + inst = instance_table(&instances), + now = esc(&nexus_core::now_iso8601()), + ) +} + +fn gpu_table(gpus: &[GpuSample]) -> String { + if gpus.is_empty() { + return "

Keine GPU-Werte (nvidia-smi fehlt oder die Messung ist aus).

" + .to_string(); + } + let rows: String = gpus + .iter() + .map(|g| { + let pct = (g.memory_used_mb * 100) + .checked_div(g.memory_total_mb) + .unwrap_or(0) + .min(100); + format!( + "GPU {} {} von {} ({pct} %){}{}", + g.index, + mb(Some(g.memory_used_mb)), + mb(Some(g.memory_total_mb)), + g.utilization_percent + .map(|u| format!("{u} %")) + .unwrap_or_else(|| "–".to_string()), + g.temperature_c + .map(|t| format!("{t} °C")) + .unwrap_or_else(|| "–".to_string()), + ) + }) + .collect(); + format!( + "{rows}
GPUSpeicherAuslastungTemperatur
" + ) +} + +fn instance_table(instances: &[InstanceSample]) -> String { + if instances.is_empty() { + return "

Kein Modell geladen. Ein Modell startet mit der ersten Anfrage.

" + .to_string(); + } + let rows: String = instances + .iter() + .map(|i| { + format!( + "{}{}{}{}{}", + esc(&i.model), + esc(&i.engine), + i.instance_id, + mb(i.vram_mb), + mb(i.ram_mb) + ) + }) + .collect(); + format!( + "{rows}
ModellEngineInstanzVRAMRAM
" + ) +} + +async fn models_page(State(state): State>, headers: HeaderMap) -> Response { + let Some(key) = session(&state, &headers) else { + return redirect("/ui/login"); + }; + let loaded = state.runtime.metrics.instances(); + let rows: String = { + let store = state.store(); + store + .list_models(false) + .unwrap_or_default() + .into_iter() + .map(|m| { + let plan = store.start_plan(&m.name).ok().flatten(); + let running = loaded.iter().find(|i| i.model == m.name); + format!( + "{}{}{}{}{}{}{}", + esc(&m.name), + plan.as_ref().map(|p| esc(&p.engine_name)).unwrap_or_default(), + if m.enabled { "freigegeben" } else { "gesperrt" }, + plan.as_ref() + .map(|p| p.gpus.iter().map(u32::to_string).collect::>().join(", ")) + .unwrap_or_default(), + opt(plan.as_ref().and_then(|p| p.context)), + running + .map(|i| format!("geladen ({})", mb(i.vram_mb))) + .unwrap_or_else(|| "nicht geladen".to_string()), + plan.as_ref() + .map(|p| esc(&p.model_path.display().to_string())) + .unwrap_or_default(), + ) + }) + .collect() + }; + let body = if rows.is_empty() { + "

Keine Modelle registriert (nexus model add).

" + .to_string() + } else { + format!( + "{rows}
NameEngineStatusGPUsKontextZustandModell
" + ) + }; + html( + StatusCode::OK, + layout("Modelle", "/ui/modelle", &key, &body), + ) +} + +async fn requests_page(State(state): State>, headers: HeaderMap) -> Response { + let Some(key) = session(&state, &headers) else { + return redirect("/ui/login"); + }; + let rows: String = state + .store() + .recent_request_view(ROWS) + .unwrap_or_default() + .into_iter() + .map(|r| { + let class = if r.status >= 500 { + " class=\"schlecht\"" + } else if r.status >= 400 || r.aborted { + " class=\"warnung\"" + } else { + "" + }; + format!( + "{}{}{}{}{}{}{}{}{} / {}{}{}", + esc(&r.time), + esc(&r.correlation), + esc(r.key.as_deref().unwrap_or("–")), + esc(r.model.as_deref().unwrap_or("–")), + r.status, + opt(r.wait_ms), + opt(r.latency_ms), + opt(r.duration_ms), + opt(r.tokens_in), + opt(r.tokens_out), + esc(r.engine.as_deref().unwrap_or("–")), + if r.aborted { "ja" } else { "" }, + ) + }) + .collect(); + let body = if rows.is_empty() { + "

Noch keine Anfragen.

".to_string() + } else { + format!( + "

Die letzten {ROWS} Anfragen, nur Metadaten (keine Prompts oder Antworten). Zeiten in ms.

\ +
\ + \ + {rows}
ZeitKorrelationKeyModellStatusWartenLatenzDauerTokens ein / ausEngineAbgebr.
" + ) + }; + html( + StatusCode::OK, + layout("Anfragen", "/ui/anfragen", &key, &body), + ) +} + +async fn audit_page(State(state): State>, headers: HeaderMap) -> Response { + let Some(key) = session(&state, &headers) else { + return redirect("/ui/login"); + }; + let rows: String = state + .store() + .recent_audit(ROWS) + .unwrap_or_default() + .into_iter() + .map(|a| { + format!( + "{}{}{}{}", + esc(&a.time), + esc(&a.actor), + esc(&a.action), + esc(a.target.as_deref().unwrap_or("–")) + ) + }) + .collect(); + let body = if rows.is_empty() { + "

Noch keine Einträge.

".to_string() + } else { + format!( + "{rows}
ZeitWerAktionZiel
" + ) + }; + html(StatusCode::OK, layout("Audit", "/ui/audit", &key, &body)) +} + +// --- Dateien ----------------------------------------------------------------- + +const APP_JS: &str = r#"// Lädt Teile der Seite mit data-refresh regelmäßig neu (wie hx-trigger="every 5s"). +document.querySelectorAll("[data-refresh]").forEach(function (el) { + var url = el.getAttribute("data-refresh"); + var ms = parseInt(el.getAttribute("data-interval"), 10) || 5000; + setInterval(function () { + fetch(url, { credentials: "same-origin" }).then(function (r) { + if (r.status === 401) { window.location.href = "/ui/login"; return null; } + return r.ok ? r.text() : null; + }).then(function (text) { + if (text !== null && text !== undefined) { el.innerHTML = text; } + }).catch(function () {}); + }, ms); +}); +"#; + +const APP_CSS: &str = r#":root{--bg:#f7f7f5;--fg:#1d1d1b;--muted:#6b6b66;--line:#dcdcd6;--card:#fff;--accent:#2f5fb3;--warn:#fff4d6;--bad:#fde2e0} +@media (prefers-color-scheme:dark){:root{--bg:#161615;--fg:#ececea;--muted:#9a9a94;--line:#33332f;--card:#1f1f1d;--accent:#7aa5f0;--warn:#3a3218;--bad:#43201d}} +*{box-sizing:border-box}body{margin:0;font:15px/1.45 system-ui,sans-serif;background:var(--bg);color:var(--fg)} +header{display:flex;flex-wrap:wrap;gap:12px 20px;align-items:center;padding:10px 16px;border-bottom:1px solid var(--line);background:var(--card)} +header nav{display:flex;gap:14px;flex-wrap:wrap}header nav a{color:var(--fg);text-decoration:none;padding:2px 0} +header nav a[aria-current]{border-bottom:2px solid var(--accent);font-weight:600} +header form{margin-left:auto;display:flex;gap:10px;align-items:center}.wer{color:var(--muted)} +main{padding:16px;max-width:1200px;margin:0 auto}h1{font-size:22px;margin:4px 0 16px}h2{font-size:17px;margin:22px 0 8px} +footer{padding:16px;color:var(--muted);font-size:13px;text-align:center} +table{border-collapse:collapse;width:100%;background:var(--card);border:1px solid var(--line)} +th,td{text-align:left;padding:6px 10px;border-bottom:1px solid var(--line);vertical-align:top}th{font-weight:600;font-size:13px;color:var(--muted)} +tr.warnung td{background:var(--warn)}tr.schlecht td{background:var(--bad)} +.breit{overflow-x:auto}.pfad{font-size:12px;color:var(--muted);word-break:break-all} +.kacheln{display:grid;grid-template-columns:repeat(auto-fill,minmax(160px,1fr));gap:10px} +.kacheln div{background:var(--card);border:1px solid var(--line);padding:10px 12px;border-radius:6px} +.kacheln span{display:block;font-size:12px;color:var(--muted)}.kacheln b{font-size:20px} +.leer,.klein{color:var(--muted)}.klein{font-size:13px}meter{width:120px;vertical-align:middle} +button{font:inherit;padding:5px 12px;border:1px solid var(--line);border-radius:5px;background:var(--card);color:var(--fg);cursor:pointer} +.anmeldung{max-width:420px;margin:10vh auto}.anmeldung form{display:flex;flex-direction:column;gap:8px} +input{font:inherit;padding:7px 9px;border:1px solid var(--line);border-radius:5px;background:var(--card);color:var(--fg)} +.fehler{background:var(--bad);padding:8px 10px;border-radius:5px}code{font-size:13px} +"#; + +async fn app_js() -> Response { + secure(Response::builder()) + .header(CONTENT_TYPE, "text/javascript; charset=utf-8") + .body(Body::from(APP_JS)) + .unwrap_or_default() +} + +async fn app_css() -> Response { + secure(Response::builder()) + .header(CONTENT_TYPE, "text/css; charset=utf-8") + .body(Body::from(APP_CSS)) + .unwrap_or_default() +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn html_wird_maskiert() { + assert_eq!( + esc(""), + "<script>"a"&'b'</script>" + ); + } + + #[test] + fn formularfeld_wird_gelesen_und_dekodiert() { + assert_eq!( + form_field(b"x=1&key=nx-ab%2Bc+d&y=2", "key").as_deref(), + Some("nx-ab+c d") + ); + assert_eq!(form_field(b"x=1", "key"), None); + assert_eq!(form_field(b"key=%zz%4", "key").as_deref(), Some("%zz%4")); + } + + #[test] + fn cookie_wird_unter_mehreren_gefunden() { + let mut h = HeaderMap::new(); + h.insert(COOKIE, HeaderValue::from_static("a=1; nexus_ui=abc; b=2")); + assert_eq!(cookie_token(&h).as_deref(), Some("abc")); + } + + #[test] + fn fremde_herkunft_wird_erkannt() { + let mut h = HeaderMap::new(); + h.insert(HOST, HeaderValue::from_static("127.0.0.1:8080")); + assert!(same_origin(&h), "ohne Origin erlaubt"); + h.insert(ORIGIN, HeaderValue::from_static("http://127.0.0.1:8080")); + assert!(same_origin(&h)); + h.insert(ORIGIN, HeaderValue::from_static("http://boese.example")); + assert!(!same_origin(&h)); + } + + #[test] + fn laufzeit_und_groessen_lesbar() { + assert_eq!(uptime(59), "0 min"); + assert_eq!(uptime(3_700), "1 h 1 min"); + assert_eq!(uptime(90_000), "1 d 1 h"); + assert_eq!(mb(Some(638)), "638 MB"); + assert_eq!(mb(Some(21_906)), "21,4 GB"); + assert_eq!(mb(None), "–"); + } +} diff --git a/crates/nexus-api/tests/api.rs b/crates/nexus-api/tests/api.rs index 5581a06..a7407e4 100644 --- a/crates/nexus-api/tests/api.rs +++ b/crates/nexus-api/tests/api.rs @@ -239,6 +239,7 @@ async fn gateway(delay_ms: u64, fail: bool) -> Gateway { &Rights { models: vec!["bonsai".to_string()], metrics: false, + ui: false, }, Priority::Normal, Priority::Normal, @@ -254,6 +255,7 @@ async fn gateway(delay_ms: u64, fail: bool) -> Gateway { &Rights { models: vec!["*".to_string()], metrics: true, + ui: false, }, Priority::Normal, Priority::Normal, diff --git a/crates/nexus-store/src/keys.rs b/crates/nexus-store/src/keys.rs index e6a1624..fc71dae 100644 --- a/crates/nexus-store/src/keys.rs +++ b/crates/nexus-store/src/keys.rs @@ -14,6 +14,9 @@ pub struct Rights { /// Darf `GET /gateway/v1/metrics` lesen. Ältere Keys ohne dieses Feld: nein. #[serde(default)] pub metrics: bool, + /// Darf sich an der Weboberfläche anmelden (nur lesend). Ältere Keys: nein. + #[serde(default)] + pub ui: bool, } impl Default for Rights { @@ -21,6 +24,7 @@ impl Default for Rights { Self { models: vec!["*".to_string()], metrics: false, + ui: false, } } } @@ -197,6 +201,7 @@ mod tests { let r = Rights { models: vec!["bonsai".to_string()], metrics: false, + ui: false, }; assert!(r.allows("bonsai")); assert!(!r.allows("anderes")); diff --git a/crates/nexus-store/src/lib.rs b/crates/nexus-store/src/lib.rs index 41e85d3..9606ed9 100644 --- a/crates/nexus-store/src/lib.rs +++ b/crates/nexus-store/src/lib.rs @@ -15,7 +15,7 @@ mod logs; mod registry; pub use keys::{ApiKeyRecord, Rights}; -pub use logs::{AuditRow, RequestLogEntry, RequestLogRow}; +pub use logs::{AuditRow, RequestLogEntry, RequestLogRow, RequestView}; pub use registry::{ModelEntry, NewLlm, StartPlan}; /// Alle Migrationen in Reihenfolge. Index 0 ergibt Schema-Version 1. diff --git a/crates/nexus-store/src/logs.rs b/crates/nexus-store/src/logs.rs index c1f04d1..52ead4c 100644 --- a/crates/nexus-store/src/logs.rs +++ b/crates/nexus-store/src/logs.rs @@ -47,6 +47,23 @@ pub struct RequestLogRow { pub aborted: bool, } +/// Eine Zeile des Anfrage-Logs mit Namen statt IDs (für die Oberfläche). +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct RequestView { + pub time: String, + pub correlation: String, + pub key: Option, + pub model: Option, + pub status: i64, + pub wait_ms: Option, + pub latency_ms: Option, + pub duration_ms: Option, + pub tokens_in: Option, + pub tokens_out: Option, + pub engine: Option, + pub aborted: bool, +} + #[derive(Debug, Clone, PartialEq, Eq)] pub struct AuditRow { pub time: String, @@ -114,6 +131,40 @@ impl Store { rows.collect::>>().map_err(db) } + /// Die letzten `limit` Anfragen mit Key- und Modellnamen, neueste zuerst. + pub fn recent_request_view(&self, limit: u32) -> Result> { + let mut stmt = self + .connection() + .prepare( + "SELECT a.zeit, a.korrelation, k.name, m.name, a.status, a.wartezeit_ms, a.latenz_ms, + a.dauer_ms, a.tokens_ein, a.tokens_aus, a.engine, a.abgebrochen + FROM anfrage_log a + LEFT JOIN api_key k ON k.id = a.api_key_id + LEFT JOIN model m ON m.id = a.model_id + ORDER BY a.id DESC LIMIT ?1", + ) + .map_err(db)?; + let rows = stmt + .query_map([limit], |r| { + Ok(RequestView { + time: r.get(0)?, + correlation: r.get(1)?, + key: r.get(2)?, + model: r.get(3)?, + status: r.get(4)?, + wait_ms: r.get(5)?, + latency_ms: r.get(6)?, + duration_ms: r.get(7)?, + tokens_in: r.get(8)?, + tokens_out: r.get(9)?, + engine: r.get(10)?, + aborted: r.get::<_, i64>(11)? != 0, + }) + }) + .map_err(db)?; + rows.collect::>>().map_err(db) + } + /// Löscht Anfrage-Log-Zeilen, die älter als `days` Tage sind. Liefert die /// Zahl der gelöschten Zeilen. `0` Tage löscht nichts (unbegrenzt). pub fn purge_requests_older_than(&self, days: u32) -> Result { @@ -292,4 +343,44 @@ mod tests { assert_eq!(row.instance_id, Some(1)); assert!(row.aborted); } + + #[test] + fn ansicht_der_anfragen_zeigt_namen_statt_ids() { + let mut store = Store::open_in_memory().unwrap(); + store + .register_llm(&NewLlm { + name: "bonsai".to_string(), + engine: "llama.cpp".to_string(), + path: PathBuf::from("/m/b.gguf"), + quantization: None, + size_bytes: None, + gpus: vec![0], + context: None, + vram_mb: None, + ram_mb: None, + enabled: true, + }) + .unwrap(); + let key = store + .create_api_key( + "client", + &Rights::default(), + Priority::Normal, + Priority::Normal, + ) + .unwrap(); + let key_id = store.find_api_key(&key).unwrap().unwrap().id; + store + .log_request(&eintrag(Some("bonsai"), Some(key_id))) + .unwrap(); + store + .log_request(&eintrag(Some("unbekannt"), None)) + .unwrap(); + let v = store.recent_request_view(10).unwrap(); + assert_eq!(v[0].model, None); + assert_eq!(v[0].key, None); + assert_eq!(v[1].model.as_deref(), Some("bonsai")); + assert_eq!(v[1].key.as_deref(), Some("client")); + assert_eq!(v[1].tokens_out, Some(34)); + } } diff --git a/crates/nexus/src/admin.rs b/crates/nexus/src/admin.rs index 870f2e8..785f5b0 100644 --- a/crates/nexus/src/admin.rs +++ b/crates/nexus/src/admin.rs @@ -52,7 +52,7 @@ fn key_create(args: &[String]) -> Result<(), String> { "models", "config", ], - &["metrics"], + &["metrics", "ui"], )?; let name = flags.require("name")?; let default = priority(&flags, "default-priority", Priority::Normal)?; @@ -78,6 +78,7 @@ fn key_create(args: &[String]) -> Result<(), String> { &Rights { models, metrics: flags.has("metrics"), + ui: flags.has("ui"), }, default, max, diff --git a/crates/nexus/src/main.rs b/crates/nexus/src/main.rs index c087734..d23437c 100644 --- a/crates/nexus/src/main.rs +++ b/crates/nexus/src/main.rs @@ -20,7 +20,7 @@ Aufruf: nexus version Version anzeigen nexus selftest [--config PFAD] Konfiguration, Datenverzeichnis und Datenbank prüfen nexus serve [--config PFAD] Gateway starten - nexus key create --name N [--max-priority low|normal|high] [--default-priority ...] [--models a,b|*] + nexus key create --name N [--max-priority low|normal|high] [--default-priority ...] [--models a,b|*] [--metrics] [--ui] nexus key list | enable --name N | disable --name N nexus model add --name N --path PFAD [--gpus 0,1] [--context N] [--vram-mb N] [--ram-mb N] [--quant Q] [--disabled] nexus model add --name N --engine ollama --tag MODELLNAME [--gpus 0] [--disabled]