Files
plm-lottery/apps/accounts/throttle.py
T
davideandClaude Sonnet 5.5 efb3e2e702 A5: sign up, sign in, sign out, profile and the base layout (WEB-02, WEB-06, WEB-11, WEB-50..54)
Registration (case-insensitive unique names, 8-256 char passwords, no email),
sign-in with a generic error and a fresh session, internal-only ?next=,
POST-only sign-out, password change that closes the other sessions. The
failed-login backoff, the registration quota and the password-change guard
live in the database so every web process shares them; the client IP is the
last X-Forwarded-For hop. One responsive stylesheet with light/dark theme,
labelled fields, alerts and no inline scripts or styles; Italian error pages
and a readable CSRF failure. Mutation checks: open redirects, uncounted
failures and a missing CSRF middleware are all caught.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-16 14:07:45 +01:00

99 lines
3.8 KiB
Python

"""Throttles for credentials, shared by every web process (WEB-02, SEC-54, SEC-55).
Two kinds, as in the old server (B-33, B-58):
* `Backoff` — for failed guesses at a secret. After `threshold` failures in a row the next attempt must wait
`base_delay * 2**(failures - threshold)` seconds (capped), counted from the last failure; a streak ends when
the key stays quiet for `decay_seconds`, so a shared address is not punished forever for earlier mistakes.
* `Quota` — for "how many of these may one source create": a count in a rolling window, on completed actions.
"""
from dataclasses import dataclass
from datetime import datetime, timedelta
from django.utils import timezone
from .models import ThrottleEvent
@dataclass(frozen=True)
class Backoff:
scope: str
threshold: int
base_delay: float
max_delay: float
decay_seconds: float
@dataclass(frozen=True)
class Quota:
scope: str
limit: int
window_seconds: float
LOGIN = Backoff("login", threshold=5, base_delay=2.0, max_delay=300.0, decay_seconds=900.0)
LOGIN_IP = Backoff("login_ip", threshold=20, base_delay=2.0, max_delay=300.0, decay_seconds=900.0)
CHANGE_PASSWORD = Backoff("chpwd", threshold=5, base_delay=2.0, max_delay=300.0, decay_seconds=900.0)
REGISTER = Quota("register", limit=5, window_seconds=3600.0)
_KEY_MAX = 150
def _key(key: str) -> str:
return key[:_KEY_MAX]
def _streak(rule: Backoff, key: str) -> list[datetime]:
"""Timestamps of the current streak of failures, oldest first."""
events = list(
ThrottleEvent.objects.filter(scope=rule.scope, key=_key(key)).order_by("-created_at")
.values_list("created_at", flat=True)
)
streak: list[datetime] = []
for created_at in events: # newest first: walk back while the gap stays within the decay
if streak and (streak[-1] - created_at).total_seconds() > rule.decay_seconds:
break
streak.append(created_at)
return streak[::-1]
def retry_after(rule: Backoff | Quota, key: str, now: datetime | None = None) -> float:
"""Seconds until this key may try again; 0.0 while it may."""
now = now or timezone.now()
if isinstance(rule, Quota):
window_start = now - timedelta(seconds=rule.window_seconds)
recent = list(
ThrottleEvent.objects.filter(scope=rule.scope, key=_key(key), created_at__gt=window_start)
.order_by("-created_at").values_list("created_at", flat=True)[: rule.limit]
)
if len(recent) < rule.limit:
return 0.0
return max(0.0, (recent[-1] + timedelta(seconds=rule.window_seconds) - now).total_seconds())
streak = _streak(rule, key)
if len(streak) < rule.threshold:
return 0.0
if (now - streak[-1]).total_seconds() > rule.decay_seconds:
return 0.0
delay = min(rule.max_delay, rule.base_delay * 2 ** (len(streak) - rule.threshold))
return max(0.0, (streak[-1] + timedelta(seconds=delay) - now).total_seconds())
def record(rule: Backoff | Quota, key: str, now: datetime | None = None) -> None:
"""Count one failure (Backoff) or one completed action (Quota), and drop what no longer matters."""
now = now or timezone.now()
ThrottleEvent.objects.create(scope=rule.scope, key=_key(key), created_at=now)
horizon = rule.window_seconds if isinstance(rule, Quota) else rule.decay_seconds
if isinstance(rule, Backoff):
streak = _streak(rule, key)
if streak: # events before the current streak can never count again
ThrottleEvent.objects.filter(scope=rule.scope, key=_key(key), created_at__lt=streak[0]).delete()
else:
ThrottleEvent.objects.filter(scope=rule.scope, created_at__lt=now - timedelta(seconds=horizon)).delete()
def reset(rule: Backoff, key: str) -> None:
"""A success ends the streak of that key."""
ThrottleEvent.objects.filter(scope=rule.scope, key=_key(key)).delete()