""" Lightweight in-memory rate limiter for authentication endpoints. No external dependencies required — uses a simple sliding-window counter per IP. Usage in main.py: from core.rate_limiter import RateLimiterMiddleware app.add_middleware(RateLimiterMiddleware) """ import time import asyncio from collections import defaultdict from fastapi import Request from fastapi.responses import JSONResponse from starlette.middleware.base import BaseHTTPMiddleware from core.logging import get_logger logger = get_logger(__name__) # --- CONFIGURATION --- # Path-specific limits: (max_requests, window_seconds) RATE_LIMITS = { "/api/v1/auth/login": (5, 60), # 5 attempts per minute "/api/v1/auth/forgot-password": (3, 300), # 3 attempts per 5 minutes "/api/v1/auth/reset-password": (3, 300), # 3 attempts per 5 minutes "/api/v1/auth/register": (3, 300), # 3 registrations per 5 minutes } class _SlidingWindowCounter: """Thread-safe sliding window counter for a single IP+path pair.""" __slots__ = ("timestamps", "lock") def __init__(self): self.timestamps: list[float] = [] self.lock = asyncio.Lock() async def is_allowed(self, max_requests: int, window_seconds: int) -> bool: async with self.lock: now = time.monotonic() cutoff = now - window_seconds # Prune expired entries self.timestamps = [t for t in self.timestamps if t > cutoff] if len(self.timestamps) >= max_requests: return False self.timestamps.append(now) return True async def get_retry_after(self, window_seconds: int) -> int: """Returns seconds until the oldest entry expires.""" async with self.lock: if not self.timestamps: return 0 now = time.monotonic() oldest = self.timestamps[0] return max(1, int(window_seconds - (now - oldest))) # Global counters: keyed by (client_ip, path) _counters: dict[tuple[str, str], _SlidingWindowCounter] = defaultdict(_SlidingWindowCounter) # Periodic cleanup to prevent memory leak from abandoned IPs _last_cleanup = time.monotonic() _CLEANUP_INTERVAL = 600 # 10 minutes def _cleanup_stale_counters(): """Remove counters with no recent activity to prevent unbounded memory growth.""" global _last_cleanup now = time.monotonic() if now - _last_cleanup < _CLEANUP_INTERVAL: return _last_cleanup = now stale_keys = [] for key, counter in _counters.items(): if not counter.timestamps or (now - counter.timestamps[-1]) > 600: stale_keys.append(key) for k in stale_keys: del _counters[k] class RateLimiterMiddleware(BaseHTTPMiddleware): """ Applies per-IP rate limiting to sensitive authentication endpoints. Non-auth endpoints pass through with zero overhead. """ async def dispatch(self, request: Request, call_next): path = request.url.path.rstrip("/") # Only rate-limit configured paths if path not in RATE_LIMITS: return await call_next(request) max_requests, window_seconds = RATE_LIMITS[path] # Extract client IP (respects X-Forwarded-For for proxied deployments) client_ip = request.headers.get("X-Forwarded-For", "").split(",")[0].strip() if not client_ip: client_ip = request.client.host if request.client else "unknown" counter = _counters[(client_ip, path)] if not await counter.is_allowed(max_requests, window_seconds): retry_after = await counter.get_retry_after(window_seconds) logger.warning( f"RATE LIMIT: {client_ip} exceeded {max_requests} requests on {path} " f"(window: {window_seconds}s). Retry after: {retry_after}s" ) return JSONResponse( status_code=429, content={ "detail": "Too many requests. Please try again later.", "retry_after_seconds": retry_after, }, headers={"Retry-After": str(retry_after)}, ) # Periodic cleanup _cleanup_stale_counters() return await call_next(request)