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 @pytest.fixture def cache_down(monkeypatch): from unittest.mock import Mock broken = Mock(side_effect=ConnectionError("redis down")) for name in ("get", "incr", "set"): monkeypatch.setattr(f"apps.accounts.throttle.cache.{name}", broken) @pytest.fixture(autouse=True) def _reset_local_limiter(): from .views import login_throttle login_throttle._local.clear() yield login_throttle._local.clear() @pytest.mark.django_db def test_login_still_works_when_the_throttle_cache_is_down(client, alice, cache_down): assert _bad_login(client).status_code == 200 good = client.post(reverse("accounts:login"), {"username": "alice", "password": "pw-alice-123"}) assert good.status_code == 302 @pytest.mark.django_db def test_a_redis_outage_degrades_to_a_local_limit_instead_of_no_limit(client, alice, cache_down): """R2-S4: previously every attempt was allowed while the cache was down, so an outage switched brute-force protection off entirely.""" for _ in range(LOGIN_RATE_LIMIT_MAX_ATTEMPTS_PER_USERNAME): _bad_login(client) blocked = client.post( reverse("accounts:login"), {"username": "alice", "password": "pw-alice-123"} ) assert blocked.status_code == 302 assert blocked.url == reverse("accounts:login"), "even the right password is refused" class TestLocalLimiter: def test_counts_per_key_and_expires(self, monkeypatch): import time as time_module from .throttle import LoginThrottle throttle = LoginThrottle(window_seconds=60) for _ in range(3): throttle._local_record("k") assert throttle._local_count("k") == 3 assert throttle._local_count("other") == 0 real = time_module.monotonic() monkeypatch.setattr("apps.accounts.throttle.time.monotonic", lambda: real + 61) assert throttle._local_count("k") == 0 def test_memory_is_bounded(self, monkeypatch): from . import throttle as throttle_module monkeypatch.setattr(throttle_module, "LOCAL_MAX_KEYS", 5) throttle = throttle_module.LoginThrottle(window_seconds=60) for i in range(50): throttle._local_record(f"k{i}") assert len(throttle._local) <= 5 class TestClientAddress: def _request(self, remote, forwarded=None): from django.test import RequestFactory extra = {"REMOTE_ADDR": remote} if forwarded is not None: extra["HTTP_X_FORWARDED_FOR"] = forwarded return RequestFactory().get("/", **extra) def test_unset_keeps_the_legacy_first_hop_behavior(self, settings): from .throttle import client_address settings.EVECTION_TRUSTED_PROXIES = [] assert client_address(self._request("10.0.0.5", "1.2.3.4, 10.0.0.5")) == "1.2.3.4" assert client_address(self._request("10.0.0.5")) == "10.0.0.5" def test_trusted_proxy_uses_the_rightmost_untrusted_hop_not_the_spoofable_first(self, settings): import ipaddress from .throttle import client_address settings.EVECTION_TRUSTED_PROXIES = [ipaddress.ip_network("10.0.0.5/32")] # The client sent "X-Forwarded-For: 6.6.6.6"; the proxy appended the # address it actually saw (203.0.113.9). request = self._request("10.0.0.5", "6.6.6.6, 203.0.113.9") assert client_address(request) == "203.0.113.9" def test_forwarded_for_from_an_untrusted_peer_is_ignored(self, settings): import ipaddress from .throttle import client_address settings.EVECTION_TRUSTED_PROXIES = [ipaddress.ip_network("10.0.0.5/32")] # Someone reaching gunicorn directly and claiming to be 1.2.3.4. assert client_address(self._request("198.51.100.7", "1.2.3.4")) == "198.51.100.7" def test_chained_trusted_proxies_are_skipped(self, settings): import ipaddress from .throttle import client_address settings.EVECTION_TRUSTED_PROXIES = [ipaddress.ip_network("10.0.0.0/24")] request = self._request("10.0.0.5", "203.0.113.9, 10.0.0.7") assert client_address(request) == "203.0.113.9" def test_trusted_peer_with_no_forwarded_header_falls_back_to_the_peer(self, settings): import ipaddress from .throttle import client_address settings.EVECTION_TRUSTED_PROXIES = [ipaddress.ip_network("10.0.0.5/32")] assert client_address(self._request("10.0.0.5")) == "10.0.0.5" class TestDeployCheck: def test_warns_when_trusted_proxies_is_unset_in_production(self, settings): from .checks import trusted_proxies_configured settings.DEBUG = False settings.EVECTION_TRUSTED_PROXIES = [] warnings = trusted_proxies_configured(None) assert [w.id for w in warnings] == ["evection.W001"] def test_quiet_when_configured_or_in_debug(self, settings): import ipaddress from .checks import trusted_proxies_configured settings.DEBUG = False settings.EVECTION_TRUSTED_PROXIES = [ipaddress.ip_network("10.0.0.5/32")] assert trusted_proxies_configured(None) == [] settings.DEBUG = True settings.EVECTION_TRUSTED_PROXIES = [] assert trusted_proxies_configured(None) == []