fix:routen
This commit is contained in:
1 parent
8b6f74f364
commit
90fbbffc20
1 file changed
+90
-26
@@ -34,43 +34,107 @@ PROTECTED_PREFIXES = ("/admin", "/forms", "/account")
|
|||||||
DUMMY_ID = "00000000-0000-0000-0000-000000000000"
|
DUMMY_ID = "00000000-0000-0000-0000-000000000000"
|
||||||
|
|
||||||
|
|
||||||
def _routes(app: Any) -> list[tuple[str, Any]]:
|
def _dep_calls(obj: Any) -> set[Any]:
|
||||||
"""(voller Pfad, Endpunkt) für alle Endpunkte, auch in eingebundenen Routern."""
|
"""Abhängigkeiten eines Endpunkts oder Routers (Depends(...) und aufgelöster Baum)."""
|
||||||
found: list[tuple[str, Any]] = []
|
calls: set[Any] = set()
|
||||||
|
for dep in getattr(obj, "dependencies", None) or ():
|
||||||
|
if getattr(dep, "dependency", None) is not None:
|
||||||
|
calls.add(dep.dependency)
|
||||||
|
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 walk(routes: Any, prefix: str) -> None:
|
|
||||||
for route in routes:
|
|
||||||
path = getattr(route, "path", "") or ""
|
|
||||||
full = path if path.startswith(prefix) else prefix + path
|
|
||||||
sub = getattr(route, "routes", None)
|
|
||||||
if sub and not getattr(route, "methods", None):
|
|
||||||
walk(sub, full)
|
|
||||||
elif getattr(route, "methods", None) and getattr(route, "dependant", None):
|
|
||||||
found.append((full, route))
|
|
||||||
|
|
||||||
walk(app.routes, "")
|
def _is_endpoint(obj: Any) -> bool:
|
||||||
|
return bool(getattr(obj, "methods", None)) and isinstance(getattr(obj, "path", None), str)
|
||||||
|
|
||||||
|
|
||||||
|
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 hasattr(v, "path") or hasattr(v, "routes"))
|
||||||
|
elif value is not None and (hasattr(value, "routes") or _is_endpoint(value)):
|
||||||
|
found.append(value)
|
||||||
return found
|
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 ""
|
||||||
|
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:
|
def _fill(path: str, route: Any) -> str:
|
||||||
"""Pfad mit Platzhalter-Werten passenden Typs (Zahl oder UUID-Text)."""
|
"""Pfad mit Platzhalter-Werten passenden Typs (Zahl oder UUID-Text)."""
|
||||||
kinds = {p.name: p.field_info.annotation for p in route.dependant.path_params}
|
kinds: dict[str, Any] = {}
|
||||||
return re.sub(r"\{([^}:]+)[^}]*\}",
|
dependant = getattr(route, "dependant", None)
|
||||||
lambda m: "1" if kinds.get(m.group(1)) is int else DUMMY_ID, path)
|
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:
|
def test_every_post_route_checks_csrf(app: Any) -> None:
|
||||||
from surveybox.web.deps import verify_csrf
|
from surveybox.web.deps import verify_csrf
|
||||||
|
|
||||||
missing = []
|
routes = _routes(app)
|
||||||
for full, route in _routes(app):
|
posts = [(full, deps) for full, route, deps in routes
|
||||||
if not set(route.methods) & {"POST", "PUT", "PATCH", "DELETE"}:
|
if set(route.methods) & {"POST", "PUT", "PATCH", "DELETE"}]
|
||||||
continue
|
assert len(posts) > 40, _describe(app) # die Prüfung erfasst die Routen wirklich
|
||||||
deps = {d.call for d in route.dependant.dependencies}
|
missing = [full for full, deps in posts if verify_csrf not in deps and full not in CSRF_EXEMPT]
|
||||||
if verify_csrf not in deps and full not in CSRF_EXEMPT:
|
|
||||||
missing.append(full)
|
|
||||||
assert missing == [], f"POST ohne CSRF-Prüfung: {missing}"
|
assert missing == [], f"POST ohne CSRF-Prüfung: {missing}"
|
||||||
assert sum(1 for _, r in _routes(app) if "POST" in r.methods) > 40 # wirklich erfasst
|
|
||||||
# Und wirklich: angemeldet, aber ohne Token wird abgewiesen
|
# Und wirklich: angemeldet, aber ohne Token wird abgewiesen
|
||||||
root = admin(app)
|
root = admin(app)
|
||||||
for path in ("/admin/appearance", "/forms", "/logout"):
|
for path in ("/admin/appearance", "/forms", "/logout"):
|
||||||
@@ -81,7 +145,7 @@ def test_protected_pages_need_login_and_rights(app: Any) -> None:
|
|||||||
guest = new_client(app)
|
guest = new_client(app)
|
||||||
paul = participant(app)
|
paul = participant(app)
|
||||||
checked = 0
|
checked = 0
|
||||||
for full, route in _routes(app):
|
for full, route, _deps in _routes(app):
|
||||||
if "GET" not in route.methods or not full.startswith(PROTECTED_PREFIXES):
|
if "GET" not in route.methods or not full.startswith(PROTECTED_PREFIXES):
|
||||||
continue
|
continue
|
||||||
path = _fill(full, route)
|
path = _fill(full, route)
|
||||||
@@ -95,7 +159,7 @@ def test_protected_pages_need_login_and_rights(app: Any) -> None:
|
|||||||
if denied.status_code == 303:
|
if denied.status_code == 303:
|
||||||
assert not denied.headers["location"].startswith(path), path
|
assert not denied.headers["location"].startswith(path), path
|
||||||
checked += 1
|
checked += 1
|
||||||
assert checked > 40 # die Prüfung erfasst die Routen wirklich
|
assert checked > 40, _describe(app) # die Prüfung erfasst die Routen wirklich
|
||||||
|
|
||||||
|
|
||||||
def test_security_headers_on_all_kinds_of_responses(app: Any) -> None:
|
def test_security_headers_on_all_kinds_of_responses(app: Any) -> None:
|
||||||
|
|||||||
Reference in new issue
Block a user