Files
Evection/apps/accounts/throttle.py
T
ksmithandClaude Sonnet 5.5 ac5e951749 Harden the login throttle and cache readiness aggregates (R2-S4, R2-C5; #36, #45)
S4: the throttle keyed on the first X-Forwarded-For entry, which a client
or a proxy that appends can choose, and disabled itself entirely when
Redis was down.

EVECTION_TRUSTED_PROXIES (IPs/CIDRs of your reverse proxy) makes it
strict: X-Forwarded-For is only believed when the TCP peer is a trusted
proxy, and the rightmost entry that isn't itself a trusted proxy — the
address the proxy actually saw — is used instead of the spoofable first
one. Unset keeps the previous behavior so existing installs don't
suddenly share one bucket behind a proxy, and `manage.py check --deploy`
warns (evection.W001) until it's set. During a Redis outage the throttle
now falls back to a bounded in-process limiter instead of switching off.

C5: /health/ready/ reuses its queue/feed aggregates for 15s
(EVECTION_HEALTH_CACHE_SECONDS) so a fast-polling monitor can't create
steady load; the database, Redis and poller probes stay live. Docs
cover both settings, restricting the endpoint at the proxy, and the
tombstone/purge behavior from the previous changes.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-01 12:08:13 -07:00

107 lines
3.7 KiB
Python

"""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