""" Detection Service — Enterprise API Key Security DB-backed token validation with scope enforcement and per-token Redis rate limiting. """ from __future__ import annotations import threading import time from typing import Optional from fastapi import HTTPException, Request, Security, status from fastapi.security import APIKeyHeader from app.core.config import get_settings from app.core.logging import get_logger from app.db.redis import get_redis from app.db.session import async_session_factory from app.models.api_token import ApiToken from app.repositories.api_token_repository import TokenRepository logger = get_logger(__name__) _api_key_header = APIKeyHeader(name="X-API-Key", auto_error=False) # ── Scope Enforcement Matrix ── # Endpoint → Required scope # POST /detect → DETECTION # POST /classify → CLASSIFICATION # POST /analyze → DETECTION_AND_CLASSIFICATION SCOPE_MAP = { "/api/v1/detect": "DETECTION", "/api/v1/classify": "CLASSIFICATION", "/api/v1/analyze": "DETECTION_AND_CLASSIFICATION", } # Scopes that grant access to other scopes (hierarchy) SCOPE_GRANTS = { "FULL_ACCESS": {"DETECTION", "CLASSIFICATION", "DETECTION_AND_CLASSIFICATION", "FULL_ACCESS"}, "DETECTION_AND_CLASSIFICATION": {"DETECTION", "CLASSIFICATION", "DETECTION_AND_CLASSIFICATION"}, "DETECTION_AND_CURE": {"DETECTION"}, "CLASSIFICATION_AND_CURE": {"CLASSIFICATION"}, "DETECTION": {"DETECTION"}, "CLASSIFICATION": {"CLASSIFICATION"}, } # ── Thread-safe in-memory metrics for token failures ── _token_metrics_lock = threading.Lock() _token_metrics = { "validation_failures": 0, "rate_limit_exceeded": 0, } def get_token_metrics() -> dict: with _token_metrics_lock: return _token_metrics.copy() def _increment_metric(key: str) -> None: """Thread-safe metric increment.""" with _token_metrics_lock: _token_metrics[key] += 1 def _scope_allows(token_scope: str, required_scope: str) -> bool: """Check if a token's scope grants access to the required scope.""" if token_scope == "FULL_ACCESS": return True allowed = SCOPE_GRANTS.get(token_scope, {token_scope}) return required_scope in allowed async def _check_redis_rate_limit(token_hash: str, minute_limit: int, daily_limit: int) -> bool: """ Redis-based per-token rate limiter. Minute Key: ratelimit:min:{token_hash} (1-min TTL) Daily Key: ratelimit:day:{token_hash} (24-h TTL) Returns True if allowed, False if exceeded. """ try: redis = await get_redis() if redis is None: return True min_key = f"rl:min:{token_hash}" day_key = f"rl:day:{token_hash}" # 1. Minute Limit Check minute_count = await redis.get(min_key) if minute_count and int(minute_count) >= minute_limit: return False # 2. Daily Limit Check daily_count = await redis.get(day_key) if daily_count and int(daily_count) >= daily_limit: return False # 3. Increment counters pipe = redis.pipeline() if not minute_count: pipe.set(min_key, 1, ex=60) else: pipe.incr(min_key) if not daily_count: # TTL until end of day (approx 24h) pipe.set(day_key, 1, ex=86400) else: pipe.incr(day_key) await pipe.execute() return True except Exception as exc: logger.warning("rate_limit_redis_error", error=str(exc)) return True import hmac import hashlib async def verify_internal_signature(request: Request) -> bool: """Verifies HMAC SHA-256 signature from Core Service.""" timestamp = request.headers.get("X-Service-Timestamp") signature = request.headers.get("X-Service-Signature") if not timestamp or not signature: return False # Replay attack prevention (5 minutes) try: request_time = int(timestamp) / 1000 # JS timestamp is ms if abs(time.time() - request_time) > 300: return False except: return False settings = get_settings() method = request.method.upper() # Check both full path with query string (which core-service sends) and path without query string path_with_query = f"{request.url.path}?{request.url.query}" if request.url.query else request.url.path path_without_query = request.url.path body = "" for test_path in (path_with_query, path_without_query): payload = f"{timestamp}:{method}:{test_path}:{body}" expected = hmac.new( settings.internal_service_secret.encode(), payload.encode(), hashlib.sha256 ).hexdigest() if hmac.compare_digest(signature, expected): return True return False async def verify_api_key( request: Request, api_key: Optional[str] = Security(_api_key_header), ) -> str: """ Enterprise token validation dependency. 1. Check if HMAC Internal Signature is present and valid (Core Service call) 2. Fallback: Check X-API-Key (External B2B call) """ # ── 1. Inter-service HMAC check (Layer 3) ── if await verify_internal_signature(request): return "internal-service" settings = get_settings() # ── 2. Standard API Key check ── if api_key is None: if not settings.api_keys_list: return "dev-open" _increment_metric("validation_failures") raise HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, detail="Missing X-API-Key or invalid internal signature", ) # ... rest of verify_api_key remains same ... # ── Determine required scope from route path ── path = request.url.path.lower() required_scope = "FULL_ACCESS" for route_prefix, scope in SCOPE_MAP.items(): if path.startswith(route_prefix): required_scope = scope break # ── Try DB-backed validation first ── try: async with async_session_factory() as session: repo = TokenRepository(session) token_row: Optional[ApiToken] = await repo.validate_token(api_key) if token_row is not None: # ── Scope check ── if not _scope_allows(token_row.scope, required_scope): _increment_metric("validation_failures") logger.warning( "token_scope_mismatch", token_scope=token_row.scope, required=required_scope, ) raise HTTPException( status_code=status.HTTP_403_FORBIDDEN, detail=f"Token scope '{token_row.scope}' does not grant access to '{required_scope}'", ) # ── Per-token Redis rate limiting ── allowed = await _check_redis_rate_limit( token_row.token_hash, token_row.rate_limit_per_minute, token_row.daily_quota ) if not allowed: _increment_metric("rate_limit_exceeded") logger.warning( "rate_limit_exceeded", token_id=str(token_row.id), limit=token_row.rate_limit_per_minute, ) raise HTTPException( status_code=status.HTTP_429_TOO_MANY_REQUESTS, detail="Rate limit exceeded (minute/daily quota for this token)", ) # ── Increment usage ── await repo.increment_usage(token_row.id) logger.info( "token_validated", token_id=str(token_row.id), scope=token_row.scope, ) return api_key except HTTPException: raise # re-raise rate limit / scope errors except Exception as exc: logger.warning("token_db_validation_error", error=str(exc)) # Fall through to static key check # ── Fallback: static ENV keys (backward compatibility / dev mode) ── if api_key in settings.api_keys_list: return api_key # ── All validation failed ── _increment_metric("validation_failures") logger.warning("token_rejected", key_prefix=api_key[:8] if api_key else "none") raise HTTPException( status_code=status.HTTP_403_FORBIDDEN, detail="Invalid API key", )