"""Deny-by-default safety net for the coder's general-purpose shell tool. This is deliberately a denylist, not an allowlist: ``run_command`` must be able to run arbitrary build/test/lint/package-manager commands across unknown project types, so an allowlist (like the stricter read-only ``run_verification_command`` path uses) would be too restrictive here. This only rejects patterns that are essentially never legitimate for an ordinary coding task -- destructive system operations, machine shutdown/reconfiguration, security-control tampering, and piping a remote script directly into a shell interpreter (a common supply-chain and prompt-injection payload pattern) -- while leaving normal file edits inside the project directory untouched (that boundary is already enforced by the git branch/worktree isolation, not by this policy). This is a meaningful safety net, not a complete sandbox: a sufficiently obfuscated command can still evade a string-pattern denylist. It complements, rather than replaces, running AFK against a disposable/least-privilege environment for real isolation. """ from __future__ import annotations import re from dataclasses import dataclass _DENY_PATTERNS: tuple[tuple[str, str], ...] = ( ( r"\brm\s+-\w*[rR]\w*[fF]\w*\s+(/|~|\$HOME|/\*|~/\*)(\s|$)", "recursive force-delete of a root or home directory", ), ( r"\brm\s+-\w*[fF]\w*[rR]\w*\s+(/|~|\$HOME|/\*|~/\*)(\s|$)", "recursive force-delete of a root or home directory", ), ( r"remove-item\b[^\n]*-recurse\b[^\n]*-force\b[^\n]*\s" r"(['\"]?[a-zA-Z]:\\?['\"]?|\$env:(systemroot|windir|systemdrive|userprofile))(\s|['\"]|$)", "recursive force-delete of a system or user root", ), ( r"\bdel\s+/\w*[sS]\w*\s+/\w*[qQ]\w*\s+[a-zA-Z]:\\", "recursive quiet delete of a drive root", ), (r"\bformat\s+[a-zA-Z]:", "disk format"), (r"\bdiskpart\b", "disk partitioning tool"), (r"\bmkfs(\.\w+)?\b", "filesystem creation (would destroy a disk/partition)"), (r"\bshutdown\b", "machine shutdown or restart"), (r"\brestart-computer\b", "machine restart"), (r"\bstop-computer\b", "machine shutdown"), ( r"(curl|wget|invoke-webrequest|\biwr\b)[^\n|]*\|\s*(sh|bash|zsh|python\d?|iex|powershell)\b", "remote script piped directly into a shell interpreter", ), (r"\biex\s*\(", "dynamic remote/obfuscated code execution (Invoke-Expression)"), (r"\bnet\s+user\b", "local account modification"), (r"\breg(\.exe)?\s+delete\b", "registry deletion"), (r"\bsc(\.exe)?\s+(delete|stop|config)\b", "Windows service tampering"), (r"set-mppreference\b[^\n]*-disable", "disabling Windows Defender protections"), (r"netsh\s+advfirewall\s+set[^\n]*off", "disabling the firewall"), ) _COMPILED: tuple[tuple[re.Pattern[str], str], ...] = tuple( (re.compile(pattern, re.IGNORECASE), reason) for pattern, reason in _DENY_PATTERNS ) def _has_unscoped_pytest(command: str) -> bool: """Return whether any pytest invocation lacks an explicit test-file selector. This deliberately recognizes only project-relative Python test paths. It therefore rejects collection-wide forms such as ``python -m pytest -q`` and ``pytest -k name`` while allowing the focused commands required by a narrow task, e.g. ``python -m pytest tests/test_contract.py -q``. """ # A Python one-liner can hide collection-wide pytest behind # ``pytest.main(...)``. Its embedded selector cannot be safely parsed at # this tool boundary, so scoped tasks must use a normal shell pytest # invocation where project-relative paths are visible to the policy. if re.search(r"\bpytest\s*\.\s*main\s*\(", command, re.IGNORECASE): return True tokens = re.findall(r"[^\s;|&]+", command) for index, token in enumerate(tokens): lower = token.lower() is_pytest = lower in {"pytest", "pytest.exe"} is_module_pytest = ( lower == "-m" and index + 1 < len(tokens) and tokens[index + 1].lower() in {"pytest", "pytest.exe"} ) if not (is_pytest or is_module_pytest): continue start = index + (2 if is_module_pytest else 1) invocation = tokens[start:] has_test_path = any( candidate.startswith(("tests/", "tests\\")) or candidate.startswith("test_") or candidate.endswith(".py") for candidate in invocation if not candidate.startswith("-") ) if not has_test_path: return True return False @dataclass(frozen=True) class CommandPolicyResult: """Whether a shell command may run, and why not when it is refused.""" allowed: bool reason: str = "" def evaluate_command( command: str, *, disallow_unscoped_pytest: bool = False ) -> CommandPolicyResult: """Return whether ``command`` is safe enough to hand to the shell. Matches against a single-line, whitespace-normalized view of the command so patterns spanning newlines or irregular spacing are not trivially evaded. """ normalized = " ".join(command.split()) for compiled, reason in _COMPILED: if compiled.search(normalized): return CommandPolicyResult(allowed=False, reason=reason) if disallow_unscoped_pytest and _has_unscoped_pytest(normalized): return CommandPolicyResult( allowed=False, reason="this task prohibits an unscoped pytest run; include a project-relative test file path", ) return CommandPolicyResult(allowed=True)