Files
ksmithandClaude Sonnet 5.5 ac5e951749 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>
2026-11-01 12:08:13 -07:00

106 lines
4.1 KiB
Python

import logging
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.db import IntegrityError, transaction
from django.shortcuts import redirect, render
from .forms import CreateUserForm, SetupForm
from .middleware import SetupWizardMiddleware
from .models import SetupLock, User
from .throttle import LoginThrottle, client_address
logger = logging.getLogger(__name__)
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
login_throttle = LoginThrottle(LOGIN_RATE_LIMIT_WINDOW_SECONDS)
def _attempts_key(kind: str, value: str) -> str:
return f"login-attempts:{kind}:{value}"
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 login_throttle.is_blocked(
address_key, LOGIN_RATE_LIMIT_MAX_ATTEMPTS_PER_ADDRESS
) or login_throttle.is_blocked(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):
login_throttle.record(_attempts_key("addr", client_address(self.request)))
login_throttle.record(_attempts_key("user", self.request.POST.get("username", "")[:150]))
return super().form_invalid(form)
def setup(request):
if User.objects.exists():
return redirect("accounts:login")
form = SetupForm(request.POST or None)
if request.method == "POST" and form.is_valid():
try:
with transaction.atomic():
# Claims the one-time setup slot: the first of any
# concurrent requests to reach this INSERT wins it, and
# every other one raises IntegrityError instead of also
# creating an admin account. See SetupLock's docstring.
SetupLock.objects.create()
user = form.save(commit=False)
user.set_password(form.cleaned_data["password"])
user.is_staff = True
user.is_superuser = True
user.save()
except IntegrityError:
messages.info(request, "Setup was already completed. Log in with that account.")
return redirect("accounts:login")
SetupWizardMiddleware._a_user_exists = True
login(request, user)
messages.success(request, "Welcome to Evection! Your admin account is ready.")
return redirect("reader:stream")
return render(request, "accounts/setup.html", {"form": form})
@is_admin
def manage_users(request):
users = User.objects.order_by("username")
return render(request, "accounts/manage_users.html", {"users": users})
@is_admin
def create_user(request):
form = CreateUserForm(request.POST or None)
if request.method == "POST" and form.is_valid():
user = form.save(commit=False)
user.set_password(form.cleaned_data["password"])
user.save()
messages.success(request, f"Account '{user.username}' created.")
return redirect("accounts:manage_users")
return render(request, "accounts/create_user.html", {"form": form})