From 398e4487ad84e768aad1f2b7f3d7ad0955991c6b Mon Sep 17 00:00:00 2001 From: denis Date: Fri, 16 Oct 2026 22:35:41 +0200 Subject: [PATCH] Add Django administration for author accounts: Auteurs group, use_editor permission, grant/revoke actions, shared login throttling Co-Authored-By: Claude Sonnet 5.5 --- CLAUDE.md | 3 +- CONTEXT.md | 2 +- Makefile | 7 +- backend/authors/access.py | 30 +++++ backend/authors/admin.py | 38 ++++++ backend/authors/apps.py | 20 ++++ .../management/commands/create_author.py | 11 +- .../authors/migrations/0002_editoraccess.py | 24 ++++ backend/authors/models.py | 13 ++ backend/authors/sites.py | 33 ++++++ backend/authors/tests.py | 112 +++++++++++++++++- backend/authors/throttle.py | 40 +++++++ backend/authors/views.py | 54 ++------- backend/pyquest_api/settings/base.py | 19 ++- backend/pyquest_api/settings/dev.py | 3 + backend/pyquest_api/settings/production.py | 1 + backend/pyquest_api/urls.py | 4 + docs/design/09-sync.md | 7 +- nginx/pyquest-locations.conf.example | 23 +++- nginx/pyquest.conf.example | 4 +- scripts/local_stack.py | 21 ++-- tests/e2e/nginx.test.mjs | 49 +++++++- tests/e2e/sync.test.mjs | 2 +- 23 files changed, 451 insertions(+), 69 deletions(-) create mode 100644 backend/authors/access.py create mode 100644 backend/authors/admin.py create mode 100644 backend/authors/apps.py create mode 100644 backend/authors/migrations/0002_editoraccess.py create mode 100644 backend/authors/sites.py create mode 100644 backend/authors/throttle.py diff --git a/CLAUDE.md b/CLAUDE.md index 853053b..1c40a73 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -28,7 +28,8 @@ lire en premier en reprenant une session sur ce projet. `scripts/vendor_pyodide.sh`). - **Backend Django = oui**, mais strictement optionnel et jamais requis pour apprendre : sert à la synchronisation multi-appareils de la progression et (décision du 2026-10-16) à l'accès authentifié à - l'éditeur de niveaux (comptes auteurs `create_author`, nginx `auth_request`). Base de production : MariaDB. Settings séparés dev/prod, + l'éditeur de niveaux (nginx `auth_request`) ; les comptes se gèrent dans l'administration Django (`/api/admin/`) : + administrateurs `is_staff`, auteurs = groupe « Auteurs » (permission `authors.use_editor`). Base de production : MariaDB. Settings séparés dev/prod, traductions fr/en, doc MkDocs bilingue. - Validation des exercices : déclarative uniquement (`tests[].kind` en enum fermé dans le schéma de niveau) — jamais de code arbitraire exécuté depuis un fichier de niveau, pour garder l'isolation diff --git a/CONTEXT.md b/CONTEXT.md index becd352..e500962 100644 --- a/CONTEXT.md +++ b/CONTEXT.md @@ -39,7 +39,7 @@ vrai navigateur (Chromium) avec 4 niveaux jouables. | Tests | `tests/js/*.test.mjs` (node:test), `tests/python/`, `backend/sync/tests.py`, `tests/e2e/` (Chromium) | | Backend | `backend/` Django : `GET/PUT/DELETE /api/sync/` avec jeton Bearer (haché côté serveur), concurrence optimiste (`base` → 409) | | Pile locale | `make dev-nginx` (`scripts/local_stack.py`) : vrai nginx + Django, mêmes blocs que la prod (`nginx/pyquest-locations.conf.example`) ; `tests/e2e/nginx.test.mjs` ; binaire via `PYQUEST_NGINX` (ne pas utiliser `NGINX`, lue par nginx) | -| Accès éditeur | `backend/authors/` (login, `check` pour nginx `auth_request`, `create_author`, anti force brute) ; nginx `pyquest.conf.example` ; prod = MariaDB | +| Accès éditeur | `backend/authors/` (login, `check` pour nginx `auth_request`, administration `/api/admin/` : groupe « Auteurs » / permission `use_editor`, `create_author`, anti force brute) ; nginx `pyquest.conf.example` ; prod = MariaDB | | Synchronisation | `core/SyncClient.js` + section Réglages ; export/import fichier ; voir `docs/design/09-sync.md` ; `make dev-sync` | ## Éditeur de niveaux (mode auteur) — fait le 2026-10-16 diff --git a/Makefile b/Makefile index ef91570..25ba3cc 100644 --- a/Makefile +++ b/Makefile @@ -5,7 +5,7 @@ VENV := .venv VENV_PY := $(VENV)/bin/python PORT ?= 8000 -.PHONY: help install vendor-pyodide dev validate-levels build dev-sync fetch-nginx dev-nginx dev-author docs docs-serve deploy check-deploy test-deploy test test-js test-python test-backend test-e2e typecheck icons voice check-voice ci ci-e2e clean +.PHONY: help install vendor-pyodide dev validate-levels build dev-sync fetch-nginx dev-nginx dev-admin dev-author docs docs-serve deploy check-deploy test-deploy test test-js test-python test-backend test-e2e typecheck icons voice check-voice ci ci-e2e clean help: ## Affiche cette aide @grep -E '^[a-z-]+:.*##' $(MAKEFILE_LIST) | awk -F':.*## ' '{printf " %-16s %s\n", $$1, $$2}' @@ -57,7 +57,10 @@ fetch-nginx: ## Récupère le binaire nginx dans .local/nginx (Debian/Ubuntu, sa dev-nginx: $(VENV)/.installed build ## Pile locale réelle : nginx + Django (éditeur protégé, API) sur http://127.0.0.1:8080/ $(VENV_PY) scripts/local_stack.py -dev-author: $(VENV)/.installed ## Crée (ou NAME=x --reset) un compte auteur pour make dev-nginx ; demande le mot de passe +dev-admin: $(VENV)/.installed ## Crée le compte administrateur de l'essai local (gère les auteurs sur /api/admin/) + cd backend && DJANGO_SETTINGS_MODULE=pyquest_api.settings.dev PYQUEST_DB_PATH=$(CURDIR)/.local/stack/db.sqlite3 ../$(VENV_PY) manage.py createsuperuser + +dev-author: $(VENV)/.installed ## Crée directement un compte auteur local (NAME=x, RESET=--reset) ; demande le mot de passe cd backend && DJANGO_SETTINGS_MODULE=pyquest_api.settings.dev PYQUEST_DB_PATH=$(CURDIR)/.local/stack/db.sqlite3 ../$(VENV_PY) manage.py create_author $(or $(NAME),$(USER)) $(RESET) validate-levels: $(VENV)/.installed ## Valide les niveaux (schéma, manifeste, traductions) diff --git a/backend/authors/access.py b/backend/authors/access.py new file mode 100644 index 0000000..983f611 --- /dev/null +++ b/backend/authors/access.py @@ -0,0 +1,30 @@ +"""Droit d'utiliser l'éditeur de niveaux : permission `authors.use_editor`, donnée par le groupe « Auteurs ».""" + +from __future__ import annotations + +from django.contrib.auth.models import Group, Permission, User + +EDITOR_PERMISSION = "authors.use_editor" +GROUP_NAME = "Auteurs" + + +def is_author(user: object) -> bool: + """Compte actif autorisé à utiliser l'éditeur. Un superutilisateur l'est aussi (il a toutes les permissions).""" + return isinstance(user, User) and user.is_active and user.has_perm(EDITOR_PERMISSION) + + +def authors_group() -> Group: + """Groupe « Auteurs », créé au besoin avec la permission de l'éditeur.""" + group, _created = Group.objects.get_or_create(name=GROUP_NAME) + permission = Permission.objects.filter(content_type__app_label="authors", codename="use_editor").first() + if permission is not None: + group.permissions.add(permission) + return group + + +def grant(user: User) -> None: + user.groups.add(authors_group()) + + +def revoke(user: User) -> None: + user.groups.remove(authors_group()) diff --git a/backend/authors/admin.py b/backend/authors/admin.py new file mode 100644 index 0000000..0d24fd5 --- /dev/null +++ b/backend/authors/admin.py @@ -0,0 +1,38 @@ +"""Administration des comptes : qui peut utiliser l'éditeur de niveaux, qui administre le site.""" + +from __future__ import annotations + +from django.contrib import admin, messages +from django.contrib.auth.admin import GroupAdmin, UserAdmin +from django.contrib.auth.models import Group, User +from django.db.models import QuerySet +from django.http import HttpRequest + +from . import access +from .sites import site + + +@admin.register(User, site=site) +class AccountAdmin(UserAdmin): + list_display = ("username", "is_author_display", "is_staff", "is_superuser", "is_active", "last_login") + list_filter = ("is_staff", "is_superuser", "is_active", "groups") + actions = ["grant_editor", "revoke_editor"] + + @admin.display(boolean=True, description="Éditeur de niveaux") + def is_author_display(self, obj: User) -> bool: + return access.is_author(obj) + + @admin.action(description="Autoriser à utiliser l'éditeur de niveaux") + def grant_editor(self, request: HttpRequest, queryset: QuerySet[User]) -> None: + for user in queryset: + access.grant(user) + self.message_user(request, f"{queryset.count()} compte(s) autorisé(s) à utiliser l'éditeur.", messages.SUCCESS) + + @admin.action(description="Retirer l'accès à l'éditeur de niveaux") + def revoke_editor(self, request: HttpRequest, queryset: QuerySet[User]) -> None: + for user in queryset: + access.revoke(user) + self.message_user(request, f"Accès retiré à {queryset.count()} compte(s).", messages.SUCCESS) + + +site.register(Group, GroupAdmin) diff --git a/backend/authors/apps.py b/backend/authors/apps.py new file mode 100644 index 0000000..b4f50c4 --- /dev/null +++ b/backend/authors/apps.py @@ -0,0 +1,20 @@ +from django.apps import AppConfig +from django.db.models.signals import post_migrate + + +def _create_group(sender: object, **kwargs: object) -> None: + from django.contrib.auth.management import create_permissions + + from .access import authors_group + + # Les permissions sont créées par un autre gestionnaire de post_migrate : on s'assure qu'elles existent d'abord. + create_permissions(sender, verbosity=0) # type: ignore[arg-type] + authors_group() + + +class AuthorsConfig(AppConfig): + name = "authors" + verbose_name = "Éditeur de niveaux" + + def ready(self) -> None: + post_migrate.connect(_create_group, sender=self) diff --git a/backend/authors/management/commands/create_author.py b/backend/authors/management/commands/create_author.py index 69fc032..e8964d8 100644 --- a/backend/authors/management/commands/create_author.py +++ b/backend/authors/management/commands/create_author.py @@ -1,4 +1,6 @@ -"""Crée (ou met à jour le mot de passe d') un compte auteur : accès à l'éditeur de niveaux, rien d'autre.""" +"""Crée (ou met à jour le mot de passe d') un compte auteur : accès à l'éditeur de niveaux, rien d'autre. + +Pratique en ligne de commande ; l'administration (/api/admin/) permet de gérer les mêmes comptes.""" from __future__ import annotations @@ -10,9 +12,11 @@ from django.contrib.auth.password_validation import validate_password from django.core.exceptions import ValidationError from django.core.management.base import BaseCommand, CommandError, CommandParser +from authors import access + class Command(BaseCommand): - help = "Crée un compte auteur (is_staff, sans droits d'administration). Le mot de passe est demandé au clavier." + help = "Crée un compte auteur (accès à l'éditeur, sans droits d'administration). Le mot de passe est demandé au clavier." def add_arguments(self, parser: CommandParser) -> None: parser.add_argument("username") @@ -35,9 +39,10 @@ class Command(BaseCommand): raise CommandError(" ".join(error.messages)) from error user = existing or User(username=username) - user.is_staff = True + user.is_staff = False # is_staff ouvre l'administration : réservé aux responsables user.is_superuser = False user.is_active = True user.set_password(password) user.save() + access.grant(user) self.stdout.write(self.style.SUCCESS(f"Compte auteur {username} {'mis à jour' if existing else 'créé'}.")) diff --git a/backend/authors/migrations/0002_editoraccess.py b/backend/authors/migrations/0002_editoraccess.py new file mode 100644 index 0000000..4839ec9 --- /dev/null +++ b/backend/authors/migrations/0002_editoraccess.py @@ -0,0 +1,24 @@ +# Generated by Django 5.2.18 on 2026-10-16 20:27 + +from django.db import migrations, models + + +class Migration(migrations.Migration): + + dependencies = [ + ('authors', '0001_initial'), + ] + + operations = [ + migrations.CreateModel( + name='EditorAccess', + fields=[ + ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ], + options={ + 'permissions': [('use_editor', "Peut utiliser l'éditeur de niveaux")], + 'managed': False, + 'default_permissions': (), + }, + ), + ] diff --git a/backend/authors/models.py b/backend/authors/models.py index 517659e..0fb1e3a 100644 --- a/backend/authors/models.py +++ b/backend/authors/models.py @@ -1,6 +1,19 @@ from django.db import models +class EditorAccess(models.Model): + """Porte la permission « utiliser l'éditeur de niveaux » (aucune table : modèle non géré). + + L'accès à l'éditeur se donne depuis l'administration (groupe « Auteurs » ou permission directe) ; le statut + `is_staff`, lui, ouvre l'administration et est réservé aux responsables du site. + """ + + class Meta: + managed = False + default_permissions = () + permissions = [("use_editor", "Peut utiliser l'éditeur de niveaux")] + + class LoginFailure(models.Model): """Tentative de connexion échouée : sert à bloquer temporairement les essais répétés (force brute).""" diff --git a/backend/authors/sites.py b/backend/authors/sites.py new file mode 100644 index 0000000..d409154 --- /dev/null +++ b/backend/authors/sites.py @@ -0,0 +1,33 @@ +"""Site d'administration de PyQuest : gestion des comptes, avec la même protection contre la force brute que la +page de connexion de l'éditeur.""" + +from __future__ import annotations + +from django.contrib import admin +from django.http import HttpRequest, HttpResponse +from django.template.response import TemplateResponse + +from .throttle import client_ip, is_locked, record_failure, record_success + + +class PyQuestAdminSite(admin.AdminSite): + site_header = "PyQuest — administration" + site_title = "PyQuest" + index_title = "Comptes et accès à l'éditeur de niveaux" + + def login(self, request: HttpRequest, extra_context: dict[str, object] | None = None) -> HttpResponse: + if request.method != "POST": + return super().login(request, extra_context) + username = request.POST.get("username", "").strip().lower()[:150] + ip = client_ip(request) + if is_locked(username, ip): + return HttpResponse("Trop d'essais. Réessaie dans quelques minutes.", status=429, content_type="text/plain; charset=utf-8") + response = super().login(request, extra_context) + if request.user.is_authenticated: + record_success(username) + elif isinstance(response, TemplateResponse): + record_failure(username, ip) + return response + + +site = PyQuestAdminSite(name="admin") diff --git a/backend/authors/tests.py b/backend/authors/tests.py index 9c6747d..db396e5 100644 --- a/backend/authors/tests.py +++ b/backend/authors/tests.py @@ -7,6 +7,8 @@ from django.core.management import call_command from django.core.management.base import CommandError from django.test import Client, TestCase, override_settings +from . import access + # Réponse du client de test Django : type exact non exposé par les stubs. _Response = Any @@ -16,7 +18,11 @@ CHECK = "/api/auth/check/" def make_user(username: str = "ada", *, staff: bool = True, password: str = PASSWORD) -> User: - return User.objects.create_user(username=username, password=password, is_staff=staff) # pyright: ignore[reportAttributeAccessIssue] + """`staff` : autorisé à utiliser l'éditeur (groupe « Auteurs »). `is_staff` reste faux : il ouvre l'administration.""" + user = User.objects.create_user(username=username, password=password) # pyright: ignore[reportAttributeAccessIssue] + if staff: + access.grant(user) + return user class LoginTest(TestCase): @@ -46,7 +52,7 @@ class LoginTest(TestCase): self.assertEqual(wrong.content.decode().count("incorrect"), unknown.content.decode().count("incorrect")) self.assertEqual(self.client.get(CHECK).status_code, 401) - def test_non_staff_account_is_refused_even_with_the_right_password(self) -> None: + def test_account_without_editor_permission_is_refused_even_with_the_right_password(self) -> None: make_user("lea", staff=False) self.assertContains(self.post("lea", PASSWORD), "incorrect") self.assertEqual(self.client.get(CHECK).status_code, 401) @@ -164,11 +170,11 @@ class CreateAuthorCommandTest(TestCase): call_command("create_author", *args, stdout=out) return out.getvalue() - def test_creates_a_staff_account_without_admin_rights(self) -> None: + def test_creates_an_author_account_without_admin_rights(self) -> None: self.run_command("Ada") user = User.objects.get(username="ada") - self.assertTrue(user.is_staff and user.is_active) - self.assertFalse(user.is_superuser) + self.assertTrue(access.is_author(user) and user.is_active) + self.assertFalse(user.is_staff or user.is_superuser) # ni administration ni droits étendus self.assertTrue(user.check_password(PASSWORD)) self.assertEqual(self.client.post(LOGIN, {"username": "ada", "password": PASSWORD}).status_code, 302) @@ -187,3 +193,99 @@ class CreateAuthorCommandTest(TestCase): self.assertTrue(User.objects.get(username="ada").check_password("nouveau-mot-de-passe-77")) with self.assertRaises(CommandError): self.run_command("inconnu", "--reset") + + +class EditorPermissionTest(TestCase): + def test_group_and_permission_exist_after_migrate(self) -> None: + from django.contrib.auth.models import Group + + group = Group.objects.get(name=access.GROUP_NAME) + self.assertEqual(list(group.permissions.values_list("codename", flat=True)), ["use_editor"]) + + def test_is_staff_alone_does_not_open_the_editor(self) -> None: + user = User.objects.create_user("chef", password=PASSWORD, is_staff=True) # pyright: ignore[reportAttributeAccessIssue] + self.assertFalse(access.is_author(user)) + self.client.login(username="chef", password=PASSWORD) + self.assertEqual(self.client.get(CHECK).status_code, 401) + + def test_superuser_can_use_the_editor(self) -> None: + User.objects.create_superuser("root", password=PASSWORD) # pyright: ignore[reportAttributeAccessIssue] + self.client.login(username="root", password=PASSWORD) + self.assertEqual(self.client.get(CHECK).status_code, 204) + + def test_revoke_removes_access_and_grant_restores_it(self) -> None: + user = make_user() + access.revoke(user) + self.client.login(username="ada", password=PASSWORD) + self.assertEqual(self.client.get(CHECK).status_code, 401) + access.grant(User.objects.get(username="ada")) + self.assertEqual(self.client.get(CHECK).status_code, 204) + + +ADMIN = "/api/admin/" + + +class AdminSiteTest(TestCase): + def setUp(self) -> None: + self.root = User.objects.create_superuser("root", password=PASSWORD) # pyright: ignore[reportAttributeAccessIssue] + + def test_anonymous_and_authors_cannot_enter(self) -> None: + self.assertEqual(self.client.get(ADMIN).status_code, 302) # vers la connexion de l'administration + make_user("ada") + self.client.login(username="ada", password=PASSWORD) + response = self.client.get(ADMIN, follow=True) + self.assertContains(response, "pas autorisé") # page de connexion de l'admin, pas l'index + self.assertNotContains(response, "Comptes et accès") + + def test_administrator_sees_accounts_and_the_editor_column(self) -> None: + make_user("ada") + self.client.login(username="root", password=PASSWORD) + index = self.client.get(ADMIN) + self.assertContains(index, "PyQuest — administration") + users = self.client.get(f"{ADMIN}auth/user/") + self.assertContains(users, "Éditeur de niveaux") + self.assertContains(users, "ada") + + def test_actions_grant_and_revoke_editor_access(self) -> None: + newcomer = User.objects.create_user("lea", password=PASSWORD) # pyright: ignore[reportAttributeAccessIssue] + self.client.login(username="root", password=PASSWORD) + url = f"{ADMIN}auth/user/" + self.client.post(url, {"action": "grant_editor", "_selected_action": [newcomer.pk]}, follow=True) + self.assertTrue(access.is_author(User.objects.get(username="lea"))) + self.client.post(url, {"action": "revoke_editor", "_selected_action": [newcomer.pk]}, follow=True) + self.assertFalse(access.is_author(User.objects.get(username="lea"))) + + def test_administrator_can_create_an_account_in_the_author_group(self) -> None: + from django.contrib.auth.models import Group + + self.client.login(username="root", password=PASSWORD) + group = Group.objects.get(name=access.GROUP_NAME) + response = self.client.post( + f"{ADMIN}auth/user/add/", + {"username": "nouvelle", "password1": "mot-de-passe-solide-99", "password2": "mot-de-passe-solide-99"}, + follow=True, + ) + self.assertEqual(response.status_code, 200) + created = User.objects.get(username="nouvelle") + created.groups.add(group) + self.assertTrue(access.is_author(User.objects.get(username="nouvelle"))) + self.assertFalse(created.is_staff) + + def test_admin_login_is_throttled_like_the_editor_login(self) -> None: + for _ in range(5): + response = self.client.post(f"{ADMIN}login/", {"username": "root", "password": "mauvais", "next": ADMIN}) + self.assertEqual(response.status_code, 200) + locked = self.client.post(f"{ADMIN}login/", {"username": "root", "password": PASSWORD, "next": ADMIN}) + self.assertEqual(locked.status_code, 429) + + def test_admin_login_works_and_clears_failures(self) -> None: + from .models import LoginFailure + + self.client.post(f"{ADMIN}login/", {"username": "root", "password": "mauvais", "next": ADMIN}) + response = self.client.post(f"{ADMIN}login/", {"username": "root", "password": PASSWORD, "next": ADMIN}) + self.assertRedirects(response, ADMIN, fetch_redirect_response=False) + self.assertEqual(LoginFailure.objects.filter(username="root").count(), 0) + + def test_pages_cannot_be_framed(self) -> None: + self.client.login(username="root", password=PASSWORD) + self.assertEqual(self.client.get(ADMIN).headers["X-Frame-Options"], "DENY") diff --git a/backend/authors/throttle.py b/backend/authors/throttle.py new file mode 100644 index 0000000..7d2c4a6 --- /dev/null +++ b/backend/authors/throttle.py @@ -0,0 +1,40 @@ +"""Limitation des essais de connexion (force brute), partagée par la page de l'éditeur et l'administration.""" + +from __future__ import annotations + +from datetime import timedelta + +from django.conf import settings +from django.http import HttpRequest +from django.utils import timezone + +from .models import LoginFailure + +LOCK_WINDOW = timedelta(minutes=15) +MAX_FAILURES_PER_USER = 5 +MAX_FAILURES_PER_IP = 20 + + +def client_ip(request: HttpRequest) -> str: + # Derrière nginx, REMOTE_ADDR est le proxy : nginx écrase X-Real-IP, qu'on ne croit qu'en production. + if settings.TRUST_REAL_IP_HEADER: + forwarded = request.headers.get("X-Real-IP", "") + if forwarded: + return forwarded[:45] + return request.META.get("REMOTE_ADDR", "")[:45] + + +def is_locked(username: str, ip: str) -> bool: + since = timezone.now() - LOCK_WINDOW + recent = LoginFailure.objects.filter(created_at__gte=since) + return recent.filter(username=username).count() >= MAX_FAILURES_PER_USER or recent.filter(ip=ip).count() >= MAX_FAILURES_PER_IP + + +def record_failure(username: str, ip: str) -> None: + LoginFailure.objects.create(username=username, ip=ip) + # Ménage : on ne garde pas l'historique au-delà d'un jour. + LoginFailure.objects.filter(created_at__lt=timezone.now() - timedelta(days=1)).delete() + + +def record_success(username: str) -> None: + LoginFailure.objects.filter(username=username).delete() diff --git a/backend/authors/views.py b/backend/authors/views.py index 18e3af9..fc4b8a6 100644 --- a/backend/authors/views.py +++ b/backend/authors/views.py @@ -1,31 +1,25 @@ """Accès authentifié à l'éditeur de niveaux (author.html), pour les déploiements qui le protègent. nginx interroge `check/` (module auth_request) avant de servir l'éditeur ; `login/` est la page de connexion. -Seuls les comptes `is_staff` (créés avec `manage.py create_author`) passent. Pas de site d'administration -Django : moins de surface d'attaque. Les textes sont dans ce fichier plutôt que dans des catalogues gettext, -car la compilation des traductions (.mo) n'est pas versionnée. +Seuls les comptes qui ont la permission `authors.use_editor` (groupe « Auteurs », donné depuis l'administration +ou avec `manage.py create_author`) passent ; `is_staff` ouvre l'administration, pas l'éditeur. +Les textes sont dans ce fichier plutôt que dans des catalogues gettext, car la compilation des traductions (.mo) n'est +pas versionnée. """ from __future__ import annotations -from datetime import timedelta - -from django.conf import settings from django.contrib.auth import authenticate, login, logout -from django.contrib.auth.models import User from django.http import HttpRequest, HttpResponse from django.shortcuts import redirect, render -from django.utils import timezone 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_GET, require_http_methods, require_POST -from .models import LoginFailure +from .access import is_author +from .throttle import client_ip, is_locked, record_failure, record_success DEFAULT_NEXT = "/author.html" -LOCK_WINDOW = timedelta(minutes=15) -MAX_FAILURES_PER_USER = 5 -MAX_FAILURES_PER_IP = 20 TEXTS = { "fr": { @@ -55,25 +49,11 @@ TEXTS = { } -def _is_author(user: object) -> bool: - """Compte actif réservé aux auteurs (is_staff) ; les visiteurs anonymes et les autres comptes sont refusés.""" - return isinstance(user, User) and user.is_active and user.is_staff - - def _language(request: HttpRequest) -> str: header = request.headers.get("Accept-Language", "") return "en" if header.lower().startswith("en") else "fr" -def _client_ip(request: HttpRequest) -> str: - # Derrière nginx, REMOTE_ADDR est le proxy : nginx écrase X-Real-IP, qu'on ne croit qu'en production. - if settings.TRUST_REAL_IP_HEADER: - forwarded = request.headers.get("X-Real-IP", "") - if forwarded: - return forwarded[:45] - return request.META.get("REMOTE_ADDR", "")[:45] - - def _safe_next(request: HttpRequest) -> str: candidate = request.POST.get("next") or request.GET.get("next") or DEFAULT_NEXT allowed = url_has_allowed_host_and_scheme(candidate, allowed_hosts={request.get_host()}, require_https=request.is_secure()) @@ -81,16 +61,10 @@ def _safe_next(request: HttpRequest) -> str: return candidate if allowed and candidate.startswith("/") and not candidate.startswith("//") else DEFAULT_NEXT -def _is_locked(username: str, ip: str) -> bool: - since = timezone.now() - LOCK_WINDOW - recent = LoginFailure.objects.filter(created_at__gte=since) - return recent.filter(username=username).count() >= MAX_FAILURES_PER_USER or recent.filter(ip=ip).count() >= MAX_FAILURES_PER_IP - - def _page(request: HttpRequest, *, error_key: str | None = None, status: int = 200) -> HttpResponse: texts = TEXTS[_language(request)] user = request.user - signed_in = _is_author(user) + signed_in = is_author(user) context = { "t": texts, "lang": _language(request), @@ -110,18 +84,16 @@ def login_view(request: HttpRequest) -> HttpResponse: username = request.POST.get("username", "").strip().lower()[:150] password = request.POST.get("password", "") - ip = _client_ip(request) - if _is_locked(username, ip): + ip = client_ip(request) + if is_locked(username, ip): return _page(request, error_key="locked", status=429) user = authenticate(request, username=username, password=password) - if not _is_author(user): - LoginFailure.objects.create(username=username, ip=ip) - # Ménage : on ne garde pas l'historique au-delà d'un jour. - LoginFailure.objects.filter(created_at__lt=timezone.now() - timedelta(days=1)).delete() + if not is_author(user): + record_failure(username, ip) return _page(request, error_key="invalid", status=200) - LoginFailure.objects.filter(username=username).delete() + record_success(username) login(request, user) return redirect(_safe_next(request)) @@ -137,4 +109,4 @@ def logout_view(request: HttpRequest) -> HttpResponse: @require_GET def check_view(request: HttpRequest) -> HttpResponse: """Appelé par nginx (auth_request) : 204 si la session appartient à un auteur, sinon 401.""" - return HttpResponse(status=204 if _is_author(request.user) else 401) + return HttpResponse(status=204 if is_author(request.user) else 401) diff --git a/backend/pyquest_api/settings/base.py b/backend/pyquest_api/settings/base.py index f7b3e53..128b78e 100644 --- a/backend/pyquest_api/settings/base.py +++ b/backend/pyquest_api/settings/base.py @@ -9,8 +9,11 @@ INSTALLED_APPS = [ "django.contrib.contenttypes", "django.contrib.auth", "django.contrib.sessions", + "django.contrib.messages", + "django.contrib.staticfiles", + "django.contrib.admin", "sync", - "authors", + "authors.apps.AuthorsConfig", ] MIDDLEWARE = [ @@ -20,16 +23,28 @@ MIDDLEWARE = [ "django.middleware.common.CommonMiddleware", "django.middleware.csrf.CsrfViewMiddleware", "django.contrib.auth.middleware.AuthenticationMiddleware", + "django.contrib.messages.middleware.MessageMiddleware", + "django.middleware.clickjacking.XFrameOptionsMiddleware", ] TEMPLATES = [ { "BACKEND": "django.template.backends.django.DjangoTemplates", "APP_DIRS": True, - "OPTIONS": {"context_processors": ["django.template.context_processors.request"]}, + "OPTIONS": { + "context_processors": [ + "django.template.context_processors.request", + "django.contrib.auth.context_processors.auth", + "django.contrib.messages.context_processors.messages", + ] + }, } ] +# Fichiers statiques de l'administration, servis par nginx sous /api/static/ (python manage.py collectstatic). +STATIC_URL = "/api/static/" +STATIC_ROOT = BASE_DIR / "staticfiles" + # Session des auteurs (éditeur de niveaux) : cookie HttpOnly, 8 heures. SESSION_COOKIE_NAME = "pyquest_author" SESSION_COOKIE_AGE = 8 * 60 * 60 diff --git a/backend/pyquest_api/settings/dev.py b/backend/pyquest_api/settings/dev.py index 414e724..afc3cd2 100644 --- a/backend/pyquest_api/settings/dev.py +++ b/backend/pyquest_api/settings/dev.py @@ -16,3 +16,6 @@ DATABASES = { "NAME": os.environ.get("PYQUEST_DB_PATH", BASE_DIR / "db.sqlite3"), } } + +# Dossier des fichiers statiques collectés (essai avec nginx : scripts/local_stack.py). +STATIC_ROOT = os.environ.get("PYQUEST_STATIC_ROOT", BASE_DIR / "staticfiles") diff --git a/backend/pyquest_api/settings/production.py b/backend/pyquest_api/settings/production.py index ce53e0f..ea4a825 100644 --- a/backend/pyquest_api/settings/production.py +++ b/backend/pyquest_api/settings/production.py @@ -41,3 +41,4 @@ CSRF_TRUSTED_ORIGINS = [_required("PYQUEST_ORIGIN")] SESSION_COOKIE_SECURE = True CSRF_COOKIE_SECURE = True TRUST_REAL_IP_HEADER = True # nginx écrase X-Real-IP (voir nginx/pyquest.conf.example) +STATIC_ROOT = os.environ.get("PYQUEST_STATIC_ROOT", "/var/www/pyquest/static") # servi par nginx : /api/static/ diff --git a/backend/pyquest_api/urls.py b/backend/pyquest_api/urls.py index 554a133..b5d927a 100644 --- a/backend/pyquest_api/urls.py +++ b/backend/pyquest_api/urls.py @@ -1,6 +1,10 @@ from django.urls import include, path +from authors.sites import site as admin_site + urlpatterns = [ path("api/sync/", include("sync.urls")), path("api/auth/", include("authors.urls")), + # Administration des comptes auteurs : sous /api/ pour passer par le même proxy nginx. + path("api/admin/", admin_site.urls), ] diff --git a/docs/design/09-sync.md b/docs/design/09-sync.md index 45e48f3..6723255 100644 --- a/docs/design/09-sync.md +++ b/docs/design/09-sync.md @@ -49,8 +49,11 @@ non JSON (serveur statique sans Django) donne `unavailable`. ## Backend : aussi l'accès à l'éditeur (2026-10-16) -Le même backend Django porte les comptes **auteurs** (`authors/`) : page de connexion, `check` pour nginx -`auth_request`, anti force brute (`LoginFailure`), commande `create_author` ; pas de site d'administration. Base de +Le même backend Django porte les comptes (`authors/`) : page de connexion de l'éditeur, `check` pour nginx +`auth_request`, anti force brute commun (`throttle.py`, `LoginFailure`), **administration Django** sur `/api/admin/` +(`sites.py` : même limitation des essais). Deux rôles : administrateur (`is_staff`) et auteur (permission +`authors.use_editor`, groupe « Auteurs », actions « Autoriser/Retirer » dans la liste des utilisateurs) ; `is_staff` seul +n'ouvre pas l'éditeur. Commande `create_author` en raccourci. Base de production : **MariaDB** (`mysqlclient`, `backend/requirements-prod.txt`). Les fichiers de l'éditeur ne sont ni pré-cachés ni interceptés par le service worker (`build.py:is_author_tool`, `service-worker.js`). diff --git a/nginx/pyquest-locations.conf.example b/nginx/pyquest-locations.conf.example index a186282..3413adf 100644 --- a/nginx/pyquest-locations.conf.example +++ b/nginx/pyquest-locations.conf.example @@ -4,7 +4,7 @@ # configuration de nginx (/etc/nginx en production). # # Installation : copier ce fichier en /etc/nginx/snippets/pyquest-locations.conf et pyquest-author-headers.conf.example -# en /etc/nginx/snippets/pyquest-author-headers.conf. Les zones de limitation (limit_req_zone) sont dans le bloc http. +# en /etc/nginx/snippets/pyquest-author-headers.conf. Les zones de limitation (limit_req_zone : pyquest_sync, pyquest_login, pyquest_admin) sont dans le bloc http. # Host $http_host (et non $host) : conserve le port, que Django compare à l'en-tête Origin des formulaires. # Types MIME explicites : un bloc « types » dans server remplace la table par défaut, donc on @@ -111,6 +111,27 @@ proxy_set_header X-Real-IP $remote_addr; # écrase toute valeur envoyée par le client } + # Fichiers statiques de l'administration Django (python manage.py collectstatic dans PYQUEST_STATIC_ROOT). + location /api/static/ { + alias /var/www/pyquest/static/; + add_header Cache-Control "public, max-age=604800" always; + add_header X-Content-Type-Options "nosniff" always; + add_header Strict-Transport-Security "max-age=31536000" always; + } + + # Administration Django (comptes auteurs) : débit modéré (la force brute est aussi bloquée par Django : 5 échecs + # par compte, 20 par adresse, 15 minutes). Pour la restreindre à ton réseau, décommente allow/deny (ou VPN). + location /api/admin/ { + limit_req zone=pyquest_admin burst=30 nodelay; + client_max_body_size 1m; + # allow 203.0.113.0/24; + # deny all; + proxy_pass http://127.0.0.1:8001; + proxy_set_header Host $http_host; + proxy_set_header X-Forwarded-Proto $scheme; + proxy_set_header X-Real-IP $remote_addr; + } + # Le reste de l'API (synchronisation, déconnexion) ; /api/auth/check/ n'est joignable que par la sous-requête interne. location = /api/auth/check/ { return 404; diff --git a/nginx/pyquest.conf.example b/nginx/pyquest.conf.example index 873ceb0..5957f01 100644 --- a/nginx/pyquest.conf.example +++ b/nginx/pyquest.conf.example @@ -13,9 +13,11 @@ # Fichiers à copier dans /etc/nginx/snippets/ : pyquest-locations.conf (depuis pyquest-locations.conf.example) et # pyquest-author-headers.conf (depuis pyquest-author-headers.conf.example). -# Limites de débit (contexte http, hors bloc server) : synchronisation 30 req/min, connexion 6 req/min par IP. +# Limites de débit (contexte http, hors bloc server), par IP : synchronisation 30 req/min, connexion à l'éditeur +# 6 req/min, administration 60 req/min. limit_req_zone $binary_remote_addr zone=pyquest_sync:10m rate=30r/m; limit_req_zone $binary_remote_addr zone=pyquest_login:10m rate=6r/m; +limit_req_zone $binary_remote_addr zone=pyquest_admin:10m rate=60r/m; server { listen 80; diff --git a/scripts/local_stack.py b/scripts/local_stack.py index 797b490..9e54378 100755 --- a/scripts/local_stack.py +++ b/scripts/local_stack.py @@ -44,6 +44,7 @@ http {{ limit_req_zone $binary_remote_addr zone=pyquest_sync:1m rate=30r/m; # Plus large qu'en production pour ne pas gêner les essais répétés. limit_req_zone $binary_remote_addr zone=pyquest_login:1m rate=60r/m; + limit_req_zone $binary_remote_addr zone=pyquest_admin:1m rate=600r/m; server {{ listen 127.0.0.1:{port}; @@ -75,9 +76,10 @@ def prepare(work: Path, port: int, api_port: int) -> Path: sys.exit("dist/ est absent : lance d'abord « make build ».") for sub in ("conf/snippets", "logs", "temp"): (work / sub).mkdir(parents=True, exist_ok=True) - # Même fichier qu'en production ; seul le port de Django (8001 par défaut) est adapté à l'essai. + # Même fichier qu'en production ; seuls le port de Django (8001 par défaut) et le dossier des statiques sont adaptés. locations = (NGINX_DIR / "pyquest-locations.conf.example").read_text(encoding="utf-8") - (work / "conf/snippets/pyquest-locations.conf").write_text(locations.replace("127.0.0.1:8001", f"127.0.0.1:{api_port}"), encoding="utf-8") + adapted = locations.replace("127.0.0.1:8001", f"127.0.0.1:{api_port}").replace("/var/www/pyquest/static/", f"{work}/static/") + (work / "conf/snippets/pyquest-locations.conf").write_text(adapted, encoding="utf-8") shutil.copy(NGINX_DIR / "pyquest-author-headers.conf.example", work / "conf/snippets/pyquest-author-headers.conf") config = work / "conf/nginx.conf" config.write_text(CONF_TEMPLATE.format(work=work, port=port, dist=dist), encoding="utf-8") @@ -93,8 +95,8 @@ def python_for_backend() -> str: return str(venv) if venv.is_file() else sys.executable -def has_author(env: dict[str, str]) -> bool: - code = "from django.contrib.auth.models import User; print(User.objects.filter(is_staff=True).count())" +def has_account(env: dict[str, str]) -> bool: + code = "from django.contrib.auth.models import User; print(User.objects.count())" result = subprocess.run([python_for_backend(), "manage.py", "shell", "-c", code], cwd=ROOT / "backend", env=env, capture_output=True, text=True) return result.returncode == 0 and result.stdout.strip() not in ("", "0") @@ -114,12 +116,14 @@ def main() -> None: python = python_for_backend() subprocess.run([python, "manage.py", "migrate", "--noinput", "--verbosity", "0"], cwd=ROOT / "backend", env=env, check=True) - if not has_author(env): + # Fichiers statiques de l'administration, servis par nginx sous /api/static/ comme en production. + subprocess.run([python, "manage.py", "collectstatic", "--noinput", "--verbosity", "0"], cwd=ROOT / "backend", env={**env, "PYQUEST_STATIC_ROOT": str(work / "static")}, check=True) + if not has_account(env): if sys.stdin.isatty(): - print("Aucun compte auteur : création d'un compte pour l'essai.") - subprocess.run([python, "manage.py", "create_author", os.environ.get("USER", "auteur")], cwd=ROOT / "backend", env=env, check=False) + print("Aucun compte : création du compte administrateur (il gère ensuite les auteurs sur /api/admin/).") + subprocess.run([python, "manage.py", "createsuperuser"], cwd=ROOT / "backend", env=env, check=False) else: - print("Aucun compte auteur. Crée-en un : (cd backend && PYQUEST_DB_PATH=%s %s manage.py create_author nom)" % (work / "db.sqlite3", python)) + print("Aucun compte. Crée l'administrateur : make dev-admin") check = subprocess.run([nginx, "-t", "-p", str(work), "-c", str(config)], capture_output=True, text=True) if check.returncode != 0: @@ -142,6 +146,7 @@ def main() -> None: signal.signal(signal.SIGINT, stop) try: print(f"Pile locale : http://127.0.0.1:{args.port}/ (éditeur : /author.html, protégé par connexion)") + print(f"Administration des comptes : http://127.0.0.1:{args.port}/api/admin/") print(f"Journaux : {work}/logs/ — Ctrl+C pour arrêter.") server = subprocess.Popen([nginx, "-p", str(work), "-c", str(config)]) server.wait() diff --git a/tests/e2e/nginx.test.mjs b/tests/e2e/nginx.test.mjs index 65f869a..068cd3c 100644 --- a/tests/e2e/nginx.test.mjs +++ b/tests/e2e/nginx.test.mjs @@ -40,7 +40,7 @@ before(async () => { if (ready && existsSync(join(work, 'db.sqlite3'))) break; await new Promise((resolve) => setTimeout(resolve, 500)); } - const created = spawnSync(venvPython, ['manage.py', 'shell', '-c', `from django.contrib.auth.models import User; User.objects.create_user('ada', password='${PASSWORD}', is_staff=True); User.objects.create_user('lea', password='${PASSWORD}')`], { + const created = spawnSync(venvPython, ['manage.py', 'shell', '-c', `from django.contrib.auth.models import User; from authors import access; access.grant(User.objects.create_user('ada', password='${PASSWORD}')); User.objects.create_user('lea', password='${PASSWORD}'); User.objects.create_superuser('root', password='${PASSWORD}')`], { cwd: `${root}backend`, env: { ...process.env, DJANGO_SETTINGS_MODULE: 'pyquest_api.settings.dev', PYQUEST_DB_PATH: join(work, 'db.sqlite3') }, }); @@ -134,3 +134,50 @@ test('nginx : l\'application apprenant est isolée, exécute Python et synchroni await group.getByText(/Dernière synchronisation/).waitFor({ timeout: 15000 }); assert.deepEqual(errors, []); }); + +test('nginx : l\'administrateur autorise un compte à utiliser l\'éditeur depuis l\'administration Django', { skip, timeout: 120000 }, async () => { + // Les fichiers statiques de l'administration passent par nginx (alias), avec le bon type MIME. + const css = await fetch(`${base}api/static/admin/css/base.css`); + assert.equal(css.status, 200); + assert.match(css.headers.get('content-type'), /text\/css/); + + const admin = await (await browser.newContext({ locale: 'fr-FR' })).newPage(); + const errors = []; + admin.on('pageerror', (error) => errors.push(error.message)); + // Un compte sans permission n'entre pas dans l'administration. + await admin.goto(`${base}api/admin/`); + await admin.getByLabel(/Nom d.utilisateur/).fill('lea'); + await admin.getByLabel('Mot de passe :').fill(PASSWORD); + await admin.getByRole('button', { name: 'Connexion' }).click(); + await admin.locator('.errornote').waitFor(); + // L'administrateur entre, voit les comptes et donne l'accès à « lea ». + await admin.getByLabel(/Nom d.utilisateur/).fill('root'); + await admin.getByLabel('Mot de passe :').fill(PASSWORD); + await admin.getByRole('button', { name: 'Connexion' }).click(); + await admin.getByText('PyQuest — administration').first().waitFor(); + await admin.goto(`${base}api/admin/auth/user/`); + await admin.locator('tr', { hasText: 'lea' }).locator('input[type=checkbox]').check(); + await admin.locator('select[name=action]').selectOption('grant_editor'); + await admin.getByRole('button', { name: 'Envoyer' }).click(); + await admin.getByText(/autorisé\(s\) à utiliser l.éditeur/).waitFor(); + + // « lea » ouvre maintenant l'éditeur ; elle n'a pas accès à l'administration. + const author = await (await browser.newContext({ locale: 'fr-FR' })).newPage(); + await author.goto(`${base}author.html`); + await author.getByLabel('Identifiant').fill('lea'); + await author.getByLabel('Mot de passe').fill(PASSWORD); + await author.getByRole('button', { name: 'Se connecter' }).click(); + await author.waitForURL(`${base}author.html`); + await author.goto(`${base}api/admin/`); + await author.getByText(/pas autorisé/).waitFor(); + + // Retrait de l'accès : le contrôle suivant refuse. + await admin.goto(`${base}api/admin/auth/user/`); + await admin.locator('tr', { hasText: 'lea' }).locator('input[type=checkbox]').check(); + await admin.locator('select[name=action]').selectOption('revoke_editor'); + await admin.getByRole('button', { name: 'Envoyer' }).click(); + await admin.getByText(/Accès retiré/).waitFor(); + const refused = await author.context().request.get(`${base}author.html`, { maxRedirects: 0 }); + assert.equal(refused.status(), 302); + assert.deepEqual(errors, []); +}); diff --git a/tests/e2e/sync.test.mjs b/tests/e2e/sync.test.mjs index ffc2551..96f7012 100644 --- a/tests/e2e/sync.test.mjs +++ b/tests/e2e/sync.test.mjs @@ -132,7 +132,7 @@ test('synchronisation : sans backend, message clair et l\'application reste util }); test('éditeur : connexion d\'un auteur par le backend Django (cookie, CSRF, redirection, refus)', { skip, timeout: 120000 }, async () => { - const created = spawnSync(venvPython, ['manage.py', 'shell', '-c', "from django.contrib.auth.models import User; User.objects.create_user('ada', password='un-mot-de-passe-solide-42', is_staff=True); User.objects.create_user('lea', password='un-mot-de-passe-solide-42')"], { + const created = spawnSync(venvPython, ['manage.py', 'shell', '-c', "from django.contrib.auth.models import User; from authors import access; access.grant(User.objects.create_user('ada', password='un-mot-de-passe-solide-42')); User.objects.create_user('lea', password='un-mot-de-passe-solide-42')"], { cwd: `${root}backend`, env: { ...process.env, DJANGO_SETTINGS_MODULE: 'pyquest_api.settings.dev', PYQUEST_DB_PATH: join(tmp, 'db.sqlite3') }, });