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:
222
crates/nexus-store/src/keys.rs
Normal file
222
crates/nexus-store/src/keys.rs
Normal file
@ -0,0 +1,222 @@
|
||||
//! API-Keys: erzeugen, prüfen, auflisten.
|
||||
|
||||
use nexus_core::{Error, Priority, Result, generate_api_key, hash_api_key};
|
||||
use rusqlite::OptionalExtension;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::{Store, db};
|
||||
|
||||
/// Rechte eines Keys, gespeichert als JSON in `api_key.rechte`.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct Rights {
|
||||
/// Erlaubte Modell-Namen; `*` erlaubt alle.
|
||||
pub models: Vec<String>,
|
||||
}
|
||||
|
||||
impl Default for Rights {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
models: vec!["*".to_string()],
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Rights {
|
||||
pub fn allows(&self, model: &str) -> bool {
|
||||
self.models.iter().any(|m| m == "*" || m == model)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct ApiKeyRecord {
|
||||
pub id: i64,
|
||||
pub name: String,
|
||||
pub rights: Rights,
|
||||
pub default_priority: Priority,
|
||||
pub max_priority: Priority,
|
||||
pub active: bool,
|
||||
}
|
||||
|
||||
fn priority(text: &str) -> Result<Priority> {
|
||||
Priority::parse(text)
|
||||
.ok_or_else(|| Error::Db(format!("ungültige Priorität \"{text}\" in der Datenbank")))
|
||||
}
|
||||
|
||||
fn record(row: &rusqlite::Row<'_>) -> rusqlite::Result<(i64, String, String, String, String, i64)> {
|
||||
Ok((
|
||||
row.get(0)?,
|
||||
row.get(1)?,
|
||||
row.get(2)?,
|
||||
row.get(3)?,
|
||||
row.get(4)?,
|
||||
row.get(5)?,
|
||||
))
|
||||
}
|
||||
|
||||
fn build(raw: (i64, String, String, String, String, i64)) -> Result<ApiKeyRecord> {
|
||||
let (id, name, rights, default, max, active) = raw;
|
||||
let rights = serde_json::from_str(&rights)
|
||||
.map_err(|e| Error::Db(format!("Rechte von Key \"{name}\" unlesbar: {e}")))?;
|
||||
Ok(ApiKeyRecord {
|
||||
id,
|
||||
name,
|
||||
rights,
|
||||
default_priority: priority(&default)?,
|
||||
max_priority: priority(&max)?,
|
||||
active: active == 1,
|
||||
})
|
||||
}
|
||||
|
||||
const COLUMNS: &str = "id, name, rechte, standard_prioritaet, max_prioritaet, aktiv";
|
||||
|
||||
impl Store {
|
||||
/// Legt einen Key an und gibt ihn **einmalig** im Klartext zurück; in der
|
||||
/// Datenbank steht nur der Hash.
|
||||
pub fn create_api_key(
|
||||
&self,
|
||||
name: &str,
|
||||
rights: &Rights,
|
||||
default_priority: Priority,
|
||||
max_priority: Priority,
|
||||
) -> Result<String> {
|
||||
if name.trim().is_empty() {
|
||||
return Err(Error::Db("Key-Name darf nicht leer sein".to_string()));
|
||||
}
|
||||
if default_priority > max_priority {
|
||||
return Err(Error::Db(
|
||||
"Standardpriorität darf nicht über der Höchstpriorität liegen".to_string(),
|
||||
));
|
||||
}
|
||||
let key = generate_api_key()?;
|
||||
let rights_json = serde_json::to_string(rights).map_err(|e| Error::Db(e.to_string()))?;
|
||||
self.connection()
|
||||
.execute(
|
||||
"INSERT INTO api_key (name, hash, rechte, standard_prioritaet, max_prioritaet) VALUES (?1, ?2, ?3, ?4, ?5)",
|
||||
(
|
||||
name,
|
||||
hash_api_key(&key),
|
||||
rights_json,
|
||||
default_priority.as_str(),
|
||||
max_priority.as_str(),
|
||||
),
|
||||
)
|
||||
.map_err(db)?;
|
||||
Ok(key)
|
||||
}
|
||||
|
||||
/// Sucht einen aktiven Key anhand des Klartexts.
|
||||
pub fn find_api_key(&self, key: &str) -> Result<Option<ApiKeyRecord>> {
|
||||
let raw = self
|
||||
.connection()
|
||||
.query_row(
|
||||
&format!("SELECT {COLUMNS} FROM api_key WHERE hash = ?1 AND aktiv = 1"),
|
||||
[hash_api_key(key)],
|
||||
record,
|
||||
)
|
||||
.optional()
|
||||
.map_err(db)?;
|
||||
raw.map(build).transpose()
|
||||
}
|
||||
|
||||
pub fn list_api_keys(&self) -> Result<Vec<ApiKeyRecord>> {
|
||||
let mut stmt = self
|
||||
.connection()
|
||||
.prepare(&format!("SELECT {COLUMNS} FROM api_key ORDER BY name"))
|
||||
.map_err(db)?;
|
||||
let rows = stmt.query_map([], record).map_err(db)?;
|
||||
let mut out = Vec::new();
|
||||
for row in rows {
|
||||
out.push(build(row.map_err(db)?)?);
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// Schaltet einen Key ein oder aus. Liefert `false`, wenn es ihn nicht gibt.
|
||||
pub fn set_api_key_active(&self, name: &str, active: bool) -> Result<bool> {
|
||||
let changed = self
|
||||
.connection()
|
||||
.execute(
|
||||
"UPDATE api_key SET aktiv = ?1 WHERE name = ?2",
|
||||
(active as i64, name),
|
||||
)
|
||||
.map_err(db)?;
|
||||
Ok(changed > 0)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn key_wird_angelegt_gefunden_und_nur_als_hash_gespeichert() {
|
||||
let store = Store::open_in_memory().unwrap();
|
||||
let key = store
|
||||
.create_api_key("test", &Rights::default(), Priority::Normal, Priority::High)
|
||||
.unwrap();
|
||||
let found = store.find_api_key(&key).unwrap().expect("gefunden");
|
||||
assert_eq!(found.name, "test");
|
||||
assert_eq!(found.max_priority, Priority::High);
|
||||
assert!(found.rights.allows("irgendein-modell"));
|
||||
|
||||
let gespeichert: String = store
|
||||
.connection()
|
||||
.query_row("SELECT hash FROM api_key", [], |r| r.get(0))
|
||||
.unwrap();
|
||||
assert_ne!(gespeichert, key);
|
||||
assert!(!gespeichert.contains(&key));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn falscher_oder_deaktivierter_key_wird_nicht_gefunden() {
|
||||
let store = Store::open_in_memory().unwrap();
|
||||
let key = store
|
||||
.create_api_key("a", &Rights::default(), Priority::Normal, Priority::Normal)
|
||||
.unwrap();
|
||||
assert!(store.find_api_key("nx-falsch").unwrap().is_none());
|
||||
assert!(store.set_api_key_active("a", false).unwrap());
|
||||
assert!(store.find_api_key(&key).unwrap().is_none());
|
||||
assert!(!store.set_api_key_active("gibt-es-nicht", false).unwrap());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn standardprioritaet_ueber_hoechstprioritaet_wird_abgelehnt() {
|
||||
let store = Store::open_in_memory().unwrap();
|
||||
let err = store
|
||||
.create_api_key("a", &Rights::default(), Priority::High, Priority::Normal)
|
||||
.unwrap_err();
|
||||
assert!(err.to_string().contains("Höchstpriorität"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rechte_pruefen_modellnamen() {
|
||||
let r = Rights {
|
||||
models: vec!["bonsai".to_string()],
|
||||
};
|
||||
assert!(r.allows("bonsai"));
|
||||
assert!(!r.allows("anderes"));
|
||||
assert!(Rights::default().allows("x"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn doppelter_name_wird_abgelehnt_und_liste_ist_sortiert() {
|
||||
let store = Store::open_in_memory().unwrap();
|
||||
for n in ["b", "a"] {
|
||||
store
|
||||
.create_api_key(n, &Rights::default(), Priority::Low, Priority::Low)
|
||||
.unwrap();
|
||||
}
|
||||
assert!(
|
||||
store
|
||||
.create_api_key("a", &Rights::default(), Priority::Low, Priority::Low)
|
||||
.is_err()
|
||||
);
|
||||
let names: Vec<_> = store
|
||||
.list_api_keys()
|
||||
.unwrap()
|
||||
.into_iter()
|
||||
.map(|k| k.name)
|
||||
.collect();
|
||||
assert_eq!(names, ["a", "b"]);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user