diff --git a/.dockerignore b/.dockerignore index 71eb667..823f6c5 100644 --- a/.dockerignore +++ b/.dockerignore @@ -6,7 +6,9 @@ dist vendor site tests -docs +docs/design +docs/ci +docs/MAINTAINERS.md backend/db.sqlite3 backend/staticfiles **/__pycache__ diff --git a/CONTEXT.md b/CONTEXT.md index fe92c9a..88d442d 100644 --- a/CONTEXT.md +++ b/CONTEXT.md @@ -43,6 +43,13 @@ vrai navigateur (Chromium) avec 4 niveaux jouables. | 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` | +## Documentation en ligne (/docs/) + +mkdocs construit dans `dist/docs/` (`make build` dépend de `make docs` ; `server_update.sh` et l'image Docker aussi), +protégée par nginx `auth_request` → `/api/auth/check-docs/` : auteurs **et** comptes `is_staff`. Hors précache du service +worker (`is_author_tool`, `isAuthorTool`). Liens : bouton « Documentation » de l'éditeur (affiché si `/docs/` existe) et +gabarit `backend/authors/templates/admin/base_site.html` (`authors` est avant `admin` dans INSTALLED_APPS). + ## Déploiement sur le VPS — état et reprise (mis à jour 2026-10-17) **État : rien n'est déployé.** Tout est préparé et testé sans serveur. **Flux retenu par l'utilisateur : il est root sur le diff --git a/Makefile b/Makefile index 45f6a00..708f2b2 100644 --- a/Makefile +++ b/Makefile @@ -70,8 +70,8 @@ dev-author: $(VENV)/.installed ## Compte local direct : NAME=x, RESET=--reset (m validate-levels: $(VENV)/.installed ## Valide les niveaux (schéma, manifeste, traductions) $(VENV_PY) scripts/validate_levels.py -build: $(VENV)/.installed ## Construit dist/ pour la production - $(VENV_PY) scripts/build.py +build: $(VENV)/.installed docs ## Construit dist/ pour la production (avec la documentation, servie sous /docs/) + $(VENV_PY) scripts/build.py --docs site test: test-js test-python test-backend test-deploy validate-levels check-voice ## Lance tous les tests diff --git a/app/js/author/AuthorApp.js b/app/js/author/AuthorApp.js index ded6c05..47bd0fc 100644 --- a/app/js/author/AuthorApp.js +++ b/app/js/author/AuthorApp.js @@ -28,6 +28,7 @@ export class AuthorApp { #store; #catalogs; #root; + #hasDocs = false; // documentation en ligne publiée par le serveur (/docs/) #account = null; // { username, csrf } si l'éditeur est protégé par une connexion (backend Django), sinon null #knownIds = []; #model = emptyLevelModel(); @@ -66,6 +67,7 @@ export class AuthorApp { async run() { this.#account = await this.#loadAccount(); + await this.#detectDocs(); this.#knownIds = (await this.#lessons.listLevels()).map((level) => level.id); const draft = await this.#store.get(DRAFT_KEY).catch(() => undefined); if (draft) { @@ -97,6 +99,23 @@ export class AuthorApp { } } + /** + * Lien vers la documentation en ligne (/docs/), seulement si le serveur la publie : sinon (essai local sans + * documentation) pas de lien mort. La vérification est faite une fois, à l'ouverture. + */ + async #detectDocs() { + try { + const response = await fetch(new URL('docs/', document.baseURI), { method: 'HEAD', cache: 'no-store', credentials: 'same-origin', redirect: 'manual' }); + this.#hasDocs = response.ok; + } catch { + this.#hasDocs = false; + } + } + + #docsLink() { + return this.#hasDocs ? el('a', { class: 'btn', id: 'author-docs', href: 'docs/', target: '_blank', rel: 'noopener', text: this.#t('author.toolbar.docs') }) : null; + } + /** Formulaire de déconnexion (vrai POST protégé par CSRF : la page de connexion s'affiche ensuite). */ #accountControl() { if (!this.#account) { @@ -152,6 +171,7 @@ export class AuthorApp { fileInput, el('button', { type: 'button', class: 'btn btn-primary', id: 'author-download', text: t('author.toolbar.download'), onclick: () => this.#download() }), languages, + this.#docsLink(), el('a', { class: 'btn', href: './', text: t('author.toolbar.back') }), ), this.#accountControl(), diff --git a/app/js/i18n/author.en.json b/app/js/i18n/author.en.json index 1f8cca6..8d192f3 100644 --- a/app/js/i18n/author.en.json +++ b/app/js/i18n/author.en.json @@ -151,6 +151,7 @@ "author.kind.drawing_colors": "Drawing: colours used", "author.kind.drawing_colors.help": "Colours that must all appear, comma-separated: “red,blue”.", "lint.drawing_value_invalid": "Malformed drawing test value (see the test type help; colours: black, red, green, blue, orange, purple, gray).", + "author.toolbar.docs": "Documentation (new tab)", "author.account.label": "Account", "author.account.signed_in": "Signed in: {name}", "author.account.logout": "Sign out" diff --git a/app/js/i18n/author.fr.json b/app/js/i18n/author.fr.json index 41df112..11279a9 100644 --- a/app/js/i18n/author.fr.json +++ b/app/js/i18n/author.fr.json @@ -151,6 +151,7 @@ "author.kind.drawing_colors": "Dessin : couleurs utilisées", "author.kind.drawing_colors.help": "Couleurs qui doivent toutes apparaître, séparées par des virgules : « red,blue ».", "lint.drawing_value_invalid": "Valeur de test de dessin mal formée (voir l'aide du type de test ; couleurs : black, red, green, blue, orange, purple, gray).", + "author.toolbar.docs": "Documentation (nouvel onglet)", "author.account.label": "Compte", "author.account.signed_in": "Connecté : {name}", "author.account.logout": "Se déconnecter" diff --git a/app/service-worker.js b/app/service-worker.js index 6845df3..64ed1b4 100644 --- a/app/service-worker.js +++ b/app/service-worker.js @@ -55,7 +55,8 @@ function isNarration(pathname) { } function isAuthorTool(pathname) { - return pathname === '/author.html' || pathname === '/css/author.css' || pathname.startsWith('/js/author/') || /^\/js\/i18n\/author\.[a-z]+\.json$/.test(pathname); + // /docs/ : documentation en ligne, éventuellement protégée par connexion, hors application (jamais mise en cache). + return pathname.startsWith('/docs/') || pathname === '/docs' || pathname === '/author.html' || pathname === '/css/author.css' || pathname.startsWith('/js/author/') || /^\/js\/i18n\/author\.[a-z]+\.json$/.test(pathname); } async function fromCache(request, cacheName) { diff --git a/backend/authors/access.py b/backend/authors/access.py index 983f611..56f9bb6 100644 --- a/backend/authors/access.py +++ b/backend/authors/access.py @@ -13,6 +13,11 @@ def is_author(user: object) -> bool: return isinstance(user, User) and user.is_active and user.has_perm(EDITOR_PERMISSION) +def can_read_docs(user: object) -> bool: + """Documentation en ligne (/docs/) : auteurs et administrateurs (comptes `is_staff`) actifs.""" + return isinstance(user, User) and user.is_active and (user.is_staff or is_author(user)) + + 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) diff --git a/backend/authors/templates/admin/base_site.html b/backend/authors/templates/admin/base_site.html new file mode 100644 index 0000000..65f0fcc --- /dev/null +++ b/backend/authors/templates/admin/base_site.html @@ -0,0 +1,4 @@ +{% extends "admin/base_site.html" %} + +{# Documentation en ligne (réservée aux auteurs et administrateurs : /docs/). #} +{% block userlinks %}Documentation / {{ block.super }}{% endblock %} diff --git a/backend/authors/tests.py b/backend/authors/tests.py index 0b1096a..8372078 100644 --- a/backend/authors/tests.py +++ b/backend/authors/tests.py @@ -136,6 +136,36 @@ class CheckAndLogoutTest(TestCase): self.assertEqual(response.status_code, 204) self.assertIn("no-store", response.headers["Cache-Control"]) + def test_docs_check_admits_authors_and_administrators_only(self) -> None: + url = "/api/auth/check-docs/" + self.assertEqual(self.client.get(url).status_code, 401) + make_user("lea", staff=False) + self.client.login(username="lea", password=PASSWORD) + self.assertEqual(self.client.get(url).status_code, 401) + make_user("ada") + self.client.login(username="ada", password=PASSWORD) + response = self.client.get(url) + self.assertEqual(response.status_code, 204) + self.assertIn("no-store", response.headers["Cache-Control"]) + admin = make_user("root", staff=False) + admin.is_staff = True + admin.save() + self.client.login(username="root", password=PASSWORD) + self.assertEqual(self.client.get(url).status_code, 204) + # L'éditeur, lui, reste réservé à la permission d'auteur. + self.assertEqual(self.client.get(CHECK).status_code, 401) + admin.is_active = False + admin.save() + self.assertEqual(self.client.get(url).status_code, 401) + self.assertEqual(self.client.post(url).status_code, 405) + + def test_admin_pages_link_to_the_documentation(self) -> None: + admin = make_user("root", staff=False) + admin.is_staff = admin.is_superuser = True + admin.save() + self.client.login(username="root", password=PASSWORD) + self.assertContains(self.client.get("/api/admin/"), 'href="/docs/"') + def test_check_refuses_other_methods(self) -> None: self.assertEqual(self.client.post(CHECK).status_code, 405) diff --git a/backend/authors/urls.py b/backend/authors/urls.py index 4fd8d07..9f5547b 100644 --- a/backend/authors/urls.py +++ b/backend/authors/urls.py @@ -6,5 +6,6 @@ urlpatterns = [ path("login/", views.login_view, name="login"), path("logout/", views.logout_view, name="logout"), path("check/", views.check_view, name="check"), + path("check-docs/", views.check_docs_view, name="check_docs"), path("me/", views.me_view, name="me"), ] diff --git a/backend/authors/views.py b/backend/authors/views.py index d977d00..fb8e8d4 100644 --- a/backend/authors/views.py +++ b/backend/authors/views.py @@ -17,7 +17,7 @@ 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 .access import is_author +from .access import can_read_docs, is_author from .throttle import client_ip, is_locked, record_failure, record_success DEFAULT_NEXT = "/author.html" @@ -113,6 +113,13 @@ def check_view(request: HttpRequest) -> HttpResponse: return HttpResponse(status=204 if is_author(request.user) else 401) +@never_cache +@require_GET +def check_docs_view(request: HttpRequest) -> HttpResponse: + """Appelé par nginx (auth_request) pour /docs/ : 204 pour un auteur ou un administrateur, sinon 401.""" + return HttpResponse(status=204 if can_read_docs(request.user) else 401) + + @never_cache @require_GET def me_view(request: HttpRequest) -> HttpResponse: diff --git a/backend/pyquest_api/settings/base.py b/backend/pyquest_api/settings/base.py index 128b78e..a8a35cf 100644 --- a/backend/pyquest_api/settings/base.py +++ b/backend/pyquest_api/settings/base.py @@ -11,9 +11,9 @@ INSTALLED_APPS = [ "django.contrib.sessions", "django.contrib.messages", "django.contrib.staticfiles", + "authors.apps.AuthorsConfig", # avant l'administration : ses gabarits (lien vers la documentation) la surchargent "django.contrib.admin", "sync", - "authors.apps.AuthorsConfig", ] MIDDLEWARE = [ diff --git a/docker/Dockerfile b/docker/Dockerfile index 0efa8fc..a076e5d 100644 --- a/docker/Dockerfile +++ b/docker/Dockerfile @@ -2,6 +2,15 @@ # Contexte de construction : la racine du dépôt (voir docker/compose.*.yaml). # syntax=docker/dockerfile:1 +# ---- Documentation en ligne (mkdocs) : servie sous /docs/ pour les auteurs et les administrateurs ----------------------- +FROM python:3.12-slim-bookworm AS docs +WORKDIR /src +COPY requirements-docs.txt . +RUN pip install --no-cache-dir -r requirements-docs.txt +COPY mkdocs.yml . +COPY docs/site docs/site +RUN mkdocs build --quiet --site-dir /site + # ---- Site statique : moteur Python (Pyodide, version épinglée et vérifiée) puis construction de dist/ ------------------- FROM python:3.12-slim-bookworm AS site RUN apt-get update && apt-get install -y --no-install-recommends curl bzip2 ca-certificates \ @@ -12,7 +21,8 @@ RUN ./scripts/vendor_pyodide.sh COPY app app COPY levels levels COPY scripts/build.py scripts/ -RUN python scripts/build.py +COPY --from=docs /site site +RUN python scripts/build.py --docs site # ---- Serveur web : nginx (>= 1.25.1 pour http2 on) --------------------------------------------------------------------- FROM nginx:1.27-alpine AS web diff --git a/docs/site/en/host/deploy.md b/docs/site/en/host/deploy.md index 292bac1..d3319c6 100644 --- a/docs/site/en/host/deploy.md +++ b/docs/site/en/host/deploy.md @@ -52,6 +52,20 @@ cd /opt/PyQuest The whole procedure (MariaDB database, starting the service, first administrator, publishing, backups, rollback, troubleshooting) is in [Going live and operations](operations.md). +## Online documentation (`/docs/`) + +The site publishes its own documentation under `https://your-domain/docs/` (French and English). It is **restricted to +signed-in accounts**: **authors** (editor permission) and **administrators** (`is_staff` accounts). Without a session, +nginx redirects to the sign-in page, which then returns to the documentation. Links are in the level editor +(**Documentation** button) and in the Django administration (top right). + +- It is built with the site: `make build` (and `./scripts/server_update.sh`, or the Docker image) generate `dist/docs/`. + `./scripts/server_update.sh --no-docs` publishes without it. +- An administrator who is **not** an author signs in on `/api/admin/` first: the session is the same. +- The documentation holds no secret: to make it **public**, remove `auth_request` and `error_page` from the + `location ^~ /docs/` block in `nginx/pyquest-locations.conf.example`. +- Pages are never kept by the service worker (outside the application, always online). + ## Testing locally before deploying Three levels of testing, from the simplest to the most faithful to production: diff --git a/docs/site/fr/host/deploy.md b/docs/site/fr/host/deploy.md index f50c978..1de2c95 100644 --- a/docs/site/fr/host/deploy.md +++ b/docs/site/fr/host/deploy.md @@ -53,6 +53,20 @@ cd /opt/PyQuest Toute la marche à suivre (base MariaDB, démarrage du service, premier administrateur, publication, sauvegardes, retour arrière, dépannage) est dans [Mise en service et exploitation](operations.md). +## La documentation en ligne (`/docs/`) + +Le site publie sa propre documentation sous `https://ton-domaine/docs/` (français et anglais). Elle est **réservée aux +comptes connectés** : les **auteurs** (permission de l'éditeur) et les **administrateurs** (comptes `is_staff`). Sans +session, nginx renvoie vers la page de connexion, qui ramène ensuite sur la documentation. Les liens se trouvent dans +l'éditeur de niveaux (bouton **Documentation**) et dans l'administration Django (en haut à droite). + +- Elle est construite avec le site : `make build` (et `./scripts/server_update.sh`, ou l'image Docker) génèrent + `dist/docs/`. `./scripts/server_update.sh --no-docs` publie sans elle. +- Un administrateur qui n'est **pas** auteur s'identifie d'abord sur `/api/admin/` : la session est la même. +- La documentation n'a rien de secret : pour la **rendre publique**, supprimer `auth_request` et `error_page` du bloc + `location ^~ /docs/` dans `nginx/pyquest-locations.conf.example`. +- Les pages ne sont jamais conservées par le service worker (hors de l'application, toujours en ligne). + ## Tester en local avant de déployer Trois niveaux d'essai, du plus simple au plus fidèle à la production : diff --git a/nginx/pyquest-locations.conf.example b/nginx/pyquest-locations.conf.example index 9947727..01fbc97 100644 --- a/nginx/pyquest-locations.conf.example +++ b/nginx/pyquest-locations.conf.example @@ -76,6 +76,16 @@ proxy_set_header X-Forwarded-Proto $scheme; } + # Idem pour la documentation en ligne : auteurs ET administrateurs (comptes is_staff) y accèdent. + location = /_docs_check { + internal; + proxy_pass http://127.0.0.1:8001/api/auth/check-docs/; + 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; @@ -103,6 +113,14 @@ include snippets/pyquest-author-headers.conf; } + # Documentation en ligne (mkdocs, copiée dans dist/docs/ par make build) : réservée aux comptes connectés. + # Pour la rendre publique, supprimer les deux lignes auth_request et error_page de ce bloc. + location ^~ /docs/ { + auth_request /_docs_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). @@ -140,6 +158,9 @@ location = /api/auth/check/ { return 404; } + location = /api/auth/check-docs/ { + return 404; + } location /api/ { limit_req zone=pyquest_sync burst=20 nodelay; client_max_body_size 300k; diff --git a/scripts/build.py b/scripts/build.py index 3775228..7a78ca0 100644 --- a/scripts/build.py +++ b/scripts/build.py @@ -17,10 +17,11 @@ 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).""" + """Fichiers propres à l'éditeur de niveaux et documentation en ligne (/docs/) : 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" + relative.startswith("docs/") + or relative == "author.html" or relative == "css/author.css" or relative.startswith("js/author/") or (relative.startswith("js/i18n/author.") and relative.endswith(".json")) @@ -54,6 +55,14 @@ def content_hash(paths: list[str]) -> str: def main() -> int: + # --docs DOSSIER : documentation déjà générée (mkdocs build), copiée dans dist/docs/ (non pré-cachée). + docs: Path | None = None + if "--docs" in sys.argv: + index = sys.argv.index("--docs") + docs = Path(sys.argv[index + 1]) if index + 1 < len(sys.argv) else None + if docs is None or not (docs / "index.html").is_file(): + print("--docs : dossier de documentation générée introuvable (make docs).", file=sys.stderr) + return 1 pyodide = ROOT / "vendor" / "pyodide" if not pyodide.exists(): print("vendor/pyodide absent : lancez `make vendor-pyodide` d'abord.", file=sys.stderr) @@ -64,6 +73,8 @@ def main() -> int: copy_tree(ROOT / "app", DIST) copy_tree(ROOT / "levels", DIST / "levels") shutil.copytree(pyodide, DIST / "vendor" / "pyodide") + if docs is not None: + shutil.copytree(docs, DIST / "docs") precache = shell_files() worker = DIST / "service-worker.js" diff --git a/scripts/check_deploy.sh b/scripts/check_deploy.sh index 20e1d2f..fb4c4c4 100755 --- a/scripts/check_deploy.sh +++ b/scripts/check_deploy.sh @@ -62,6 +62,16 @@ else ko "author.html : 200 (public) ou 302 vers la connexion attendus, reçu ${author_code}" fi +# Documentation en ligne : réservée aux comptes connectés derrière le backend (302 vers la connexion) ; sinon publique. +docs_code="$(status "${BASE}/docs/")" +if [[ "${author_code}" == 302 ]]; then + docs_location="$(header "${BASE}/docs/" Location)" + if [[ "${docs_code}" == 302 && "${docs_location}" == *"/api/auth/login/?next=/docs/"* ]]; then ok "documentation protégée par connexion (/docs/)"; else ko "/docs/ : 302 vers la connexion attendu, reçu ${docs_code}"; fi + expect_status "${BASE}/api/auth/check-docs/" 404 +else + echo " info /docs/ répond ${docs_code} (200 = documentation publiée, 404 = absente)" +fi + if [[ "${BASE}" == https://* ]]; then redirect="$(curl -s -o /dev/null -w '%{http_code}' --max-time 20 "http://${BASE#https://}/")" if [[ "${redirect}" == 301 || "${redirect}" == 308 ]]; then ok "HTTP redirige vers HTTPS (${redirect})"; else ko "HTTP devrait rediriger vers HTTPS, code ${redirect}"; fi diff --git a/scripts/server_update.sh b/scripts/server_update.sh index b07be02..abfc98a 100755 --- a/scripts/server_update.sh +++ b/scripts/server_update.sh @@ -5,7 +5,7 @@ # # ./scripts/server_update.sh # tout # ./scripts/server_update.sh --rollback # revient à la version précédente du site -# Options : --no-pull --no-build --no-restart --no-check --dry-run +# Options : --no-pull --no-build --no-docs --no-restart --no-check --dry-run # # Variables : PYQUEST_WEB_ROOT (défaut /var/www/pyquest), PYQUEST_KEEP (versions conservées, défaut 3), # PYQUEST_ENV_FILE (défaut /etc/pyquest/env), PYQUEST_SERVICE (défaut pyquest). @@ -17,12 +17,13 @@ KEEP="${PYQUEST_KEEP:-3}" ENV_FILE="${PYQUEST_ENV_FILE:-/etc/pyquest/env}" SERVICE="${PYQUEST_SERVICE:-pyquest}" VENV="${REPO}/.venv-prod" -PULL=1; BUILD=1; RESTART=1; CHECK=1; DRY_RUN=0; ROLLBACK=0 +PULL=1; BUILD=1; DOCS=1; RESTART=1; CHECK=1; DRY_RUN=0; ROLLBACK=0 for arg in "$@"; do case "${arg}" in --no-pull) PULL=0 ;; --no-build) BUILD=0 ;; + --no-docs) DOCS=0 ;; --no-restart) RESTART=0 ;; --no-check) CHECK=0 ;; --dry-run) DRY_RUN=1 ;; @@ -69,7 +70,21 @@ COMMIT="$(git -C "${REPO}" rev-parse --short HEAD 2>/dev/null || echo nogit)" if [[ "${BUILD}" == 1 ]]; then step "Moteur Python (Pyodide) et construction du site" run "${REPO}/scripts/vendor_pyodide.sh" - run python3 "${REPO}/scripts/build.py" + BUILD_ARGS=() + if [[ "${DOCS}" == 1 ]]; then + # Documentation en ligne (/docs/, réservée aux comptes connectés) : un échec ne bloque pas la mise à jour du site. + DOCS_VENV="${REPO}/.venv-docs" + if [[ "${DRY_RUN}" == 1 ]]; then + echo "[dry-run] mkdocs build (documentation, ${DOCS_VENV})" + BUILD_ARGS=(--docs "${REPO}/site") + elif { [[ -x "${DOCS_VENV}/bin/mkdocs" ]] || { python3 -m venv "${DOCS_VENV}" && "${DOCS_VENV}/bin/pip" install --quiet -r "${REPO}/requirements-docs.txt"; }; } \ + && (cd "${REPO}" && "${DOCS_VENV}/bin/mkdocs" build --quiet 2>/dev/null); then + BUILD_ARGS=(--docs "${REPO}/site") + else + echo "ATTENTION : la documentation n'a pas pu être construite (paquet python3-venv, accès à PyPI ?) : le site est publié sans elle." >&2 + fi + fi + run python3 "${REPO}/scripts/build.py" "${BUILD_ARGS[@]}" fi [[ "${DRY_RUN}" == 1 || -f "${REPO}/dist/index.html" ]] || { echo "dist/ est absent : relancer sans --no-build." >&2; exit 1; } [[ "${DRY_RUN}" == 1 || -f "${REPO}/dist/vendor/pyodide/pyodide.asm.wasm" ]] || { echo "Pyodide manque dans dist/." >&2; exit 1; } diff --git a/tests/deploy/test_docker.sh b/tests/deploy/test_docker.sh index 521607f..2a503b0 100755 --- a/tests/deploy/test_docker.sh +++ b/tests/deploy/test_docker.sh @@ -44,6 +44,9 @@ check_stack() { # nom curl-args... : vérifications communes une fois la pile d [[ "$(c -I "${base}/vendor/pyodide/pyodide.asm.wasm" | tr -d '\r' | grep -ci 'content-type: application/wasm')" == 1 ]] || fail "${name} : type MIME wasm" code_loc="$(c -o /dev/null -w '%{http_code} %{redirect_url}' "${base}/author.html")" [[ "${code_loc}" == "302 "*"/api/auth/login/?next=/author.html" ]] || fail "${name} : author.html doit renvoyer vers la connexion (reçu : ${code_loc})" + docs_loc="$(c -o /dev/null -w '%{http_code} %{redirect_url}' "${base}/docs/")" + [[ "${docs_loc}" == "302 "*"/api/auth/login/?next=/docs/" ]] || fail "${name} : /docs/ doit exiger une connexion (reçu : ${docs_loc})" + [[ "$(c -o /dev/null -w '%{http_code}' "${base}/api/auth/check-docs/")" == 404 ]] || fail "${name} : /api/auth/check-docs/ doit rester interne" [[ "$(c -o /dev/null -w '%{http_code}' "${base}/api/auth/login/")" == 200 ]] || fail "${name} : page de connexion" [[ "$(c -o /dev/null -w '%{http_code}' "${base}/api/auth/check/")" == 404 ]] || fail "${name} : /api/auth/check/ doit rester interne" [[ "$(c -o /dev/null -w '%{http_code}' "${base}/api/static/admin/css/base.css")" == 200 ]] || fail "${name} : fichiers statiques de l'administration (volume partagé)" diff --git a/tests/e2e/nginx.test.mjs b/tests/e2e/nginx.test.mjs index e8bd831..0045bae 100644 --- a/tests/e2e/nginx.test.mjs +++ b/tests/e2e/nginx.test.mjs @@ -83,8 +83,15 @@ test('nginx : l\'éditeur exige une connexion, puis fonctionne isolé ; déconne assert.equal(response.status, 302, path); assert.match(response.headers.get('location'), /\/api\/auth\/login\/\?next=\//, path); } + // La documentation en ligne exige elle aussi une connexion (aucune page servie). + for (const path of ['docs/', 'docs/fr/', 'docs/assets/stylesheets/main.css']) { + const response = await fetch(`${base}${path}`, { redirect: 'manual' }); + assert.equal(response.status, 302, path); + assert.match(response.headers.get('location'), /\/api\/auth\/login\/\?next=\/docs\//, path); + } // Le contrôle interne n'est pas joignable de l'extérieur. assert.equal((await fetch(`${base}api/auth/check/`)).status, 404); + assert.equal((await fetch(`${base}api/auth/check-docs/`)).status, 404); const context = await browser.newContext({ locale: 'fr-FR' }); const page = await context.newPage(); @@ -111,6 +118,13 @@ test('nginx : l\'éditeur exige une connexion, puis fonctionne isolé ; déconne assert.deepEqual(errors, []); assert.equal((await context.request.get(`${base}js/author/main.js`)).status(), 200); + // La documentation est lisible avec la session, isolée comme le reste, et l'éditeur y renvoie par un lien. + await page.locator('#author-docs').waitFor(); + const docs = await context.request.get(`${base}docs/`); + assert.equal(docs.status(), 200); + assert.match(await docs.text(), /PyQuest/); + assert.equal(docs.headers()['cross-origin-opener-policy'], 'same-origin'); + // Déconnexion depuis l'éditeur lui-même : nom affiché, bouton, retour à la page de connexion. await page.getByText('Connecté : ada').waitFor(); await page.getByRole('button', { name: 'Se déconnecter' }).click(); @@ -118,6 +132,7 @@ test('nginx : l\'éditeur exige une connexion, puis fonctionne isolé ; déconne await page.getByRole('button', { name: 'Se connecter' }).waitFor(); const after = await context.request.get(`${base}author.html`, { maxRedirects: 0 }); assert.equal(after.status(), 302); + assert.equal((await context.request.get(`${base}docs/`, { maxRedirects: 0 })).status(), 302, 'la documentation se referme avec la session'); }); test('nginx : l\'application apprenant est isolée, exécute Python et synchronise par le proxy', { skip, timeout: 120000 }, async () => { @@ -156,6 +171,9 @@ test('nginx : l\'administrateur autorise un compte à utiliser l\'éditeur depui await admin.getByLabel('Mot de passe :').fill(PASSWORD); await admin.getByRole('button', { name: 'Connexion' }).click(); await admin.getByText('PyQuest — administration').first().waitFor(); + // Le lien « Documentation » de l'administration mène à la documentation, ouverte à l'administrateur. + await admin.getByRole('link', { name: 'Documentation' }).waitFor(); + assert.equal((await admin.context().request.get(`${base}docs/`)).status(), 200); 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');