import asyncio from datetime import UTC, datetime, timedelta import hashlib import time from typing import Any, Optional from uuid import uuid4 import bcrypt from fastapi import Depends, HTTPException, status from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer from jose import JWTError, jwt import redis import redis.asyncio as aioredis from sqlalchemy import select from sqlalchemy.ext.asyncio import AsyncSession from app.core.config import settings from app.core.logging import get_logger from app.db.session import get_db from app.models.user import User logger = get_logger(__name__, service="security") oauth2_scheme = HTTPBearer() REVOKED_KEY_PREFIX = "revoked_jwt:" LOCAL_REVOKED_MAX_ENTRIES = 10_000 REDIS_OP_TIMEOUT_SECONDS = 1.5 _LOCAL_REVOKED_TOKENS: dict[str, float] = {} class _RedisClient: _client = None @classmethod def get_client(cls): if cls._client is None: redis_url = settings.REDIS_URL if redis_url.startswith(("redis://", "rediss://")): cls._client = redis.from_url( redis_url, decode_responses=True, socket_connect_timeout=2, socket_timeout=2, ) else: cls._client = redis.Redis( host=settings.REDIS_SERVER, port=settings.REDIS_PORT, db=settings.REDIS_DB, password=settings.REDIS_PASSWORD or None, decode_responses=True, socket_connect_timeout=2, socket_timeout=2, ) return cls._client class _AsyncRedisClient: _client: aioredis.Redis | None = None _loop: asyncio.AbstractEventLoop | None = None @classmethod def get_client(cls) -> aioredis.Redis: loop = asyncio.get_running_loop() if cls._client is None or cls._loop is not loop: redis_url = settings.REDIS_URL if redis_url.startswith(("redis://", "rediss://")): cls._client = aioredis.from_url( redis_url, decode_responses=True, socket_connect_timeout=1.5, socket_timeout=1.5, ) else: cls._client = aioredis.Redis( host=settings.REDIS_SERVER, port=settings.REDIS_PORT, db=settings.REDIS_DB, password=settings.REDIS_PASSWORD or None, decode_responses=True, socket_connect_timeout=1.5, socket_timeout=1.5, ) cls._loop = loop return cls._client redis_client = _RedisClient.get_client() def _token_digest(token: str) -> str: return hashlib.sha256(token.encode("utf-8")).hexdigest() def _prune_local_revocations(now: float | None = None) -> None: current = now if now is not None else time.monotonic() expired = [key for key, deadline in _LOCAL_REVOKED_TOKENS.items() if deadline <= current] for key in expired: _LOCAL_REVOKED_TOKENS.pop(key, None) while len(_LOCAL_REVOKED_TOKENS) > LOCAL_REVOKED_MAX_ENTRIES: oldest_key = next(iter(_LOCAL_REVOKED_TOKENS)) _LOCAL_REVOKED_TOKENS.pop(oldest_key, None) def _record_local_revocation(token_digest: str, ttl_seconds: int) -> None: now = time.monotonic() _prune_local_revocations(now) _LOCAL_REVOKED_TOKENS[token_digest] = now + max(60, ttl_seconds) def _is_locally_revoked(token_digest: str) -> bool: now = time.monotonic() deadline = _LOCAL_REVOKED_TOKENS.get(token_digest) if deadline is None: return False if deadline <= now: _LOCAL_REVOKED_TOKENS.pop(token_digest, None) return False return True def _is_monkeypatched_sync_redis(candidate: Any) -> bool: if candidate is None: return False if not isinstance(candidate, redis.Redis): return True return "sismember" in getattr(candidate, "__dict__", {}) def _token_revocation_ttl_seconds( token: str, default_ttl: int | None = None, *, decoded_payload: dict[str, Any] | None = None, ) -> int: fallback = default_ttl if default_ttl is not None else max(settings.REFRESH_TOKEN_EXPIRE_DAYS, 7) * 86400 payload = decoded_payload if decoded_payload is not None else decode_token(token) if payload and payload.get("exp") is not None: try: remaining = int(float(payload["exp"]) - datetime.now(UTC).timestamp()) return max(60, remaining) except (TypeError, ValueError): pass return max(60, int(fallback)) def verify_password(plain_password: str, hashed_password: str) -> bool: return bcrypt.checkpw(plain_password.encode(), hashed_password.encode()) def get_password_hash(password: str) -> str: return bcrypt.hashpw(password.encode(), bcrypt.gensalt()).decode() def create_access_token(data: dict, expires_delta: Optional[timedelta] = None) -> str: to_encode = data.copy() if expires_delta: expire = datetime.now(UTC) + expires_delta elif settings.ACCESS_TOKEN_EXPIRE_MINUTES > 0: expire = datetime.now(UTC) + timedelta(minutes=settings.ACCESS_TOKEN_EXPIRE_MINUTES) else: expire = None if expire: to_encode.update({"exp": expire}) to_encode.update({"type": "access", "jti": uuid4().hex}) if "sub" in to_encode: to_encode["sub"] = str(to_encode["sub"]) return jwt.encode(to_encode, settings.SECRET_KEY, algorithm=settings.ALGORITHM) def create_refresh_token(data: dict) -> str: to_encode = data.copy() if settings.REFRESH_TOKEN_EXPIRE_DAYS > 0: expire = datetime.now(UTC) + timedelta(days=settings.REFRESH_TOKEN_EXPIRE_DAYS) to_encode.update({"exp": expire}) to_encode.update({"type": "refresh", "jti": uuid4().hex}) if "sub" in to_encode: to_encode["sub"] = str(to_encode["sub"]) return jwt.encode(to_encode, settings.SECRET_KEY, algorithm=settings.ALGORITHM) def decode_token(token: str) -> Optional[dict]: try: payload = jwt.decode(token, settings.SECRET_KEY, algorithms=[settings.ALGORITHM]) return payload except JWTError: return None async def revoke_token(token: str, *, ttl_seconds: int | None = None) -> None: """Revoke a verified, unexpired JWT in Redis with bounded TTL plus local fallback.""" if not token: return payload = decode_token(token) if payload is None: return digest = _token_digest(token) ttl = _token_revocation_ttl_seconds( token, default_ttl=ttl_seconds, decoded_payload=payload, ) _record_local_revocation(digest, ttl) try: client = _AsyncRedisClient.get_client() await asyncio.wait_for( client.set(f"{REVOKED_KEY_PREFIX}{digest}", "1", ex=ttl), timeout=REDIS_OP_TIMEOUT_SECONDS, ) except Exception as exc: logger.warning_event( "Failed to persist revoked token to Redis; kept in local revocation cache", event="auth.redis_revoke.unavailable", context={"error": str(exc)}, ) async def is_token_blacklisted(token: str, *, legacy_sync_client: Any = None) -> bool: """Check whether a JWT was revoked without blocking the event loop or failing 500 on Redis outage.""" if not token: return False digest = _token_digest(token) if _is_locally_revoked(digest): return True for candidate in (legacy_sync_client, redis_client): if _is_monkeypatched_sync_redis(candidate): try: return bool(candidate.sismember("blacklisted_tokens", token)) except Exception as exc: logger.warning_event( "Sync token blacklist check failed; degrading safely", event="auth.redis_blacklist.sync_unavailable", context={"error": str(exc)}, ) return False try: client = _AsyncRedisClient.get_client() if await asyncio.wait_for( client.exists(f"{REVOKED_KEY_PREFIX}{digest}"), timeout=REDIS_OP_TIMEOUT_SECONDS, ): return True return bool( await asyncio.wait_for( client.sismember("blacklisted_tokens", token), timeout=REDIS_OP_TIMEOUT_SECONDS, ) ) except Exception as exc: logger.warning_event( "Async token blacklist check failed; degrading safely", event="auth.redis_blacklist.unavailable", context={"error": str(exc)}, ) return False async def _load_active_user(user_id: str, db: AsyncSession) -> User: try: parsed_id = int(user_id) except (TypeError, ValueError): raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid token") result = await db.execute(select(User).where(User.id == parsed_id)) user = result.scalar_one_or_none() if user is None or not user.is_active: raise HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, detail="User not found or inactive", ) return user async def get_current_user( credentials: HTTPAuthorizationCredentials = Depends(oauth2_scheme), db: AsyncSession = Depends(get_db), ) -> User: token = credentials.credentials if await is_token_blacklisted(token): raise HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, detail="Token has been revoked", ) payload = decode_token(token) if payload is None or payload.get("type") != "access": raise HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid token", ) user_id = payload.get("sub") if user_id is None: raise HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid token", ) return await _load_active_user(user_id, db) async def get_current_user_refresh( credentials: HTTPAuthorizationCredentials = Depends(oauth2_scheme), db: AsyncSession = Depends(get_db), ) -> User: token = credentials.credentials if await is_token_blacklisted(token): raise HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, detail="Token has been revoked", ) payload = decode_token(token) if payload is None or payload.get("type") != "refresh": raise HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid refresh token", ) user_id = payload.get("sub") if user_id is None: raise HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid token", ) return await _load_active_user(user_id, db) def blacklist_token(token: str) -> None: """Best-effort revocation helper for legacy synchronous callers.""" if not token: return payload = decode_token(token) if payload is None: return digest = _token_digest(token) ttl = _token_revocation_ttl_seconds(token, decoded_payload=payload) _record_local_revocation(digest, ttl) try: redis_client.set(f"{REVOKED_KEY_PREFIX}{digest}", "1", ex=ttl) except Exception as exc: logger.warning_event( "Failed to write sync token revocation to Redis", event="auth.redis_revoke.sync_unavailable", context={"error": str(exc)}, )