From efb3e2e702914cf70146132f8d8ec88d4b63b071 Mon Sep 17 00:00:00 2001 From: Davide Grilli Date: Mon, 16 Nov 2026 14:07:45 +0100 Subject: [PATCH] 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 --- CLAUDE.md | 4 +- README.md | 2 +- apps/accounts/backends.py | 20 + apps/accounts/client_ip.py | 13 + apps/accounts/forms.py | 70 +++ .../migrations/0002_throttle_event.py | 26 + apps/accounts/models.py | 16 + apps/accounts/templates/accounts/_field.html | 6 + .../templates/accounts/_form_errors.html | 4 + apps/accounts/templates/accounts/login.html | 15 + apps/accounts/templates/accounts/profile.html | 28 + .../accounts/templates/accounts/register.html | 16 + apps/accounts/throttle.py | 98 ++++ apps/accounts/urls.py | 11 + apps/accounts/validators.py | 31 ++ apps/accounts/views.py | 136 +++++ apps/web/static/web/site.css | 70 +++ apps/web/templates/web/app_home.html | 6 + apps/web/templates/web/base.html | 47 ++ apps/web/templates/web/error.html | 7 + apps/web/templates/web/home.html | 19 +- apps/web/urls.py | 1 + apps/web/views.py | 33 ++ config/settings.py | 13 +- config/urls.py | 4 + docs/sito-e-app.md | 50 ++ roadmap.md | 2 +- tests/django/test_accounts.py | 506 ++++++++++++++++++ 28 files changed, 1232 insertions(+), 22 deletions(-) create mode 100644 apps/accounts/backends.py create mode 100644 apps/accounts/client_ip.py create mode 100644 apps/accounts/forms.py create mode 100644 apps/accounts/migrations/0002_throttle_event.py create mode 100644 apps/accounts/templates/accounts/_field.html create mode 100644 apps/accounts/templates/accounts/_form_errors.html create mode 100644 apps/accounts/templates/accounts/login.html create mode 100644 apps/accounts/templates/accounts/profile.html create mode 100644 apps/accounts/templates/accounts/register.html create mode 100644 apps/accounts/throttle.py create mode 100644 apps/accounts/urls.py create mode 100644 apps/accounts/validators.py create mode 100644 apps/accounts/views.py create mode 100644 apps/web/static/web/site.css create mode 100644 apps/web/templates/web/app_home.html create mode 100644 apps/web/templates/web/base.html create mode 100644 apps/web/templates/web/error.html create mode 100644 tests/django/test_accounts.py diff --git a/CLAUDE.md b/CLAUDE.md index 6866272..49b7ef5 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -8,7 +8,7 @@ The user communicates in Italian in chat — reply to them in Italian. Everythin ## Project status -All 10 stages of the original build order are code-complete and unit-tested — 912 tests, the old stack's under `tests/unit/` and the Django ones under `tests/django/` (`tests/integration/` is an empty package). Beyond them: Docker + Caddy deployment, admin dashboard (`/admin`), static test UI (`/`), pending-inclusive balance display, an SSE push channel layered over the original polling, self-service password change + admin password reset, and the reconciliation/corroboration machinery below. +All 10 stages of the original build order are code-complete and unit-tested — 992 tests, the old stack's under `tests/unit/` and the Django ones under `tests/django/` (`tests/integration/` is an empty package). Beyond them: Docker + Caddy deployment, admin dashboard (`/admin`), static test UI (`/`), pending-inclusive balance display, an SSE push channel layered over the original polling, self-service password change + admin password reset, and the reconciliation/corroboration machinery below. Verified on mainnet with real money: registration + address derivation, deposit crediting (at the time, 1-conf; deposits now need `deposit_confirmations`), a real 10 PLM bet (broadcast → confirmed → change credited back), and one full round cycle (close → draw on a real block hash → 70/30 payout with sat math checked against the broadcast tx → confirmation → close → next round auto-opened). **Withdrawal and the RBF bump path have never been exercised against a live broadcast** — unit-tested only. @@ -61,7 +61,7 @@ PYTHONPATH=. python scripts/decrypt_master_key.py # ops recovery: decrypt+pr PYTHONPATH=. python scripts/encrypt_master_key.py # ops bootstrap: import an externally-generated xprv (--overwrite to replace) PYTHONPATH=. python scripts/electrum_smoke_test.py # manual check: connect, handshake, subscribe to headers, print the tip -python -m pytest # all 912 tests +python -m pytest # all 992 tests python -m pytest tests/unit/test_hd.py # one file python -m pytest tests/unit/test_hd.py::test_derivation_is_deterministic # one test ``` diff --git a/README.md b/README.md index 9944676..96ce0f9 100644 --- a/README.md +++ b/README.md @@ -62,7 +62,7 @@ python -m pytest # all tests python -m pytest tests/unit/test_hd.py # one file ``` -912 unit tests cover HD derivation, PSBT building, the Electrum client, bets, +992 unit tests cover HD derivation, PSBT building, the Electrum client, bets, deposits, withdrawals, the round/draw engine, RBF fee-bumping, admin config, the pending-inclusive balance calculation, and the SSE push channel. No automated integration tests against a live Electrum connection — mainnet diff --git a/apps/accounts/backends.py b/apps/accounts/backends.py new file mode 100644 index 0000000..37eba60 --- /dev/null +++ b/apps/accounts/backends.py @@ -0,0 +1,20 @@ +from django.contrib.auth import get_user_model +from django.contrib.auth.backends import ModelBackend + + +class CaseInsensitiveBackend(ModelBackend): + """Usernames are one case-insensitive namespace (ADR-38): `Mario` and `mario` log in as the same account.""" + + def authenticate(self, request, username=None, password=None, **kwargs): + User = get_user_model() + if username is None or password is None: + return None + try: + user = User.objects.get(username__iexact=username) + except User.DoesNotExist: + # Run the hasher anyway, so an unknown name costs as much as a wrong password (SEC-19). + User().set_password(password) + return None + if user.check_password(password) and self.user_can_authenticate(user): + return user + return None diff --git a/apps/accounts/client_ip.py b/apps/accounts/client_ip.py new file mode 100644 index 0000000..4ce6e8a --- /dev/null +++ b/apps/accounts/client_ip.py @@ -0,0 +1,13 @@ +"""The caller's address, for the throttles that are keyed by it (SEC-42, B-54).""" + + +def client_ip(request) -> str: + """The *last* hop of X-Forwarded-For: the one written by our own proxy. The first elements are whatever + the client sent, so reading from the front would let a fake value per request dodge every IP-keyed + control. Caddy also overwrites the header with the real peer (Caddyfile), so either half closes it; + without the header (direct access) the socket peer is used.""" + forwarded = request.META.get("HTTP_X_FORWARDED_FOR", "") + hops = [hop.strip() for hop in forwarded.split(",") if hop.strip()] + if hops: + return hops[-1] + return request.META.get("REMOTE_ADDR", "unknown") diff --git a/apps/accounts/forms.py b/apps/accounts/forms.py new file mode 100644 index 0000000..5352285 --- /dev/null +++ b/apps/accounts/forms.py @@ -0,0 +1,70 @@ +from django import forms +from django.contrib.auth import get_user_model +from django.contrib.auth.password_validation import validate_password + +from .validators import username_validator + +User = get_user_model() + + +class LoginForm(forms.Form): + username = forms.CharField(label="Nome utente", max_length=150, strip=True, + widget=forms.TextInput(attrs={"autocomplete": "username", "autocapitalize": "none", + "spellcheck": "false", "autofocus": True})) + password = forms.CharField(label="Password", max_length=1024, strip=False, + widget=forms.PasswordInput(attrs={"autocomplete": "current-password"})) + + +class RegisterForm(forms.Form): + username = forms.CharField( + label="Nome utente", min_length=3, max_length=32, strip=True, validators=[username_validator], + help_text="Da 3 a 32 caratteri: lettere, numeri, punto, trattino e trattino basso.", + widget=forms.TextInput(attrs={"autocomplete": "username", "autocapitalize": "none", "spellcheck": "false", + "autofocus": True}), + ) + password = forms.CharField(label="Password", strip=False, help_text="Almeno 8 caratteri.", + widget=forms.PasswordInput(attrs={"autocomplete": "new-password"})) + password_confirm = forms.CharField(label="Ripeti la password", strip=False, + widget=forms.PasswordInput(attrs={"autocomplete": "new-password"})) + + def clean_username(self): + username = self.cleaned_data["username"] + if User.objects.filter(username__iexact=username).exists(): # one namespace, any case (ADR-38) + raise forms.ValidationError("Questo nome utente è già in uso.", code="username_taken") + return username + + def clean_password(self): + password = self.cleaned_data["password"] + validate_password(password) + return password + + def clean(self): + cleaned = super().clean() + if cleaned.get("password") and cleaned.get("password_confirm") and cleaned["password"] != cleaned["password_confirm"]: + self.add_error("password_confirm", "Le due password non coincidono.") + return cleaned + + +class PasswordChangeForm(forms.Form): + current_password = forms.CharField(label="Password attuale", max_length=1024, strip=False, + widget=forms.PasswordInput(attrs={"autocomplete": "current-password"})) + new_password = forms.CharField(label="Nuova password", strip=False, help_text="Almeno 8 caratteri.", + widget=forms.PasswordInput(attrs={"autocomplete": "new-password"})) + new_password_confirm = forms.CharField(label="Ripeti la nuova password", strip=False, + widget=forms.PasswordInput(attrs={"autocomplete": "new-password"})) + + def __init__(self, user, *args, **kwargs): + super().__init__(*args, **kwargs) + self.user = user + + def clean_new_password(self): + password = self.cleaned_data["new_password"] + validate_password(password, self.user) + return password + + def clean(self): + cleaned = super().clean() + if cleaned.get("new_password") and cleaned.get("new_password_confirm") and \ + cleaned["new_password"] != cleaned["new_password_confirm"]: + self.add_error("new_password_confirm", "Le due password non coincidono.") + return cleaned diff --git a/apps/accounts/migrations/0002_throttle_event.py b/apps/accounts/migrations/0002_throttle_event.py new file mode 100644 index 0000000..490f196 --- /dev/null +++ b/apps/accounts/migrations/0002_throttle_event.py @@ -0,0 +1,26 @@ +# Generated by Django 5.2.19 on 2026-11-16 12:52 + +import django.utils.timezone +from django.db import migrations, models + + +class Migration(migrations.Migration): + + dependencies = [ + ('accounts', '0001_initial'), + ] + + operations = [ + migrations.CreateModel( + name='ThrottleEvent', + fields=[ + ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('scope', models.CharField(max_length=16)), + ('key', models.CharField(max_length=150)), + ('created_at', models.DateTimeField(default=django.utils.timezone.now)), + ], + options={ + 'indexes': [models.Index(fields=['scope', 'key', 'created_at'], name='accounts_th_scope_248904_idx')], + }, + ), + ] diff --git a/apps/accounts/models.py b/apps/accounts/models.py index 8dc6041..a3f225e 100644 --- a/apps/accounts/models.py +++ b/apps/accounts/models.py @@ -1,6 +1,7 @@ from django.contrib.auth.models import AbstractUser from django.db import models from django.db.models.functions import Lower +from django.utils import timezone class User(AbstractUser): @@ -14,3 +15,18 @@ class User(AbstractUser): # ADR-38: one case-insensitive namespace. The name is stored as typed. models.UniqueConstraint(Lower("username"), name="accounts_user_username_ci_unique"), ] + + +class ThrottleEvent(models.Model): + """One counted event of a throttle (failed login, registration, wrong current password). + + In the database, not in memory: the web runs as several processes (ADR-55, ARC-72), and a throttle + kept in one process's memory is bypassed by whichever other process answers the next request. + """ + + scope = models.CharField(max_length=16) + key = models.CharField(max_length=150) + created_at = models.DateTimeField(default=timezone.now) + + class Meta: + indexes = [models.Index(fields=["scope", "key", "created_at"])] diff --git a/apps/accounts/templates/accounts/_field.html b/apps/accounts/templates/accounts/_field.html new file mode 100644 index 0000000..f25f95b --- /dev/null +++ b/apps/accounts/templates/accounts/_field.html @@ -0,0 +1,6 @@ +
+ + {{ field }} + {% if field.help_text %}

{{ field.help_text }}

{% endif %} + {% for error in field.errors %}{% endfor %} +
diff --git a/apps/accounts/templates/accounts/_form_errors.html b/apps/accounts/templates/accounts/_form_errors.html new file mode 100644 index 0000000..6db3437 --- /dev/null +++ b/apps/accounts/templates/accounts/_form_errors.html @@ -0,0 +1,4 @@ +{% if throttled_seconds %} + +{% endif %} +{% for error in form.non_field_errors %}{% endfor %} diff --git a/apps/accounts/templates/accounts/login.html b/apps/accounts/templates/accounts/login.html new file mode 100644 index 0000000..ffa7942 --- /dev/null +++ b/apps/accounts/templates/accounts/login.html @@ -0,0 +1,15 @@ +{% extends "web/base.html" %} +{% block title %}Accedi · PLM Lottery{% endblock %} +{% block content %} +
+

Accedi

+
+ {% csrf_token %} + + {% include "accounts/_form_errors.html" %} + {% for field in form %}{% include "accounts/_field.html" %}{% endfor %} + +
+

Non hai un account? Registrati.

+
+{% endblock %} diff --git a/apps/accounts/templates/accounts/profile.html b/apps/accounts/templates/accounts/profile.html new file mode 100644 index 0000000..2aa21cb --- /dev/null +++ b/apps/accounts/templates/accounts/profile.html @@ -0,0 +1,28 @@ +{% extends "web/base.html" %} +{% block title %}Profilo · PLM Lottery{% endblock %} +{% block content %} +

Profilo

+
+

Il tuo account

+
+
Nome utente
{{ user.get_username }}
+
Iscritto dal
{{ user.date_joined|date:"j F Y" }}
+
+
+
+

Cambia password

+
+ {% csrf_token %} + {% include "accounts/_form_errors.html" %} + {% for field in form %}{% include "accounts/_field.html" %}{% endfor %} + +
+
+
+

Esci

+
+ {% csrf_token %} + +
+
+{% endblock %} diff --git a/apps/accounts/templates/accounts/register.html b/apps/accounts/templates/accounts/register.html new file mode 100644 index 0000000..f8e125f --- /dev/null +++ b/apps/accounts/templates/accounts/register.html @@ -0,0 +1,16 @@ +{% extends "web/base.html" %} +{% block title %}Registrati · PLM Lottery{% endblock %} +{% block content %} +
+

Crea il tuo account

+
+ {% csrf_token %} + + {% include "accounts/_form_errors.html" %} + {% for field in form %}{% include "accounts/_field.html" %}{% endfor %} +

Non raccogliamo email: se perdi la password non esiste un recupero automatico, solo un reset da parte dell'operatore.

+ +
+

Hai già un account? Accedi.

+
+{% endblock %} diff --git a/apps/accounts/throttle.py b/apps/accounts/throttle.py new file mode 100644 index 0000000..685e865 --- /dev/null +++ b/apps/accounts/throttle.py @@ -0,0 +1,98 @@ +"""Throttles for credentials, shared by every web process (WEB-02, SEC-54, SEC-55). + +Two kinds, as in the old server (B-33, B-58): + +* `Backoff` — for failed guesses at a secret. After `threshold` failures in a row the next attempt must wait + `base_delay * 2**(failures - threshold)` seconds (capped), counted from the last failure; a streak ends when + the key stays quiet for `decay_seconds`, so a shared address is not punished forever for earlier mistakes. +* `Quota` — for "how many of these may one source create": a count in a rolling window, on completed actions. +""" + +from dataclasses import dataclass +from datetime import datetime, timedelta + +from django.utils import timezone + +from .models import ThrottleEvent + + +@dataclass(frozen=True) +class Backoff: + scope: str + threshold: int + base_delay: float + max_delay: float + decay_seconds: float + + +@dataclass(frozen=True) +class Quota: + scope: str + limit: int + window_seconds: float + + +LOGIN = Backoff("login", threshold=5, base_delay=2.0, max_delay=300.0, decay_seconds=900.0) +LOGIN_IP = Backoff("login_ip", threshold=20, base_delay=2.0, max_delay=300.0, decay_seconds=900.0) +CHANGE_PASSWORD = Backoff("chpwd", threshold=5, base_delay=2.0, max_delay=300.0, decay_seconds=900.0) +REGISTER = Quota("register", limit=5, window_seconds=3600.0) + +_KEY_MAX = 150 + + +def _key(key: str) -> str: + return key[:_KEY_MAX] + + +def _streak(rule: Backoff, key: str) -> list[datetime]: + """Timestamps of the current streak of failures, oldest first.""" + events = list( + ThrottleEvent.objects.filter(scope=rule.scope, key=_key(key)).order_by("-created_at") + .values_list("created_at", flat=True) + ) + streak: list[datetime] = [] + for created_at in events: # newest first: walk back while the gap stays within the decay + if streak and (streak[-1] - created_at).total_seconds() > rule.decay_seconds: + break + streak.append(created_at) + return streak[::-1] + + +def retry_after(rule: Backoff | Quota, key: str, now: datetime | None = None) -> float: + """Seconds until this key may try again; 0.0 while it may.""" + now = now or timezone.now() + if isinstance(rule, Quota): + window_start = now - timedelta(seconds=rule.window_seconds) + recent = list( + ThrottleEvent.objects.filter(scope=rule.scope, key=_key(key), created_at__gt=window_start) + .order_by("-created_at").values_list("created_at", flat=True)[: rule.limit] + ) + if len(recent) < rule.limit: + return 0.0 + return max(0.0, (recent[-1] + timedelta(seconds=rule.window_seconds) - now).total_seconds()) + + streak = _streak(rule, key) + if len(streak) < rule.threshold: + return 0.0 + if (now - streak[-1]).total_seconds() > rule.decay_seconds: + return 0.0 + delay = min(rule.max_delay, rule.base_delay * 2 ** (len(streak) - rule.threshold)) + return max(0.0, (streak[-1] + timedelta(seconds=delay) - now).total_seconds()) + + +def record(rule: Backoff | Quota, key: str, now: datetime | None = None) -> None: + """Count one failure (Backoff) or one completed action (Quota), and drop what no longer matters.""" + now = now or timezone.now() + ThrottleEvent.objects.create(scope=rule.scope, key=_key(key), created_at=now) + horizon = rule.window_seconds if isinstance(rule, Quota) else rule.decay_seconds + if isinstance(rule, Backoff): + streak = _streak(rule, key) + if streak: # events before the current streak can never count again + ThrottleEvent.objects.filter(scope=rule.scope, key=_key(key), created_at__lt=streak[0]).delete() + else: + ThrottleEvent.objects.filter(scope=rule.scope, created_at__lt=now - timedelta(seconds=horizon)).delete() + + +def reset(rule: Backoff, key: str) -> None: + """A success ends the streak of that key.""" + ThrottleEvent.objects.filter(scope=rule.scope, key=_key(key)).delete() diff --git a/apps/accounts/urls.py b/apps/accounts/urls.py new file mode 100644 index 0000000..d71f35c --- /dev/null +++ b/apps/accounts/urls.py @@ -0,0 +1,11 @@ +from django.urls import path + +from . import views + +app_name = "accounts" +urlpatterns = [ + path("accedi/", views.login_view, name="login"), + path("registrati/", views.register_view, name="register"), + path("esci/", views.logout_view, name="logout"), + path("app/profilo/", views.profile_view, name="profile"), +] diff --git a/apps/accounts/validators.py b/apps/accounts/validators.py new file mode 100644 index 0000000..72d0032 --- /dev/null +++ b/apps/accounts/validators.py @@ -0,0 +1,31 @@ +import re + +from django.core.exceptions import ValidationError +from django.core.validators import RegexValidator + +MIN_PASSWORD_LENGTH = 8 # SEC-17 +MAX_PASSWORD_LENGTH = 256 # bounds the hashing work an anonymous caller can ask for (SEC-17) + +username_validator = RegexValidator( + re.compile(r"^[A-Za-z0-9_.-]+$"), "Usa solo lettere, numeri, punto, trattino e trattino basso." +) + + +class MinimumLengthValidator: + def validate(self, password, user=None): + if len(password) < MIN_PASSWORD_LENGTH: + raise ValidationError(f"La password deve avere almeno {MIN_PASSWORD_LENGTH} caratteri.", + code="password_too_short") + + def get_help_text(self): + return f"Almeno {MIN_PASSWORD_LENGTH} caratteri." + + +class MaximumLengthValidator: + def validate(self, password, user=None): + if len(password) > MAX_PASSWORD_LENGTH: + raise ValidationError(f"La password può avere al massimo {MAX_PASSWORD_LENGTH} caratteri.", + code="password_too_long") + + def get_help_text(self): + return f"Al massimo {MAX_PASSWORD_LENGTH} caratteri." diff --git a/apps/accounts/views.py b/apps/accounts/views.py new file mode 100644 index 0000000..9f6be59 --- /dev/null +++ b/apps/accounts/views.py @@ -0,0 +1,136 @@ +"""Sign in, sign up, sign out and the profile (WEB-02, WEB-11, roadmap A5).""" + +from django.conf import settings +from django.contrib import messages +from django.contrib.auth import authenticate, login, logout, update_session_auth_hash +from django.contrib.auth.decorators import login_required +from django.db import IntegrityError, transaction +from django.shortcuts import redirect, render +from django.utils.http import url_has_allowed_host_and_scheme +from django.views.decorators.cache import never_cache +from django.views.decorators.http import require_http_methods, require_POST + +from apps.lottery import audit + +from . import throttle +from .client_ip import client_ip +from .forms import LoginForm, PasswordChangeForm, RegisterForm +from .models import User + +BACKEND = "apps.accounts.backends.CaseInsensitiveBackend" + + +def safe_next(request, value: str | None) -> str: + """WEB-11: a destination after sign-in is honoured only if it is a path on this site. An external + address, a protocol-relative `//host`, a backslash trick or a scheme (`javascript:`) all fall back to + the default, so the login page cannot be used to send people elsewhere.""" + if ( + value + and value.startswith("/") + and not value.startswith("//") + and "\\" not in value + and url_has_allowed_host_and_scheme(value, allowed_hosts={request.get_host()}, require_https=request.is_secure()) + ): + return value + return settings.LOGIN_REDIRECT_URL + + +def _too_many(request, template: str, context: dict, wait: float): + seconds = int(wait) + 1 + context = {**context, "throttled_seconds": seconds} + response = render(request, template, context, status=429) + response["Retry-After"] = str(seconds) + return response + + +@never_cache +@require_http_methods(["GET", "POST"]) +def login_view(request): + next_url = request.POST.get("next") or request.GET.get("next") or "" + if request.user.is_authenticated: + return redirect(safe_next(request, next_url)) + + form = LoginForm(request.POST or None) + context = {"form": form, "next": next_url} + if request.method == "POST": + ip = client_ip(request) + user_key = request.POST.get("username", "").strip().lower() + wait = max(throttle.retry_after(throttle.LOGIN, user_key), throttle.retry_after(throttle.LOGIN_IP, ip)) + if wait > 0: # refused before the password is even looked at + return _too_many(request, "accounts/login.html", context, wait) + user = None + if form.is_valid(): + user = authenticate(request, username=form.cleaned_data["username"], password=form.cleaned_data["password"]) + if user is None: + # The same answer whether the name does not exist or the password is wrong (SEC-19). + throttle.record(throttle.LOGIN, user_key) + throttle.record(throttle.LOGIN_IP, ip) + form.add_error(None, "Nome utente o password non corretti.") + return render(request, "accounts/login.html", context, status=200) + throttle.reset(throttle.LOGIN, user_key) # the address keeps its count: one success must not wipe a spray + login(request, user, backend=BACKEND) # also gives the session a fresh key + return redirect(safe_next(request, next_url)) + return render(request, "accounts/login.html", context) + + +@never_cache +@require_http_methods(["GET", "POST"]) +def register_view(request): + next_url = request.POST.get("next") or request.GET.get("next") or "" + if request.user.is_authenticated: + return redirect(safe_next(request, next_url)) + + form = RegisterForm(request.POST or None) + context = {"form": form, "next": next_url} + if request.method == "POST": + ip = client_ip(request) + wait = throttle.retry_after(throttle.REGISTER, ip) + if wait > 0: + return _too_many(request, "accounts/register.html", context, wait) + if form.is_valid(): + try: + with transaction.atomic(): + user = User.objects.create_user(form.cleaned_data["username"], password=form.cleaned_data["password"]) + audit.record("user_registered", actor=user, subject_type="user", subject_id=user.pk) + except IntegrityError: # lost a race for the same name: the constraint is the backstop + form.add_error("username", "Questo nome utente è già in uso.") + else: + throttle.record(throttle.REGISTER, ip) # counts accounts that exist, not attempts + login(request, user, backend=BACKEND) + return redirect(safe_next(request, next_url)) + return render(request, "accounts/register.html", context) + + +@require_POST +def logout_view(request): + logout(request) + return redirect(settings.LOGOUT_REDIRECT_URL) + + +@never_cache +@login_required +@require_http_methods(["GET", "POST"]) +def profile_view(request): + form = PasswordChangeForm(request.user, request.POST or None) + if request.method == "POST": + key = str(request.user.pk) + wait = throttle.retry_after(throttle.CHANGE_PASSWORD, key) + if wait > 0: + return _too_many(request, "accounts/profile.html", {"form": form}, wait) + if form.is_valid(): + if not request.user.check_password(form.cleaned_data["current_password"]): + # SEC-54: a stolen session must not be able to guess the password and lock the owner out. + throttle.record(throttle.CHANGE_PASSWORD, key) + form.add_error("current_password", "La password attuale non è corretta.") + else: + with transaction.atomic(): + request.user.set_password(form.cleaned_data["new_password"]) + request.user.save(update_fields=["password"]) + audit.record("password_changed", actor=request.user, subject_type="user", subject_id=request.user.pk) + throttle.reset(throttle.CHANGE_PASSWORD, key) + # This session stays signed in; every other one is signed out, because a session is bound + # to the hash of the password it was created with (B-34). + update_session_auth_hash(request, request.user) + messages.success(request, "Password aggiornata. Le altre sessioni sono state chiuse.") + return redirect("accounts:profile") + return render(request, "accounts/profile.html", {"form": form}) diff --git a/apps/web/static/web/site.css b/apps/web/static/web/site.css new file mode 100644 index 0000000..c0058bb --- /dev/null +++ b/apps/web/static/web/site.css @@ -0,0 +1,70 @@ +/* One stylesheet for the whole site (ADR-54). Mobile first, no inline styles or scripts anywhere, so the + Content-Security-Policy can be tightened for these pages (Caddyfile). */ +:root { + --bg: #f6f7f9; --surface: #ffffff; --text: #16202a; --muted: #5a6672; --line: #d9dee4; + --accent: #1b5fd6; --accent-text: #ffffff; --error: #b42318; --error-bg: #fdecea; --ok: #067647; --ok-bg: #e7f6ec; + --radius: 10px; --gap: 1rem; + color-scheme: light dark; +} +@media (prefers-color-scheme: dark) { + :root { + --bg: #10161c; --surface: #19222b; --text: #e8edf2; --muted: #9aa7b3; --line: #2b3742; + --accent: #6ea0ff; --accent-text: #0b1220; --error: #ff8f85; --error-bg: #3a1d1b; --ok: #6ddba0; --ok-bg: #12301f; + } +} +*, *::before, *::after { box-sizing: border-box; } +html { -webkit-text-size-adjust: 100%; } +body { margin: 0; background: var(--bg); color: var(--text); line-height: 1.55; + font: 1rem/1.55 system-ui, -apple-system, "Segoe UI", Roboto, sans-serif; } +h1 { font-size: 1.6rem; line-height: 1.25; margin: 1.2rem 0 .8rem; } +h2 { font-size: 1.2rem; margin: 0 0 .8rem; } +a { color: var(--accent); } +.wrap { width: 100%; max-width: 60rem; margin-inline: auto; padding-inline: 1rem; } +main { padding-block: 1rem 3rem; min-height: 60vh; } +main:focus { outline: none; } + +.skip-link { position: absolute; left: .5rem; top: -4rem; background: var(--accent); color: var(--accent-text); + padding: .6rem 1rem; border-radius: var(--radius); z-index: 10; } +.skip-link:focus { top: .5rem; } + +.site-header { background: var(--surface); border-bottom: 1px solid var(--line); } +.bar { display: flex; flex-wrap: wrap; align-items: center; justify-content: space-between; gap: .5rem 1rem; padding-block: .6rem; } +.brand { font-weight: 700; font-size: 1.15rem; color: var(--text); text-decoration: none; } +.nav { display: flex; flex-wrap: wrap; align-items: center; gap: .25rem .9rem; } +.nav a { text-decoration: none; padding: .5rem .2rem; } +.nav a.button { padding: .5rem .9rem; } +.inline { display: inline; margin: 0; } + +.card { background: var(--surface); border: 1px solid var(--line); border-radius: var(--radius); padding: 1.2rem; margin-block: 1rem; } +.narrow { max-width: 28rem; } + +.field { margin-bottom: 1rem; } +label { display: block; font-weight: 600; margin-bottom: .3rem; } +input[type=text], input[type=password] { width: 100%; min-height: 2.75rem; padding: .55rem .75rem; font: inherit; color: var(--text); + background: var(--bg); border: 1px solid var(--line); border-radius: 8px; } +.has-error input { border-color: var(--error); } +.hint { color: var(--muted); font-size: .9rem; margin: .3rem 0 0; } +.error { color: var(--error); font-size: .95rem; margin: .3rem 0 0; } +.error.box { background: var(--error-bg); border-radius: 8px; padding: .6rem .8rem; margin: 0 0 1rem; } +.messages { margin-block: 1rem 0; } +.message { background: var(--ok-bg); color: var(--ok); border-radius: 8px; padding: .6rem .8rem; margin: 0 0 .5rem; } +.message.error { background: var(--error-bg); color: var(--error); } + +.button, .link-button { font: inherit; cursor: pointer; } +.button { display: inline-flex; align-items: center; justify-content: center; min-height: 2.75rem; padding: .55rem 1.2rem; border: 0; + border-radius: 8px; background: var(--accent); color: var(--accent-text); font-weight: 600; text-decoration: none; } +.button.secondary { background: transparent; color: var(--accent); border: 1px solid var(--accent); } +.button.small { min-height: 2.25rem; padding: .3rem .9rem; } +.link-button { background: none; border: 0; color: var(--accent); padding: .5rem .2rem; text-decoration: underline; } +.aside { color: var(--muted); margin: 1rem 0 0; } + +.facts { display: grid; grid-template-columns: max-content 1fr; gap: .3rem 1rem; margin: 0; } +.facts dt { color: var(--muted); } .facts dd { margin: 0; } + +.site-footer { border-top: 1px solid var(--line); color: var(--muted); font-size: .9rem; padding-block: 1rem; } + +/* Keyboard users always see where they are (WEB-06). */ +:focus-visible { outline: 3px solid var(--accent); outline-offset: 2px; } + +@media (min-width: 40rem) { h1 { font-size: 2rem; } .card { padding: 1.6rem; } } +@media (prefers-reduced-motion: reduce) { * { transition: none !important; animation: none !important; } } diff --git a/apps/web/templates/web/app_home.html b/apps/web/templates/web/app_home.html new file mode 100644 index 0000000..c5f02ad --- /dev/null +++ b/apps/web/templates/web/app_home.html @@ -0,0 +1,6 @@ +{% extends "web/base.html" %} +{% block title %}Gioca · PLM Lottery{% endblock %} +{% block content %} +

Area giocatore

+

Ciao {{ user.get_username }}. La schermata di gioco è in costruzione.

+{% endblock %} diff --git a/apps/web/templates/web/base.html b/apps/web/templates/web/base.html new file mode 100644 index 0000000..5a091ec --- /dev/null +++ b/apps/web/templates/web/base.html @@ -0,0 +1,47 @@ +{% load static %} + + + + + + {% block title %}PLM Lottery{% endblock %} + + + + + + +
+ {% if messages %} +
+ {% for message in messages %}

{{ message }}

{% endfor %} +
+ {% endif %} + {% block content %}{% endblock %} +
+ +
+
+

Ambiente di prova su rete regtest: nessun denaro reale.

+
+
+ + diff --git a/apps/web/templates/web/error.html b/apps/web/templates/web/error.html new file mode 100644 index 0000000..a2a3d89 --- /dev/null +++ b/apps/web/templates/web/error.html @@ -0,0 +1,7 @@ +{% extends "web/base.html" %} +{% block title %}{{ title }} · PLM Lottery{% endblock %} +{% block content %} +

{{ title }}

+

{{ message }}

+

Torna alla home

+{% endblock %} diff --git a/apps/web/templates/web/home.html b/apps/web/templates/web/home.html index 4fe5816..209d589 100644 --- a/apps/web/templates/web/home.html +++ b/apps/web/templates/web/home.html @@ -1,14 +1,5 @@ - - - - - - PLM Lottery - - -
-

PLM Lottery

-

Il sito è in costruzione.

-
- - +{% extends "web/base.html" %} +{% block content %} +

PLM Lottery

+

Il sito è in costruzione.

+{% endblock %} diff --git a/apps/web/urls.py b/apps/web/urls.py index 90f2092..f9aa9d9 100644 --- a/apps/web/urls.py +++ b/apps/web/urls.py @@ -5,5 +5,6 @@ from . import views app_name = "web" urlpatterns = [ path("", views.home, name="home"), + path("app/", views.app_home, name="app-home"), path("health/live", views.health_live, name="health-live"), ] diff --git a/apps/web/views.py b/apps/web/views.py index c1b4790..93d1657 100644 --- a/apps/web/views.py +++ b/apps/web/views.py @@ -1,6 +1,8 @@ +from django.contrib.auth.decorators import login_required from django.db import connection from django.http import HttpResponse, JsonResponse from django.shortcuts import render +from django.views.decorators.cache import never_cache def home(request): @@ -8,6 +10,13 @@ def home(request): return render(request, "web/home.html") +@never_cache +@login_required +def app_home(request): + """Placeholder of the player area (WEB-20): the play screen arrives with A7.""" + return render(request, "web/app_home.html") + + def health_live(request): """Liveness for the container healthcheck: the process answers and the database opens (ARC-73).""" try: @@ -16,3 +25,27 @@ def health_live(request): except Exception: return HttpResponse("database unavailable", status=503, content_type="text/plain") return JsonResponse({"status": "ok"}) + + +# Error pages in Italian, in the site's own layout, with a way out (WEB-06). + + +def csrf_failure(request, reason=""): + return render(request, "web/error.html", { + "title": "Sessione scaduta", + "message": "Il modulo non è più valido, probabilmente perché la pagina è rimasta aperta a lungo. " + "Ricarica la pagina e riprova.", + }, status=403) + + +def not_found(request, exception=None): + return render(request, "web/error.html", { + "title": "Pagina non trovata", "message": "L'indirizzo richiesto non esiste.", + }, status=404) + + +def server_error(request): + return render(request, "web/error.html", { + "title": "Qualcosa è andato storto", + "message": "Si è verificato un errore. Riprova fra qualche istante.", + }, status=500) diff --git a/config/settings.py b/config/settings.py index 5c977ae..2284f3c 100644 --- a/config/settings.py +++ b/config/settings.py @@ -53,8 +53,9 @@ MIDDLEWARE = [ "django.middleware.security.SecurityMiddleware", "whitenoise.middleware.WhiteNoiseMiddleware", "django.contrib.sessions.middleware.SessionMiddleware", + "django.middleware.locale.LocaleMiddleware", "django.middleware.common.CommonMiddleware", - "django.middleware.csrf.CsrfViewMiddleware", + "django.middleware.csrf.CsrfViewMiddleware", "django.contrib.auth.middleware.AuthenticationMiddleware", "django.contrib.messages.middleware.MessageMiddleware", "django.middleware.clickjacking.XFrameOptionsMiddleware", @@ -102,14 +103,16 @@ PASSWORD_HASHERS = [ "django.contrib.auth.hashers.Argon2PasswordHasher", "django.contrib.auth.hashers.PBKDF2PasswordHasher", ] +# SEC-17: 8 to 256 characters, nothing more — the same thresholds as the old server. AUTH_PASSWORD_VALIDATORS = [ - {"NAME": "django.contrib.auth.password_validation.MinimumLengthValidator", "OPTIONS": {"min_length": 8}}, - {"NAME": "django.contrib.auth.password_validation.CommonPasswordValidator"}, - {"NAME": "django.contrib.auth.password_validation.NumericPasswordValidator"}, + {"NAME": "apps.accounts.validators.MinimumLengthValidator"}, + {"NAME": "apps.accounts.validators.MaximumLengthValidator"}, ] +AUTHENTICATION_BACKENDS = ["apps.accounts.backends.CaseInsensitiveBackend"] # ADR-60: Italian only for the pilot; gettext is on so other languages can be added later. LANGUAGE_CODE = "it" +LANGUAGES = [("it", "Italiano")] # one language: the middleware activates it, so Django's own messages are Italian too TIME_ZONE = "UTC" USE_I18N = True USE_TZ = True @@ -126,6 +129,7 @@ STORAGES = { SECURE_PROXY_SSL_HEADER = ("HTTP_X_FORWARDED_PROTO", "https") SESSION_COOKIE_SECURE = not DEBUG CSRF_COOKIE_SECURE = not DEBUG +SESSION_COOKIE_AGE = 24 * 3600 # a session lasts a day, like the old token (ADR-36) SESSION_COOKIE_HTTPONLY = True SESSION_COOKIE_SAMESITE = "Lax" CSRF_COOKIE_SAMESITE = "Lax" @@ -136,6 +140,7 @@ SECURE_REFERRER_POLICY = "strict-origin-when-cross-origin" LOGIN_URL = "/accedi/" LOGIN_REDIRECT_URL = "/app/" LOGOUT_REDIRECT_URL = "/" +CSRF_FAILURE_VIEW = "apps.web.views.csrf_failure" LOGGING = { "version": 1, diff --git a/config/urls.py b/config/urls.py index 33cdcca..99f48c0 100644 --- a/config/urls.py +++ b/config/urls.py @@ -3,5 +3,9 @@ from django.urls import include, path urlpatterns = [ path("admin/", admin.site.urls), + path("", include("apps.accounts.urls")), path("", include("apps.web.urls")), ] + +handler404 = "apps.web.views.not_found" +handler500 = "apps.web.views.server_error" diff --git a/docs/sito-e-app.md b/docs/sito-e-app.md index 1ef0eb8..13695ee 100644 --- a/docs/sito-e-app.md +++ b/docs/sito-e-app.md @@ -32,6 +32,10 @@ backend FastAPI (vedi [architettura.md](architettura.md)). - **[WEB-02]** L'autenticazione usa le sessioni Django; ogni scrittura è protetta da CSRF e il cookie di sessione ha gli attributi `Secure`, `HttpOnly` e `SameSite`. + *Stato:* implementato (A5): sessione di 24 ore, cookie `Secure`/`HttpOnly`/`SameSite=Lax`, CSRF su ogni modulo con + pagina di errore leggibile · + *Codice:* `config/settings.py`, `apps/web/views.py:csrf_failure` · + *Test:* `tests/django/test_accounts.py::test_the_session_cookie_is_httponly_secure_and_samesite`, `test_a_form_without_the_csrf_token_is_refused` - **[WEB-03]** Ogni richiesta dell'area giocatore legge o modifica soltanto i dati dell'utente autenticato; un identificativo di un altro utente dà 404. - **[WEB-04]** Importi e saldi si rappresentano in unità minime intere @@ -44,6 +48,11 @@ backend FastAPI (vedi [architettura.md](architettura.md)). pagina; ricaricare non perde lo stato salvato. - **[WEB-06]** Le pagine sono utilizzabili da smartphone e da desktop e navigabili da tastiera, con stati distinti di errore, attesa e conferma. + *Stato:* base implementata (A5): layout fluido da 400 px, foglio di stile unico con tema chiaro/scuro, collegamento «Vai al + contenuto», focus sempre visibile, etichette su ogni campo, errori annunciati (`role="alert"`), nessuno script né stile + inline, pagine d'errore in italiano; la verifica su telefono e desktop con le schermate finali è l'A10 · + *Codice:* `apps/web/templates/web/base.html`, `apps/web/static/web/site.css` · + *Test:* `tests/django/test_accounts.py::test_every_page_is_responsive_and_keyboard_friendly`, `test_every_input_has_its_label`, `test_pages_use_no_inline_scripts_or_styles` - **[WEB-07]** Il sito si avvia e si naviga in locale su `http://localhost` (stesso `docker-compose.yml` di sempre, `SITE_ADDRESS` non impostato) con @@ -64,6 +73,7 @@ backend FastAPI (vedi [architettura.md](architettura.md)). - **[WEB-11]** «Partecipa» porta a `/app/`; se serve il login, dopo l'accesso riporta alla schermata di gioco. Il pulsante apre il flusso: la puntata richiede una conferma esplicita. + *Stato:* il ritorno alla destinazione interna è implementato (A5, [WEB-52]); il pulsante con l'A6. - **[WEB-12]** `/risultati/` pubblica esito e prova dell'estrazione, riproducibile con i dati del protocollo ([RND-14]…[RND-20]), senza username né dati dell'account. Il pagamento risulta confermato solo quando lo è. @@ -137,3 +147,43 @@ Servizi: `web` (Django + gunicorn, applica le migrazioni), `worker` ([ARC-71]) e Con un dominio reale basta `SITE_ADDRESS=lottery.example.com docker compose up -d` ([WEB-07]). Il vecchio `docs/setup.md` e `docs/running-the-server.md` descrivono lo stack FastAPI, che non è più nel compose. + +## 7 · Accesso e account + +- **[WEB-50]** **Registrazione.** `/registrati/` crea un account con nome utente di 3–32 caratteri `[A-Za-z0-9_.-]`, unico + **senza distinzione fra maiuscole e minuscole** e salvato come digitato ([ADR-38](adr/ADR-38-username-unico-spazio-nomi-senza-distinzione.md)), + e password di 8–256 caratteri da ripetere due volte ([SEC-17]). Non si raccoglie alcuna email, quindi non esiste un recupero + automatico ([ADR-37](adr/ADR-37-nessun-recupero-password-reset.md)). Alla fine l'utente è già connesso e la + registrazione è nell'audit (`user_registered`). La password è salvata con Argon2 ([ADR-36](adr/ADR-36-password-argon2-sessioni-jwt-hs256-24.md)). + *Stato:* implementato (A5) · + *Codice:* `apps/accounts/views.py:register_view`, `apps/accounts/forms.py:RegisterForm`, `apps/accounts/validators.py` · + *Test:* `tests/django/test_accounts.py::test_registering_creates_the_account_and_signs_in`, `test_a_name_that_differs_only_by_case_is_taken`, `test_password_length_limits` +- **[WEB-51]** **Accesso.** `/accedi/` ammette il nome utente in qualunque combinazione di maiuscole e minuscole e risponde + **allo stesso modo** a un nome inesistente e a una password sbagliata ([SEC-19]); al login la sessione riceve una chiave nuova; + un account disattivato non entra; un utente già connesso che apre `/accedi/` o `/registrati/` è rimandato avanti. + *Stato:* implementato (A5) · + *Codice:* `apps/accounts/views.py:login_view`, `apps/accounts/backends.py:CaseInsensitiveBackend` · + *Test:* `tests/django/test_accounts.py::test_unknown_name_and_wrong_password_look_the_same`, `test_signing_in_gives_a_fresh_session`, `test_login_ignores_the_case_of_the_name` +- **[WEB-52]** **Destinazione dopo l'accesso.** `?next=` (e il campo nascosto che lo porta attraverso un errore o il passaggio alla + registrazione) è rispettato **solo se è un percorso del sito**: un indirizzo esterno, `//host`, una barra rovesciata o uno schema + (`javascript:`) ricadono su `/app/`, così la pagina di accesso non può mandare altrove. `/app/` e `/app/profilo/` senza sessione + rimandano ad `/accedi/?next=…`. + *Stato:* implementato (A5) · + *Codice:* `apps/accounts/views.py:safe_next` · + *Test:* `tests/django/test_accounts.py::test_an_open_redirect_is_refused`, `test_an_internal_destination_is_honoured`, `test_the_destination_survives_a_wrong_password_and_the_trip_to_registration` +- **[WEB-53]** **Limiti ai tentativi, condivisi fra i processi.** Lo stato sta nel database (`ThrottleEvent`), non in memoria + ([ARC-72]). *Accesso:* dopo 5 errori sullo stesso nome (20 sullo stesso indirizzo) ogni tentativo deve attendere + `2 s · 2^(errori − soglia)`, fino a 300 s dall'ultimo errore; la serie finisce dopo 900 s di quiete; un accesso riuscito azzera il + nome ma **non** l'indirizzo; durante l'attesa non si guarda nemmeno la password (risposta `429` con `Retry-After`). + *Registrazione:* al massimo 5 account all'ora per indirizzo, contando gli account creati e non i tentativi. *Cambio password:* + 5 errori sulla password attuale per utente, poi attesa ([SEC-54]). L'indirizzo del cliente è l'**ultimo** elemento di + `X-Forwarded-For`, quello scritto dal nostro proxy ([B-54]). + *Stato:* implementato (A5) · + *Codice:* `apps/accounts/throttle.py`, `apps/accounts/client_ip.py` · + *Test:* `tests/django/test_accounts.py::test_five_wrong_guesses_lock_the_name_for_a_while`, `test_the_wait_doubles_with_every_further_failure_and_is_capped`, `test_spraying_one_password_over_many_names_is_caught_by_the_address`, `test_one_address_can_register_five_accounts_an_hour`, `test_a_forged_forwarded_header_cannot_dodge_the_ip_controls` +- **[WEB-54]** **Uscita e cambio password.** L'uscita è solo `POST` (con CSRF) e chiude la sessione. Il cambio password chiede la password + attuale, chiude **tutte le altre sessioni** (una sessione è legata all'impronta della password con cui nasce, [B-34]), lascia + connessa quella corrente e scrive `password_changed` nell'audit. `/app/profilo/` mostra solo i dati dell'utente connesso ([WEB-03]). + *Stato:* implementato (A5); le segnalazioni del profilo non sono ancora previste · + *Codice:* `apps/accounts/views.py:logout_view`, `apps/accounts/views.py:profile_view` · + *Test:* `tests/django/test_accounts.py::test_a_password_change_signs_out_every_other_session`, `test_signing_out_ends_the_session_and_only_by_post`, `test_the_profile_shows_only_the_owner` diff --git a/roadmap.md b/roadmap.md index 5f2d872..1408060 100644 --- a/roadmap.md +++ b/roadmap.md @@ -28,7 +28,7 @@ Uscita: un giocatore completa il round dimostrativo in `localhost`, l'operatore - [x] **A2 · Modelli e vincoli.** Account, Round (parametri fotografati all'apertura), Partecipazione, Movimento, Transazione, Audit (solo aggiunta). Importi interi in unità minime; un solo round attivo e una sola puntata per utente e round come vincoli del database. *Requisiti:* WEB-04, DAT. *Test:* violazione di ogni vincolo. - [x] **A3 · Ledger simulato.** Interfaccia dei servizi (deposito, puntata, pagamento) con implementazione simulata e **chiave di idempotenza**: un doppio invio produce una sola operazione. *Requisiti:* WEB-23, ADR-59. *Test:* doppio invio, saldo insufficiente, importi al limite. - [x] **A4 · Ciclo del round e worker.** Apertura, chiusura, estrazione e pagamento 70/30 nel worker (`manage.py run_worker`), con l'estrazione commit-reveal dello stesso algoritmo del motore. *Requisiti:* RND esistenti riletti sul modello nuovo. *Test:* round completo deterministico, ripresa dopo riavvio del worker. -- [ ] **A5 · Autenticazione e base grafica.** `/registrati/`, `/accedi/`, `/app/profilo/` (password, logout), CSRF, cookie di sessione, ritorno alla destinazione interna (`next`) solo se interna, template base e CSS responsivo. *Requisiti:* WEB-02, WEB-06. *Test:* redirect aperto rifiutato, cookie, throttling dei tentativi. +- [x] **A5 · Autenticazione e base grafica.** `/registrati/`, `/accedi/`, `/app/profilo/` (password, logout), CSRF, cookie di sessione, ritorno alla destinazione interna (`next`) solo se interna, template base e CSS responsivo. *Requisiti:* WEB-02, WEB-06. *Test:* redirect aperto rifiutato, cookie, throttling dei tentativi. - [ ] **A6 · Home pubblica.** `/` con quota, montepremi confermato, chiusura (ora server) e i sei stati, «Partecipa», aggiornamento a polling. *Requisiti:* WEB-05, WEB-10, WEB-11. *Test:* un test per stato, polling dell'endpoint. - [ ] **A7 · Area giocatore.** `/app/` (puntata con conferma esplicita), `/app/portafoglio/` (saldo spendibile e in conferma, deposito simulato **solo fuori da mainnet**), `/app/movimenti/`. *Requisiti:* WEB-03, WEB-20, WEB-21, WEB-22. *Test:* isolamento tra utenti (404 su dati altrui), stato salvato dopo ricarica. - [ ] **A8 · Pagine pubbliche di risultato e guida.** `/risultati/`, `/risultati//` con prova riproducibile senza dati dell'account, `/guida/`, `/regole/` con gli stessi termini dell'app. *Requisiti:* WEB-12, WEB-13. *Test:* la prova ricalcola il vincitore; nessuno username nelle pagine. diff --git a/tests/django/test_accounts.py b/tests/django/test_accounts.py new file mode 100644 index 0000000..5a7a899 --- /dev/null +++ b/tests/django/test_accounts.py @@ -0,0 +1,506 @@ +"""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 '' in html + assert '' in html and 'class="skip-link"' in html and '
' 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 "