AI coding agents can edit files, run shell commands, and touch infrastructure. One bad rm -rf, force-push, or docker compose down -v can wipe hours of work or production data.
| 1 | # SPDX-License-Identifier: MIT |
| 2 | from __future__ import annotations |
| 3 | |
| 4 | from pathlib import Path |
| 5 | |
| 6 | from agent_guard.filesystem import ( |
| 7 | is_dangerous_root_target, |
| 8 | is_sensitive_filename, |
| 9 | looks_like_build_artifact, |
| 10 | matches_protected_path, |
| 11 | resolve_against_root, |
| 12 | ) |
| 13 | from agent_guard.normalizer import normalize_path_text |
| 14 | |
| 15 | |
| 16 | def test_dangerous_roots() -> None: |
| 17 | assert is_dangerous_root_target("/") |
| 18 | assert is_dangerous_root_target("C:\\") |
| 19 | assert is_dangerous_root_target("C:/") |
| 20 | assert not is_dangerous_root_target("./src") |
| 21 | |
| 22 | |
| 23 | def test_path_traversal_resolve(tmp_path: Path) -> None: |
| 24 | rel, escapes = resolve_against_root("./src/../.env", tmp_path) |
| 25 | assert rel == ".env" |
| 26 | assert escapes is False |
| 27 | |
| 28 | |
| 29 | def test_escape_root(tmp_path: Path) -> None: |
| 30 | rel, escapes = resolve_against_root("../../etc/passwd", tmp_path) |
| 31 | assert escapes is True or ".." in rel or rel.endswith("passwd") |
| 32 | |
| 33 | |
| 34 | def test_protected_match(tmp_path: Path) -> None: |
| 35 | patterns = [".env", ".env.*", ".git/**", "secrets/**"] |
| 36 | assert matches_protected_path(".env", patterns, tmp_path) == ".env" |
| 37 | assert matches_protected_path(".env.production", patterns, tmp_path) is not None |
| 38 | assert matches_protected_path("secrets/a.txt", patterns, tmp_path) is not None |
| 39 | |
| 40 | |
| 41 | def test_sensitive_filenames() -> None: |
| 42 | assert is_sensitive_filename(".env") |
| 43 | assert is_sensitive_filename("id_rsa") |
| 44 | assert is_sensitive_filename("creds.pem") |
| 45 | assert is_sensitive_filename("credentials.json") |
| 46 | |
| 47 | |
| 48 | def test_build_artifact() -> None: |
| 49 | assert looks_like_build_artifact("./node_modules") |
| 50 | assert looks_like_build_artifact("build") |
| 51 | assert not looks_like_build_artifact("./src") |
| 52 | |
| 53 | |
| 54 | def test_normalize_dotdot() -> None: |
| 55 | assert normalize_path_text("./src/../.env") == ".env" |