Spaces:
Paused

File size: 3,008 Bytes
b7980f7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
"""
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.")