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>
This commit is contained in:
ksmithandClaude Sonnet 5.5 committed 2026-11-01 12:08:13 -07:00
1 parent aacb41d1d3
commit ac5e951749
12 files changed
+386 -53

No files matched your search

+135 -10
View File
@@ -74,19 +74,144 @@ def test_too_many_failed_attempts_against_one_username_blocks_that_username(clie
assert response.wsgi_request.user == bob
@pytest.mark.django_db
def test_login_still_works_when_the_throttle_cache_is_down(client, monkeypatch):
@pytest.fixture
def cache_down(monkeypatch):
from unittest.mock import Mock
from django.contrib.auth import get_user_model
get_user_model().objects.create_user("alice", password="pw-alice-123")
broken = Mock(side_effect=ConnectionError("redis down"))
monkeypatch.setattr("apps.accounts.views.cache.get", broken)
monkeypatch.setattr("apps.accounts.views.cache.incr", broken)
monkeypatch.setattr("apps.accounts.views.cache.set", broken)
for name in ("get", "incr", "set"):
monkeypatch.setattr(f"apps.accounts.throttle.cache.{name}", broken)
bad = client.post(reverse("accounts:login"), {"username": "alice", "password": "wrong"})
assert bad.status_code == 200
@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) == []