"""TS-10 — forbidden dangerous patterns MUST be absent from src/ (grep-pin)."""

from __future__ import annotations

import re
from pathlib import Path

_SRC = Path(__file__).resolve().parents[2] / "src" / "mgf" / "fastapi"

# (regex, human reason). Each MUST NOT appear in shipped source.
_FORBIDDEN = [
    (r"shell\s*=\s*True", "subprocess shell=True (SC — shell injection)"),
    (r"\bos\.system\s*\(", "os.system (shell injection)"),
    (r"\beval\s*\(", "eval() on dynamic input"),
    (r"\bexec\s*\(", "exec() on dynamic input"),
    (r"\bpickle\.loads?\s*\(", "pickle load (deserialization RCE)"),
    (r"yaml\.load\s*\((?![^)]*Loader)", "yaml.load without a safe Loader"),
    (r"hashlib\.(md5|sha1)\s*\(", "weak hash (md5/sha1) — use sha256+"),
]


def test_no_forbidden_patterns_in_source() -> None:
    hits = []
    for py in _SRC.rglob("*.py"):
        text = py.read_text(encoding="utf-8")
        for pat, reason in _FORBIDDEN:
            for m in re.finditer(pat, text):
                line = text[: m.start()].count("\n") + 1
                hits.append(f"{py.relative_to(_SRC.parents[2])}:{line} — {reason}")
    assert not hits, "TS-10: forbidden patterns found:\n  " + "\n  ".join(hits)
