revocation_cache.py
python
| 1 | """ |
| 2 | In-memory token revocation cache. |
| 3 | |
| 4 | Reduces DB hits on every authenticated request. Cache key is token hash; |
| 5 | value is whether the token is revoked. TTL is configurable; on revoke |
| 6 | we clear the cache so revocation is visible on the next request. |
| 7 | """ |
| 8 | from __future__ import annotations |
| 9 | |
| 10 | import time |
| 11 | |
| 12 | from musehub.config import settings |
| 13 | |
| 14 | # token_hash -> (revoked: bool, expires_at: float) |
| 15 | _cache: dict[str, tuple[bool, float]] = {} |
| 16 | |
| 17 | |
| 18 | def get_revocation_status(token_hash: str) -> bool | None: |
| 19 | """ |
| 20 | Return cached revocation status if present and not expired. |
| 21 | |
| 22 | Returns: |
| 23 | True if cached as revoked, False if cached as valid, None if miss or expired. |
| 24 | """ |
| 25 | entry = _cache.get(token_hash) |
| 26 | if entry is None: |
| 27 | return None |
| 28 | revoked, expires_at = entry |
| 29 | if time.monotonic() > expires_at: |
| 30 | del _cache[token_hash] |
| 31 | return None |
| 32 | return revoked |
| 33 | |
| 34 | |
| 35 | def set_revocation_status(token_hash: str, revoked: bool) -> None: |
| 36 | """Cache revocation status for token_hash for the configured TTL.""" |
| 37 | ttl = settings.token_revocation_cache_ttl_seconds |
| 38 | _cache[token_hash] = (revoked, time.monotonic() + ttl) |
| 39 | |
| 40 | |
| 41 | def clear_revocation_cache() -> None: |
| 42 | """Clear the entire cache. Call after revoking token(s) so next request sees DB state.""" |
| 43 | _cache.clear() |