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 | """Filesystem path matching and dangerous-target detection.""" |
| 3 | |
| 4 | from __future__ import annotations |
| 5 | |
| 6 | import fnmatch |
| 7 | import re |
| 8 | from pathlib import Path, PurePosixPath |
| 9 | |
| 10 | from agent_guard.normalizer import normalize_path_text |
| 11 | |
| 12 | DANGEROUS_ROOT_TARGETS = frozenset( |
| 13 | { |
| 14 | "/", |
| 15 | "\\", |
| 16 | "c:/", |
| 17 | "c:\\", |
| 18 | "c:", |
| 19 | "~", |
| 20 | "~/", |
| 21 | } |
| 22 | ) |
| 23 | |
| 24 | SENSITIVE_PATH_GLOBS = ( |
| 25 | ".env", |
| 26 | ".env.*", |
| 27 | "*.pem", |
| 28 | "*.key", |
| 29 | "id_rsa", |
| 30 | "id_ed25519", |
| 31 | "credentials.json", |
| 32 | "service-account.json", |
| 33 | ".aws/credentials", |
| 34 | "**/.aws/credentials", |
| 35 | ".ssh/**", |
| 36 | "**/.ssh/**", |
| 37 | ) |
| 38 | |
| 39 | |
| 40 | def expand_user_token(path: str) -> str: |
| 41 | """Expand ``~`` using the current user home for matching only.""" |
| 42 | if path.startswith("~/") or path == "~": |
| 43 | home = Path.home().as_posix() |
| 44 | if path == "~": |
| 45 | return home |
| 46 | return f"{home}/{path[2:]}" |
| 47 | if path.startswith("~\\"): |
| 48 | home = Path.home().as_posix() |
| 49 | return f"{home}/{path[2:].replace(chr(92), '/')}" |
| 50 | return path |
| 51 | |
| 52 | |
| 53 | def resolve_against_root(path: str, project_root: Path) -> tuple[str, bool]: |
| 54 | """ |
| 55 | Resolve *path* relative to *project_root* without following symlinks. |
| 56 | |
| 57 | Returns (normalized_relative_or_absolute, escapes_root). |
| 58 | """ |
| 59 | norm = normalize_path_text(path) |
| 60 | if not norm: |
| 61 | return "", False |
| 62 | |
| 63 | # Absolute |
| 64 | if norm.startswith("/") or re.match(r"^[A-Za-z]:/", norm): |
| 65 | try: |
| 66 | abs_path = Path(norm) |
| 67 | root = project_root.resolve() |
| 68 | try: |
| 69 | relative = abs_path.resolve().relative_to(root) |
| 70 | return relative.as_posix(), False |
| 71 | except ValueError: |
| 72 | return norm, True |
| 73 | except (OSError, RuntimeError, ValueError): |
| 74 | return norm, True |
| 75 | |
| 76 | # Relative — pure resolution of . and .. |
| 77 | pure = PurePosixPath(norm) |
| 78 | stack: list[str] = [] |
| 79 | escapes = False |
| 80 | for part in pure.parts: |
| 81 | if part in (".",): |
| 82 | continue |
| 83 | if part == "..": |
| 84 | if stack: |
| 85 | stack.pop() |
| 86 | else: |
| 87 | escapes = True |
| 88 | continue |
| 89 | stack.append(part) |
| 90 | relative_path = "/".join(stack) if stack else "." |
| 91 | return relative_path, escapes |
| 92 | |
| 93 | |
| 94 | def is_dangerous_root_target(path: str) -> bool: |
| 95 | raw = path.strip().lower().replace("\\", "/") |
| 96 | if raw in {"/", "\\", "c:/", "c:", "~", "~/"}: |
| 97 | return True |
| 98 | norm = normalize_path_text(path).lower() |
| 99 | if norm in {"/", "\\", ".", ""} and raw in {"/", "\\"}: |
| 100 | return True |
| 101 | if norm in {"/", "\\"}: |
| 102 | return True |
| 103 | # Drive roots (do not rstrip in a way that empties "/") |
| 104 | stripped = norm.rstrip("/") if len(norm) > 1 else norm |
| 105 | candidates = {norm, stripped, stripped + "/", raw} |
| 106 | for c in candidates: |
| 107 | if c in DANGEROUS_ROOT_TARGETS: |
| 108 | return True |
| 109 | if c.rstrip("/") in {"c:", "c"}: |
| 110 | return True |
| 111 | return bool(re.fullmatch(r"[a-z]:/?", stripped)) |
| 112 | |
| 113 | |
| 114 | def is_system_path(path: str) -> bool: |
| 115 | """Detect well-known sensitive system directories.""" |
| 116 | norm = normalize_path_text(path).lower() |
| 117 | expanded = expand_user_token(norm).lower() |
| 118 | system_prefixes = ( |
| 119 | "/etc", |
| 120 | "/var", |
| 121 | "/var/lib", |
| 122 | "/usr", |
| 123 | "/boot", |
| 124 | "/root", |
| 125 | "c:/windows", |
| 126 | "c:/program files", |
| 127 | ) |
| 128 | for prefix in system_prefixes: |
| 129 | if expanded == prefix or expanded.startswith(prefix + "/"): |
| 130 | return True |
| 131 | |
| 132 | low = path.lower().replace("\\", "/") |
| 133 | markers = ("~/.ssh", "~/.aws", "~/.config", "~/.gnupg", ".git") |
| 134 | for marker in markers: |
| 135 | if low == marker or low.startswith(marker + "/"): |
| 136 | return True |
| 137 | if f"/{marker.lstrip('~/')}/" in f"/{expanded}/": |
| 138 | return True |
| 139 | return False |
| 140 | |
| 141 | |
| 142 | def path_matches_pattern(path: str, pattern: str, project_root: Path | None = None) -> bool: |
| 143 | """Match *path* against a config pattern (exact, glob, directory).""" |
| 144 | path_norm = normalize_path_text(path).replace("\\", "/") |
| 145 | pat = pattern.strip().replace("\\", "/") |
| 146 | |
| 147 | # Directory pattern ending with / |
| 148 | if pat.endswith("/") and not any(ch in pat for ch in "*?[]"): |
| 149 | base = pat.rstrip("/") |
| 150 | return path_norm == base or path_norm.startswith(base + "/") |
| 151 | |
| 152 | # Glob |
| 153 | if any(ch in pat for ch in "*?[]"): |
| 154 | name = PurePosixPath(path_norm).name |
| 155 | if fnmatch.fnmatch(path_norm, pat) or fnmatch.fnmatch(name, pat): |
| 156 | return True |
| 157 | # **/ style |
| 158 | if pat.startswith("**/"): |
| 159 | return fnmatch.fnmatch(path_norm, pat[3:]) or fnmatch.fnmatch(path_norm, pat) |
| 160 | return False |
| 161 | |
| 162 | # Exact |
| 163 | if path_norm == pat or path_norm.rstrip("/") == pat.rstrip("/"): |
| 164 | return True |
| 165 | |
| 166 | # basename match for simple names like .env |
| 167 | return PurePosixPath(path_norm).name == pat |
| 168 | |
| 169 | |
| 170 | def matches_protected_path( |
| 171 | path: str, |
| 172 | protected_paths: list[str], |
| 173 | project_root: Path, |
| 174 | ) -> str | None: |
| 175 | """Return the matching protected pattern, or None.""" |
| 176 | rel, escapes = resolve_against_root(path, project_root) |
| 177 | candidates = [path, rel, normalize_path_text(path)] |
| 178 | if escapes: |
| 179 | # Escaping root is itself sensitive when targeting protected-looking names |
| 180 | candidates.append(path) |
| 181 | |
| 182 | for candidate in candidates: |
| 183 | for pattern in protected_paths: |
| 184 | if path_matches_pattern(candidate, pattern, project_root): |
| 185 | return pattern |
| 186 | # Also try basename of candidate |
| 187 | base = PurePosixPath(normalize_path_text(candidate)).name |
| 188 | if path_matches_pattern(base, pattern, project_root): |
| 189 | return pattern |
| 190 | return None |
| 191 | |
| 192 | |
| 193 | def is_sensitive_filename(path: str) -> bool: |
| 194 | norm = normalize_path_text(path) |
| 195 | return any(path_matches_pattern(norm, pattern) for pattern in SENSITIVE_PATH_GLOBS) |
| 196 | |
| 197 | |
| 198 | def looks_like_build_artifact(path: str) -> bool: |
| 199 | """Heuristic: common regenerable directories.""" |
| 200 | norm = normalize_path_text(path).lower() |
| 201 | name = PurePosixPath(norm).name |
| 202 | return name in { |
| 203 | "build", |
| 204 | "dist", |
| 205 | "node_modules", |
| 206 | "target", |
| 207 | "__pycache__", |
| 208 | ".venv", |
| 209 | "venv", |
| 210 | "tmp", |
| 211 | "temp", |
| 212 | "coverage", |
| 213 | ".next", |
| 214 | ".cache", |
| 215 | } |
| 216 | |
| 217 | |
| 218 | def join_safe(root: Path, *parts: str) -> Path: |
| 219 | """Join paths under root; raise if result would escape.""" |
| 220 | candidate = root.joinpath(*parts) |
| 221 | try: |
| 222 | resolved = candidate.resolve() |
| 223 | resolved.relative_to(root.resolve()) |
| 224 | except ValueError as exc: |
| 225 | raise ValueError("path escapes project root") from exc |
| 226 | return candidate |