diff --git a/apps/accounts/test_rate_limit.py b/apps/accounts/test_rate_limit.py new file mode 100644 index 0000000..96bae3c --- /dev/null +++ b/apps/accounts/test_rate_limit.py @@ -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 diff --git a/apps/accounts/urls.py b/apps/accounts/urls.py index 650a52f..925c3d5 100644 --- a/apps/accounts/urls.py +++ b/apps/accounts/urls.py @@ -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"), diff --git a/apps/accounts/views.py b/apps/accounts/views.py index 03b7a11..27136f3 100644 --- a/apps/accounts/views.py +++ b/apps/accounts/views.py @@ -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(): diff --git a/config/settings/test.py b/config/settings/test.py index 54e27fe..b1fe71e 100644 --- a/config/settings/test.py +++ b/config/settings/test.py @@ -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"}} diff --git a/docs/install.md b/docs/install.md index 7fb8d2e..8eaf12b 100644 --- a/docs/install.md +++ b/docs/install.md @@ -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)