Spaces:
Running
Running
Download app/security.py from Reaper1909/wade-ips: direct link, hf CLI and curl.
- Browser
- Download file 1.14 kB
-
https://huggingface.co/spaces/Reaper1909/wade-ips/resolve/main/app/security.py
- Command line
-
hf download hf://spaces/Reaper1909/wade-ips/app/security.py
-
curl -L -o security.py https://huggingface.co/spaces/Reaper1909/wade-ips/resolve/main/app/security.py
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 | |