feat(phase-34): resolve blocking tech debt — Redis, domain exceptions, indexes, CI
Some checks failed
Aegis CI / lint-and-test (push) Has been cancelled
Some checks failed
Aegis CI / lint-and-test (push) Has been cancelled
Foundational changes required before any new feature work can begin. - 0.1 Redis infrastructure: add redis:7-alpine to docker-compose dev and prod, REDIS_URL config, singleton client in app/infrastructure/redis_client.py - 0.2 Token blacklist on Redis SEC-001: replace in-memory dict with Redis SETEX keyed by jti, auto-expiring TTL derived from token exp - 0.3 Database indexes SR-006: Alembic migration b019 with 5 composite indexes for scoring, MTTD/MTTR, remediation, and notification queries - 0.4 Domain exceptions TD-003: app/domain/exceptions.py with typed errors, error_handler middleware mapping them to HTTP, services decoupled from FastAPI - 0.5 Fix silenced exceptions TD-007: replace 4 bare except-pass blocks in test_workflow_service with logger.warning with exc_info - 0.6 CI pipeline TD-009: GitHub Actions workflow with Postgres and Redis service containers, ruff lint, pytest; ruff.toml for baseline config
This commit is contained in:
@@ -4,12 +4,12 @@ Security utilities: password hashing and JWT token management.
|
||||
This module provides pure functions for:
|
||||
- Hashing and verifying passwords using bcrypt via passlib.
|
||||
- Creating JWT access tokens using python-jose.
|
||||
- Managing an in-memory token blacklist for revocation.
|
||||
- Managing a Redis-backed token blacklist for revocation.
|
||||
|
||||
No endpoints are defined here.
|
||||
"""
|
||||
|
||||
import threading
|
||||
import logging
|
||||
import uuid as _uuid
|
||||
from datetime import datetime, timedelta, timezone
|
||||
|
||||
@@ -18,6 +18,8 @@ from passlib.context import CryptContext
|
||||
|
||||
from app.config import settings
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Password hashing
|
||||
# ---------------------------------------------------------------------------
|
||||
@@ -58,36 +60,43 @@ def create_access_token(data: dict) -> str:
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Token blacklist (in-memory)
|
||||
# Token blacklist (Redis-backed)
|
||||
# ---------------------------------------------------------------------------
|
||||
# Stores (jti, expiry_timestamp) tuples. Entries are automatically purged
|
||||
# once they are past their original expiry (the token would be invalid
|
||||
# anyway at that point). Thread-safe via a simple lock.
|
||||
# Each revoked token's ``jti`` is stored in Redis with a TTL equal to the
|
||||
# token's remaining lifetime. This means entries auto-expire exactly when
|
||||
# the token would have become invalid anyway — no manual cleanup needed.
|
||||
#
|
||||
# For multi-worker / multi-process deployments, consider replacing this
|
||||
# with a shared store like Redis.
|
||||
# Redis survives backend restarts, so blacklisted tokens stay revoked
|
||||
# across deploys and multi-worker setups.
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
_blacklist: dict[str, float] = {} # jti → expiry epoch
|
||||
_blacklist_lock = threading.Lock()
|
||||
_BLACKLIST_PREFIX = "blacklist:"
|
||||
|
||||
|
||||
def blacklist_token(jti: str, exp: float) -> None:
|
||||
"""Add *jti* to the blacklist until it naturally expires at *exp*."""
|
||||
with _blacklist_lock:
|
||||
_blacklist[jti] = exp
|
||||
_cleanup_blacklist()
|
||||
"""Add *jti* to the Redis blacklist with a TTL derived from *exp*.
|
||||
|
||||
*exp* is the token's ``exp`` claim (epoch timestamp). The TTL is set
|
||||
to ``exp - now`` so the key vanishes when the token would have expired
|
||||
naturally.
|
||||
"""
|
||||
from app.infrastructure.redis_client import get_redis
|
||||
|
||||
ttl = max(int(exp - datetime.now(timezone.utc).timestamp()), 1)
|
||||
try:
|
||||
r = get_redis()
|
||||
r.setex(f"{_BLACKLIST_PREFIX}{jti}", ttl, "1")
|
||||
except Exception:
|
||||
logger.warning("Failed to blacklist token %s in Redis", jti, exc_info=True)
|
||||
|
||||
|
||||
def is_token_blacklisted(jti: str) -> bool:
|
||||
"""Return ``True`` if *jti* has been revoked."""
|
||||
with _blacklist_lock:
|
||||
return jti in _blacklist
|
||||
"""Return ``True`` if *jti* has been revoked (exists in Redis)."""
|
||||
from app.infrastructure.redis_client import get_redis
|
||||
|
||||
|
||||
def _cleanup_blacklist() -> None:
|
||||
"""Remove entries whose tokens have already expired (caller holds lock)."""
|
||||
now = datetime.now(timezone.utc).timestamp()
|
||||
expired = [k for k, exp in _blacklist.items() if exp < now]
|
||||
for k in expired:
|
||||
del _blacklist[k]
|
||||
try:
|
||||
r = get_redis()
|
||||
return r.exists(f"{_BLACKLIST_PREFIX}{jti}") > 0
|
||||
except Exception:
|
||||
logger.warning("Failed to check blacklist for %s in Redis", jti, exc_info=True)
|
||||
return False
|
||||
|
||||
Reference in New Issue
Block a user