Spaces:
Running
Running
Delete security.py
Browse files- security.py +0 -35
security.py
DELETED
|
@@ -1,35 +0,0 @@
|
|
| 1 |
-
"""API-key authentication (per tenant). Keys are only ever held as SHA-256 digests in memory."""
|
| 2 |
-
from __future__ import annotations
|
| 3 |
-
|
| 4 |
-
import hashlib
|
| 5 |
-
import hmac
|
| 6 |
-
import secrets
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
def hash_key(key: str) -> str:
|
| 10 |
-
return hashlib.sha256(key.encode()).hexdigest()
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
def generate_key() -> str:
|
| 14 |
-
"""URL-safe random key with 256 bits of entropy."""
|
| 15 |
-
return "wade_" + secrets.token_urlsafe(32)
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
class ApiKeyStore:
|
| 19 |
-
def __init__(self, keys: dict[str, str] | None = None):
|
| 20 |
-
# digest -> tenant
|
| 21 |
-
self._by_digest: dict[str, str] = {hash_key(k): t for k, t in (keys or {}).items()}
|
| 22 |
-
|
| 23 |
-
def __bool__(self) -> bool:
|
| 24 |
-
return bool(self._by_digest)
|
| 25 |
-
|
| 26 |
-
def authenticate(self, presented: str | None) -> str | None:
|
| 27 |
-
"""Return the tenant for a valid key, else None. Comparison is constant-time."""
|
| 28 |
-
if not presented or len(presented) > 256:
|
| 29 |
-
return None
|
| 30 |
-
digest = hash_key(presented)
|
| 31 |
-
found = None
|
| 32 |
-
for known, tenant in self._by_digest.items(): # iterate all: no early exit
|
| 33 |
-
if hmac.compare_digest(known, digest):
|
| 34 |
-
found = tenant
|
| 35 |
-
return found
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|