mirror of
https://github.com/deunix-educ/PyQuest.git
synced 2026-11-25 08:19:44 +01:00
Add local full-stack test with real nginx (make dev-nginx), share nginx location blocks with production, e2e through nginx
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -36,3 +36,4 @@ build/
|
||||
.vscode/*
|
||||
!.vscode/extensions.json
|
||||
.DS_Store
|
||||
.local/
|
||||
|
||||
@@ -38,6 +38,7 @@ vrai navigateur (Chromium) avec 4 niveaux jouables.
|
||||
| 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) |
|
||||
| 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 |
|
||||
| Synchronisation | `core/SyncClient.js` + section Réglages ; export/import fichier ; voir `docs/design/09-sync.md` ; `make dev-sync` |
|
||||
|
||||
|
||||
@@ -27,6 +27,11 @@ Deux possibilités :
|
||||
- **Tu peux lancer `make voice`** : fais-le et inclus les fichiers `levels/<id>/audio/` dans ta contribution.
|
||||
- **Tu ne peux pas** : mets `voice: false` sur tes étapes ; un mainteneur activera la narration avant la fusion.
|
||||
|
||||
## Essayer la pile complète en local
|
||||
|
||||
`make dev-nginx` lance un vrai nginx (mêmes blocs qu'en production) devant `dist/` et le backend Django : éditeur
|
||||
protégé par connexion, isolation, synchronisation. Il faut un binaire nginx (voir `docs/site/fr/host/deploy.md`).
|
||||
|
||||
## Documentation
|
||||
|
||||
La documentation (MkDocs, bilingue) est dans `docs/site/fr` et `docs/site/en`, avec les mêmes pages dans les deux
|
||||
|
||||
@@ -5,7 +5,7 @@ VENV := .venv
|
||||
VENV_PY := $(VENV)/bin/python
|
||||
PORT ?= 8000
|
||||
|
||||
.PHONY: help install vendor-pyodide dev validate-levels build dev-sync 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 dev-nginx 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}'
|
||||
@@ -51,6 +51,9 @@ docs: $(DOCS_VENV)/.installed ## Génère la documentation bilingue dans site/ (
|
||||
docs-serve: $(DOCS_VENV)/.installed ## Documentation en direct sur http://127.0.0.1:8003/
|
||||
$(DOCS_VENV)/bin/mkdocs serve --dev-addr 127.0.0.1:8003
|
||||
|
||||
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
|
||||
|
||||
validate-levels: $(VENV)/.installed ## Valide les niveaux (schéma, manifeste, traductions)
|
||||
$(VENV_PY) scripts/validate_levels.py
|
||||
|
||||
|
||||
@@ -0,0 +1,125 @@
|
||||
# Parties communes du vhost PyQuest : types MIME, compression, en-têtes d'isolation, éditeur protégé, API Django.
|
||||
# Incluses par le bloc « server » de pyquest.conf.example (production) ET par scripts/local_stack.py (essai local avec
|
||||
# un vrai nginx) : on teste ainsi exactement ce qui sera déployé. Le chemin d'include est relatif au dossier de
|
||||
# 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.
|
||||
# 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
|
||||
# liste tout ce que l'application sert. Les scripts-modules exigent text/javascript.
|
||||
types {
|
||||
text/html html;
|
||||
text/css css;
|
||||
text/javascript js mjs;
|
||||
application/json json;
|
||||
application/manifest+json webmanifest;
|
||||
application/wasm wasm;
|
||||
image/svg+xml svg;
|
||||
image/png png;
|
||||
image/x-icon ico;
|
||||
audio/mpeg mp3;
|
||||
font/woff2 woff2;
|
||||
text/plain txt py yaml;
|
||||
}
|
||||
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 / {
|
||||
try_files $uri $uri/ =404;
|
||||
# Pages et scripts : revalidés à chaque chargement (le service worker passe par le réseau d'abord).
|
||||
add_header Cache-Control "no-cache" always;
|
||||
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;
|
||||
}
|
||||
|
||||
# Pyodide est versionné et immuable : cache long.
|
||||
location /vendor/pyodide/ {
|
||||
add_header Cache-Control "public, max-age=31536000, immutable" always;
|
||||
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;
|
||||
}
|
||||
|
||||
# ---- É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 $http_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 snippets/pyquest-author-headers.conf;
|
||||
}
|
||||
location = /css/author.css {
|
||||
auth_request /_auth_check;
|
||||
error_page 401 = @author_login;
|
||||
include snippets/pyquest-author-headers.conf;
|
||||
}
|
||||
location ^~ /js/author/ {
|
||||
auth_request /_auth_check;
|
||||
error_page 401 = @author_login;
|
||||
include snippets/pyquest-author-headers.conf;
|
||||
}
|
||||
location ~ ^/js/i18n/author\.[a-z]+\.json$ {
|
||||
auth_request /_auth_check;
|
||||
error_page 401 = @author_login;
|
||||
include 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 $http_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/ {
|
||||
limit_req zone=pyquest_sync burst=20 nodelay;
|
||||
client_max_body_size 300k;
|
||||
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;
|
||||
}
|
||||
+5
-116
@@ -10,6 +10,8 @@
|
||||
# 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.
|
||||
# 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.
|
||||
limit_req_zone $binary_remote_addr zone=pyquest_sync:10m rate=30r/m;
|
||||
@@ -42,120 +44,7 @@ server {
|
||||
root /var/www/pyquest/current;
|
||||
index index.html;
|
||||
|
||||
# Types MIME explicites : un bloc « types » dans server remplace la table par défaut, donc on
|
||||
# liste tout ce que l'application sert. Les scripts-modules exigent text/javascript.
|
||||
types {
|
||||
text/html html;
|
||||
text/css css;
|
||||
text/javascript js mjs;
|
||||
application/json json;
|
||||
application/manifest+json webmanifest;
|
||||
application/wasm wasm;
|
||||
image/svg+xml svg;
|
||||
image/png png;
|
||||
image/x-icon ico;
|
||||
audio/mpeg mp3;
|
||||
font/woff2 woff2;
|
||||
text/plain txt py yaml;
|
||||
}
|
||||
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 / {
|
||||
try_files $uri $uri/ =404;
|
||||
# Pages et scripts : revalidés à chaque chargement (le service worker passe par le réseau d'abord).
|
||||
add_header Cache-Control "no-cache" always;
|
||||
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;
|
||||
}
|
||||
|
||||
# Pyodide est versionné et immuable : cache long.
|
||||
location /vendor/pyodide/ {
|
||||
add_header Cache-Control "public, max-age=31536000, immutable" always;
|
||||
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;
|
||||
}
|
||||
|
||||
# ---- É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/ {
|
||||
limit_req zone=pyquest_sync burst=20 nodelay;
|
||||
client_max_body_size 300k;
|
||||
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;
|
||||
}
|
||||
# Types MIME, compression, en-têtes, éditeur protégé par Django et API : voir ce fichier (copié dans
|
||||
# /etc/nginx/snippets/pyquest-locations.conf). Il est aussi utilisé par l'essai local (make dev-nginx).
|
||||
include snippets/pyquest-locations.conf;
|
||||
}
|
||||
|
||||
Executable
+153
@@ -0,0 +1,153 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Pile complète en local, comme en production : nginx (vrais blocs de nginx/pyquest-locations.conf.example)
|
||||
devant dist/ et le backend Django (SQLite jetable). Permet d'essayer l'éditeur protégé par connexion, la
|
||||
synchronisation, les en-têtes d'isolation et les types MIME sans VPS.
|
||||
|
||||
make build && python3 scripts/local_stack.py # http://127.0.0.1:8080/
|
||||
|
||||
nginx n'a pas besoin d'être installé en tant que service : seul le binaire est utilisé (variable PYQUEST_NGINX ou
|
||||
option --nginx), avec des dossiers de travail dans .local/stack/. Rien n'est écrit hors du dépôt.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import os
|
||||
import shutil
|
||||
import signal
|
||||
import subprocess
|
||||
import sys
|
||||
from pathlib import Path
|
||||
from types import FrameType
|
||||
|
||||
ROOT = Path(__file__).resolve().parent.parent
|
||||
NGINX_DIR = ROOT / "nginx"
|
||||
|
||||
CONF_TEMPLATE = """\
|
||||
# Généré par scripts/local_stack.py : ne pas éditer (régénéré à chaque lancement).
|
||||
daemon off;
|
||||
pid {work}/nginx.pid;
|
||||
error_log {work}/logs/error.log warn;
|
||||
|
||||
events {{
|
||||
worker_connections 256;
|
||||
}}
|
||||
|
||||
http {{
|
||||
access_log {work}/logs/access.log;
|
||||
client_body_temp_path {work}/temp/body;
|
||||
proxy_temp_path {work}/temp/proxy;
|
||||
fastcgi_temp_path {work}/temp/fastcgi;
|
||||
uwsgi_temp_path {work}/temp/uwsgi;
|
||||
scgi_temp_path {work}/temp/scgi;
|
||||
|
||||
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;
|
||||
|
||||
server {{
|
||||
listen 127.0.0.1:{port};
|
||||
server_name localhost;
|
||||
root {dist};
|
||||
index index.html;
|
||||
include snippets/pyquest-locations.conf;
|
||||
}}
|
||||
}}
|
||||
"""
|
||||
|
||||
|
||||
def find_nginx(explicit: str | None) -> str:
|
||||
candidate = explicit or os.environ.get("PYQUEST_NGINX") or shutil.which("nginx")
|
||||
if not candidate or not Path(candidate).is_file():
|
||||
sys.exit(
|
||||
"nginx introuvable. Installe-le (sudo apt install nginx) ou récupère seulement le binaire sans droits root :\n"
|
||||
" mkdir -p /tmp/ngx && cd /tmp/ngx && apt-get download nginx && dpkg -x nginx_*.deb root\n"
|
||||
" PYQUEST_NGINX=/tmp/ngx/root/usr/sbin/nginx python3 scripts/local_stack.py"
|
||||
)
|
||||
return candidate
|
||||
|
||||
|
||||
def prepare(work: Path, port: int, api_port: int) -> Path:
|
||||
"""Écrit la configuration nginx et copie les parties communes sous leur nom d'installation."""
|
||||
dist = ROOT / "dist"
|
||||
if not (dist / "index.html").is_file():
|
||||
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.
|
||||
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")
|
||||
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")
|
||||
return config
|
||||
|
||||
|
||||
def django_env(work: Path) -> dict[str, str]:
|
||||
return {**os.environ, "DJANGO_SETTINGS_MODULE": "pyquest_api.settings.dev", "PYQUEST_DB_PATH": str(work / "db.sqlite3")}
|
||||
|
||||
|
||||
def python_for_backend() -> str:
|
||||
venv = ROOT / ".venv/bin/python"
|
||||
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())"
|
||||
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")
|
||||
|
||||
|
||||
def main() -> None:
|
||||
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
||||
parser.add_argument("--port", type=int, default=8080, help="port de nginx (défaut 8080)")
|
||||
parser.add_argument("--api-port", type=int, default=8001, help="port de Django (défaut 8001, celui attendu par nginx)")
|
||||
parser.add_argument("--workdir", type=Path, default=ROOT / ".local/stack", help="dossier de travail (config, journaux, base)")
|
||||
parser.add_argument("--nginx", help="chemin du binaire nginx (sinon variable PYQUEST_NGINX, sinon le PATH)")
|
||||
args = parser.parse_args()
|
||||
|
||||
nginx = find_nginx(args.nginx)
|
||||
work = args.workdir.resolve()
|
||||
config = prepare(work, args.port, args.api_port)
|
||||
env = django_env(work)
|
||||
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):
|
||||
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)
|
||||
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))
|
||||
|
||||
check = subprocess.run([nginx, "-t", "-p", str(work), "-c", str(config)], capture_output=True, text=True)
|
||||
if check.returncode != 0:
|
||||
sys.exit("Configuration nginx invalide :\n" + check.stderr)
|
||||
|
||||
django = subprocess.Popen(
|
||||
[python, "manage.py", "runserver", str(args.api_port), "--noreload"],
|
||||
cwd=ROOT / "backend",
|
||||
env=env,
|
||||
stdout=subprocess.DEVNULL,
|
||||
stderr=subprocess.DEVNULL,
|
||||
)
|
||||
server: subprocess.Popen[bytes] | None = None
|
||||
|
||||
def stop(_signal: int, _frame: FrameType | None) -> None:
|
||||
if server:
|
||||
server.terminate()
|
||||
|
||||
signal.signal(signal.SIGTERM, stop)
|
||||
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"Journaux : {work}/logs/ — Ctrl+C pour arrêter.")
|
||||
server = subprocess.Popen([nginx, "-p", str(work), "-c", str(config)])
|
||||
server.wait()
|
||||
finally:
|
||||
django.terminate()
|
||||
django.wait(timeout=10)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,136 @@
|
||||
// Pile complète avec un vrai nginx (mêmes blocs que la production, nginx/pyquest-locations.conf.example) devant dist/
|
||||
// et Django : isolation, éditeur protégé par connexion, synchronisation. Prérequis : make build ; un binaire nginx
|
||||
// (PATH ou PYQUEST_NGINX) ; make install (Django).
|
||||
import { spawn, spawnSync } from 'node:child_process';
|
||||
import { existsSync, mkdtempSync, rmSync } from 'node:fs';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { join } from 'node:path';
|
||||
import { after, before, test } from 'node:test';
|
||||
import assert from 'node:assert';
|
||||
import { chromium } from 'playwright-core';
|
||||
|
||||
const root = new URL('../../', import.meta.url).pathname;
|
||||
const executablePath = process.env.CHROMIUM ?? '/usr/bin/chromium';
|
||||
const venvPython = `${root}.venv/bin/python`;
|
||||
const nginx = process.env.PYQUEST_NGINX || spawnSync('which', ['nginx'], { encoding: 'utf8' }).stdout.trim();
|
||||
const [port, apiPort] = [8191, 8192];
|
||||
const base = `http://127.0.0.1:${port}/`;
|
||||
const PASSWORD = 'un-mot-de-passe-solide-42';
|
||||
const skip = !existsSync(`${root}dist/index.html`)
|
||||
? 'dist/ absent (make build)'
|
||||
: !nginx || !existsSync(nginx)
|
||||
? 'nginx absent (PATH ou PYQUEST_NGINX)'
|
||||
: !existsSync(executablePath)
|
||||
? `navigateur absent (${executablePath})`
|
||||
: !existsSync(venvPython)
|
||||
? 'make install requis (Django)'
|
||||
: false;
|
||||
|
||||
let stack;
|
||||
let browser;
|
||||
let work;
|
||||
|
||||
before(async () => {
|
||||
if (skip) return;
|
||||
work = mkdtempSync(join(tmpdir(), 'pyquest-stack-'));
|
||||
stack = spawn('python3', [`${root}scripts/local_stack.py`, '--port', String(port), '--api-port', String(apiPort), '--workdir', work, '--nginx', nginx], { stdio: 'ignore' });
|
||||
// Attend que nginx réponde et que la base existe.
|
||||
for (let attempt = 0; attempt < 60; attempt++) {
|
||||
const ready = await fetch(base).then((response) => response.ok, () => false);
|
||||
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}')`], {
|
||||
cwd: `${root}backend`,
|
||||
env: { ...process.env, DJANGO_SETTINGS_MODULE: 'pyquest_api.settings.dev', PYQUEST_DB_PATH: join(work, 'db.sqlite3') },
|
||||
});
|
||||
assert.equal(created.status, 0, String(created.stderr));
|
||||
browser = await chromium.launch({ executablePath, args: ['--no-sandbox'] });
|
||||
});
|
||||
|
||||
after(async () => {
|
||||
await browser?.close();
|
||||
stack?.kill('SIGTERM');
|
||||
await new Promise((resolve) => setTimeout(resolve, 500));
|
||||
if (work) rmSync(work, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
test('nginx : en-têtes d\'isolation, types MIME et fichiers publics', { skip, timeout: 60000 }, async () => {
|
||||
const check = async (path, expected) => {
|
||||
const response = await fetch(`${base}${path}`);
|
||||
assert.equal(response.status, 200, path);
|
||||
for (const [name, value] of Object.entries(expected)) {
|
||||
assert.ok((response.headers.get(name) ?? '').includes(value), `${path} : ${name} attendu « ${value} », reçu « ${response.headers.get(name)} »`);
|
||||
}
|
||||
return response;
|
||||
};
|
||||
const isolation = { 'cross-origin-opener-policy': 'same-origin', 'cross-origin-embedder-policy': 'require-corp', 'cross-origin-resource-policy': 'same-origin' };
|
||||
await check('', { ...isolation, 'content-type': 'text/html' });
|
||||
await check('css/base.css', { ...isolation, 'content-type': 'text/css' });
|
||||
await check('js/main.js', { ...isolation, 'content-type': 'text/javascript' });
|
||||
await check('vendor/pyodide/pyodide.asm.wasm', { ...isolation, 'content-type': 'application/wasm', 'cache-control': 'immutable' });
|
||||
await check('service-worker.js', { ...isolation, 'cache-control': 'no-cache' });
|
||||
await check('manifest.webmanifest', { 'content-type': 'manifest+json' });
|
||||
await check('levels/manifest.json', { ...isolation });
|
||||
const compressed = await fetch(`${base}js/main.js`, { headers: { 'Accept-Encoding': 'gzip' } });
|
||||
assert.equal(compressed.headers.get('content-encoding'), 'gzip');
|
||||
});
|
||||
|
||||
test('nginx : l\'éditeur exige une connexion, puis fonctionne isolé ; déconnexion', { skip, timeout: 120000 }, async () => {
|
||||
// Sans session : tout fichier de l'éditeur redirige vers la connexion (aucun contenu servi).
|
||||
for (const path of ['author.html', 'js/author/main.js', 'css/author.css', 'js/i18n/author.fr.json']) {
|
||||
const response = await fetch(`${base}${path}`, { redirect: 'manual' });
|
||||
assert.equal(response.status, 302, path);
|
||||
assert.match(response.headers.get('location'), /\/api\/auth\/login\/\?next=\//, path);
|
||||
}
|
||||
// Le contrôle interne n'est pas joignable de l'extérieur.
|
||||
assert.equal((await fetch(`${base}api/auth/check/`)).status, 404);
|
||||
|
||||
const context = await browser.newContext({ locale: 'fr-FR' });
|
||||
const page = await context.newPage();
|
||||
const errors = [];
|
||||
page.on('pageerror', (error) => errors.push(error.message));
|
||||
|
||||
await page.goto(`${base}author.html`);
|
||||
assert.match(page.url(), /\/api\/auth\/login\/\?next=\/author\.html$/);
|
||||
|
||||
// Un compte qui n'est pas auteur est refusé ; l'auteur arrive sur l'éditeur.
|
||||
await page.getByLabel('Identifiant').fill('lea');
|
||||
await page.getByLabel('Mot de passe').fill(PASSWORD);
|
||||
await page.getByRole('button', { name: 'Se connecter' }).click();
|
||||
await page.getByRole('alert').filter({ hasText: 'incorrect' }).waitFor();
|
||||
await page.getByLabel('Identifiant').fill('ada');
|
||||
await page.getByLabel('Mot de passe').fill(PASSWORD);
|
||||
await page.getByRole('button', { name: 'Se connecter' }).click();
|
||||
await page.waitForURL(`${base}author.html`);
|
||||
await page.locator('h1').first().waitFor();
|
||||
assert.equal(await page.evaluate(() => crossOriginIsolated), true, 'l\'éditeur est isolé (Pyodide)');
|
||||
|
||||
// L'éditeur charge ses modules protégés avec la session (aucune erreur de chargement).
|
||||
await page.waitForTimeout(1000);
|
||||
assert.deepEqual(errors, []);
|
||||
assert.equal((await context.request.get(`${base}js/author/main.js`)).status(), 200);
|
||||
|
||||
// Déconnexion : l'accès est de nouveau refusé.
|
||||
await page.goto(`${base}api/auth/login/`);
|
||||
await page.getByRole('button', { name: 'Se déconnecter' }).click();
|
||||
await page.getByRole('button', { name: 'Se connecter' }).waitFor();
|
||||
const after = await context.request.get(`${base}author.html`, { maxRedirects: 0 });
|
||||
assert.equal(after.status(), 302);
|
||||
});
|
||||
|
||||
test('nginx : l\'application apprenant est isolée, exécute Python et synchronise par le proxy', { skip, timeout: 120000 }, async () => {
|
||||
const page = await (await browser.newContext({ locale: 'fr-FR' })).newPage();
|
||||
const errors = [];
|
||||
page.on('pageerror', (error) => errors.push(error.message));
|
||||
await page.goto(base);
|
||||
await page.waitForSelector('.explain', { timeout: 60000 });
|
||||
assert.equal(await page.evaluate(() => crossOriginIsolated), true);
|
||||
|
||||
// Synchronisation via /api/ (même origine, Host et limitation de débit corrects).
|
||||
await page.locator('#settings-toggle').click();
|
||||
const group = page.locator('.settings .sync-group');
|
||||
await group.getByRole('button', { name: 'Activer la synchronisation' }).click();
|
||||
await group.getByText(/Dernière synchronisation/).waitFor({ timeout: 15000 });
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
Reference in New Issue
Block a user