Benutzer, Gruppen und Rollen (User, Lecturer, Administrator)

- Benutzer mit Rolle, Sperre und Deaktivierung (Stand für den LDAP-Abgleich);
  der erste Administrator kommt aus der Konfiguration (first_admin)
- Gruppen gehören einem Lecturer; Mitglieder über den Benutzernamen, auch vor
  der Registrierung
- Kontingente gehören einem Lecturer und sind einer Gruppe (Grenzen je
  Mitglied) oder einer Person zugeteilt; Zähler je Kontingent und Person
- Keys haben einen Inhaber; gesperrte oder deaktivierte Benutzer werden mit
  ihren Keys abgewiesen, ein Gruppenkontingent gilt nur für Mitglieder
- Rechte aus dem Konzept zentral in accounts.rs (anlegen, sehen, widerrufen,
  verwalten); /omega/status, Zeitplan, Audit-Log nur für Administratoren
- Exklusive Nutzung für Gruppen und Personen, nicht nur Keys
- Kommandozeile in cli.rs mit --as BENUTZER: user, group, key, quota,
  schedule, usage, audit; Audit-Log mit Handelndem
- Unit-Tests für die Rechteregeln und tests/multispark/accounts_test.py

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Stephan RehfeldandClaude Opus 5.5 committed 2026-11-20 13:35:45 +01:00
1 parent ab4803e264
commit abe72e643d
16 files changed
+1686 -434

No files matched your search

+221 -59
View File
@@ -21,6 +21,8 @@ pub struct Db {
pub struct ApiKey {
pub id: i64,
/// Inhaber; ohne Inhaber hat ihn der Betreiber auf dem Server angelegt
pub user_id: Option<i64>,
pub name: String,
pub prefix: String,
pub revoked: bool,
@@ -31,11 +33,16 @@ pub struct ApiKey {
}
/// Ein angemeldeter Key
#[derive(Clone, Copy, Debug)]
#[derive(Clone, Debug)]
pub struct Caller {
pub key_id: i64,
pub is_super: bool,
pub quota_id: Option<i64>,
/// Inhaber des Keys
pub user_id: Option<i64>,
pub is_admin: bool,
/// Gruppen des Inhabers
pub groups: Vec<i64>,
}
#[derive(Default)]
@@ -49,6 +56,7 @@ pub struct Usage {
pub completion_tokens: Option<u64>,
pub duration_ms: u64,
pub quota_id: Option<i64>,
pub user_id: Option<i64>,
/// Beginn einer gezählten Anfrage; ihre Token werden den Zeiträumen dieses Zeitpunkts gebucht
pub counted_at: Option<DateTime<Local>>,
}
@@ -57,14 +65,16 @@ pub struct Usage {
#[derive(Clone, Copy)]
pub enum Scope {
Key(i64),
Quota(i64),
/// Kontingent und Benutzer: Die Grenzen eines Gruppenkontingents gelten je Mitglied.
/// Keys ohne Inhaber zählen unter Benutzer 0.
Quota(i64, i64),
}
impl Scope {
fn parts(self) -> (&'static str, i64) {
fn parts(self) -> (&'static str, i64, i64) {
match self {
Scope::Key(id) => ("key", id),
Scope::Quota(id) => ("quota", id),
Scope::Key(id) => ("key", id, 0),
Scope::Quota(id, user) => ("quota", id, user),
}
}
}
@@ -149,11 +159,34 @@ impl Db {
CREATE TABLE IF NOT EXISTS usage_counters (
scope TEXT NOT NULL,
scope_id INTEGER NOT NULL,
user_id INTEGER NOT NULL DEFAULT 0,
period TEXT NOT NULL,
requests INTEGER NOT NULL DEFAULT 0,
prompt_tokens INTEGER NOT NULL DEFAULT 0,
completion_tokens INTEGER NOT NULL DEFAULT 0,
PRIMARY KEY (scope, scope_id, period)
PRIMARY KEY (scope, scope_id, user_id, period)
);
CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY,
username TEXT NOT NULL UNIQUE,
email TEXT,
role TEXT NOT NULL,
active INTEGER NOT NULL DEFAULT 1,
blocked INTEGER NOT NULL DEFAULT 0,
created_at INTEGER NOT NULL
);
CREATE TABLE IF NOT EXISTS groups (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL UNIQUE,
owner_id INTEGER REFERENCES users(id),
created_at INTEGER NOT NULL
);
-- Über den Benutzernamen, damit auch Personen ohne Konto Mitglied sein können
CREATE TABLE IF NOT EXISTS group_members (
group_id INTEGER NOT NULL REFERENCES groups(id),
username TEXT NOT NULL,
added_at INTEGER NOT NULL,
PRIMARY KEY (group_id, username)
);
CREATE INDEX IF NOT EXISTS usage_ts ON usage (ts);
CREATE TABLE IF NOT EXISTS audit_log (
@@ -168,12 +201,19 @@ impl Db {
Ok(Self { conn: Mutex::new(conn) })
}
fn conn(&self) -> std::sync::MutexGuard<'_, Connection> {
pub(crate) fn conn(&self) -> std::sync::MutexGuard<'_, Connection> {
self.conn.lock().unwrap_or_else(|e| e.into_inner())
}
/// Legt einen Key an und gibt ihn im Klartext zurück. Gespeichert wird nur der Hash.
pub fn create_key(&self, name: &str, is_super: bool, quota_id: Option<i64>) -> Result<(i64, String)> {
pub fn create_key(
&self,
actor: &str,
name: &str,
is_super: bool,
quota_id: Option<i64>,
user_id: Option<i64>,
) -> Result<(i64, String)> {
if is_super && quota_id.is_some() {
bail!("Super-Keys haben kein Kontingent");
}
@@ -188,20 +228,20 @@ impl Db {
let prefix = key[..14].to_string();
let conn = self.conn();
conn.execute(
"INSERT INTO api_keys (name, key_hash, prefix, created_at, is_super, quota_id)
VALUES (?1, ?2, ?3, ?4, ?5, ?6)",
params![name, hash_key(&key), prefix, now(), is_super, quota_id],
"INSERT INTO api_keys (name, key_hash, prefix, created_at, is_super, quota_id, user_id)
VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)",
params![name, hash_key(&key), prefix, now(), is_super, quota_id, user_id],
)?;
let id = conn.last_insert_rowid();
drop(conn);
self.audit("cli", "key.create", &format!("id={id} name={name} super={is_super} quota={quota_id:?}"))?;
self.audit(actor, "key.create", &format!("id={id} name={name} super={is_super} quota={quota_id:?} user={user_id:?}"))?;
Ok((id, key))
}
pub fn list_keys(&self) -> Result<Vec<ApiKey>> {
let conn = self.conn();
let mut stmt = conn.prepare(
"SELECT id, name, prefix, revoked_at IS NOT NULL, is_super, quota_id
"SELECT id, name, prefix, revoked_at IS NOT NULL, is_super, quota_id, user_id
FROM api_keys ORDER BY id",
)?;
let keys = stmt
@@ -213,40 +253,63 @@ impl Db {
revoked: r.get(3)?,
is_super: r.get(4)?,
quota_id: r.get(5)?,
user_id: r.get(6)?,
})
})?
.collect::<Result<_, _>>()?;
Ok(keys)
}
pub fn revoke_key(&self, id: i64) -> Result<bool> {
pub fn revoke_key(&self, actor: &str, id: i64) -> Result<bool> {
let changed = self.conn().execute(
"UPDATE api_keys SET revoked_at = ?1 WHERE id = ?2 AND revoked_at IS NULL",
params![now(), id],
)?;
if changed > 0 {
self.audit("cli", "key.revoke", &format!("id={id}"))?;
self.audit(actor, "key.revoke", &format!("id={id}"))?;
}
Ok(changed > 0)
}
/// Prüft einen Key; widerrufene Keys gelten nicht.
pub fn authenticate(&self, key: &str) -> Result<Option<Caller>> {
Ok(self
/// Prüft einen Key. Widerrufene Keys gelten nicht, ebenso wenig Keys gesperrter oder
/// deaktivierter Benutzer; der Fehler nennt den Grund.
pub fn authenticate(&self, key: &str) -> Result<Result<Caller, &'static str>> {
type Row = (i64, bool, Option<i64>, Option<i64>, Option<String>, Option<String>, Option<bool>, Option<bool>);
let row: Option<Row> = self
.conn()
.query_row(
"SELECT id, is_super, quota_id FROM api_keys WHERE key_hash = ?1 AND revoked_at IS NULL",
"SELECT k.id, k.is_super, k.quota_id, k.user_id, u.username, u.role, u.active, u.blocked
FROM api_keys k LEFT JOIN users u ON u.id = k.user_id
WHERE k.key_hash = ?1 AND k.revoked_at IS NULL",
params![hash_key(key)],
|r| Ok(Caller { key_id: r.get(0)?, is_super: r.get(1)?, quota_id: r.get(2)? }),
|r| Ok((r.get(0)?, r.get(1)?, r.get(2)?, r.get(3)?, r.get(4)?, r.get(5)?, r.get(6)?, r.get(7)?)),
)
.optional()?)
.optional()?;
let Some((key_id, is_super, quota_id, user_id, username, role, active, blocked)) = row else {
return Ok(Err("ungültiger oder widerrufener API-Key"));
};
if blocked == Some(true) {
return Ok(Err("der Benutzer dieses Keys ist gesperrt"));
}
if active == Some(false) {
return Ok(Err("das Konto dieses Keys ist deaktiviert"));
}
let groups = match &username {
Some(name) => self.groups_of(name)?.into_iter().map(|g| g.id).collect(),
None => Vec::new(),
};
Ok(Ok(Caller { key_id, is_super, quota_id, user_id, is_admin: role.as_deref() == Some("admin"), groups }))
}
pub fn key(&self, id: i64) -> Result<Option<ApiKey>> {
Ok(self.list_keys()?.into_iter().find(|k| k.id == id))
}
pub fn record_usage(&self, u: &Usage) -> Result<()> {
self.conn().execute(
"INSERT INTO usage (ts, key_id, engine, model, path, status, prompt_tokens,
completion_tokens, duration_ms, quota_id)
VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10)",
completion_tokens, duration_ms, quota_id, user_id)
VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11)",
params![
now(),
u.key_id,
@@ -257,7 +320,8 @@ impl Db {
u.prompt_tokens,
u.completion_tokens,
u.duration_ms,
u.quota_id
u.quota_id,
u.user_id
],
)?;
Ok(())
@@ -293,7 +357,7 @@ impl Db {
Ok(())
}
pub fn add_schedule(&self, e: &Entry) -> Result<i64> {
pub fn add_schedule(&self, actor: &str, e: &Entry) -> Result<i64> {
let (days, start, end) = match &e.time.weekly {
Some(w) => (
Some(schedule::days_str(&w.days)),
@@ -304,7 +368,10 @@ impl Db {
};
let (node, engine, model, subjects) = match &e.kind {
Kind::Pin { node, engine, model } => (Some(node), Some(engine), Some(model), None),
Kind::Exclusive { keys } => (None, None, None, Some(serde_json::to_string(keys)?)),
Kind::Exclusive { keys, users, groups } => {
let subjects = serde_json::json!({ "keys": keys, "users": users, "groups": groups });
(None, None, None, Some(subjects.to_string()))
}
Kind::Window { models } => (None, None, None, Some(serde_json::to_string(models)?)),
};
let conn = self.conn();
@@ -330,7 +397,7 @@ impl Db {
let id = conn.last_insert_rowid();
drop(conn);
self.audit(
"cli",
actor,
"schedule.add",
&format!("id={id} {} {} {}", e.kind_name(), e.subject(), e.time.describe()),
)?;
@@ -384,7 +451,20 @@ impl Db {
engine: engine.unwrap_or_default(),
model: model.unwrap_or_default(),
},
"exklusiv" => Kind::Exclusive { keys: serde_json::from_str(&subjects)? },
"exklusiv" => {
// Früher eine Liste von Keys, jetzt Keys, Benutzer und Gruppen
let v: serde_json::Value = serde_json::from_str(&subjects)?;
let ids = |v: Option<&serde_json::Value>| -> Vec<i64> {
v.and_then(serde_json::Value::as_array)
.map(|a| a.iter().filter_map(serde_json::Value::as_i64).collect())
.unwrap_or_default()
};
if v.is_array() {
Kind::Exclusive { keys: ids(Some(&v)), users: Vec::new(), groups: Vec::new() }
} else {
Kind::Exclusive { keys: ids(v.get("keys")), users: ids(v.get("users")), groups: ids(v.get("groups")) }
}
}
"fenster" => Kind::Window { models: serde_json::from_str(&subjects)? },
other => anyhow::bail!("Zeitplan-Eintrag {id}: unbekannte Art {other}"),
};
@@ -400,15 +480,15 @@ impl Db {
Ok(list)
}
pub fn remove_schedule(&self, id: i64) -> Result<bool> {
pub fn remove_schedule(&self, actor: &str, id: i64) -> Result<bool> {
let changed = self.conn().execute("DELETE FROM schedule WHERE id = ?1", params![id])?;
if changed > 0 {
self.audit("cli", "schedule.remove", &format!("id={id}"))?;
self.audit(actor, "schedule.remove", &format!("id={id}"))?;
}
Ok(changed > 0)
}
pub fn set_key_quota(&self, key_id: i64, quota_id: Option<i64>) -> Result<()> {
pub fn set_key_quota(&self, actor: &str, key_id: i64, quota_id: Option<i64>) -> Result<()> {
if let Some(id) = quota_id
&& self.quota(id)?.is_none()
{
@@ -421,10 +501,10 @@ impl Db {
if changed == 0 {
bail!("kein Key mit ID {key_id}, oder es ist ein Super-Key");
}
self.audit("cli", "key.quota", &format!("id={key_id} quota={quota_id:?}"))
self.audit(actor, "key.quota", &format!("id={key_id} quota={quota_id:?}"))
}
pub fn create_quota(&self, q: &Quota) -> Result<i64> {
pub fn create_quota(&self, actor: &str, q: &Quota) -> Result<i64> {
let (days, start, end) = match &q.time.weekly {
Some(w) => (
Some(schedule::days_str(&w.days)),
@@ -442,23 +522,31 @@ impl Db {
let conn = self.conn();
conn.execute(
"INSERT INTO quotas (name, valid_from, valid_until, days, time_start, time_end, models,
tokens_hour, tokens_day, tokens_week, tokens_month, tokens_total, requests_hour, requests_day, requests_week, requests_month, requests_total, note, created_at)
VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13, ?14, ?15, ?16, ?17, ?18, ?19)",
tokens_hour, tokens_day, tokens_week, tokens_month, tokens_total, requests_hour, requests_day, requests_week, requests_month, requests_total, note, created_at,
owner_id, group_id, user_id)
VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13, ?14, ?15, ?16, ?17, ?18, ?19, ?20, ?21, ?22)",
params![
q.name, q.time.from, q.time.until, days, start, end, models, limits[0], limits[1], limits[2],
limits[3], limits[4], limits[5], limits[6], limits[7], limits[8], limits[9], q.note, now()
limits[3], limits[4], limits[5], limits[6], limits[7], limits[8], limits[9], q.note, now(),
q.owner_id, q.group_id, q.user_id
],
)?;
let id = conn.last_insert_rowid();
drop(conn);
self.audit("cli", "quota.create", &format!("id={id} {}: {}", q.name, q.describe()))?;
let target = match (q.group_id, q.user_id) {
(Some(g), _) => format!(" group={g}"),
(_, Some(u)) => format!(" user={u}"),
_ => String::new(),
};
self.audit(actor, "quota.create", &format!("id={id} {}{target}: {}", q.name, q.describe()))?;
Ok(id)
}
fn quotas_where(&self, filter: &str, args: &[&dyn rusqlite::ToSql]) -> Result<Vec<Quota>> {
let conn = self.conn();
let mut stmt = conn.prepare(&format!(
"SELECT id, name, valid_from, valid_until, days, time_start, time_end, models, tokens_hour, tokens_day, tokens_week, tokens_month, tokens_total, requests_hour, requests_day, requests_week, requests_month, requests_total, note
"SELECT id, name, valid_from, valid_until, days, time_start, time_end, models, tokens_hour, tokens_day, tokens_week, tokens_month, tokens_total, requests_hour, requests_day, requests_week, requests_month, requests_total, note,
owner_id, group_id, user_id
FROM quotas {filter} ORDER BY id"
))?;
let mut rows = stmt.query(args)?;
@@ -485,6 +573,9 @@ impl Db {
tokens,
requests,
note: r.get(18)?,
owner_id: r.get(19)?,
group_id: r.get(20)?,
user_id: r.get(21)?,
});
}
Ok(list)
@@ -499,7 +590,7 @@ impl Db {
}
/// Nur ein Kontingent, an dem keine Keys mehr hängen, kann entfernt werden.
pub fn remove_quota(&self, id: i64) -> Result<()> {
pub fn remove_quota(&self, actor: &str, id: i64) -> Result<()> {
let conn = self.conn();
let keys: i64 = conn.query_row("SELECT count(*) FROM api_keys WHERE quota_id = ?1", params![id], |r| r.get(0))?;
if keys > 0 {
@@ -510,21 +601,21 @@ impl Db {
}
conn.execute("DELETE FROM usage_counters WHERE scope = 'quota' AND scope_id = ?1", params![id])?;
drop(conn);
self.audit("cli", "quota.remove", &format!("id={id}"))
self.audit(actor, "quota.remove", &format!("id={id}"))
}
/// Verbrauch in den Zeiträumen, in die t fällt
fn counters(conn: &Connection, scope: Scope, t: DateTime<Local>) -> Result<Vec<(Period, Counter)>> {
let (scope, id) = scope.parts();
let (scope, id, user) = scope.parts();
let mut stmt = conn.prepare_cached(
"SELECT requests, prompt_tokens, completion_tokens FROM usage_counters
WHERE scope = ?1 AND scope_id = ?2 AND period = ?3",
WHERE scope = ?1 AND scope_id = ?2 AND user_id = ?3 AND period = ?4",
)?;
Period::ALL
.iter()
.map(|p| {
let c = stmt
.query_row(params![scope, id, p.key(t)], |r| {
.query_row(params![scope, id, user, p.key(t)], |r| {
Ok(Counter { requests: r.get(0)?, prompt_tokens: r.get(1)?, completion_tokens: r.get(2)? })
})
.optional()?
@@ -538,39 +629,61 @@ impl Db {
Self::counters(&self.conn(), scope, t)
}
/// Verbrauch eines Kontingents je Benutzer in einem Zeitraum
pub fn quota_usage_by_user(&self, quota_id: i64, period: Period, t: DateTime<Local>) -> Result<Vec<(i64, Counter)>> {
let conn = self.conn();
let mut stmt = conn.prepare(
"SELECT user_id, requests, prompt_tokens, completion_tokens FROM usage_counters
WHERE scope = 'quota' AND scope_id = ?1 AND period = ?2 ORDER BY user_id",
)?;
let rows = stmt
.query_map(params![quota_id, period.key(t)], |r| {
Ok((r.get(0)?, Counter { requests: r.get(1)?, prompt_tokens: r.get(2)?, completion_tokens: r.get(3)? }))
})?
.collect::<Result<_, _>>()?;
Ok(rows)
}
/// Addiert (oder bei negativen Werten subtrahiert) in allen Zeiträumen von t.
fn add(conn: &Connection, scope: Scope, t: DateTime<Local>, requests: i64, prompt: i64, completion: i64) -> Result<()> {
let (scope, id) = scope.parts();
let (scope, id, user) = scope.parts();
let mut stmt = conn.prepare_cached(
"INSERT INTO usage_counters (scope, scope_id, period, requests, prompt_tokens, completion_tokens)
VALUES (?1, ?2, ?3, ?4, ?5, ?6)
ON CONFLICT (scope, scope_id, period) DO UPDATE SET
"INSERT INTO usage_counters (scope, scope_id, user_id, period, requests, prompt_tokens, completion_tokens)
VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)
ON CONFLICT (scope, scope_id, user_id, period) DO UPDATE SET
requests = requests + excluded.requests,
prompt_tokens = prompt_tokens + excluded.prompt_tokens,
completion_tokens = completion_tokens + excluded.completion_tokens",
)?;
for p in Period::ALL {
stmt.execute(params![scope, id, p.key(t), requests, prompt, completion])?;
stmt.execute(params![scope, id, user, p.key(t), requests, prompt, completion])?;
}
Ok(())
}
fn scopes(key_id: i64, quota_id: Option<i64>) -> Vec<Scope> {
std::iter::once(Scope::Key(key_id)).chain(quota_id.map(Scope::Quota)).collect()
fn scopes(key_id: i64, user_id: Option<i64>, quota_id: Option<i64>) -> Vec<Scope> {
let user = user_id.unwrap_or(0);
std::iter::once(Scope::Key(key_id)).chain(quota_id.map(|q| Scope::Quota(q, user))).collect()
}
/// Prüft das Kontingent und zählt die Anfrage, in einer Transaktion, damit gleichzeitige
/// Anfragen die Grenzen nicht gemeinsam überschreiten. `quota` ist None für Keys ohne
/// Kontingent und für Super-Keys; gezählt wird beim Key trotzdem.
pub fn begin_request(&self, key_id: i64, quota: Option<&Quota>, t: DateTime<Local>) -> Result<Result<(), Denial>> {
pub fn begin_request(
&self,
key_id: i64,
user_id: Option<i64>,
quota: Option<&Quota>,
t: DateTime<Local>,
) -> Result<Result<(), Denial>> {
let mut conn = self.conn();
let tx = conn.transaction()?;
if let Some(q) = quota
&& let Err(denial) = q.check_usage(&Self::counters(&tx, Scope::Quota(q.id), t)?, t)
&& let Err(denial) = q.check_usage(&Self::counters(&tx, Scope::Quota(q.id, user_id.unwrap_or(0)), t)?, t)
{
return Ok(Err(denial));
}
for scope in Self::scopes(key_id, quota.map(|q| q.id)) {
for scope in Self::scopes(key_id, user_id, quota.map(|q| q.id)) {
Self::add(&tx, scope, t, 1, 0, 0)?;
}
tx.commit()?;
@@ -578,20 +691,28 @@ impl Db {
}
/// Nimmt eine gezählte Anfrage zurück, die die Engine nie erreicht hat (z. B. Modell nicht ladbar).
pub fn refund_request(&self, key_id: i64, quota_id: Option<i64>, t: DateTime<Local>) -> Result<()> {
pub fn refund_request(&self, key_id: i64, user_id: Option<i64>, quota_id: Option<i64>, t: DateTime<Local>) -> Result<()> {
let mut conn = self.conn();
let tx = conn.transaction()?;
for scope in Self::scopes(key_id, quota_id) {
for scope in Self::scopes(key_id, user_id, quota_id) {
Self::add(&tx, scope, t, -1, 0, 0)?;
}
Ok(tx.commit()?)
}
/// Bucht die Token einer beendeten Anfrage in die Zeiträume ihres Beginns.
pub fn book_tokens(&self, key_id: i64, quota_id: Option<i64>, t: DateTime<Local>, prompt: u64, completion: u64) -> Result<()> {
pub fn book_tokens(
&self,
key_id: i64,
user_id: Option<i64>,
quota_id: Option<i64>,
t: DateTime<Local>,
prompt: u64,
completion: u64,
) -> Result<()> {
let mut conn = self.conn();
let tx = conn.transaction()?;
for scope in Self::scopes(key_id, quota_id) {
for scope in Self::scopes(key_id, user_id, quota_id) {
Self::add(&tx, scope, t, 0, prompt as i64, completion as i64)?;
}
Ok(tx.commit()?)
@@ -599,13 +720,23 @@ impl Db {
/// Löscht Einzeleinträge der Nutzung, die älter als `days` Tage sind. Die Zähler der
/// Kontingente und Keys bleiben unberührt.
pub fn prune_usage(&self, days: u32) -> Result<usize> {
pub fn prune_usage(&self, actor: &str, days: u32) -> Result<usize> {
let cutoff = now() - i64::from(days) * 86_400;
let deleted = self.conn().execute("DELETE FROM usage WHERE ts < ?1", params![cutoff])?;
self.audit("cli", "usage.prune", &format!("older_than_days={days} deleted={deleted}"))?;
self.audit(actor, "usage.prune", &format!("older_than_days={days} deleted={deleted}"))?;
Ok(deleted)
}
/// Die letzten Einträge des Audit-Logs, neueste zuerst
pub fn audit_log(&self, limit: u32) -> Result<Vec<(i64, String, String, String)>> {
let conn = self.conn();
let mut stmt = conn.prepare("SELECT ts, actor, action, detail FROM audit_log ORDER BY id DESC LIMIT ?1")?;
let rows = stmt
.query_map(params![limit], |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?, r.get(3)?)))?
.collect::<Result<_, _>>()?;
Ok(rows)
}
pub fn audit(&self, actor: &str, action: &str, detail: &str) -> Result<()> {
self.conn().execute(
"INSERT INTO audit_log (ts, actor, action, detail) VALUES (?1, ?2, ?3, ?4)",
@@ -632,6 +763,37 @@ fn migrate(conn: &Connection) -> Result<()> {
if !has_column(conn, "usage", "quota_id")? {
conn.execute("ALTER TABLE usage ADD COLUMN quota_id INTEGER", [])?;
}
if !has_column(conn, "usage", "user_id")? {
conn.execute("ALTER TABLE usage ADD COLUMN user_id INTEGER", [])?;
}
if !has_column(conn, "api_keys", "user_id")? {
conn.execute("ALTER TABLE api_keys ADD COLUMN user_id INTEGER REFERENCES users(id)", [])?;
}
for column in ["owner_id", "group_id", "user_id"] {
if !has_column(conn, "quotas", column)? {
conn.execute(&format!("ALTER TABLE quotas ADD COLUMN {column} INTEGER"), [])?;
}
}
// Die Zähler bekamen mit den Gruppenkontingenten eine Spalte für den Benutzer, die zum
// Primärschlüssel gehört; SQLite kann den nur durch Neuanlegen ändern.
if !has_column(conn, "usage_counters", "user_id")? {
conn.execute_batch(
"ALTER TABLE usage_counters RENAME TO usage_counters_old;
CREATE TABLE usage_counters (
scope TEXT NOT NULL,
scope_id INTEGER NOT NULL,
user_id INTEGER NOT NULL DEFAULT 0,
period TEXT NOT NULL,
requests INTEGER NOT NULL DEFAULT 0,
prompt_tokens INTEGER NOT NULL DEFAULT 0,
completion_tokens INTEGER NOT NULL DEFAULT 0,
PRIMARY KEY (scope, scope_id, user_id, period)
);
INSERT INTO usage_counters (scope, scope_id, user_id, period, requests, prompt_tokens, completion_tokens)
SELECT scope, scope_id, 0, period, requests, prompt_tokens, completion_tokens FROM usage_counters_old;
DROP TABLE usage_counters_old;",
)?;
}
// Pins lagen bis zum gemeinsamen Zeitplan in einer eigenen Tabelle.
let has_pins: bool = conn.query_row(
"SELECT count(*) > 0 FROM sqlite_master WHERE type = 'table' AND name = 'pins'",