# SPDX-License-Identifier: AGPL-3.0-or-later """Abnahme, Sicherheit: Prüfungen über alle Routen statt einzelner Seiten (CI). - Jede ändernde Anfrage (POST) hat die CSRF-Prüfung; Ausnahmen sind benannt. - Jede Seite unter /admin, /forms und /account verlangt eine Anmeldung; /admin zusätzlich Administratorrechte. - Sicherheits-Header auf allen Arten von Antworten. - Keine Weiterleitung nach außen, Cookies mit HttpOnly und SameSite. - Teilnehmer-Seite unter 100 KB ohne Bilder und ohne externe Ressourcen. """ from __future__ import annotations import re from typing import Any import pytest pytest.importorskip("fastapi") from fastapi.routing import APIRoute from helpers import PASSWORD, login, new_client, token_for from test_forms import creator, participant, simple_form from test_mail import admin pytestmark = pytest.mark.db # POST ohne CSRF-Prüfung, jeweils mit Grund CSRF_EXEMPT = { # Abmelden per Klick im Mailprogramm (RFC 8058): kommt ohne Cookies; der # signierte Schlüssel im Link ist die Berechtigung "/mail/unsubscribe/{token}", } PROTECTED_PREFIXES = ("/admin", "/forms", "/account") DUMMY_ID = "00000000-0000-0000-0000-000000000000" def _routes(app: Any) -> list[APIRoute]: return [r for r in app.routes if isinstance(r, APIRoute)] def _fill(route: APIRoute) -> str: """Pfad mit Platzhalter-Werten passenden Typs (Zahl oder UUID-Text).""" kinds = {p.name: p.field_info.annotation for p in route.dependant.path_params} return re.sub(r"\{([^}:]+)[^}]*\}", lambda m: "1" if kinds.get(m.group(1)) is int else DUMMY_ID, route.path) def test_every_post_route_checks_csrf(app: Any) -> None: from surveybox.web.deps import verify_csrf missing = [] for route in _routes(app): if not route.methods & {"POST", "PUT", "PATCH", "DELETE"}: continue deps = {d.call for d in route.dependant.dependencies} if verify_csrf not in deps and route.path not in CSRF_EXEMPT: missing.append(route.path) assert missing == [], f"POST ohne CSRF-Prüfung: {missing}" # Und wirklich: angemeldet, aber ohne Token wird abgewiesen root = admin(app) for path in ("/admin/appearance", "/forms", "/logout"): assert root.post(path, data={"x": "1"}).status_code == 403, path def test_protected_pages_need_login_and_rights(app: Any) -> None: guest = new_client(app) paul = participant(app) checked = 0 for route in _routes(app): if "GET" not in route.methods or not route.path.startswith(PROTECTED_PREFIXES): continue path = _fill(route) resp = guest.get(path) assert resp.status_code in (303, 401, 403, 404), (path, resp.status_code) if resp.status_code == 303: assert resp.headers["location"].startswith("/login"), path if route.path.startswith("/admin"): denied = paul.get(path) assert denied.status_code in (303, 403, 404), path if denied.status_code == 303: assert not denied.headers["location"].startswith(path), path checked += 1 assert checked > 40 # die Prüfung erfasst die Routen wirklich def test_security_headers_on_all_kinds_of_responses(app: Any) -> None: client = new_client(app) for path in ("/login", "/static/css/app.css", "/gibt-es-nicht", "/favicon.ico", "/f/unbekannt"): resp = client.get(path) headers = resp.headers assert headers["X-Content-Type-Options"] == "nosniff", path assert "default-src 'self'" in headers["Content-Security-Policy"], path assert "script-src 'self'" in headers["Content-Security-Policy"], path assert headers["Referrer-Policy"] == "same-origin", path assert "server" not in headers, path if not path.startswith("/static/"): assert headers["Cache-Control"] == "no-store", path html = client.get("/login").text assert "