Spaces:
3SCError404
/
Paused

nexus / core /token_blocklist.py
dushyantsingh0
backend stabilization
b7980f7
Raw History Blame Contribute Delete
3.01 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
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 Redis client for the token blocklist."""
global _redis_client
if _redis_client is None:
settings = get_settings()
_redis_client = aioredis.from_url(
settings.CACHE_REDIS_URL,
decode_responses=True,
socket_connect_timeout=5,
retry_on_timeout=True,
)
logger.info(f"Token blocklist Redis connected: {settings.CACHE_REDIS_URL}")
return _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)")
return True
except Exception as e:
logger.error(f"Failed to blocklist token {jti[:8]}...: {e}")
return False
async def is_token_blocked(jti: str) -> bool:
"""
Check if a token's JTI has been revoked.
Returns:
True if the token is blocklisted, False otherwise.
Returns False on Redis failure (fail-open to prevent lockout).
"""
if not jti:
return False
try:
r = await _get_redis()
key = f"{_BLOCKLIST_PREFIX}{jti}"
result = await r.exists(key)
return bool(result)
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 Redis connection on shutdown."""
global _redis_client
if _redis_client:
await _redis_client.close()
_redis_client = None
logger.info("Token blocklist Redis connection closed.")