mirror of
https://github.com/deunix-educ/PyQuest.git
synced 2026-11-25 08:19:44 +01:00
Add Django author accounts for level editor access (login, nginx auth_request, brute-force lockout), MariaDB production settings
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -27,7 +27,8 @@ lire en premier en reprenant une session sur ce projet.
|
|||||||
- **`vendor/pyodide/` est gitignored**, régénéré par `make vendor-pyodide` (script à écrire dans
|
- **`vendor/pyodide/` est gitignored**, régénéré par `make vendor-pyodide` (script à écrire dans
|
||||||
`scripts/vendor_pyodide.sh`).
|
`scripts/vendor_pyodide.sh`).
|
||||||
- **Backend Django = oui**, mais strictement optionnel et jamais requis pour apprendre : sert
|
- **Backend Django = oui**, mais strictement optionnel et jamais requis pour apprendre : sert
|
||||||
uniquement à la synchronisation multi-appareils de la progression. Settings séparés dev/prod,
|
à 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,
|
||||||
traductions fr/en, doc MkDocs bilingue.
|
traductions fr/en, doc MkDocs bilingue.
|
||||||
- Validation des exercices : déclarative uniquement (`tests[].kind` en enum fermé dans le schéma de
|
- 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
|
niveau) — jamais de code arbitraire exécuté depuis un fichier de niveau, pour garder l'isolation
|
||||||
|
|||||||
@@ -38,6 +38,7 @@ vrai navigateur (Chromium) avec 4 niveaux jouables.
|
|||||||
| Tooling | `Makefile`, `scripts/{dev_server,validate_levels,build}.py`, `scripts/vendor_pyodide.sh` |
|
| Tooling | `Makefile`, `scripts/{dev_server,validate_levels,build}.py`, `scripts/vendor_pyodide.sh` |
|
||||||
| Tests | `tests/js/*.test.mjs` (node:test), `tests/python/`, `backend/sync/tests.py`, `tests/e2e/` (Chromium) |
|
| 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) |
|
| Backend | `backend/` Django : `GET/PUT/DELETE /api/sync/` avec jeton Bearer (haché côté serveur), concurrence optimiste (`base` → 409) |
|
||||||
|
| Accès éditeur | `backend/authors/` (login, `check` pour nginx `auth_request`, `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` |
|
| 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
|
## Éditeur de niveaux (mode auteur) — fait le 2026-10-16
|
||||||
|
|||||||
+10
-1
@@ -27,12 +27,21 @@ self.addEventListener('fetch', (event) => {
|
|||||||
if (request.method !== 'GET' || url.origin !== self.location.origin) {
|
if (request.method !== 'GET' || url.origin !== self.location.origin) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
// L'éditeur de niveaux peut être protégé par une connexion (redirection vers une page de login) : on le laisse
|
||||||
|
// au navigateur, sans pré-cache ni mise en cache, pour ne jamais conserver une page de connexion à sa place.
|
||||||
|
if (isAuthorTool(url.pathname)) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
// Pyodide (versionné, immuable, lourd) : cache d'abord. Tout le reste (code, niveaux, audio) :
|
// Pyodide (versionné, immuable, lourd) : cache d'abord. Tout le reste (code, niveaux, audio) :
|
||||||
// réseau d'abord, cache en repli hors ligne — jamais de code périmé servi en ligne.
|
// réseau d'abord, cache en repli hors ligne — jamais de code périmé servi en ligne.
|
||||||
const immutable = url.pathname.startsWith('/vendor/pyodide/');
|
const immutable = url.pathname.startsWith('/vendor/pyodide/');
|
||||||
event.respondWith(immutable ? fromCache(request) : fromNetwork(request));
|
event.respondWith(immutable ? fromCache(request) : fromNetwork(request));
|
||||||
});
|
});
|
||||||
|
|
||||||
|
function isAuthorTool(pathname) {
|
||||||
|
return pathname === '/author.html' || pathname === '/css/author.css' || pathname.startsWith('/js/author/') || /^\/js\/i18n\/author\.[a-z]+\.json$/.test(pathname);
|
||||||
|
}
|
||||||
|
|
||||||
async function fromCache(request) {
|
async function fromCache(request) {
|
||||||
const cache = await caches.open(CACHE_VERSION);
|
const cache = await caches.open(CACHE_VERSION);
|
||||||
const cached = await cache.match(request);
|
const cached = await cache.match(request);
|
||||||
@@ -50,7 +59,7 @@ async function fromNetwork(request) {
|
|||||||
const cache = await caches.open(CACHE_VERSION);
|
const cache = await caches.open(CACHE_VERSION);
|
||||||
try {
|
try {
|
||||||
const response = await fetch(request);
|
const response = await fetch(request);
|
||||||
if (response.ok) {
|
if (response.ok && !response.redirected) {
|
||||||
cache.put(request, response.clone());
|
cache.put(request, response.clone());
|
||||||
}
|
}
|
||||||
return response;
|
return response;
|
||||||
|
|||||||
@@ -0,0 +1,43 @@
|
|||||||
|
"""Crée (ou met à jour le mot de passe d') un compte auteur : accès à l'éditeur de niveaux, rien d'autre."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from getpass import getpass
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
from django.contrib.auth.models import User
|
||||||
|
from django.contrib.auth.password_validation import validate_password
|
||||||
|
from django.core.exceptions import ValidationError
|
||||||
|
from django.core.management.base import BaseCommand, CommandError, CommandParser
|
||||||
|
|
||||||
|
|
||||||
|
class Command(BaseCommand):
|
||||||
|
help = "Crée un compte auteur (is_staff, sans droits d'administration). Le mot de passe est demandé au clavier."
|
||||||
|
|
||||||
|
def add_arguments(self, parser: CommandParser) -> None:
|
||||||
|
parser.add_argument("username")
|
||||||
|
parser.add_argument("--reset", action="store_true", help="Change le mot de passe d'un compte existant")
|
||||||
|
|
||||||
|
def handle(self, *args: Any, **options: Any) -> None:
|
||||||
|
username: str = options["username"].strip().lower()
|
||||||
|
existing = User.objects.filter(username=username).first()
|
||||||
|
if existing and not options["reset"]:
|
||||||
|
raise CommandError(f"{username} existe déjà (utilise --reset pour changer son mot de passe).")
|
||||||
|
if not existing and options["reset"]:
|
||||||
|
raise CommandError(f"{username} n'existe pas.")
|
||||||
|
|
||||||
|
password = getpass("Mot de passe : ")
|
||||||
|
if password != getpass("Confirmation : "):
|
||||||
|
raise CommandError("Les mots de passe ne correspondent pas.")
|
||||||
|
try:
|
||||||
|
validate_password(password)
|
||||||
|
except ValidationError as error:
|
||||||
|
raise CommandError(" ".join(error.messages)) from error
|
||||||
|
|
||||||
|
user = existing or User(username=username)
|
||||||
|
user.is_staff = True
|
||||||
|
user.is_superuser = False
|
||||||
|
user.is_active = True
|
||||||
|
user.set_password(password)
|
||||||
|
user.save()
|
||||||
|
self.stdout.write(self.style.SUCCESS(f"Compte auteur {username} {'mis à jour' if existing else 'créé'}."))
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
# Generated by Django 5.2.18 on 2026-10-16 19:17
|
||||||
|
|
||||||
|
from django.db import migrations, models
|
||||||
|
|
||||||
|
|
||||||
|
class Migration(migrations.Migration):
|
||||||
|
|
||||||
|
initial = True
|
||||||
|
|
||||||
|
dependencies = [
|
||||||
|
]
|
||||||
|
|
||||||
|
operations = [
|
||||||
|
migrations.CreateModel(
|
||||||
|
name='LoginFailure',
|
||||||
|
fields=[
|
||||||
|
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
|
||||||
|
('username', models.CharField(db_index=True, max_length=150)),
|
||||||
|
('ip', models.CharField(db_index=True, max_length=45)),
|
||||||
|
('created_at', models.DateTimeField(auto_now_add=True, db_index=True)),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
]
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
from django.db import models
|
||||||
|
|
||||||
|
|
||||||
|
class LoginFailure(models.Model):
|
||||||
|
"""Tentative de connexion échouée : sert à bloquer temporairement les essais répétés (force brute)."""
|
||||||
|
|
||||||
|
username = models.CharField(max_length=150, db_index=True)
|
||||||
|
ip = models.CharField(max_length=45, db_index=True)
|
||||||
|
created_at = models.DateTimeField(auto_now_add=True, db_index=True)
|
||||||
|
|
||||||
|
def __str__(self) -> str:
|
||||||
|
return f"LoginFailure({self.username!r}, {self.ip})"
|
||||||
@@ -0,0 +1,43 @@
|
|||||||
|
<!doctype html>
|
||||||
|
<html lang="{{ lang }}">
|
||||||
|
<head>
|
||||||
|
<meta charset="utf-8">
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||||
|
<meta name="robots" content="noindex">
|
||||||
|
<title>{{ t.title }}</title>
|
||||||
|
<style>
|
||||||
|
:root { color-scheme: light dark; }
|
||||||
|
body { font-family: system-ui, sans-serif; max-width: 26rem; margin: 3rem auto; padding: 0 1rem; line-height: 1.5; }
|
||||||
|
label { display: block; margin-top: 1rem; font-weight: 700; }
|
||||||
|
input[type=text], input[type=password] { width: 100%; box-sizing: border-box; padding: 0.6rem; font: inherit; min-height: 2.75rem; }
|
||||||
|
button, .button { margin-top: 1.25rem; padding: 0.6rem 1.2rem; font: inherit; min-height: 2.75rem; cursor: pointer; }
|
||||||
|
.error { margin-top: 1rem; padding: 0.75rem; border: 2px solid #b3261e; border-radius: 0.4rem; }
|
||||||
|
.error::before { content: "✘ "; }
|
||||||
|
:focus-visible { outline: 3px solid #1a73e8; outline-offset: 2px; }
|
||||||
|
</style>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<main>
|
||||||
|
<h1>{{ t.heading }}</h1>
|
||||||
|
{% if signed_in %}
|
||||||
|
<p role="status">{{ signed_in_text }}</p>
|
||||||
|
<p><a class="button" href="{{ next }}">{{ t.open }}</a></p>
|
||||||
|
<form method="post" action="{% url 'logout' %}">
|
||||||
|
{% csrf_token %}
|
||||||
|
<button type="submit">{{ t.logout }}</button>
|
||||||
|
</form>
|
||||||
|
{% else %}
|
||||||
|
{% if error %}<p class="error" role="alert">{{ error }}</p>{% endif %}
|
||||||
|
<form method="post">
|
||||||
|
{% csrf_token %}
|
||||||
|
<input type="hidden" name="next" value="{{ next }}">
|
||||||
|
<label for="username">{{ t.username }}</label>
|
||||||
|
<input id="username" name="username" type="text" autocomplete="username" autocapitalize="none" spellcheck="false" required autofocus>
|
||||||
|
<label for="password">{{ t.password }}</label>
|
||||||
|
<input id="password" name="password" type="password" autocomplete="current-password" required>
|
||||||
|
<button type="submit">{{ t.submit }}</button>
|
||||||
|
</form>
|
||||||
|
{% endif %}
|
||||||
|
</main>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
@@ -0,0 +1,189 @@
|
|||||||
|
from io import StringIO
|
||||||
|
from typing import Any
|
||||||
|
from unittest import mock
|
||||||
|
|
||||||
|
from django.contrib.auth.models import User
|
||||||
|
from django.core.management import call_command
|
||||||
|
from django.core.management.base import CommandError
|
||||||
|
from django.test import Client, TestCase, override_settings
|
||||||
|
|
||||||
|
# Réponse du client de test Django : type exact non exposé par les stubs.
|
||||||
|
_Response = Any
|
||||||
|
|
||||||
|
PASSWORD = "un-mot-de-passe-solide-42"
|
||||||
|
LOGIN = "/api/auth/login/"
|
||||||
|
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]
|
||||||
|
|
||||||
|
|
||||||
|
class LoginTest(TestCase):
|
||||||
|
def post(self, username: str, password: str, client: Client | None = None, **extra: str) -> _Response:
|
||||||
|
return (client or self.client).post(LOGIN, {"username": username, "password": password, **extra})
|
||||||
|
|
||||||
|
def test_login_page_is_a_real_form(self) -> None:
|
||||||
|
response = self.client.get(LOGIN)
|
||||||
|
self.assertEqual(response.status_code, 200)
|
||||||
|
self.assertContains(response, 'name="password"')
|
||||||
|
self.assertContains(response, "csrfmiddlewaretoken")
|
||||||
|
self.assertContains(response, 'lang="fr"')
|
||||||
|
self.assertEqual(self.client.get(LOGIN, headers={"Accept-Language": "en-US"}).context["lang"], "en")
|
||||||
|
self.assertIn("no-store", response.headers["Cache-Control"])
|
||||||
|
|
||||||
|
def test_staff_can_sign_in_and_is_sent_to_the_editor(self) -> None:
|
||||||
|
make_user()
|
||||||
|
response = self.post("Ada", PASSWORD) # identifiant insensible à la casse
|
||||||
|
self.assertRedirects(response, "/author.html", fetch_redirect_response=False)
|
||||||
|
self.assertEqual(self.client.get(CHECK).status_code, 204)
|
||||||
|
|
||||||
|
def test_wrong_password_and_unknown_user_look_the_same(self) -> None:
|
||||||
|
make_user()
|
||||||
|
wrong = self.post("ada", "mauvais")
|
||||||
|
unknown = self.post("inconnu", "mauvais")
|
||||||
|
self.assertContains(wrong, "incorrect")
|
||||||
|
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:
|
||||||
|
make_user("lea", staff=False)
|
||||||
|
self.assertContains(self.post("lea", PASSWORD), "incorrect")
|
||||||
|
self.assertEqual(self.client.get(CHECK).status_code, 401)
|
||||||
|
|
||||||
|
def test_inactive_account_is_refused(self) -> None:
|
||||||
|
user = make_user()
|
||||||
|
user.is_active = False
|
||||||
|
user.save()
|
||||||
|
self.assertContains(self.post("ada", PASSWORD), "incorrect")
|
||||||
|
|
||||||
|
def test_next_is_only_followed_for_local_paths(self) -> None:
|
||||||
|
make_user()
|
||||||
|
for hostile in ("https://evil.example/x", "//evil.example/x", "javascript:alert(1)", "http://testserver.evil/x"):
|
||||||
|
client = Client()
|
||||||
|
response = self.post("ada", PASSWORD, client, next=hostile)
|
||||||
|
self.assertRedirects(response, "/author.html", fetch_redirect_response=False, msg_prefix=hostile)
|
||||||
|
response = self.post("ada", PASSWORD, Client(), next="/js/author/main.js")
|
||||||
|
self.assertRedirects(response, "/js/author/main.js", fetch_redirect_response=False)
|
||||||
|
|
||||||
|
def test_csrf_is_enforced_on_login(self) -> None:
|
||||||
|
make_user()
|
||||||
|
strict = Client(enforce_csrf_checks=True)
|
||||||
|
self.assertEqual(self.post("ada", PASSWORD, strict).status_code, 403)
|
||||||
|
|
||||||
|
def test_lockout_after_repeated_failures_even_for_the_right_password(self) -> None:
|
||||||
|
make_user()
|
||||||
|
for _ in range(5):
|
||||||
|
self.assertEqual(self.post("ada", "mauvais").status_code, 200)
|
||||||
|
locked = self.post("ada", PASSWORD)
|
||||||
|
self.assertEqual(locked.status_code, 429)
|
||||||
|
self.assertEqual(self.client.get(CHECK).status_code, 401)
|
||||||
|
|
||||||
|
def test_lockout_expires(self) -> None:
|
||||||
|
from datetime import timedelta
|
||||||
|
|
||||||
|
from django.utils import timezone
|
||||||
|
|
||||||
|
from .models import LoginFailure
|
||||||
|
|
||||||
|
make_user()
|
||||||
|
for _ in range(5):
|
||||||
|
self.post("ada", "mauvais")
|
||||||
|
LoginFailure.objects.update(created_at=timezone.now() - timedelta(minutes=16))
|
||||||
|
self.assertEqual(self.post("ada", PASSWORD).status_code, 302)
|
||||||
|
|
||||||
|
def test_failures_are_cleared_by_a_success(self) -> None:
|
||||||
|
from .models import LoginFailure
|
||||||
|
|
||||||
|
make_user()
|
||||||
|
for _ in range(3):
|
||||||
|
self.post("ada", "mauvais")
|
||||||
|
self.post("ada", PASSWORD)
|
||||||
|
self.assertEqual(LoginFailure.objects.filter(username="ada").count(), 0)
|
||||||
|
|
||||||
|
def test_ip_lockout_uses_real_ip_header_only_when_trusted(self) -> None:
|
||||||
|
from .models import LoginFailure
|
||||||
|
|
||||||
|
make_user()
|
||||||
|
with override_settings(TRUST_REAL_IP_HEADER=False):
|
||||||
|
self.client.post(LOGIN, {"username": "x", "password": "y"}, headers={"X-Real-IP": "203.0.113.9"})
|
||||||
|
with override_settings(TRUST_REAL_IP_HEADER=True):
|
||||||
|
self.client.post(LOGIN, {"username": "x", "password": "y"}, headers={"X-Real-IP": "203.0.113.9"})
|
||||||
|
self.assertEqual(sorted(LoginFailure.objects.values_list("ip", flat=True)), ["127.0.0.1", "203.0.113.9"])
|
||||||
|
|
||||||
|
def test_ip_lockout_blocks_many_usernames(self) -> None:
|
||||||
|
make_user()
|
||||||
|
for index in range(20):
|
||||||
|
self.post(f"inconnu{index}", "mauvais")
|
||||||
|
self.assertEqual(self.post("ada", PASSWORD).status_code, 429)
|
||||||
|
|
||||||
|
|
||||||
|
class CheckAndLogoutTest(TestCase):
|
||||||
|
def test_check_requires_an_author_session(self) -> None:
|
||||||
|
self.assertEqual(self.client.get(CHECK).status_code, 401)
|
||||||
|
make_user("lea", staff=False)
|
||||||
|
self.client.login(username="lea", password=PASSWORD)
|
||||||
|
self.assertEqual(self.client.get(CHECK).status_code, 401)
|
||||||
|
make_user("ada")
|
||||||
|
self.client.login(username="ada", password=PASSWORD)
|
||||||
|
response = self.client.get(CHECK)
|
||||||
|
self.assertEqual(response.status_code, 204)
|
||||||
|
self.assertIn("no-store", response.headers["Cache-Control"])
|
||||||
|
|
||||||
|
def test_check_refuses_other_methods(self) -> None:
|
||||||
|
self.assertEqual(self.client.post(CHECK).status_code, 405)
|
||||||
|
|
||||||
|
def test_logout_ends_the_session_and_needs_post(self) -> None:
|
||||||
|
make_user()
|
||||||
|
self.client.login(username="ada", password=PASSWORD)
|
||||||
|
self.assertEqual(self.client.get("/api/auth/logout/").status_code, 405)
|
||||||
|
self.assertEqual(self.client.get(CHECK).status_code, 204)
|
||||||
|
response = self.client.post("/api/auth/logout/")
|
||||||
|
self.assertRedirects(response, LOGIN, fetch_redirect_response=False)
|
||||||
|
self.assertEqual(self.client.get(CHECK).status_code, 401)
|
||||||
|
|
||||||
|
def test_signed_in_visitor_sees_open_and_logout(self) -> None:
|
||||||
|
make_user()
|
||||||
|
self.client.login(username="ada", password=PASSWORD)
|
||||||
|
page = self.client.get(LOGIN)
|
||||||
|
self.assertContains(page, "Connecté en tant que ada")
|
||||||
|
self.assertContains(page, "/api/auth/logout/")
|
||||||
|
|
||||||
|
def test_session_cookie_is_http_only(self) -> None:
|
||||||
|
make_user()
|
||||||
|
response = self.client.post(LOGIN, {"username": "ada", "password": PASSWORD})
|
||||||
|
cookie = response.cookies["pyquest_author"]
|
||||||
|
self.assertTrue(cookie["httponly"])
|
||||||
|
self.assertEqual(cookie["samesite"], "Lax")
|
||||||
|
|
||||||
|
|
||||||
|
class CreateAuthorCommandTest(TestCase):
|
||||||
|
def run_command(self, *args: str, passwords: tuple[str, str] = (PASSWORD, PASSWORD)) -> str:
|
||||||
|
out = StringIO()
|
||||||
|
with mock.patch("authors.management.commands.create_author.getpass", side_effect=list(passwords)):
|
||||||
|
call_command("create_author", *args, stdout=out)
|
||||||
|
return out.getvalue()
|
||||||
|
|
||||||
|
def test_creates_a_staff_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(user.check_password(PASSWORD))
|
||||||
|
self.assertEqual(self.client.post(LOGIN, {"username": "ada", "password": PASSWORD}).status_code, 302)
|
||||||
|
|
||||||
|
def test_rejects_weak_or_mismatched_passwords(self) -> None:
|
||||||
|
with self.assertRaises(CommandError):
|
||||||
|
self.run_command("ada", passwords=("court", "court"))
|
||||||
|
with self.assertRaises(CommandError):
|
||||||
|
self.run_command("ada", passwords=(PASSWORD, "autre-chose-42-xx"))
|
||||||
|
self.assertFalse(User.objects.filter(username="ada").exists())
|
||||||
|
|
||||||
|
def test_existing_account_needs_reset(self) -> None:
|
||||||
|
make_user()
|
||||||
|
with self.assertRaises(CommandError):
|
||||||
|
self.run_command("ada")
|
||||||
|
self.run_command("ada", "--reset", passwords=("nouveau-mot-de-passe-77", "nouveau-mot-de-passe-77"))
|
||||||
|
self.assertTrue(User.objects.get(username="ada").check_password("nouveau-mot-de-passe-77"))
|
||||||
|
with self.assertRaises(CommandError):
|
||||||
|
self.run_command("inconnu", "--reset")
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
from django.urls import path
|
||||||
|
|
||||||
|
from . import views
|
||||||
|
|
||||||
|
urlpatterns = [
|
||||||
|
path("login/", views.login_view, name="login"),
|
||||||
|
path("logout/", views.logout_view, name="logout"),
|
||||||
|
path("check/", views.check_view, name="check"),
|
||||||
|
]
|
||||||
@@ -0,0 +1,140 @@
|
|||||||
|
"""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.
|
||||||
|
"""
|
||||||
|
|
||||||
|
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
|
||||||
|
|
||||||
|
DEFAULT_NEXT = "/author.html"
|
||||||
|
LOCK_WINDOW = timedelta(minutes=15)
|
||||||
|
MAX_FAILURES_PER_USER = 5
|
||||||
|
MAX_FAILURES_PER_IP = 20
|
||||||
|
|
||||||
|
TEXTS = {
|
||||||
|
"fr": {
|
||||||
|
"title": "Éditeur de niveaux — connexion",
|
||||||
|
"heading": "Connexion à l'éditeur de niveaux",
|
||||||
|
"username": "Identifiant",
|
||||||
|
"password": "Mot de passe",
|
||||||
|
"submit": "Se connecter",
|
||||||
|
"invalid": "Identifiant ou mot de passe incorrect.",
|
||||||
|
"locked": "Trop d'essais. Réessaie dans quelques minutes.",
|
||||||
|
"signed_in": "Connecté en tant que {name}.",
|
||||||
|
"open": "Ouvrir l'éditeur",
|
||||||
|
"logout": "Se déconnecter",
|
||||||
|
},
|
||||||
|
"en": {
|
||||||
|
"title": "Level editor — sign in",
|
||||||
|
"heading": "Sign in to the level editor",
|
||||||
|
"username": "Username",
|
||||||
|
"password": "Password",
|
||||||
|
"submit": "Sign in",
|
||||||
|
"invalid": "Wrong username or password.",
|
||||||
|
"locked": "Too many attempts. Try again in a few minutes.",
|
||||||
|
"signed_in": "Signed in as {name}.",
|
||||||
|
"open": "Open the editor",
|
||||||
|
"logout": "Sign out",
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
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())
|
||||||
|
# Chemin local uniquement (pas de //hôte, pas de schéma).
|
||||||
|
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)
|
||||||
|
context = {
|
||||||
|
"t": texts,
|
||||||
|
"lang": _language(request),
|
||||||
|
"error": texts[error_key] if error_key else None,
|
||||||
|
"next": _safe_next(request),
|
||||||
|
"signed_in": signed_in,
|
||||||
|
"signed_in_text": texts["signed_in"].format(name=user.get_username()) if signed_in else "",
|
||||||
|
}
|
||||||
|
return render(request, "authors/login.html", context, status=status)
|
||||||
|
|
||||||
|
|
||||||
|
@never_cache
|
||||||
|
@require_http_methods(["GET", "POST"])
|
||||||
|
def login_view(request: HttpRequest) -> HttpResponse:
|
||||||
|
if request.method == "GET":
|
||||||
|
return _page(request)
|
||||||
|
|
||||||
|
username = request.POST.get("username", "").strip().lower()[:150]
|
||||||
|
password = request.POST.get("password", "")
|
||||||
|
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()
|
||||||
|
return _page(request, error_key="invalid", status=200)
|
||||||
|
|
||||||
|
LoginFailure.objects.filter(username=username).delete()
|
||||||
|
login(request, user)
|
||||||
|
return redirect(_safe_next(request))
|
||||||
|
|
||||||
|
|
||||||
|
@never_cache
|
||||||
|
@require_POST
|
||||||
|
def logout_view(request: HttpRequest) -> HttpResponse:
|
||||||
|
logout(request)
|
||||||
|
return redirect("login")
|
||||||
|
|
||||||
|
|
||||||
|
@never_cache
|
||||||
|
@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)
|
||||||
@@ -1,17 +1,51 @@
|
|||||||
"""Réglages communs. Le backend ne sert qu'à synchroniser la progression entre appareils."""
|
"""Réglages communs. Le backend sert à synchroniser la progression entre appareils et à protéger l'accès à
|
||||||
|
l'éditeur de niveaux (comptes auteurs). Il n'est jamais requis pour apprendre."""
|
||||||
|
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
|
||||||
BASE_DIR = Path(__file__).resolve().parent.parent.parent
|
BASE_DIR = Path(__file__).resolve().parent.parent.parent
|
||||||
|
|
||||||
INSTALLED_APPS = ["sync"]
|
INSTALLED_APPS = [
|
||||||
|
"django.contrib.contenttypes",
|
||||||
|
"django.contrib.auth",
|
||||||
|
"django.contrib.sessions",
|
||||||
|
"sync",
|
||||||
|
"authors",
|
||||||
|
]
|
||||||
|
|
||||||
MIDDLEWARE = [
|
MIDDLEWARE = [
|
||||||
"django.middleware.security.SecurityMiddleware",
|
"django.middleware.security.SecurityMiddleware",
|
||||||
"django.middleware.locale.LocaleMiddleware",
|
"django.middleware.locale.LocaleMiddleware",
|
||||||
|
"django.contrib.sessions.middleware.SessionMiddleware",
|
||||||
"django.middleware.common.CommonMiddleware",
|
"django.middleware.common.CommonMiddleware",
|
||||||
|
"django.middleware.csrf.CsrfViewMiddleware",
|
||||||
|
"django.contrib.auth.middleware.AuthenticationMiddleware",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
TEMPLATES = [
|
||||||
|
{
|
||||||
|
"BACKEND": "django.template.backends.django.DjangoTemplates",
|
||||||
|
"APP_DIRS": True,
|
||||||
|
"OPTIONS": {"context_processors": ["django.template.context_processors.request"]},
|
||||||
|
}
|
||||||
|
]
|
||||||
|
|
||||||
|
# Session des auteurs (éditeur de niveaux) : cookie HttpOnly, 8 heures.
|
||||||
|
SESSION_COOKIE_NAME = "pyquest_author"
|
||||||
|
SESSION_COOKIE_AGE = 8 * 60 * 60
|
||||||
|
SESSION_COOKIE_SAMESITE = "Lax"
|
||||||
|
CSRF_COOKIE_NAME = "pyquest_csrf"
|
||||||
|
|
||||||
|
AUTH_PASSWORD_VALIDATORS = [
|
||||||
|
{"NAME": "django.contrib.auth.password_validation.UserAttributeSimilarityValidator"},
|
||||||
|
{"NAME": "django.contrib.auth.password_validation.MinimumLengthValidator", "OPTIONS": {"min_length": 12}},
|
||||||
|
{"NAME": "django.contrib.auth.password_validation.CommonPasswordValidator"},
|
||||||
|
{"NAME": "django.contrib.auth.password_validation.NumericPasswordValidator"},
|
||||||
|
]
|
||||||
|
|
||||||
|
# Vrai seulement derrière nginx, qui écrase X-Real-IP : sert à limiter les essais de connexion par adresse.
|
||||||
|
TRUST_REAL_IP_HEADER = False
|
||||||
|
|
||||||
ROOT_URLCONF = "pyquest_api.urls"
|
ROOT_URLCONF = "pyquest_api.urls"
|
||||||
WSGI_APPLICATION = "pyquest_api.wsgi.application"
|
WSGI_APPLICATION = "pyquest_api.wsgi.application"
|
||||||
|
|
||||||
|
|||||||
@@ -16,14 +16,17 @@ DEBUG = False
|
|||||||
SECRET_KEY = _required("PYQUEST_SECRET_KEY")
|
SECRET_KEY = _required("PYQUEST_SECRET_KEY")
|
||||||
ALLOWED_HOSTS = _required("PYQUEST_ALLOWED_HOSTS").split(",")
|
ALLOWED_HOSTS = _required("PYQUEST_ALLOWED_HOSTS").split(",")
|
||||||
|
|
||||||
|
# MariaDB (ou MySQL) : pilote `mysqlclient` (voir backend/requirements-prod.txt), jeu de caractères utf8mb4.
|
||||||
DATABASES = {
|
DATABASES = {
|
||||||
"default": {
|
"default": {
|
||||||
"ENGINE": "django.db.backends.postgresql",
|
"ENGINE": "django.db.backends.mysql",
|
||||||
"NAME": _required("PYQUEST_DB_NAME"),
|
"NAME": _required("PYQUEST_DB_NAME"),
|
||||||
"USER": _required("PYQUEST_DB_USER"),
|
"USER": _required("PYQUEST_DB_USER"),
|
||||||
"PASSWORD": _required("PYQUEST_DB_PASSWORD"),
|
"PASSWORD": _required("PYQUEST_DB_PASSWORD"),
|
||||||
"HOST": os.environ.get("PYQUEST_DB_HOST", "127.0.0.1"),
|
"HOST": os.environ.get("PYQUEST_DB_HOST", "127.0.0.1"),
|
||||||
"PORT": os.environ.get("PYQUEST_DB_PORT", "5432"),
|
"PORT": os.environ.get("PYQUEST_DB_PORT", "3306"),
|
||||||
|
"OPTIONS": {"charset": "utf8mb4"},
|
||||||
|
"CONN_MAX_AGE": 60,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -32,3 +35,9 @@ SECURE_PROXY_SSL_HEADER = ("HTTP_X_FORWARDED_PROTO", "https")
|
|||||||
SECURE_SSL_REDIRECT = True
|
SECURE_SSL_REDIRECT = True
|
||||||
SECURE_HSTS_SECONDS = 31536000
|
SECURE_HSTS_SECONDS = 31536000
|
||||||
SECURE_CONTENT_TYPE_NOSNIFF = True
|
SECURE_CONTENT_TYPE_NOSNIFF = True
|
||||||
|
|
||||||
|
# Origine publique exacte (https://domaine) : requise pour les formulaires POST (connexion) derrière le proxy.
|
||||||
|
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)
|
||||||
|
|||||||
@@ -2,4 +2,5 @@ from django.urls import include, path
|
|||||||
|
|
||||||
urlpatterns = [
|
urlpatterns = [
|
||||||
path("api/sync/", include("sync.urls")),
|
path("api/sync/", include("sync.urls")),
|
||||||
|
path("api/auth/", include("authors.urls")),
|
||||||
]
|
]
|
||||||
|
|||||||
@@ -0,0 +1,5 @@
|
|||||||
|
# Production : -r requirements.txt, serveur d'application et pilote MariaDB/MySQL.
|
||||||
|
# mysqlclient se compile : sur Debian/Ubuntu, `sudo apt install pkg-config libmariadb-dev build-essential python3-dev`.
|
||||||
|
-r requirements.txt
|
||||||
|
gunicorn>=22.0
|
||||||
|
mysqlclient>=2.2
|
||||||
@@ -1,3 +1,2 @@
|
|||||||
# Backend de synchronisation (optionnel). Django LTS.
|
# Backend optionnel (synchronisation, accès à l'éditeur de niveaux). Django LTS.
|
||||||
Django>=5.2,<5.3
|
Django>=5.2,<5.3
|
||||||
gunicorn>=22.0 # production uniquement
|
|
||||||
|
|||||||
@@ -27,7 +27,7 @@ flowchart TB
|
|||||||
|
|
||||||
subgraph Backend["Backend optionnel (Django, même VPS)"]
|
subgraph Backend["Backend optionnel (Django, même VPS)"]
|
||||||
API[API REST<br/>sync multi-appareils]
|
API[API REST<br/>sync multi-appareils]
|
||||||
DB[(PostgreSQL/SQLite)]
|
DB[(MariaDB/SQLite)]
|
||||||
end
|
end
|
||||||
|
|
||||||
UI -->|clic Exécuter| PWC
|
UI -->|clic Exécuter| PWC
|
||||||
|
|||||||
@@ -47,6 +47,13 @@ non JSON (serveur statique sans Django) donne `unavailable`.
|
|||||||
- Même origine uniquement : pas de CORS, pas d'exception COEP. En dev : `make dev-sync`.
|
- Même origine uniquement : pas de CORS, pas d'exception COEP. En dev : `make dev-sync`.
|
||||||
- nginx : limite de débit et taille de corps (voir `nginx/pyquest.conf.example`).
|
- nginx : limite de débit et taille de corps (voir `nginx/pyquest.conf.example`).
|
||||||
|
|
||||||
|
## 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
|
||||||
|
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`).
|
||||||
|
|
||||||
## Non fait (volontairement)
|
## Non fait (volontairement)
|
||||||
|
|
||||||
- QR code du jeton (aurait demandé une dépendance) : copier/coller suffit pour l'instant.
|
- QR code du jeton (aurait demandé une dépendance) : copier/coller suffit pour l'instant.
|
||||||
|
|||||||
@@ -0,0 +1,9 @@
|
|||||||
|
# À installer dans /etc/nginx/snippets/pyquest-author-headers.conf (inclus par pyquest.conf.example).
|
||||||
|
# Pourquoi un fichier : add_header n'est pas hérité dès qu'un bloc location en déclare un, donc chaque location
|
||||||
|
# protégée doit répéter les en-têtes d'isolation. « no-store » : une page protégée ne reste pas dans le cache partagé.
|
||||||
|
add_header Cross-Origin-Opener-Policy "same-origin" always;
|
||||||
|
add_header Cross-Origin-Embedder-Policy "require-corp" always;
|
||||||
|
add_header Cross-Origin-Resource-Policy "same-origin" always;
|
||||||
|
add_header X-Content-Type-Options "nosniff" always;
|
||||||
|
add_header Strict-Transport-Security "max-age=31536000" always;
|
||||||
|
add_header Cache-Control "no-store" always;
|
||||||
+110
-21
@@ -1,30 +1,49 @@
|
|||||||
# Exemple de vhost PyQuest (à adapter : domaine, chemins, certificats).
|
# Vhost PyQuest complet : application statique + backend Django (synchronisation et accès à l'éditeur de niveaux).
|
||||||
# Les en-têtes COOP/COEP sont indispensables à l'interruption propre des boucles infinies
|
# À adapter : domaine, chemins, certificat. Sans backend, utiliser pyquest-static.conf.example.
|
||||||
# (SharedArrayBuffer). HTTPS obligatoire (service worker + isolation cross-origin).
|
# Contenu servi : le dossier « current » créé par scripts/deploy.sh. Django (gunicorn) écoute sur 127.0.0.1:8001.
|
||||||
# Voir docs/design/01-pyodide-choice.md.
|
# Les en-têtes COOP/COEP/CORP sont indispensables à l'interruption des boucles infinies et à input()
|
||||||
|
# (SharedArrayBuffer). Tout est servi depuis ce domaine, y compris Pyodide (COEP interdit les CDN).
|
||||||
|
#
|
||||||
|
# Éditeur de niveaux (author.html) : réservé aux comptes créés avec « manage.py create_author ». nginx demande à
|
||||||
|
# Django (auth_request → /api/auth/check/) si la session est valide ; sinon il redirige vers la page de connexion
|
||||||
|
# /api/auth/login/. Ce n'est pas indispensable à la sécurité des données (l'éditeur ne peut rien écrire sur le
|
||||||
|
# serveur) : cela évite seulement de l'exposer au public.
|
||||||
|
#
|
||||||
|
# Installation type : voir docs/site/fr/host/deploy.md. Vérifier avec « sudo nginx -t » avant de recharger.
|
||||||
|
|
||||||
# Limite de débit de l'API de synchronisation (hors bloc server, contexte http) : 30 requêtes/min par IP.
|
# Limites de débit (contexte http, hors bloc server) : synchronisation 30 req/min, connexion 6 req/min par IP.
|
||||||
limit_req_zone $binary_remote_addr zone=pyquest_sync:10m rate=30r/m;
|
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;
|
||||||
|
|
||||||
|
server {
|
||||||
|
listen 80;
|
||||||
|
listen [::]:80;
|
||||||
|
server_name pyquest.example.org;
|
||||||
|
|
||||||
|
# Défi HTTP de Let's Encrypt, puis tout le reste passe en HTTPS.
|
||||||
|
location /.well-known/acme-challenge/ {
|
||||||
|
root /var/www/letsencrypt;
|
||||||
|
}
|
||||||
|
location / {
|
||||||
|
return 301 https://$host$request_uri;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
server {
|
server {
|
||||||
listen 443 ssl;
|
listen 443 ssl;
|
||||||
http2 on; # nginx >= 1.25.1 ; avant : « listen 443 ssl http2; »
|
listen [::]:443 ssl;
|
||||||
|
http2 on; # nginx >= 1.25.1 ; avant : « listen 443 ssl http2; » ci-dessus
|
||||||
server_name pyquest.example.org;
|
server_name pyquest.example.org;
|
||||||
|
|
||||||
ssl_certificate /etc/letsencrypt/live/pyquest.example.org/fullchain.pem;
|
ssl_certificate /etc/letsencrypt/live/pyquest.example.org/fullchain.pem;
|
||||||
ssl_certificate_key /etc/letsencrypt/live/pyquest.example.org/privkey.pem;
|
ssl_certificate_key /etc/letsencrypt/live/pyquest.example.org/privkey.pem;
|
||||||
|
|
||||||
# Contenu produit par `make build`
|
# Dossier créé par scripts/deploy.sh (lien « current » basculé à chaque déploiement).
|
||||||
root /var/www/pyquest/dist;
|
root /var/www/pyquest/current;
|
||||||
index index.html;
|
index index.html;
|
||||||
|
|
||||||
add_header Cross-Origin-Opener-Policy "same-origin" always;
|
# Types MIME explicites : un bloc « types » dans server remplace la table par défaut, donc on
|
||||||
add_header Cross-Origin-Embedder-Policy "require-corp" always;
|
# liste tout ce que l'application sert. Les scripts-modules exigent text/javascript.
|
||||||
add_header Cross-Origin-Resource-Policy "same-origin" always;
|
|
||||||
add_header X-Content-Type-Options "nosniff" always;
|
|
||||||
|
|
||||||
# Types MIME explicites : un bloc « types » dans server remplace la table par défaut, donc on liste
|
|
||||||
# tout ce que l'application sert (voir pyquest-static.conf.example pour la version complète et la compression).
|
|
||||||
types {
|
types {
|
||||||
text/html html;
|
text/html html;
|
||||||
text/css css;
|
text/css css;
|
||||||
@@ -41,32 +60,102 @@ server {
|
|||||||
}
|
}
|
||||||
default_type application/octet-stream;
|
default_type application/octet-stream;
|
||||||
|
|
||||||
|
# Compression : le moteur Python (wasm) et les scripts gagnent beaucoup.
|
||||||
|
gzip on;
|
||||||
|
gzip_comp_level 6;
|
||||||
|
gzip_min_length 1024;
|
||||||
|
gzip_types text/css text/javascript application/json application/wasm image/svg+xml text/plain application/manifest+json;
|
||||||
|
|
||||||
|
# add_header n'est hérité que si le bloc location n'en déclare aucun : chaque location qui ajoute
|
||||||
|
# un en-tête (cache) doit donc répéter ceux d'isolation. On les regroupe dans ce fichier-ci.
|
||||||
|
add_header Cross-Origin-Opener-Policy "same-origin" always;
|
||||||
|
add_header Cross-Origin-Embedder-Policy "require-corp" always;
|
||||||
|
add_header Cross-Origin-Resource-Policy "same-origin" always;
|
||||||
|
add_header X-Content-Type-Options "nosniff" always;
|
||||||
|
add_header Strict-Transport-Security "max-age=31536000" always;
|
||||||
|
|
||||||
location / {
|
location / {
|
||||||
try_files $uri $uri/ =404;
|
try_files $uri $uri/ =404;
|
||||||
}
|
# Pages et scripts : revalidés à chaque chargement (le service worker passe par le réseau d'abord).
|
||||||
|
|
||||||
# Le service worker ne doit jamais être mis en cache longtemps par le navigateur.
|
|
||||||
location = /service-worker.js {
|
|
||||||
add_header Cache-Control "no-cache" always;
|
add_header Cache-Control "no-cache" always;
|
||||||
add_header Cross-Origin-Opener-Policy "same-origin" always;
|
add_header Cross-Origin-Opener-Policy "same-origin" always;
|
||||||
add_header Cross-Origin-Embedder-Policy "require-corp" always;
|
add_header Cross-Origin-Embedder-Policy "require-corp" always;
|
||||||
add_header Cross-Origin-Resource-Policy "same-origin" always;
|
add_header Cross-Origin-Resource-Policy "same-origin" always;
|
||||||
|
add_header X-Content-Type-Options "nosniff" always;
|
||||||
|
add_header Strict-Transport-Security "max-age=31536000" always;
|
||||||
}
|
}
|
||||||
|
|
||||||
# Pyodide est versionné et immuable.
|
# Pyodide est versionné et immuable : cache long.
|
||||||
location /vendor/pyodide/ {
|
location /vendor/pyodide/ {
|
||||||
add_header Cache-Control "public, max-age=31536000, immutable" always;
|
add_header Cache-Control "public, max-age=31536000, immutable" always;
|
||||||
add_header Cross-Origin-Opener-Policy "same-origin" always;
|
add_header Cross-Origin-Opener-Policy "same-origin" always;
|
||||||
add_header Cross-Origin-Embedder-Policy "require-corp" always;
|
add_header Cross-Origin-Embedder-Policy "require-corp" always;
|
||||||
add_header Cross-Origin-Resource-Policy "same-origin" always;
|
add_header Cross-Origin-Resource-Policy "same-origin" always;
|
||||||
|
add_header X-Content-Type-Options "nosniff" always;
|
||||||
|
add_header Strict-Transport-Security "max-age=31536000" always;
|
||||||
}
|
}
|
||||||
|
|
||||||
# API de synchronisation Django (optionnelle), sur le même domaine.
|
# ---- Éditeur de niveaux : protégé par la session Django -------------------------------------------------
|
||||||
|
|
||||||
|
# Sous-requête interne : Django répond 204 (auteur connecté) ou 401. Le corps de la requête n'est pas transmis.
|
||||||
|
location = /_auth_check {
|
||||||
|
internal;
|
||||||
|
proxy_pass http://127.0.0.1:8001/api/auth/check/;
|
||||||
|
proxy_pass_request_body off;
|
||||||
|
proxy_set_header Content-Length "";
|
||||||
|
proxy_set_header Host $host;
|
||||||
|
proxy_set_header X-Forwarded-Proto $scheme;
|
||||||
|
}
|
||||||
|
|
||||||
|
# Non connecté : page de connexion, qui ramène ensuite sur l'éditeur.
|
||||||
|
location @author_login {
|
||||||
|
return 302 /api/auth/login/?next=$request_uri;
|
||||||
|
}
|
||||||
|
|
||||||
|
# L'entrée et tout ce qui est propre à l'éditeur (le reste du code est commun avec l'application).
|
||||||
|
location = /author.html {
|
||||||
|
auth_request /_auth_check;
|
||||||
|
error_page 401 = @author_login;
|
||||||
|
include /etc/nginx/snippets/pyquest-author-headers.conf;
|
||||||
|
}
|
||||||
|
location = /css/author.css {
|
||||||
|
auth_request /_auth_check;
|
||||||
|
error_page 401 = @author_login;
|
||||||
|
include /etc/nginx/snippets/pyquest-author-headers.conf;
|
||||||
|
}
|
||||||
|
location ^~ /js/author/ {
|
||||||
|
auth_request /_auth_check;
|
||||||
|
error_page 401 = @author_login;
|
||||||
|
include /etc/nginx/snippets/pyquest-author-headers.conf;
|
||||||
|
}
|
||||||
|
location ~ ^/js/i18n/author\.[a-z]+\.json$ {
|
||||||
|
auth_request /_auth_check;
|
||||||
|
error_page 401 = @author_login;
|
||||||
|
include /etc/nginx/snippets/pyquest-author-headers.conf;
|
||||||
|
}
|
||||||
|
|
||||||
|
# ---- Backend Django ------------------------------------------------------------------------------------
|
||||||
|
|
||||||
|
# Connexion : peu d'essais autorisés (Django bloque aussi après 5 échecs par compte pendant 15 minutes).
|
||||||
|
location = /api/auth/login/ {
|
||||||
|
limit_req zone=pyquest_login burst=5 nodelay;
|
||||||
|
client_max_body_size 4k;
|
||||||
|
proxy_pass http://127.0.0.1:8001;
|
||||||
|
proxy_set_header Host $host;
|
||||||
|
proxy_set_header X-Forwarded-Proto $scheme;
|
||||||
|
proxy_set_header X-Real-IP $remote_addr; # écrase toute valeur envoyée par le client
|
||||||
|
}
|
||||||
|
|
||||||
|
# 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;
|
||||||
|
}
|
||||||
location /api/ {
|
location /api/ {
|
||||||
limit_req zone=pyquest_sync burst=20 nodelay;
|
limit_req zone=pyquest_sync burst=20 nodelay;
|
||||||
client_max_body_size 300k;
|
client_max_body_size 300k;
|
||||||
proxy_pass http://127.0.0.1:8001;
|
proxy_pass http://127.0.0.1:8001;
|
||||||
proxy_set_header Host $host;
|
proxy_set_header Host $host;
|
||||||
proxy_set_header X-Forwarded-Proto $scheme;
|
proxy_set_header X-Forwarded-Proto $scheme;
|
||||||
|
proxy_set_header X-Real-IP $remote_addr;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -16,6 +16,17 @@ PRECACHED_SUFFIXES = {".html", ".css", ".js", ".mjs", ".json", ".svg", ".png", "
|
|||||||
NOT_PRECACHED = {"service-worker.js"}
|
NOT_PRECACHED = {"service-worker.js"}
|
||||||
|
|
||||||
|
|
||||||
|
def is_author_tool(relative: str) -> bool:
|
||||||
|
"""Fichiers propres à l'éditeur de niveaux : sur un serveur ils peuvent être protégés par authentification,
|
||||||
|
donc jamais pré-cachés (le service worker les récupérerait sans session et mettrait une page de connexion en cache)."""
|
||||||
|
return (
|
||||||
|
relative == "author.html"
|
||||||
|
or relative == "css/author.css"
|
||||||
|
or relative.startswith("js/author/")
|
||||||
|
or (relative.startswith("js/i18n/author.") and relative.endswith(".json"))
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
def copy_tree(source: Path, target: Path) -> None:
|
def copy_tree(source: Path, target: Path) -> None:
|
||||||
shutil.copytree(source, target, ignore=shutil.ignore_patterns("__pycache__", "*.pyc", "*.md"))
|
shutil.copytree(source, target, ignore=shutil.ignore_patterns("__pycache__", "*.pyc", "*.md"))
|
||||||
|
|
||||||
@@ -29,6 +40,7 @@ def shell_files() -> list[str]:
|
|||||||
and path.suffix in PRECACHED_SUFFIXES
|
and path.suffix in PRECACHED_SUFFIXES
|
||||||
and path.name not in NOT_PRECACHED
|
and path.name not in NOT_PRECACHED
|
||||||
and not path.relative_to(DIST).parts[0] in {"vendor", "levels"}
|
and not path.relative_to(DIST).parts[0] in {"vendor", "levels"}
|
||||||
|
and not is_author_tool(path.relative_to(DIST).as_posix())
|
||||||
]
|
]
|
||||||
return ["./", *files]
|
return ["./", *files]
|
||||||
|
|
||||||
|
|||||||
+27
-7
@@ -26,7 +26,18 @@ mimetypes.add_type("application/wasm", ".wasm")
|
|||||||
|
|
||||||
# Amont Django optionnel (--api-upstream) : /api/ est relayé comme le ferait nginx en production.
|
# Amont Django optionnel (--api-upstream) : /api/ est relayé comme le ferait nginx en production.
|
||||||
API_UPSTREAM: str | None = None
|
API_UPSTREAM: str | None = None
|
||||||
FORWARDED_HEADERS = ("Authorization", "Content-Type", "Accept", "Accept-Language")
|
FORWARDED_HEADERS = ("Authorization", "Content-Type", "Accept", "Accept-Language", "Cookie", "Origin", "Referer", "Host")
|
||||||
|
RETURNED_HEADERS = ("Content-Type", "Location", "Cache-Control", "Vary")
|
||||||
|
|
||||||
|
|
||||||
|
class _NoRedirect(urllib.request.HTTPRedirectHandler):
|
||||||
|
"""Les redirections (connexion, déconnexion) sont renvoyées telles quelles au navigateur."""
|
||||||
|
|
||||||
|
def redirect_request(self, *args: Any, **kwargs: Any) -> None:
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
_OPENER = urllib.request.build_opener(_NoRedirect)
|
||||||
|
|
||||||
|
|
||||||
class DevHandler(SimpleHTTPRequestHandler):
|
class DevHandler(SimpleHTTPRequestHandler):
|
||||||
@@ -36,16 +47,22 @@ class DevHandler(SimpleHTTPRequestHandler):
|
|||||||
body = self.rfile.read(length) if length else None
|
body = self.rfile.read(length) if length else None
|
||||||
headers = {name: value for name in FORWARDED_HEADERS if (value := self.headers.get(name))}
|
headers = {name: value for name in FORWARDED_HEADERS if (value := self.headers.get(name))}
|
||||||
request = urllib.request.Request(API_UPSTREAM + self.path, data=body, headers=headers, method=self.command)
|
request = urllib.request.Request(API_UPSTREAM + self.path, data=body, headers=headers, method=self.command)
|
||||||
|
extra: list[tuple[str, str]] = []
|
||||||
try:
|
try:
|
||||||
with urllib.request.urlopen(request, timeout=10) as response:
|
with _OPENER.open(request, timeout=10) as response:
|
||||||
status, payload, content_type = response.status, response.read(), response.headers.get("Content-Type")
|
status, payload, reply = response.status, response.read(), response.headers
|
||||||
except urllib.error.HTTPError as error:
|
except urllib.error.HTTPError as error:
|
||||||
status, payload, content_type = error.code, error.read(), error.headers.get("Content-Type")
|
status, payload, reply = error.code, error.read(), error.headers
|
||||||
except OSError:
|
except OSError:
|
||||||
status, payload, content_type = 502, b"Bad gateway", "text/plain"
|
status, payload, reply = 502, b"Bad gateway", None
|
||||||
self.send_response(status)
|
self.send_response(status)
|
||||||
if content_type:
|
if reply is not None:
|
||||||
self.send_header("Content-Type", content_type)
|
extra = [(name, value) for name in RETURNED_HEADERS if (value := reply.get(name))]
|
||||||
|
extra += [("Set-Cookie", cookie) for cookie in reply.get_all("Set-Cookie") or []]
|
||||||
|
else:
|
||||||
|
extra = [("Content-Type", "text/plain")]
|
||||||
|
for name, value in extra:
|
||||||
|
self.send_header(name, value)
|
||||||
self.send_header("Content-Length", str(len(payload)))
|
self.send_header("Content-Length", str(len(payload)))
|
||||||
self.end_headers()
|
self.end_headers()
|
||||||
self.wfile.write(payload)
|
self.wfile.write(payload)
|
||||||
@@ -59,6 +76,9 @@ class DevHandler(SimpleHTTPRequestHandler):
|
|||||||
def do_HEAD(self) -> None:
|
def do_HEAD(self) -> None:
|
||||||
self._proxy_api() if self._is_api() else super().do_HEAD()
|
self._proxy_api() if self._is_api() else super().do_HEAD()
|
||||||
|
|
||||||
|
def do_POST(self) -> None:
|
||||||
|
self._proxy_api() if self._is_api() else self.send_error(405)
|
||||||
|
|
||||||
def do_PUT(self) -> None:
|
def do_PUT(self) -> None:
|
||||||
self._proxy_api() if self._is_api() else self.send_error(405)
|
self._proxy_api() if self._is_api() else self.send_error(405)
|
||||||
|
|
||||||
|
|||||||
@@ -130,3 +130,53 @@ test('synchronisation : sans backend, message clair et l\'application reste util
|
|||||||
assert.equal(await doneCount(page), 1);
|
assert.equal(await doneCount(page), 1);
|
||||||
assert.deepEqual(errors, []);
|
assert.deepEqual(errors, []);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
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')"], {
|
||||||
|
cwd: `${root}backend`,
|
||||||
|
env: { ...process.env, DJANGO_SETTINGS_MODULE: 'pyquest_api.settings.dev', PYQUEST_DB_PATH: join(tmp, 'db.sqlite3') },
|
||||||
|
});
|
||||||
|
assert.equal(created.status, 0, String(created.stderr));
|
||||||
|
|
||||||
|
const context = await browser.newContext({ locale: 'fr-FR' });
|
||||||
|
const page = await context.newPage();
|
||||||
|
const errors = [];
|
||||||
|
page.on('pageerror', (error) => errors.push(error.message));
|
||||||
|
|
||||||
|
// Sans session : l'autorisation est refusée (c'est ce que nginx verra).
|
||||||
|
assert.equal((await page.request.get(`${web}api/auth/check/`)).status(), 401);
|
||||||
|
|
||||||
|
await page.goto(`${web}api/auth/login/?next=/author.html`);
|
||||||
|
assert.equal(await page.title(), 'Éditeur de niveaux — connexion');
|
||||||
|
|
||||||
|
// Mauvais mot de passe, puis compte non auteur : message identique, toujours pas de session.
|
||||||
|
await page.getByLabel('Identifiant').fill('ada');
|
||||||
|
await page.getByLabel('Mot de passe').fill('mauvais');
|
||||||
|
await page.getByRole('button', { name: 'Se connecter' }).click();
|
||||||
|
await page.getByRole('alert').filter({ hasText: 'incorrect' }).waitFor();
|
||||||
|
await page.getByLabel('Identifiant').fill('lea');
|
||||||
|
await page.getByLabel('Mot de passe').fill('un-mot-de-passe-solide-42');
|
||||||
|
await page.getByRole('button', { name: 'Se connecter' }).click();
|
||||||
|
await page.getByRole('alert').filter({ hasText: 'incorrect' }).waitFor();
|
||||||
|
assert.equal((await page.request.get(`${web}api/auth/check/`)).status(), 401);
|
||||||
|
|
||||||
|
// Bon compte : redirection vers l'éditeur, cookie de session illisible par le JavaScript de la page.
|
||||||
|
await page.getByLabel('Identifiant').fill('ada');
|
||||||
|
await page.getByLabel('Mot de passe').fill('un-mot-de-passe-solide-42');
|
||||||
|
await page.getByRole('button', { name: 'Se connecter' }).click();
|
||||||
|
await page.waitForURL(`${web}author.html`);
|
||||||
|
assert.equal(await page.evaluate(() => document.cookie.includes('pyquest_author')), false, 'cookie HttpOnly');
|
||||||
|
const cookie = (await context.cookies()).find((entry) => entry.name === 'pyquest_author');
|
||||||
|
assert.ok(cookie?.httpOnly);
|
||||||
|
assert.equal((await page.request.get(`${web}api/auth/check/`)).status(), 204);
|
||||||
|
|
||||||
|
// Un autre navigateur n'a pas la session ; la déconnexion la supprime.
|
||||||
|
const other = await browser.newContext({ locale: 'fr-FR' });
|
||||||
|
assert.equal((await other.request.get(`${web}api/auth/check/`)).status(), 401);
|
||||||
|
await page.goto(`${web}api/auth/login/`);
|
||||||
|
await page.getByText('Connecté en tant que ada').waitFor();
|
||||||
|
await page.getByRole('button', { name: 'Se déconnecter' }).click();
|
||||||
|
await page.getByRole('button', { name: 'Se connecter' }).waitFor();
|
||||||
|
assert.equal((await page.request.get(`${web}api/auth/check/`)).status(), 401);
|
||||||
|
assert.deepEqual(errors, []);
|
||||||
|
});
|
||||||
|
|||||||
Reference in New Issue
Block a user