Spaces:
Paused
Paused
File size: 4,296 Bytes
b7980f7 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 | """
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)
|