wade-ips / app /security.py
Reaper1909's picture
Upload 13 files
56b30f7 verified
Raw History Blame Contribute Delete
1.14 kB
"""API-key authentication (per tenant). Keys are only ever held as SHA-256 digests in memory."""
from __future__ import annotations
import hashlib
import hmac
import secrets
def hash_key(key: str) -> str:
return hashlib.sha256(key.encode()).hexdigest()
def generate_key() -> str:
"""URL-safe random key with 256 bits of entropy."""
return "wade_" + secrets.token_urlsafe(32)
class ApiKeyStore:
def __init__(self, keys: dict[str, str] | None = None):
# digest -> tenant
self._by_digest: dict[str, str] = {hash_key(k): t for k, t in (keys or {}).items()}
def __bool__(self) -> bool:
return bool(self._by_digest)
def authenticate(self, presented: str | None) -> str | None:
"""Return the tenant for a valid key, else None. Comparison is constant-time."""
if not presented or len(presented) > 256:
return None
digest = hash_key(presented)
found = None
for known, tenant in self._by_digest.items(): # iterate all: no early exit
if hmac.compare_digest(known, digest):
found = tenant
return found