This commit is contained in:
2025-10-23 19:41:24 +02:00
parent c81a493fb1
commit ffb182e3ba
7 changed files with 180 additions and 643 deletions

View File

@@ -46,7 +46,11 @@ class AuthMiddleware(BaseHTTPMiddleware):
}
def __init__(
self, app: ASGIApp, *, rate_limit_per_minute: int = 5
self,
app: ASGIApp,
*,
rate_limit_per_minute: int = 5,
window_seconds: int = 60
) -> None:
super().__init__(app)
# in-memory rate limiter: ip -> {count, window_start}
@@ -54,15 +58,16 @@ class AuthMiddleware(BaseHTTPMiddleware):
# origin-based rate limiter for CORS: origin -> {count, window_start}
self._origin_rate: Dict[str, Dict[str, float]] = {}
self.rate_limit_per_minute = rate_limit_per_minute
self.window_seconds = 60
self.window_seconds = window_seconds
# Track last cleanup time to prevent memory leaks
self._last_cleanup = time.time()
self._cleanup_interval = 300 # Clean every 5 minutes
def _cleanup_old_entries(self) -> None:
"""Remove rate limit entries older than cleanup interval.
This prevents memory leaks from accumulating old IP addresses and origins.
This prevents memory leaks from accumulating old IP addresses
and origins.
"""
now = time.time()
if now - self._last_cleanup < self._cleanup_interval: