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>
This commit is contained in:
davideandClaude Sonnet 5.5 committed 2026-11-16 14:07:45 +01:00
1 parent 1d4b53d778
commit efb3e2e702
28 files changed
+1232 -22

No files matched your search

+2 -2
View File
@@ -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
```
+1 -1
View File
@@ -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
+20
View File
@@ -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
+13
View File
@@ -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")
+70
View File
@@ -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
@@ -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')],
},
),
]
+16
View File
@@ -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"])]
@@ -0,0 +1,6 @@
<div class="field{% if field.errors %} has-error{% endif %}">
<label for="{{ field.id_for_label }}">{{ field.label }}</label>
{{ field }}
{% if field.help_text %}<p class="hint" id="{{ field.id_for_label }}-hint">{{ field.help_text }}</p>{% endif %}
{% for error in field.errors %}<p class="error" role="alert">{{ error }}</p>{% endfor %}
</div>
@@ -0,0 +1,4 @@
{% if throttled_seconds %}
<p class="error box" role="alert">Troppi tentativi. Riprova fra {{ throttled_seconds }} second{{ throttled_seconds|pluralize:"o,i" }}.</p>
{% endif %}
{% for error in form.non_field_errors %}<p class="error box" role="alert">{{ error }}</p>{% endfor %}
@@ -0,0 +1,15 @@
{% extends "web/base.html" %}
{% block title %}Accedi · PLM Lottery{% endblock %}
{% block content %}
<section class="card narrow">
<h1>Accedi</h1>
<form method="post" novalidate>
{% csrf_token %}
<input type="hidden" name="next" value="{{ next }}">
{% include "accounts/_form_errors.html" %}
{% for field in form %}{% include "accounts/_field.html" %}{% endfor %}
<button class="button" type="submit">Accedi</button>
</form>
<p class="aside">Non hai un account? <a href="{% url 'accounts:register' %}{% if next %}?next={{ next|urlencode }}{% endif %}">Registrati</a>.</p>
</section>
{% endblock %}
@@ -0,0 +1,28 @@
{% extends "web/base.html" %}
{% block title %}Profilo · PLM Lottery{% endblock %}
{% block content %}
<h1>Profilo</h1>
<section class="card">
<h2>Il tuo account</h2>
<dl class="facts">
<dt>Nome utente</dt><dd>{{ user.get_username }}</dd>
<dt>Iscritto dal</dt><dd>{{ user.date_joined|date:"j F Y" }}</dd>
</dl>
</section>
<section class="card narrow">
<h2>Cambia password</h2>
<form method="post" novalidate>
{% csrf_token %}
{% include "accounts/_form_errors.html" %}
{% for field in form %}{% include "accounts/_field.html" %}{% endfor %}
<button class="button" type="submit">Aggiorna la password</button>
</form>
</section>
<section class="card narrow">
<h2>Esci</h2>
<form method="post" action="{% url 'accounts:logout' %}">
{% csrf_token %}
<button class="button secondary" type="submit">Esci da questo dispositivo</button>
</form>
</section>
{% endblock %}
@@ -0,0 +1,16 @@
{% extends "web/base.html" %}
{% block title %}Registrati · PLM Lottery{% endblock %}
{% block content %}
<section class="card narrow">
<h1>Crea il tuo account</h1>
<form method="post" novalidate>
{% csrf_token %}
<input type="hidden" name="next" value="{{ next }}">
{% include "accounts/_form_errors.html" %}
{% for field in form %}{% include "accounts/_field.html" %}{% endfor %}
<p class="hint">Non raccogliamo email: se perdi la password non esiste un recupero automatico, solo un reset da parte dell'operatore.</p>
<button class="button" type="submit">Registrati</button>
</form>
<p class="aside">Hai già un account? <a href="{% url 'accounts:login' %}{% if next %}?next={{ next|urlencode }}{% endif %}">Accedi</a>.</p>
</section>
{% endblock %}
+98
View File
@@ -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()
+11
View File
@@ -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"),
]
+31
View File
@@ -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."
+136
View File
@@ -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})
+70
View File
@@ -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; } }
+6
View File
@@ -0,0 +1,6 @@
{% extends "web/base.html" %}
{% block title %}Gioca · PLM Lottery{% endblock %}
{% block content %}
<h1>Area giocatore</h1>
<p>Ciao {{ user.get_username }}. La schermata di gioco è in costruzione.</p>
{% endblock %}
+47
View File
@@ -0,0 +1,47 @@
{% load static %}<!doctype html>
<html lang="it">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="color-scheme" content="light dark">
<title>{% block title %}PLM Lottery{% endblock %}</title>
<link rel="stylesheet" href="{% static 'web/site.css' %}">
</head>
<body>
<a class="skip-link" href="#contenuto">Vai al contenuto</a>
<header class="site-header">
<div class="wrap bar">
<a class="brand" href="{% url 'web:home' %}">PLM Lottery</a>
<nav class="nav" aria-label="Principale">
<a href="{% url 'web:home' %}">Home</a>
{% if user.is_authenticated %}
<a href="{% url 'web:app-home' %}">Gioca</a>
<a href="{% url 'accounts:profile' %}">Profilo</a>
<form class="inline" method="post" action="{% url 'accounts:logout' %}">
{% csrf_token %}
<button class="link-button" type="submit">Esci ({{ user.get_username }})</button>
</form>
{% else %}
<a href="{% url 'accounts:login' %}">Accedi</a>
<a class="button small" href="{% url 'accounts:register' %}">Registrati</a>
{% endif %}
</nav>
</div>
</header>
<main id="contenuto" class="wrap" tabindex="-1">
{% if messages %}
<div class="messages" role="status">
{% for message in messages %}<p class="message {{ message.tags }}">{{ message }}</p>{% endfor %}
</div>
{% endif %}
{% block content %}{% endblock %}
</main>
<footer class="site-footer">
<div class="wrap">
<p>Ambiente di prova su rete regtest: nessun denaro reale.</p>
</div>
</footer>
</body>
</html>
+7
View File
@@ -0,0 +1,7 @@
{% extends "web/base.html" %}
{% block title %}{{ title }} · PLM Lottery{% endblock %}
{% block content %}
<h1>{{ title }}</h1>
<p>{{ message }}</p>
<p><a class="button" href="/">Torna alla home</a></p>
{% endblock %}
+5 -14
View File
@@ -1,14 +1,5 @@
<!doctype html>
<html lang="it">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>PLM Lottery</title>
</head>
<body>
<main>
<h1>PLM Lottery</h1>
<p>Il sito è in costruzione.</p>
</main>
</body>
</html>
{% extends "web/base.html" %}
{% block content %}
<h1>PLM Lottery</h1>
<p>Il sito è in costruzione.</p>
{% endblock %}
+1
View File
@@ -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"),
]
+33
View File
@@ -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)
+9 -4
View File
@@ -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,
+4
View File
@@ -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"
+50
View File
@@ -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`
+1 -1
View File
@@ -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/<id>/` 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.
+506
View File
@@ -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 '<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"]