Files
surveybox/tests/test_audit_actions.py
marco.morath 42dd1f2d4a
CI / audit (push) Skipped
CI / checks (push) Failing after 37s
CI / image (push) Skipped
Initial Commit: Status Testing
2026-11-25 18:46:04 +01:00

84 lines
3.7 KiB
Python

# SPDX-License-Identifier: AGPL-3.0-or-later
"""Jede Protokollaktion im Code ist erlaubt (audit.ACTIONS) und hat einen Namen
für die Protokollseite (routes/admin.py: ACTION_NAMES).
Eine nicht erlaubte Aktion löst zur Laufzeit einen Fehler aus (HTTP 500). Der
Test liest nur den Quelltext und braucht keine Datenbank.
"""
from __future__ import annotations
import ast
from pathlib import Path
ROOT = Path(__file__).resolve().parent.parent / "surveybox"
def _literal_set(path: Path, name: str) -> set[str]:
tree = ast.parse(path.read_text(encoding="utf-8"))
for node in ast.walk(tree):
targets: list[ast.expr] = []
value: ast.expr | None = None
if isinstance(node, ast.Assign):
targets, value = node.targets, node.value
elif isinstance(node, ast.AnnAssign) and node.value is not None:
targets, value = [node.target], node.value
if any(isinstance(t, ast.Name) and t.id == name for t in targets) and value is not None:
if isinstance(value, ast.Set):
return {e.value for e in value.elts if isinstance(e, ast.Constant)}
if isinstance(value, ast.Dict):
return {k.value for k in value.keys if isinstance(k, ast.Constant)}
raise AssertionError(f"{name} nicht gefunden in {path}")
def _used_actions() -> dict[str, str]:
"""Aktion -> Fundstelle für audit.record(db, "…") und action="…"."""
found: dict[str, str] = {}
for path in ROOT.rglob("*.py"):
tree = ast.parse(path.read_text(encoding="utf-8"))
for node in ast.walk(tree):
if not isinstance(node, ast.Call):
continue
func = node.func
is_record = isinstance(func, ast.Attribute) and func.attr == "record" and (
isinstance(func.value, ast.Name) and func.value.id == "audit"
)
if is_record and len(node.args) >= 2 and isinstance(node.args[1], ast.Constant):
found[str(node.args[1].value)] = f"{path.name}:{node.lineno}"
name = func.attr if isinstance(func, ast.Attribute) else getattr(func, "id", "")
if name not in ("record", "create_link"):
continue
for keyword in node.keywords:
if keyword.arg == "action" and isinstance(keyword.value, ast.Constant):
found[str(keyword.value.value)] = f"{path.name}:{node.lineno}"
# Standardwerte von Parametern namens "action"
for node in ast.walk(tree):
if isinstance(node, ast.FunctionDef):
args = node.args
defaults = dict(zip(
[a.arg for a in args.args][-len(args.defaults):] if args.defaults else [],
args.defaults, strict=False,
))
value = defaults.get("action")
if isinstance(value, ast.Constant):
found[str(value.value)] = f"{path.name}:{node.lineno}"
return found
def test_every_used_action_is_allowed_and_named() -> None:
allowed = _literal_set(ROOT / "accounts" / "audit.py", "ACTIONS")
named = _literal_set(ROOT / "web" / "routes" / "admin.py", "ACTION_NAMES")
used = _used_actions()
assert used, "keine Protokollaktionen gefunden - Test prüft nichts"
missing = {a: where for a, where in used.items() if a not in allowed}
assert not missing, f"nicht in audit.ACTIONS: {missing}"
unnamed = {a: where for a, where in used.items() if a not in named}
assert not unnamed, f"nicht in ACTION_NAMES: {unnamed}"
def test_found_the_new_actions() -> None:
used = _used_actions()
for action in ("admin.mail_settings_changed", "admin.mail_test",
"account.reset_requested", "account.notifications_changed"):
assert action in used