SPB Git

Repository Public

keys.py 12.1 KB 337 lines python

1# =============================================================================2#                  SP BOUCHER | INFRASTRUCTURE & AUTOMATION3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# Project          : MacLustr LLM API7# File             : src/maclustr_llm/keys.py8# Description      : Clés API : création, rotation, révocation, résolution9#                    (cache mémoire invalidé à chaque écriture).10# Module           : maclustr_llm11# Repository       : https://git.spboucher.ai/maclustr-llm12# Created          : 2026-11-1913# Last Modified    : 2026-11-1914#15# Author           : Simon-Pierre Boucher16# Position         : Professor of Finance17# Institution      : Université du Québec en Outaouais (UQO)18# Organization     : SP Boucher19# Website          : https://spboucher.ai20# Git              : https://git.spboucher.ai21#22# Preferred Contact: admin@spboucher.ai23# Technical Contact: dev@spboucher.ai24# Security/Admin   : admin@spboucher.ai25#26# Copyright (c) 202627# Simon-Pierre Boucher28# All rights reserved where applicable. This file is governed by the29# applicable project license, copyright notices and relevant law.30# Existing third-party rights and notices remain unaffected.31#32# License          : None specified (no license file in this repository)33#34# Do not embed credentials, private keys, access tokens,35# certificates or confidential personal information.36#37# =============================================================================38# END OF SP BOUCHER SOURCE HEADER39# =============================================================================4041"""Clés API : création, rotation, révocation, résolution (cache mémoire invalidé à chaque écriture)."""4243from __future__ import annotations4445import json46import sqlite347import time48from dataclasses import dataclass49from typing import Any5051from .db import Database52from .security import KEY_PREFIX, Hasher, new_api_key, new_id5354PRIORITIES = ("admin", "internal", "client", "background")55ENDPOINTS = ("chat.completions", "completions", "models")565758@dataclass(frozen=True)59class Principal:60    """Identité d'un appelant : une clé API, ou la session administrateur (Playground)."""6162    key_id: str63    name: str64    app: str65    priority: str66    models: tuple[str, ...]67    endpoints: tuple[str, ...]68    rpm: int69    tpm: int70    daily_tokens: int71    monthly_tokens: int72    max_concurrency: int7374    def allows_model(self, model: str) -> bool:75        return "*" in self.models or model in self.models7677    def allows_endpoint(self, endpoint: str) -> bool:78        return "*" in self.endpoints or endpoint in self.endpoints798081ADMIN_PRINCIPAL = Principal(82    key_id="admin-session",83    name="Administrateur",84    app="Dashboard",85    priority="admin",86    models=("*",),87    endpoints=("*",),88    rpm=0,89    tpm=0,90    daily_tokens=0,91    monthly_tokens=0,92    max_concurrency=8,93)949596def _validate(fields: dict[str, Any], known_models: set[str]) -> dict[str, Any]:97    out: dict[str, Any] = {}98    if "name" in fields:99        name = str(fields["name"]).strip()100        if not 1 <= len(name) <= 80:101            raise ValueError("name : 1 à 80 caractères")102        out["name"] = name103    if "app" in fields:104        out["app"] = str(fields["app"] or "").strip()[:80]105    if "priority" in fields:106        if fields["priority"] not in PRIORITIES:107            raise ValueError(f"priority : une de {', '.join(PRIORITIES)}")108        out["priority"] = fields["priority"]109    if "models" in fields:110        models = list(fields["models"] or ["*"])111        for m in models:112            if m != "*" and m not in known_models:113                raise ValueError(f"modèle inconnu : {m}")114        out["models"] = json.dumps(models)115    if "endpoints" in fields:116        eps = list(fields["endpoints"] or ["*"])117        for e in eps:118            if e != "*" and e not in ENDPOINTS:119                raise ValueError(f"endpoint inconnu : {e}")120        out["endpoints"] = json.dumps(eps)121    for name_, lo, hi in (122        ("rpm", 0, 100_000),123        ("tpm", 0, 100_000_000),124        ("daily_tokens", 0, 10**12),125        ("monthly_tokens", 0, 10**13),126        ("max_concurrency", 1, 64),127    ):128        if name_ in fields:129            v = int(fields[name_])130            if not lo <= v <= hi:131                raise ValueError(f"{name_} : entre {lo} et {hi}")132            out[name_] = v133    if "expires_at" in fields:134        exp = fields["expires_at"]135        if exp is not None:136            exp = int(exp)137            if exp <= int(time.time()):138                raise ValueError("expires_at doit être dans le futur")139        out["expires_at"] = exp140    if "disabled" in fields:141        out["disabled"] = 1 if fields["disabled"] else 0142    return out143144145def _row_public(r: sqlite3.Row) -> dict[str, Any]:146    now = int(time.time())147    status = "active"148    if r["revoked_at"]:149        status = "revoked"150    elif r["disabled"]:151        status = "disabled"152    elif r["expires_at"] and r["expires_at"] <= now:153        status = "expired"154    return {155        "id": r["id"],156        "name": r["name"],157        "app": r["app"],158        "prefix": r["prefix"],159        "priority": r["priority"],160        "models": json.loads(r["models"]),161        "endpoints": json.loads(r["endpoints"]),162        "rpm": r["rpm"],163        "tpm": r["tpm"],164        "daily_tokens": r["daily_tokens"],165        "monthly_tokens": r["monthly_tokens"],166        "max_concurrency": r["max_concurrency"],167        "expires_at": r["expires_at"],168        "disabled": bool(r["disabled"]),169        "created_at": r["created_at"],170        "revoked_at": r["revoked_at"],171        "last_used_at": r["last_used_at"],172        "rotated_from": r["rotated_from"],173        "status": status,174    }175176177class KeyService:178    def __init__(self, db: Database, hasher: Hasher, known_models: set[str]) -> None:179        self.db = db180        self.hasher = hasher181        self.known_models = known_models182        self._cache: dict[str, Principal | None] = {}183        self._last_used: dict[str, int] = {}184        self._expiry: dict[str, int | None] = {}185186    def _hash(self, key: str) -> str:187        return self.hasher.digest("api-key", key)188189    def invalidate(self) -> None:190        self._cache.clear()191192    async def create(self, fields: dict[str, Any], rotated_from: str | None = None) -> tuple[dict[str, Any], str]:193        if "name" not in fields:194            raise ValueError("name requis")195        data = _validate(fields, self.known_models)196        key, prefix = new_api_key()197        kid = new_id("key")198        cols = {199            "id": kid,200            "prefix": prefix,201            "key_hash": self._hash(key),202            "created_at": int(time.time()),203            "rotated_from": rotated_from,204            **data,205        }206207        def op(conn: sqlite3.Connection) -> sqlite3.Row:208            conn.execute(209                f"INSERT INTO api_keys ({', '.join(cols)}) VALUES ({', '.join('?' for _ in cols)})",210                tuple(cols.values()),211            )212            row: sqlite3.Row = conn.execute("SELECT * FROM api_keys WHERE id=?", (kid,)).fetchone()213            return row214215        row = await self.db.run(op)216        self.invalidate()217        return _row_public(row), key218219    async def update(self, kid: str, fields: dict[str, Any]) -> dict[str, Any] | None:220        data = _validate(fields, self.known_models)221222        def op(conn: sqlite3.Connection) -> sqlite3.Row | None:223            if data:224                conn.execute(225                    f"UPDATE api_keys SET {', '.join(f'{k}=?' for k in data)} WHERE id=? AND revoked_at IS NULL",226                    (*data.values(), kid),227                )228            row: sqlite3.Row | None = conn.execute("SELECT * FROM api_keys WHERE id=?", (kid,)).fetchone()229            return row230231        row = await self.db.run(op)232        self.invalidate()233        return _row_public(row) if row else None234235    async def revoke(self, kid: str) -> bool:236        def op(conn: sqlite3.Connection) -> bool:237            cur = conn.execute(238                "UPDATE api_keys SET revoked_at=? WHERE id=? AND revoked_at IS NULL", (int(time.time()), kid)239            )240            return cur.rowcount > 0241242        ok = await self.db.run(op)243        self.invalidate()244        return ok245246    async def rotate(self, kid: str) -> tuple[dict[str, Any], str] | None:247        """Nouvelle clé aux mêmes droits ; l'ancienne est révoquée dans la même transaction."""248        key, prefix = new_api_key()249        new_kid = new_id("key")250        now = int(time.time())251252        def op(conn: sqlite3.Connection) -> sqlite3.Row | None:253            old = conn.execute("SELECT * FROM api_keys WHERE id=? AND revoked_at IS NULL", (kid,)).fetchone()254            if old is None:255                return None256            conn.execute(257                """INSERT INTO api_keys (id, name, app, prefix, key_hash, priority, models, endpoints, rpm, tpm,258                   daily_tokens, monthly_tokens, max_concurrency, expires_at, disabled, created_at, rotated_from)259                   VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)""",260                (261                    new_kid,262                    old["name"],263                    old["app"],264                    prefix,265                    self._hash(key),266                    old["priority"],267                    old["models"],268                    old["endpoints"],269                    old["rpm"],270                    old["tpm"],271                    old["daily_tokens"],272                    old["monthly_tokens"],273                    old["max_concurrency"],274                    old["expires_at"],275                    old["disabled"],276                    now,277                    kid,278                ),279            )280            conn.execute("UPDATE api_keys SET revoked_at=? WHERE id=?", (now, kid))281            row: sqlite3.Row = conn.execute("SELECT * FROM api_keys WHERE id=?", (new_kid,)).fetchone()282            return row283284        row = await self.db.tx(op)285        self.invalidate()286        return (_row_public(row), key) if row else None287288    async def list(self) -> list[dict[str, Any]]:289        rows = await self.db.run(290            lambda c: c.execute("SELECT * FROM api_keys ORDER BY revoked_at IS NOT NULL, created_at DESC").fetchall()291        )292        return [_row_public(r) for r in rows]293294    async def get(self, kid: str) -> dict[str, Any] | None:295        row = await self.db.run(lambda c: c.execute("SELECT * FROM api_keys WHERE id=?", (kid,)).fetchone())296        return _row_public(row) if row else None297298    async def resolve(self, key: str) -> Principal | None:299        """Clé présentée → Principal, ou None (inconnue, révoquée, désactivée, expirée)."""300        if not key.startswith(KEY_PREFIX) or len(key) > 128:301            return None302        h = self._hash(key)303        if h in self._cache:304            p = self._cache[h]305        else:306            row = await self.db.run(lambda c: c.execute("SELECT * FROM api_keys WHERE key_hash=?", (h,)).fetchone())307            p = None308            if row is not None and not row["revoked_at"] and not row["disabled"]:309                p = Principal(310                    key_id=row["id"],311                    name=row["name"],312                    app=row["app"],313                    priority=row["priority"],314                    models=tuple(json.loads(row["models"])),315                    endpoints=tuple(json.loads(row["endpoints"])),316                    rpm=row["rpm"],317                    tpm=row["tpm"],318                    daily_tokens=row["daily_tokens"],319                    monthly_tokens=row["monthly_tokens"],320                    max_concurrency=row["max_concurrency"],321                )322                self._expiry[p.key_id] = row["expires_at"]323            if len(self._cache) > 4096:324                self._cache.clear()325            self._cache[h] = p326        if p is None:327            return None328        exp = self._expiry.get(p.key_id)329        if exp and exp <= time.time():330            return None331        now = int(time.time())332        if now - self._last_used.get(p.key_id, 0) >= 60:333            self._last_used[p.key_id] = now334            kid = p.key_id335            await self.db.run(lambda c: c.execute("UPDATE api_keys SET last_used_at=? WHERE id=?", (now, kid)))336        return p337
Files main
Menu

Theme