"""TS-10 — negative-case pins for the mechanically-pinnable SC rules."""

from __future__ import annotations

import re
from pathlib import Path

import pytest

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


def test_no_forbidden_patterns_in_source() -> None:
    forbidden = [
        (r"shell\s*=\s*True", "shell=True"),
        (r"\beval\s*\(", "eval"),
        (r"\bexec\s*\(", "exec"),
        (r"\byaml\.load\s*\(", "unsafe yaml.load"),
        (r"hashlib\.(md5|sha1)\s*\(", "weak hash"),
    ]
    hits = []
    for py in _SRC.rglob("*.py"):
        for i, line in enumerate(py.read_text(encoding="utf-8").splitlines(), 1):
            if "# noqa" in line:
                continue
            for pat, why in forbidden:
                if re.search(pat, line):
                    hits.append(f"{py.relative_to(_SRC)}:{i} — {why}")
    assert not hits, "TS-10: forbidden patterns:\n  " + "\n  ".join(hits)


def test_safe_tar_rejects_traversal() -> None:
    """SC-15 negative pin: a ../ tar member is rejected."""
    safe_tar = pytest.importorskip("mgf.vm.core.common.safe_tar")
    # safe_destination must reject an escape attempt
    fn = getattr(safe_tar, "safe_destination", None)
    if fn is None:
        pytest.skip("safe_destination not exported")
    import pathlib

    exc = getattr(safe_tar, "TarMemberUnsafeError", ValueError)
    with pytest.raises(exc):
        fn(pathlib.Path("/tmp/base"), "../../etc/passwd")
