234 lines
9.7 KiB
Python
234 lines
9.7 KiB
Python
# 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 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}",
|
|
"/mail/invitation/{token}",
|
|
}
|
|
PROTECTED_PREFIXES = ("/admin", "/forms", "/account")
|
|
DUMMY_ID = "00000000-0000-0000-0000-000000000000"
|
|
|
|
|
|
def _get(obj: Any, name: str) -> Any:
|
|
"""Attribut oder Schlüssel (Einbindungs-Kontext kann beides sein)."""
|
|
if isinstance(obj, dict):
|
|
return obj.get(name)
|
|
return getattr(obj, name, None)
|
|
|
|
|
|
def _dep_calls(obj: Any) -> set[Any]:
|
|
"""Abhängigkeiten eines Endpunkts oder Routers (Depends(...) und aufgelöster Baum),
|
|
auch aus dem Einbindungs-Kontext (FastAPI ab 0.16x: include_router(dependencies=...))."""
|
|
calls: set[Any] = set()
|
|
for holder in (obj, _get(obj, "include_context")):
|
|
for dep in _get(holder, "dependencies") or () if holder is not None else ():
|
|
for name in ("dependency", "call"):
|
|
if getattr(dep, name, None) is not None:
|
|
calls.add(getattr(dep, name))
|
|
todo = [getattr(obj, "dependant", None)]
|
|
while todo:
|
|
node = todo.pop()
|
|
if node is None:
|
|
continue
|
|
for sub in getattr(node, "dependencies", None) or ():
|
|
if getattr(sub, "call", None) is not None:
|
|
calls.add(sub.call)
|
|
todo.append(sub)
|
|
return calls
|
|
|
|
|
|
def _is_endpoint(obj: Any) -> bool:
|
|
return bool(getattr(obj, "methods", None)) and isinstance(getattr(obj, "path", None), str)
|
|
|
|
|
|
def _is_routing(obj: Any) -> bool:
|
|
return any(hasattr(obj, name) for name in ("path", "routes", "original_router"))
|
|
|
|
|
|
def _children(obj: Any) -> list[Any]:
|
|
"""Untergeordnete Routen/Router, ohne sich auf eine bestimmte FastAPI-Version zu verlassen."""
|
|
found: list[Any] = []
|
|
try:
|
|
values = list(vars(obj).values())
|
|
except TypeError:
|
|
values = []
|
|
values.extend(getattr(obj, name, None) for name in ("routes", "router", "app",
|
|
"original_router"))
|
|
for value in values:
|
|
if isinstance(value, (list, tuple)):
|
|
found.extend(v for v in value if _is_routing(v))
|
|
elif value is not None and (_is_routing(value) and not isinstance(value, str)):
|
|
found.append(value)
|
|
return found
|
|
|
|
|
|
def _routes(app: Any) -> list[tuple[str, Any, set[Any]]]:
|
|
"""(voller Pfad, Endpunkt, Abhängigkeiten) für alle Endpunkte, auch in
|
|
eingebundenen Routern; Abhängigkeiten der Router werden mitgezählt."""
|
|
found: dict[tuple[str, str], tuple[str, Any, set[Any]]] = {}
|
|
seen: set[int] = set()
|
|
|
|
def walk(obj: Any, prefix: str, inherited: set[Any], depth: int) -> None:
|
|
if depth > 8 or id(obj) in seen:
|
|
return
|
|
seen.add(id(obj))
|
|
own = getattr(obj, "prefix", None) or _get(_get(obj, "include_context"), "prefix") or ""
|
|
own = own if isinstance(own, str) else ""
|
|
if not _is_endpoint(obj) and not own and hasattr(obj, "routes"):
|
|
own = getattr(obj, "path", "") or "" # Mount
|
|
if own and not own.startswith(prefix or "\0"):
|
|
prefix = prefix + own
|
|
elif own:
|
|
prefix = own
|
|
deps = inherited | _dep_calls(obj)
|
|
if _is_endpoint(obj):
|
|
path = obj.path if prefix and obj.path.startswith(prefix) else prefix + obj.path
|
|
key = (path, ",".join(sorted(obj.methods)))
|
|
if key in found:
|
|
deps |= found[key][2]
|
|
found[key] = (path, obj, deps)
|
|
return
|
|
for child in _children(obj):
|
|
walk(child, prefix, deps, depth + 1)
|
|
|
|
walk(app.router, "", set(), 0)
|
|
return list(found.values())
|
|
|
|
|
|
def _describe(app: Any) -> str:
|
|
"""Kurzbeschreibung der Routenstruktur für Fehlermeldungen (andere FastAPI-Version)."""
|
|
out = []
|
|
for route in list(app.routes)[:6]:
|
|
attrs = sorted(k for k in vars(route) if not k.startswith("__"))[:25]
|
|
out.append(f"{type(route).__module__}.{type(route).__name__} "
|
|
f"path={getattr(route, 'path', None)!r} attrs={attrs}")
|
|
return f"{len(list(app.routes))} Einträge: " + " | ".join(out)
|
|
|
|
|
|
def _fill(path: str, route: Any) -> str:
|
|
"""Pfad mit Platzhalter-Werten passenden Typs (Zahl oder UUID-Text)."""
|
|
kinds: dict[str, Any] = {}
|
|
dependant = getattr(route, "dependant", None)
|
|
for param in getattr(dependant, "path_params", None) or ():
|
|
kinds[param.name] = getattr(param.field_info, "annotation", None)
|
|
return re.sub(r"\{([^}:]+)(:int)?[^}]*\}",
|
|
lambda m: "1" if kinds.get(m.group(1)) is int or m.group(2) else DUMMY_ID,
|
|
path)
|
|
|
|
|
|
def test_every_post_route_checks_csrf(app: Any) -> None:
|
|
from surveybox.web.deps import verify_csrf
|
|
|
|
routes = _routes(app)
|
|
posts = [(full, deps) for full, route, deps in routes
|
|
if set(route.methods) & {"POST", "PUT", "PATCH", "DELETE"}]
|
|
assert len(posts) > 40, _describe(app) # die Prüfung erfasst die Routen wirklich
|
|
missing = [full for full, deps in posts if verify_csrf not in deps and full not in CSRF_EXEMPT]
|
|
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 full, route, _deps in _routes(app):
|
|
if "GET" not in route.methods or not full.startswith(PROTECTED_PREFIXES):
|
|
continue
|
|
path = _fill(full, 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 full.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
|
|
# Stand mit Verlauf: 40 geschützte Seiten; die Untergrenze fängt eine leere Erfassung ab
|
|
assert checked > 30, _describe(app)
|
|
|
|
|
|
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 path.startswith("/static/"):
|
|
assert headers["Cache-Control"] == "public, no-cache", path
|
|
else:
|
|
assert headers["Cache-Control"] == "no-store", path
|
|
html = client.get("/login").text
|
|
assert "<script>" not in html and " style=" not in html and "onclick" not in html
|
|
|
|
|
|
def test_no_open_redirects_and_cookie_flags(app: Any) -> None:
|
|
root = admin(app) # legt den Admin an und meldet ihn an
|
|
paul = participant(app)
|
|
client = new_client(app)
|
|
token = token_for(client, "/login")
|
|
resp = client.post("/login", data={"email": "paul@example.de", "password": PASSWORD,
|
|
"csrf_token": token, "next": "//evil.example/"})
|
|
assert resp.status_code == 303
|
|
assert resp.headers["location"].startswith("/") and "evil" not in resp.headers["location"]
|
|
for target in ("//evil.example/", "https://evil.example/", "/\\evil.example"):
|
|
location = root.get(f"/language/de?next={target}").headers.get("location", "/")
|
|
assert location.startswith("/") and not location.startswith(("//", "/\\")), target
|
|
assert paul.get("/").status_code == 200
|
|
resp = login(new_client(app), "paul@example.de")
|
|
cookies = [v for k, v in resp.headers.multi_items() if k.lower() == "set-cookie"]
|
|
session = next(c for c in cookies if "surveybox_session" in c)
|
|
assert "HttpOnly" in session and "SameSite=lax" in session.replace("Lax", "lax")
|
|
|
|
|
|
def test_participant_page_is_small_and_self_contained(app: Any) -> None:
|
|
owner = creator(app)
|
|
_, token, _ = simple_form(owner, access="link")
|
|
guest = new_client(app)
|
|
page = guest.get(f"/f/{token}")
|
|
assert page.status_code == 200
|
|
html = page.text
|
|
assets = re.findall(r'<(?:script|link)[^>]+(?:src|href)="([^"]+)"', html)
|
|
assert all(a.startswith("/") and not a.startswith("//") for a in assets), assets
|
|
total = len(page.content)
|
|
for asset in assets:
|
|
if asset.endswith((".css", ".js")) or "theme.css" in asset:
|
|
total += len(guest.get(asset.split("?")[0]).content)
|
|
assert total < 100_000, total
|