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:
2026-11-09 17:27:46 +01:00
parent ada5745c53
commit 4d53d5afa3
35 changed files with 3434 additions and 21 deletions

View File

@ -0,0 +1,66 @@
//! API-Keys erzeugen und hashen, Zufallswerte lesen.
//!
//! Keys sind 256 Bit lang und zufällig. Gespeichert wird nur der SHA-256-Hash
//! (bei so viel Zufall ist kein langsamer Passwort-Hash nötig).
use std::io::Read;
use sha2::{Digest, Sha256};
use crate::{Error, Result};
const KEY_PREFIX: &str = "nx-";
/// Liefert `bytes` Zufallsbytes als Hex-Text aus `/dev/urandom`.
pub fn random_hex(bytes: usize) -> Result<String> {
let mut buf = vec![0u8; bytes];
let path = "/dev/urandom";
std::fs::File::open(path)
.and_then(|mut f| f.read_exact(&mut buf))
.map_err(|source| Error::Io {
path: path.into(),
source,
})?;
Ok(hex(&buf))
}
/// Erzeugt einen neuen Key, zum Beispiel `nx-3f9a…` (3 + 64 Zeichen).
pub fn generate_api_key() -> Result<String> {
Ok(format!("{KEY_PREFIX}{}", random_hex(32)?))
}
/// SHA-256 des Keys als Hex-Text.
pub fn hash_api_key(key: &str) -> String {
hex(&Sha256::digest(key.as_bytes()))
}
fn hex(bytes: &[u8]) -> String {
bytes.iter().map(|b| format!("{b:02x}")).collect()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn key_hat_praefix_und_laenge_und_ist_jedes_mal_anders() {
let a = generate_api_key().unwrap();
let b = generate_api_key().unwrap();
assert!(a.starts_with("nx-"));
assert_eq!(a.len(), 3 + 64);
assert_ne!(a, b);
}
#[test]
fn hash_ist_bekannter_sha256_wert() {
assert_eq!(
hash_api_key("abc"),
"ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"
);
}
#[test]
fn zufallswert_hat_die_gewuenschte_laenge() {
assert_eq!(random_hex(8).unwrap().len(), 16);
}
}

View File

@ -9,13 +9,16 @@ use crate::{Error, Result};
///
/// Alle Felder haben Standardwerte; unbekannte Felder werden abgelehnt,
/// damit Tippfehler auffallen.
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
#[derive(Debug, Clone, PartialEq, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct Config {
/// Adresse, auf der das Gateway lauscht, zum Beispiel `127.0.0.1:8080`.
pub listen: String,
/// Ordner für Datenbank, Logs und Ergebnisse.
pub data_dir: PathBuf,
/// Rohe Einstellungen des llama.cpp-Adapters (Abschnitt `[llama_cpp]`).
/// Dieses Crate kennt die Adapter nicht; der Adapter liest die Tabelle selbst.
pub llama_cpp: toml::Table,
}
impl Default for Config {
@ -23,6 +26,7 @@ impl Default for Config {
Self {
listen: "127.0.0.1:8080".to_string(),
data_dir: PathBuf::from("data"),
llama_cpp: toml::Table::new(),
}
}
}
@ -92,6 +96,12 @@ mod tests {
assert!(err.to_string().contains("keine Adresse"), "{err}");
}
#[test]
fn adapter_abschnitt_bleibt_als_rohe_tabelle_erhalten() {
let c = Config::from_toml("[llama_cpp]\nready_timeout_secs = 5\n").unwrap();
assert_eq!(c.llama_cpp["ready_timeout_secs"].as_integer(), Some(5));
}
#[test]
fn leeres_datenverzeichnis_wird_abgelehnt() {
assert!(Config::from_toml("data_dir = \"\"").is_err());

View File

@ -2,11 +2,15 @@
//!
//! Dieses Crate hat keine Abhängigkeit zu Datenbank oder Netzwerk.
mod apikey;
mod config;
mod error;
mod priority;
pub use apikey::{generate_api_key, hash_api_key, random_hex};
pub use config::Config;
pub use error::{Error, Result};
pub use priority::Priority;
/// Version des Nexus-Workspaces.
pub const VERSION: &str = env!("CARGO_PKG_VERSION");

View File

@ -0,0 +1,50 @@
use std::fmt;
/// Priorität eines Jobs (Spezifikation, Abschnitt 6). Die Reihenfolge ist
/// `Low < Normal < High`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum Priority {
Low,
Normal,
High,
}
impl Priority {
/// Schreibweise in Datenbank und Header: `low`, `normal`, `high`.
pub fn as_str(self) -> &'static str {
match self {
Priority::Low => "low",
Priority::Normal => "normal",
Priority::High => "high",
}
}
/// Liest `low`, `normal`, `high` (Groß- und Kleinschreibung egal).
pub fn parse(text: &str) -> Option<Self> {
match text.trim().to_ascii_lowercase().as_str() {
"low" => Some(Priority::Low),
"normal" => Some(Priority::Normal),
"high" => Some(Priority::High),
_ => None,
}
}
}
impl fmt::Display for Priority {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.as_str())
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn reihenfolge_und_umwandlung() {
assert!(Priority::Low < Priority::Normal && Priority::Normal < Priority::High);
assert_eq!(Priority::parse(" HIGH "), Some(Priority::High));
assert_eq!(Priority::parse("vip"), None);
assert_eq!(Priority::Normal.to_string(), "normal");
}
}