"""Fixed-window attempt counters for credential endpoints, the Python counterpart of backend/auth/ratelimit.go. Counters live in this process; AuthGuard's own limits apply on top.""" from __future__ import annotations import threading import time from collections.abc import Callable __all__ = ["AttemptLimiter"] MAX_TRACKED_ATTEMPT_KEYS = 10000 class AttemptLimiter: """Each key may make `limit` attempts per `window` seconds; further attempts are refused until the window ends. When the table is full of live keys a new key is refused rather than tracked, so flooding distinct keys cannot grow memory without bound.""" def __init__( self, window: float, limit: int, *, clock: Callable[[], float] = time.monotonic ) -> None: self._window = window self._limit = limit self._clock = clock self._lock = threading.Lock() self._counts: dict[str, tuple[float, int]] = {} def allow(self, key: str) -> bool: """Records one attempt for key and reports whether it is within the limit.""" now = self._clock() with self._lock: tracked = key in self._counts if not tracked and len(self._counts) >= MAX_TRACKED_ATTEMPT_KEYS: self._counts = { existing: state for existing, state in self._counts.items() if now - state[0] < self._window } if len(self._counts) >= MAX_TRACKED_ATTEMPT_KEYS: return False start, count = self._counts.get(key, (now, 0)) if now - start >= self._window: start, count = now, 0 count += 1 self._counts[key] = (start, count) return count <= self._limit