Spaces:
Paused
Paused
Download core/token_blocklist.py from 3SCError404/miracle: direct link, hf CLI and curl.
- Browser
- Download file 4.04 kB
-
https://huggingface.co/spaces/3SCError404/miracle/resolve/main/core/token_blocklist.py
- Command line
-
hf download hf://spaces/3SCError404/miracle/core/token_blocklist.py
-
curl -L -o token_blocklist.py https://huggingface.co/spaces/3SCError404/miracle/resolve/main/core/token_blocklist.py
4.04 kB
| """ | |
| Redis-backed JWT token blocklist for real logout and token revocation. | |
| Uses the local Docker Redis (CACHE_REDIS_URL, port 6380) to store revoked | |
| token JTI claims with automatic TTL expiry matching the token's remaining lifetime. | |
| Usage: | |
| from core.token_blocklist import blocklist_token, is_token_blocked | |
| # On logout: | |
| await blocklist_token(jti="abc-123", expires_in_seconds=1800) | |
| # In auth dependency: | |
| if await is_token_blocked(jti): | |
| raise HTTPException(401, "Token has been revoked") | |
| """ | |
| import redis.asyncio as aioredis | |
| import time | |
| from core.config import get_settings | |
| from core.logging import get_logger | |
| logger = get_logger(__name__) | |
| _redis_client: aioredis.Redis | None = None | |
| _BLOCKLIST_PREFIX = "nexus:token:blocked:" | |
| async def _get_redis() -> aioredis.Redis: | |
| """Lazily initializes and returns the shared Redis client.""" | |
| from core.cache import get_redis_client | |
| return get_redis_client() | |
| async def blocklist_token(jti: str, expires_in_seconds: int) -> bool: | |
| """ | |
| Add a token's JTI to the blocklist with automatic expiry. | |
| Args: | |
| jti: The JWT ID claim from the token. | |
| expires_in_seconds: TTL matching the token's remaining lifetime. | |
| After this time, the entry is automatically removed (token would | |
| have expired naturally anyway). | |
| Returns: | |
| True if successfully blocklisted, False on Redis failure. | |
| """ | |
| try: | |
| r = await _get_redis() | |
| key = f"{_BLOCKLIST_PREFIX}{jti}" | |
| await r.setex(key, expires_in_seconds, "revoked") | |
| logger.info(f"Token blocklisted: {jti[:8]}... (TTL: {expires_in_seconds}s)") | |
| _set_blocklist_cache(jti, True, min(expires_in_seconds, 300)) | |
| return True | |
| except Exception as e: | |
| logger.error(f"Failed to blocklist token {jti[:8]}... via Redis: {e}") | |
| # Degrade gracefully: write to in-memory cache so the revocation is honoured | |
| # for at least the remaining lifetime of this process (up to 5 minutes). | |
| _set_blocklist_cache(jti, True, min(expires_in_seconds, 300)) | |
| logger.warning(f"Token {jti[:8]}... added to in-memory blocklist only (Redis unavailable).") | |
| return False | |
| _blocklist_cache = {} | |
| MAX_BLOCKLIST_CACHE_SIZE = 5000 | |
| def _set_blocklist_cache(jti: str, val: bool, ttl: int): | |
| global _blocklist_cache | |
| if len(_blocklist_cache) >= MAX_BLOCKLIST_CACHE_SIZE: | |
| # Clear 10% of cache if full | |
| for _ in range(MAX_BLOCKLIST_CACHE_SIZE // 10): | |
| if _blocklist_cache: | |
| it = iter(_blocklist_cache) | |
| del _blocklist_cache[next(it)] | |
| _blocklist_cache[jti] = (val, time.time() + ttl) | |
| async def is_token_blocked(jti: str) -> bool: | |
| """ | |
| Check if a token's JTI has been revoked. | |
| Uses a local 60s memory cache to prevent pounding Redis on every API call. | |
| """ | |
| if not jti: | |
| return False | |
| now = time.time() | |
| # Check L1 Cache | |
| if jti in _blocklist_cache: | |
| cached_val, expiry = _blocklist_cache[jti] | |
| if now < expiry: | |
| return cached_val | |
| try: | |
| r = await _get_redis() | |
| key = f"{_BLOCKLIST_PREFIX}{jti}" | |
| result = await r.exists(key) | |
| blocked = bool(result) | |
| # Non-blocked tokens are cached longer — they almost never become blocked mid-session. | |
| # Blocked tokens use a short TTL so revocations propagate quickly. | |
| _set_blocklist_cache(jti, blocked, 60 if blocked else 300) | |
| return blocked | |
| except Exception as e: | |
| # Fail-open: if Redis is down, do NOT block all users | |
| logger.error(f"Token blocklist check failed (fail-open): {e}") | |
| return False | |
| async def close_blocklist_redis(): | |
| """Gracefully close the shared Redis connection on shutdown.""" | |
| from core import cache as _cache_module | |
| client = _cache_module._redis_client | |
| if client: | |
| await client.aclose() | |
| _cache_module._redis_client = None | |
| logger.info("Token blocklist Redis connection closed.") | |