"""Login attempt throttling: counters live in the shared cache (Redis) so every gunicorn worker sees them, with an in-process fallback when the cache is unreachable (R2-S4) — so a Redis outage degrades throttling to per-worker limits instead of switching it off for anyone who happens to choose that moment.""" import ipaddress import logging import threading import time from django.conf import settings from django.core.cache import cache logger = logging.getLogger(__name__) LOCAL_MAX_KEYS = 10_000 class LoginThrottle: def __init__(self, window_seconds: int): self.window = window_seconds self._lock = threading.Lock() self._local: dict[str, tuple[int, float]] = {} def is_blocked(self, key: str, limit: int) -> bool: try: return cache.get(key, 0) >= limit except Exception: logger.warning("Login throttle cache unavailable; using local limiter") return self._local_count(key) >= limit def record(self, key: str) -> None: try: try: cache.incr(key) except ValueError: cache.set(key, 1, self.window) except Exception: logger.warning("Login throttle cache unavailable; using local limiter") self._local_record(key) def _local_count(self, key: str) -> int: with self._lock: entry = self._local.get(key) if entry is None or entry[1] <= time.monotonic(): return 0 return entry[0] def _local_record(self, key: str) -> None: now = time.monotonic() with self._lock: if len(self._local) >= LOCAL_MAX_KEYS: self._local = {k: v for k, v in self._local.items() if v[1] > now} if len(self._local) >= LOCAL_MAX_KEYS: self._local.clear() # under a flood, bounded memory beats perfect memory count, expires = self._local.get(key, (0, 0.0)) if expires <= now: count, expires = 0, now + self.window self._local[key] = (count + 1, expires) def _parse_ip(value: str): try: return ipaddress.ip_address(value.strip()) except ValueError: return None def _is_trusted_proxy(value: str, trusted) -> bool: ip = _parse_ip(value) return ip is not None and any(ip in network for network in trusted) def client_address(request) -> str: """The address to throttle a login attempt by. EVECTION_TRUSTED_PROXIES (comma-separated IPs/CIDRs of your reverse proxy) makes this strict: X-Forwarded-For is only believed when the TCP peer is one of those proxies, and then the *rightmost* entry that isn't itself a trusted proxy is used — the address your proxy actually saw — rather than the first entry, which is whatever the client chose to send. A client reaching gunicorn directly, or a proxy outside the list, gets its own peer address. Unset (the default), it keeps the previous behavior — trust the first X-Forwarded-For entry — which is only safe while gunicorn is reachable by nothing but a proxy that overwrites that header (docs/install.md); `manage.py check --deploy` warns until it's set. """ remote = request.META.get("REMOTE_ADDR", "unknown") forwarded = [ part.strip() for part in request.META.get("HTTP_X_FORWARDED_FOR", "").split(",") if part.strip() ] trusted = settings.EVECTION_TRUSTED_PROXIES if not trusted: return forwarded[0] if forwarded else remote if not _is_trusted_proxy(remote, trusted): return remote for address in reversed(forwarded): if not _is_trusted_proxy(address, trusted): return address return forwarded[0] if forwarded else remote