SPB Git

Repository Public

security.py 3.4 KB 98 lines python

1# =============================================================================2#                  SP BOUCHER | INFRASTRUCTURE & AUTOMATION3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# Project          : MacLustr LLM API7# File             : src/maclustr_llm/security.py8# Description      : Primitives : secret serveur, condensats HMAC, jetons9#                    aléatoires, format des clés API.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"""Primitives : secret serveur, condensats HMAC, jetons aléatoires, format des clés API."""4243from __future__ import annotations4445import hashlib46import hmac47import os48import secrets49from pathlib import Path5051KEY_PREFIX = "mlx_sk_"525354def load_or_create_secret(path: Path) -> bytes:55    """Poivre serveur (32 octets, mode 600, hors dépôt). Sert aux condensats HMAC des clés et jetons."""56    if path.exists():57        data = path.read_bytes()58        if len(data) < 32:59            raise RuntimeError(f"secret serveur invalide : {path}")60        return data61    path.parent.mkdir(parents=True, exist_ok=True)62    data = secrets.token_bytes(32)63    fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)64    with os.fdopen(fd, "wb") as fh:65        fh.write(data)66    return data676869class Hasher:70    """HMAC-SHA-256 à clé serveur. Les secrets hachés ici sont aléatoires (≥ 256 bits) :71    un condensat rapide à clé suffit, un KDF lent n'apporterait rien."""7273    def __init__(self, secret: bytes) -> None:74        self._secret = secret7576    def digest(self, purpose: str, value: str | bytes) -> str:77        raw = value.encode() if isinstance(value, str) else value78        return hmac.new(self._secret, purpose.encode() + b"\x00" + raw, hashlib.sha256).hexdigest()798081def new_token(nbytes: int = 32) -> str:82    return secrets.token_urlsafe(nbytes)838485def new_id(prefix: str) -> str:86    return f"{prefix}_{secrets.token_hex(8)}"878889def new_api_key() -> tuple[str, str]:90    """Retourne (clé complète, préfixe affichable). Le secret n'est jamais stocké."""91    public = secrets.token_hex(4)92    secret = secrets.token_urlsafe(32)93    return f"{KEY_PREFIX}{public}_{secret}", f"{KEY_PREFIX}{public}"949596def constant_eq(a: str, b: str) -> bool:97    return hmac.compare_digest(a.encode(), b.encode())98
Files main
Menu

Theme