Files
plm-lottery/tests/django/test_accounts.py
T
davideandClaude Sonnet 5.5 efb3e2e702 A5: sign up, sign in, sign out, profile and the base layout (WEB-02, WEB-06, WEB-11, WEB-50..54)
Registration (case-insensitive unique names, 8-256 char passwords, no email),
sign-in with a generic error and a fresh session, internal-only ?next=,
POST-only sign-out, password change that closes the other sessions. The
failed-login backoff, the registration quota and the password-change guard
live in the database so every web process shares them; the client IP is the
last X-Forwarded-For hop. One responsive stylesheet with light/dark theme,
labelled fields, alerts and no inline scripts or styles; Italian error pages
and a readable CSRF failure. Mutation checks: open redirects, uncounted
failures and a missing CSRF middleware are all caught.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-16 14:07:45 +01:00

507 lines
21 KiB
Python

"""A5 — sign up, sign in, sign out, profile: WEB-02, WEB-03, WEB-06, WEB-11, REG-01, SEC-17, SEC-19, SEC-54,
ADR-36, ADR-37, ADR-38, B-33, B-34, B-54, B-58."""
import re
from datetime import timedelta
from html.parser import HTMLParser
from pathlib import Path
import pytest
from django.contrib.auth import get_user_model
from django.test import Client
from django.utils import timezone
from apps.accounts import throttle
from apps.accounts.client_ip import client_ip
from apps.accounts.models import ThrottleEvent
from apps.lottery.models import AuditEntry
ROOT = Path(__file__).resolve().parents[2]
User = get_user_model()
PASSWORD = "correct-horse-battery"
pytestmark = pytest.mark.django_db
def make_user(name="mario", password=PASSWORD):
return User.objects.create_user(name, password=password)
def csrf_client():
return Client(enforce_csrf_checks=True)
def post(client, url, data, *, follow=False, **extra):
"""POST like a browser: read the form first (to get the CSRF cookie), then send its token back."""
client.get(url, **extra)
token = client.cookies["csrftoken"].value
return client.post(url, {**data, "csrfmiddlewaretoken": token}, follow=follow, **extra)
def sign_in(client, name="mario", password=PASSWORD, **extra):
return post(client, "/accedi/", {"username": name, "password": password}, **extra)
def register_data(name="luigi", password=PASSWORD, confirm=None):
return {"username": name, "password": password, "password_confirm": confirm if confirm is not None else password}
# --- pages -------------------------------------------------------------------------------------
@pytest.mark.parametrize("url", ["/accedi/", "/registrati/"])
def test_the_public_forms_render(client, url):
response = client.get(url)
assert response.status_code == 200 and "csrfmiddlewaretoken" in response.content.decode()
def test_registration_asks_for_no_email(client):
"""ADR-37: no email is ever collected."""
html = client.get("/registrati/").content.decode().lower()
assert "email" not in html.replace("non raccogliamo email", "")
def test_the_forms_work_with_the_real_csrf_protection():
"""WEB-02: the happy path passes with CSRF enforced."""
client = csrf_client()
assert post(client, "/registrati/", register_data()).status_code == 302
assert User.objects.filter(username="luigi").exists()
@pytest.mark.parametrize("url,data", [
("/accedi/", {"username": "mario", "password": PASSWORD}),
("/registrati/", register_data()),
])
def test_a_form_without_the_csrf_token_is_refused(url, data):
"""WEB-02, WEB-06: refused with a readable page, and nothing happens."""
make_user()
client = csrf_client()
response = client.post(url, data)
assert response.status_code == 403 and "Sessione scaduta" in response.content.decode()
assert "_auth_user_id" not in client.session and not User.objects.filter(username="luigi").exists()
def test_logout_and_password_change_need_the_csrf_token_too():
make_user()
client = csrf_client()
sign_in(client)
assert client.post("/esci/").status_code == 403
assert client.post("/app/profilo/", {"current_password": PASSWORD, "new_password": "n" * 10,
"new_password_confirm": "n" * 10}).status_code == 403
assert "_auth_user_id" in client.session
# --- registration ------------------------------------------------------------------------------
def test_registering_creates_the_account_and_signs_in(client):
response = post(client, "/registrati/", register_data("Luigi"))
assert response.status_code == 302 and response["Location"] == "/app/"
user = User.objects.get()
assert user.username == "Luigi" and user.check_password(PASSWORD) and not user.is_staff
assert client.session["_auth_user_id"] == str(user.pk)
assert AuditEntry.objects.get(action="user_registered").actor == user
def test_the_password_is_stored_hashed(client):
post(client, "/registrati/", register_data())
stored = User.objects.get().password
assert PASSWORD not in stored and "$" in stored
@pytest.mark.parametrize("name", ["ab", "x" * 33, "with space", "bad/char", "perché", "a@b"])
def test_invalid_usernames_are_refused(client, name):
"""REG-01: 3 to 32 characters from [A-Za-z0-9_.-]."""
response = post(client, "/registrati/", register_data(name))
assert response.status_code == 200 and User.objects.count() == 0
@pytest.mark.parametrize("name", ["abc", "x" * 32, "Mario.Rossi-1_x"])
def test_valid_usernames_are_accepted(client, name):
assert post(client, "/registrati/", register_data(name)).status_code == 302
@pytest.mark.parametrize("password", ["short", "x" * 7, "y" * 257])
def test_password_length_limits(client, password):
"""SEC-17: 8 to 256 characters."""
response = post(client, "/registrati/", register_data(password=password))
assert response.status_code == 200 and User.objects.count() == 0
@pytest.mark.parametrize("password", ["12345678", "x" * 8, "z" * 256])
def test_passwords_at_the_limits_are_accepted(client, password):
assert post(client, "/registrati/", register_data(password=password)).status_code == 302
def test_the_two_passwords_must_match(client):
response = post(client, "/registrati/", register_data(confirm="different-one"))
assert response.status_code == 200 and "non coincidono" in response.content.decode()
assert User.objects.count() == 0
def test_a_name_that_differs_only_by_case_is_taken(client):
"""ADR-38."""
make_user("Mario")
response = post(client, "/registrati/", register_data("mario"))
assert response.status_code == 200 and "già in uso" in response.content.decode()
assert User.objects.count() == 1
# --- registration quota ------------------------------------------------------------------------
def test_one_address_can_register_five_accounts_an_hour(client):
"""B-58."""
for i in range(5):
assert post(Client(), "/registrati/", register_data(f"user{i}"), REMOTE_ADDR="10.0.0.1").status_code == 302
response = post(Client(), "/registrati/", register_data("user5"), REMOTE_ADDR="10.0.0.1")
assert response.status_code == 429 and int(response["Retry-After"]) > 0
assert "Troppi tentativi" in response.content.decode() and not User.objects.filter(username="user5").exists()
assert post(Client(), "/registrati/", register_data("other"), REMOTE_ADDR="10.0.0.2").status_code == 302
def test_attempts_that_create_nothing_do_not_use_the_quota(client):
"""B-58: the limit is on accounts that exist, not on requests."""
for _ in range(8):
post(Client(), "/registrati/", register_data("ab"), REMOTE_ADDR="10.0.0.1") # too short
assert post(Client(), "/registrati/", register_data("fine"), REMOTE_ADDR="10.0.0.1").status_code == 302
def test_the_quota_frees_up_as_the_window_passes():
for i in range(5):
throttle.record(throttle.REGISTER, "9.9.9.9", now=timezone.now() - timedelta(minutes=59))
assert throttle.retry_after(throttle.REGISTER, "9.9.9.9") > 0
assert throttle.retry_after(throttle.REGISTER, "9.9.9.9", now=timezone.now() + timedelta(minutes=2)) == 0
def test_a_forged_forwarded_header_cannot_dodge_the_ip_controls(rf):
"""B-54: the last hop is the one our proxy wrote; the first ones are the client's own claim."""
request = rf.get("/", HTTP_X_FORWARDED_FOR="1.1.1.1, 2.2.2.2, 3.3.3.3", REMOTE_ADDR="172.28.0.10")
assert client_ip(request) == "3.3.3.3"
assert client_ip(rf.get("/", REMOTE_ADDR="8.8.8.8")) == "8.8.8.8"
for i in range(5):
post(Client(), "/registrati/", register_data(f"user{i}"), HTTP_X_FORWARDED_FOR=f"6.6.6.{i}, 5.5.5.5")
assert post(Client(), "/registrati/", register_data("late"), HTTP_X_FORWARDED_FOR="7.7.7.7, 5.5.5.5").status_code == 429
# --- signing in --------------------------------------------------------------------------------
def test_signing_in_opens_a_session_and_goes_to_the_player_area(client):
make_user()
response = sign_in(client)
assert response.status_code == 302 and response["Location"] == "/app/"
assert client.get("/app/").status_code == 200
def test_the_session_cookie_is_httponly_secure_and_samesite(client):
"""WEB-02."""
make_user()
cookie = sign_in(client).cookies["sessionid"]
assert cookie["httponly"] and cookie["secure"] and cookie["samesite"] == "Lax"
assert int(cookie["max-age"]) == 24 * 3600
def test_signing_in_gives_a_fresh_session(client):
"""No session fixation: the key changes at sign-in."""
make_user()
client.get("/accedi/")
before = client.session.session_key
sign_in(client)
assert client.session.session_key != before
def test_login_ignores_the_case_of_the_name(client):
make_user("Mario")
assert sign_in(client, "MARIO").status_code == 302
def test_unknown_name_and_wrong_password_look_the_same():
"""SEC-19: nothing tells an existing account from a missing one."""
make_user()
wrong = sign_in(Client(), "mario", "wrong-password-x")
unknown = sign_in(Client(), "nobody", "wrong-password-x")
assert wrong.status_code == unknown.status_code == 200
errors = lambda r: re.findall(r'class="error[^"]*"[^>]*>([^<]+)<', r.content.decode()) # noqa: E731
assert errors(wrong) == errors(unknown) == ["Nome utente o password non corretti."]
def test_an_inactive_account_cannot_sign_in(client):
user = make_user()
user.is_active = False
user.save()
sign_in(client)
assert "_auth_user_id" not in client.session
def test_a_signed_in_visitor_is_sent_on_from_the_forms(client):
make_user()
sign_in(client)
assert client.get("/accedi/")["Location"] == "/app/"
assert client.get("/registrati/")["Location"] == "/app/"
# --- where sign-in leads (WEB-11) --------------------------------------------------------------
def test_the_player_area_needs_a_session_and_comes_back_to_it(client):
make_user()
response = client.get("/app/")
assert response.status_code == 302 and response["Location"] == "/accedi/?next=/app/"
login = post(client, "/accedi/?next=/app/", {"username": "mario", "password": PASSWORD, "next": "/app/"})
assert login["Location"] == "/app/"
@pytest.mark.parametrize("destination", ["/app/profilo/", "/risultati/12/", "/app/?tab=wallet"])
def test_an_internal_destination_is_honoured(client, destination):
make_user()
response = post(client, "/accedi/", {"username": "mario", "password": PASSWORD, "next": destination})
assert response["Location"] == destination
@pytest.mark.parametrize("destination", [
"https://evil.example/", "http://evil.example", "//evil.example", "/\\evil.example", "javascript:alert(1)",
"///evil.example", "evil.example", "https:evil.example", "/ok\\@evil.example",
])
def test_an_open_redirect_is_refused(client, destination):
"""WEB-11: the login page cannot be used to send people to another site."""
make_user()
response = post(client, "/accedi/", {"username": "mario", "password": PASSWORD, "next": destination})
assert response["Location"] == "/app/"
def test_the_destination_survives_a_wrong_password_and_the_trip_to_registration(client):
html = client.get("/accedi/?next=/app/profilo/").content.decode()
assert 'name="next" value="/app/profilo/"' in html and "/registrati/?next=/app/profilo/" in html
wrong = post(client, "/accedi/", {"username": "x", "password": "y", "next": "/app/profilo/"})
assert 'name="next" value="/app/profilo/"' in wrong.content.decode()
registered = post(client, "/registrati/", {**register_data(), "next": "/app/profilo/"})
assert registered["Location"] == "/app/profilo/"
# --- sign-in throttle --------------------------------------------------------------------------
def test_five_wrong_guesses_lock_the_name_for_a_while():
"""B-33: the fifth failure starts a 2-second wait, and a correct password does not get through it."""
make_user()
for _ in range(5):
assert sign_in(Client(), password="wrong-password-x", REMOTE_ADDR="10.1.1.1").status_code == 200
locked = sign_in(Client(), password=PASSWORD, REMOTE_ADDR="10.1.1.2") # another address: the *name* is locked
assert locked.status_code == 429 and int(locked["Retry-After"]) >= 1
assert "Troppi tentativi" in locked.content.decode()
def test_the_wait_doubles_with_every_further_failure_and_is_capped():
key = "mario"
now = timezone.now()
for i in range(5):
throttle.record(throttle.LOGIN, key, now=now + timedelta(seconds=i))
last = now + timedelta(seconds=4)
assert throttle.retry_after(throttle.LOGIN, key, now=last) == pytest.approx(2.0)
throttle.record(throttle.LOGIN, key, now=last)
assert throttle.retry_after(throttle.LOGIN, key, now=last) == pytest.approx(4.0)
for _ in range(12):
throttle.record(throttle.LOGIN, key, now=last)
assert throttle.retry_after(throttle.LOGIN, key, now=last) == pytest.approx(300.0) # the cap
def test_a_quiet_spell_ends_the_streak():
now = timezone.now()
for _ in range(8):
throttle.record(throttle.LOGIN, "mario", now=now - timedelta(minutes=20))
assert throttle.retry_after(throttle.LOGIN, "mario", now=now) == 0
throttle.record(throttle.LOGIN, "mario", now=now) # a new streak starts from one
assert throttle.retry_after(throttle.LOGIN, "mario", now=now) == 0
def test_a_success_resets_the_name_but_not_the_address():
make_user()
for _ in range(4):
sign_in(Client(), password="wrong-password-x", REMOTE_ADDR="10.2.2.2")
assert sign_in(Client(), REMOTE_ADDR="10.2.2.2").status_code == 302
assert not ThrottleEvent.objects.filter(scope="login", key="mario").exists()
assert ThrottleEvent.objects.filter(scope="login_ip", key="10.2.2.2").count() == 4
def test_spraying_one_password_over_many_names_is_caught_by_the_address():
"""B-33: twenty failures from one address lock that address, whatever the names."""
for i in range(20):
sign_in(Client(), f"name{i}", "wrong-password-x", REMOTE_ADDR="10.3.3.3")
make_user("fresh")
assert sign_in(Client(), "fresh", REMOTE_ADDR="10.3.3.3").status_code == 429
assert sign_in(Client(), "fresh", REMOTE_ADDR="10.3.3.4").status_code == 302
def test_throttle_state_lives_in_the_database_not_in_memory():
"""ARC-72: another web process sees the same failures."""
for _ in range(5):
throttle.record(throttle.LOGIN, "shared")
assert ThrottleEvent.objects.filter(scope="login", key="shared").count() == 5
assert throttle.retry_after(throttle.LOGIN, "shared") > 0
# --- sign out ----------------------------------------------------------------------------------
def test_signing_out_ends_the_session_and_only_by_post(client):
make_user()
sign_in(client)
assert client.get("/esci/").status_code == 405
assert "_auth_user_id" in client.session
response = client.post("/esci/")
assert response.status_code == 302 and response["Location"] == "/"
assert "_auth_user_id" not in client.session
assert client.get("/app/").status_code == 302
# --- the profile -------------------------------------------------------------------------------
def test_the_profile_needs_a_session(client):
assert client.get("/app/profilo/")["Location"] == "/accedi/?next=/app/profilo/"
def test_the_profile_shows_only_the_owner(client):
make_user("mario")
make_user("luigi")
sign_in(client, "mario")
html = client.get("/app/profilo/").content.decode()
assert "mario" in html and "luigi" not in html
def test_changing_the_password(client):
user = make_user()
sign_in(client)
response = post(client, "/app/profilo/", {"current_password": PASSWORD, "new_password": "brand-new-pass",
"new_password_confirm": "brand-new-pass"})
assert response.status_code == 302
user.refresh_from_db()
assert user.check_password("brand-new-pass") and not user.check_password(PASSWORD)
assert AuditEntry.objects.get(action="password_changed").actor == user
assert "Password aggiornata" in client.get("/app/profilo/").content.decode()
assert client.get("/app/").status_code == 200 # this session stays signed in
def test_a_password_change_signs_out_every_other_session():
"""B-34: a session issued before the change stops working."""
make_user()
here, elsewhere = Client(), Client()
sign_in(here)
sign_in(elsewhere)
assert elsewhere.get("/app/").status_code == 200
post(here, "/app/profilo/", {"current_password": PASSWORD, "new_password": "brand-new-pass",
"new_password_confirm": "brand-new-pass"})
assert here.get("/app/").status_code == 200
assert elsewhere.get("/app/").status_code == 302
@pytest.mark.parametrize("data,message", [
({"current_password": "wrong-one-x", "new_password": "brand-new-pass", "new_password_confirm": "brand-new-pass"},
"non è corretta"),
({"current_password": PASSWORD, "new_password": "brand-new-pass", "new_password_confirm": "other-one-xx"},
"non coincidono"),
({"current_password": PASSWORD, "new_password": "short", "new_password_confirm": "short"}, "almeno 8"),
])
def test_a_bad_password_change_changes_nothing(client, data, message):
user = make_user()
sign_in(client)
response = post(client, "/app/profilo/", data)
assert response.status_code == 200 and message in response.content.decode()
user.refresh_from_db()
assert user.check_password(PASSWORD)
def test_guessing_the_current_password_is_throttled():
"""SEC-54: a stolen session cannot be used to guess the password and lock the owner out."""
make_user()
client = Client()
sign_in(client)
for _ in range(5):
post(client, "/app/profilo/", {"current_password": "guess-guess-1", "new_password": "brand-new-pass",
"new_password_confirm": "brand-new-pass"})
response = post(client, "/app/profilo/", {"current_password": PASSWORD, "new_password": "brand-new-pass",
"new_password_confirm": "brand-new-pass"})
assert response.status_code == 429
assert User.objects.get().check_password(PASSWORD)
# --- pages: layout, accessibility, security of the markup (WEB-06) -----------------------------
class _Page(HTMLParser):
def __init__(self):
super().__init__()
self.labels, self.inputs, self.attrs = set(), [], []
def handle_starttag(self, tag, attrs):
a = dict(attrs)
self.attrs.append((tag, a))
if tag == "label" and "for" in a:
self.labels.add(a["for"])
if tag == "input" and a.get("type") not in ("hidden", "submit"):
self.inputs.append(a)
def _page(client, url):
parser = _Page()
parser.feed(client.get(url).content.decode())
return parser
@pytest.mark.parametrize("url", ["/", "/accedi/", "/registrati/"])
def test_every_page_is_responsive_and_keyboard_friendly(client, url):
html = client.get(url).content.decode()
assert '<meta name="viewport" content="width=device-width, initial-scale=1">' in html
assert '<html lang="it">' in html and 'class="skip-link"' in html and '<main id="contenuto"' in html
assert '<nav class="nav" aria-label="Principale">' in html
@pytest.mark.parametrize("url", ["/accedi/", "/registrati/"])
def test_every_input_has_its_label(client, url):
page = _page(client, url)
assert page.inputs and all(i["id"] in page.labels for i in page.inputs)
def test_the_profile_inputs_have_labels_too(client):
make_user()
sign_in(client)
page = _page(client, "/app/profilo/")
assert page.inputs and all(i["id"] in page.labels for i in page.inputs)
def test_password_fields_tell_the_browser_what_they_are(client):
html = client.get("/registrati/").content.decode()
assert 'autocomplete="new-password"' in html and 'autocomplete="username"' in html
assert 'autocomplete="current-password"' in client.get("/accedi/").content.decode()
@pytest.mark.parametrize("url", ["/", "/accedi/", "/registrati/"])
def test_pages_use_no_inline_scripts_or_styles(client, url):
"""So the Content-Security-Policy can be tightened for them."""
html = client.get(url).content.decode()
assert "<script" not in html and " style=" not in html and not re.search(r"\son[a-z]+=", html)
def test_errors_are_announced_to_assistive_technology(client):
response = post(client, "/accedi/", {"username": "x", "password": "y"})
assert 'role="alert"' in response.content.decode()
def test_error_pages_are_in_italian_and_offer_a_way_out(client):
response = client.get("/non-esiste/")
html = response.content.decode()
assert response.status_code == 404 and "Pagina non trovata" in html and 'href="/"' in html
def test_the_stylesheet_has_a_responsive_layout_and_visible_focus():
css = (ROOT / "apps/web/static/web/site.css").read_text()
assert "@media (min-width" in css and ":focus-visible" in css and "prefers-color-scheme: dark" in css
assert "prefers-reduced-motion" in css
def test_forms_are_not_cached(client):
make_user()
sign_in(client)
assert "no-store" in client.get("/app/profilo/")["Cache-Control"] or "no-cache" in client.get("/app/profilo/")["Cache-Control"]