Add login rate limiting (S6)

Django's default LoginView had no throttle — an internet-facing
instance was exposed to unlimited password-guessing/credential-
stuffing attempts. apps.accounts.views.LoginView adds two independent,
Redis-cache-backed throttles (shared across all gunicorn workers,
unlike the per-process default LocMemCache): by client address (catches
one attacker spraying many usernames) and by the submitted username
(catches a distributed attack on one specific account). Either blocks
further attempts for a 5-minute window; both are generous enough not
to lock out a user who's just mistyped their own password a few times.

Client address prefers X-Forwarded-For's first hop, falling back to
REMOTE_ADDR — the same reverse-proxy trust boundary config.settings.prod
already relies on for X-Forwarded-Proto (gunicorn is never meant to be
reachable except through that proxy).

CACHES now points at Redis (already a hard install requirement for
Celery) instead of Django's implicit per-process default, since the
whole point is a shared counter across every gunicorn worker; test
settings override it back to LocMemCache so the suite doesn't need a
real Redis instance.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
ksmithandClaude Sonnet 5 committed 2026-10-31 12:46:49 -06:00
1 parent 9241a54958
commit 0567047d96
5 files changed
+147 -6

No files matched your search

+74
View File
@@ -0,0 +1,74 @@
import pytest
from django.contrib.auth import get_user_model
from django.core.cache import cache
from django.urls import reverse
from .views import (
LOGIN_RATE_LIMIT_MAX_ATTEMPTS_PER_ADDRESS,
LOGIN_RATE_LIMIT_MAX_ATTEMPTS_PER_USERNAME,
)
User = get_user_model()
@pytest.fixture(autouse=True)
def _clear_rate_limit_cache():
cache.clear()
yield
cache.clear()
@pytest.fixture
def alice(db):
return User.objects.create_user("alice", password="pw-alice-123")
def _bad_login(client, username="alice"):
return client.post(reverse("accounts:login"), {"username": username, "password": "wrong"})
@pytest.mark.django_db
def test_a_single_failed_login_still_shows_the_normal_error(client, alice):
response = _bad_login(client)
assert response.status_code == 200
assert b"Please enter a correct" in response.content or response.context["form"].errors
@pytest.mark.django_db
def test_correct_credentials_succeed_before_the_limit_is_hit(client, alice):
for _ in range(3):
_bad_login(client)
response = client.post(
reverse("accounts:login"), {"username": "alice", "password": "pw-alice-123"}
)
assert response.status_code == 302
@pytest.mark.django_db
def test_too_many_failed_attempts_from_one_address_blocks_further_tries(client, alice):
for _ in range(LOGIN_RATE_LIMIT_MAX_ATTEMPTS_PER_ADDRESS):
_bad_login(client)
# Even the correct password is now refused — the throttle runs
# before the form is ever validated.
response = client.post(
reverse("accounts:login"), {"username": "alice", "password": "pw-alice-123"}
)
assert response.status_code == 302
assert response.url == reverse("accounts:login")
assert not response.wsgi_request.user.is_authenticated
@pytest.mark.django_db
def test_too_many_failed_attempts_against_one_username_blocks_that_username(client, alice):
bob = User.objects.create_user("bob", password="pw-bob-123")
for _ in range(LOGIN_RATE_LIMIT_MAX_ATTEMPTS_PER_USERNAME):
_bad_login(client, username="alice")
# Same client address, different username — the per-username
# throttle for "alice" shouldn't affect bob logging in.
response = client.post(reverse("accounts:login"), {"username": "bob", "password": "pw-bob-123"})
assert response.status_code == 302
assert response.wsgi_request.user == bob
+1 -5
View File
@@ -7,11 +7,7 @@ app_name = "accounts"
urlpatterns = [
path("setup/", views.setup, name="setup"),
path(
"login/",
auth_views.LoginView.as_view(template_name="accounts/login.html"),
name="login",
),
path("login/", views.LoginView.as_view(), name="login"),
path("logout/", auth_views.LogoutView.as_view(), name="logout"),
path("users/", views.manage_users, name="manage_users"),
path("users/create/", views.create_user, name="create_user"),
+64
View File
@@ -1,6 +1,8 @@
from django.contrib import messages
from django.contrib.auth import login
from django.contrib.auth.decorators import user_passes_test
from django.contrib.auth.views import LoginView as DjangoLoginView
from django.core.cache import cache
from django.db import IntegrityError, transaction
from django.shortcuts import redirect, render
@@ -10,6 +12,68 @@ from .models import SetupLock, User
is_admin = user_passes_test(lambda u: u.is_authenticated and u.is_staff)
# Two independent throttles, either of which can block an attempt: by
# client address (catches one attacker spraying many usernames) and by
# the submitted username (catches a distributed/low-and-slow attack on
# one specific account from many addresses). Both are generous enough
# not to lock out a user who's just fat-fingered their own password a
# few times.
LOGIN_RATE_LIMIT_WINDOW_SECONDS = 5 * 60
LOGIN_RATE_LIMIT_MAX_ATTEMPTS_PER_ADDRESS = 15
LOGIN_RATE_LIMIT_MAX_ATTEMPTS_PER_USERNAME = 8
def _client_address(request) -> str:
# gunicorn is always run behind a reverse proxy in every deployment
# (see docs/install.md) and its bind address is never meant to be
# reachable from outside that proxy — the same trust boundary
# config.settings.prod already relies on for X-Forwarded-Proto. A
# direct request (e.g. local dev) has no X-Forwarded-For and falls
# back to REMOTE_ADDR.
forwarded_for = request.META.get("HTTP_X_FORWARDED_FOR", "")
if forwarded_for:
return forwarded_for.split(",")[0].strip()
return request.META.get("REMOTE_ADDR", "unknown")
def _attempts_key(kind: str, value: str) -> str:
return f"login-attempts:{kind}:{value}"
def _too_many_attempts(key: str, limit: int) -> bool:
return cache.get(key, 0) >= limit
def _record_failed_attempt(key: str) -> None:
try:
cache.incr(key)
except ValueError:
cache.set(key, 1, LOGIN_RATE_LIMIT_WINDOW_SECONDS)
class LoginView(DjangoLoginView):
"""Wraps Django's own LoginView with the throttle above — everything
else (form, template, redirect behavior) is unchanged."""
template_name = "accounts/login.html"
def post(self, request, *args, **kwargs):
address_key = _attempts_key("addr", _client_address(request))
username_key = _attempts_key("user", request.POST.get("username", "")[:150])
if _too_many_attempts(
address_key, LOGIN_RATE_LIMIT_MAX_ATTEMPTS_PER_ADDRESS
) or _too_many_attempts(username_key, LOGIN_RATE_LIMIT_MAX_ATTEMPTS_PER_USERNAME):
messages.error(
request, "Too many login attempts. Please wait a few minutes and try again."
)
return redirect("accounts:login")
return super().post(request, *args, **kwargs)
def form_invalid(self, form):
_record_failed_attempt(_attempts_key("addr", _client_address(self.request)))
_record_failed_attempt(_attempts_key("user", self.request.POST.get("username", "")[:150]))
return super().form_invalid(form)
def setup(request):
if User.objects.exists():
+7
View File
@@ -5,3 +5,10 @@ CELERY_TASK_ALWAYS_EAGER = True
CELERY_TASK_EAGER_PROPAGATES = True
PASSWORD_HASHERS = ["django.contrib.auth.hashers.MD5PasswordHasher"]
# base.py's CACHES needs a real Redis instance — tests must not depend on
# one being available, and a plain per-process cache is also what keeps
# login-rate-limit tests isolated from each other (LocMemCache's default
# location is per-process but shared across tests in that process; see
# apps.accounts.test_rate_limit's cache.clear() fixture).
CACHES = {"default": {"BACKEND": "django.core.cache.backends.locmem.LocMemCache"}}
+1 -1
View File
@@ -66,7 +66,7 @@ and 4 below first — prerequisites and what `.env` controls.
- Python 3.11 or 3.12, with its `venv` module (Debian/Ubuntu split this into a
separate `python3.X-venv` package — see below)
- Redis (Celery's broker)
- Redis (Celery's broker, and the app's cache — e.g. login rate limiting)
- **Postgres only**: a PostgreSQL server (12+) and its client headers if you're not
using the bundled `psycopg[binary]` wheel (most platforms are covered by the wheel,
so this is rarely needed)