import json import os from pathlib import Path import shutil import subprocess import sys import tempfile import unittest ROOT = Path(__file__).resolve().parents[2] SCRIPTS = ROOT / 'shared/hooks/scripts' SAFETY = SCRIPTS / 'command-safety.py' def hook(command, tool='Bash'): payload = json.dumps({'hook_event_name': 'PreToolUse', 'tool_name': tool, 'tool_input': {'command': command}}) return subprocess.run([sys.executable, str(SAFETY), '--hook'], input=payload, capture_output=True, encoding='utf-8', timeout=20) def check(command, workspace): return subprocess.run([sys.executable, str(SAFETY), '--command', '-', '--workspace', str(workspace)], input=command, capture_output=True, encoding='utf-8', timeout=20) class HookTests(unittest.TestCase): def assertBlocked(self, command, tool='Bash'): result = hook(command, tool) self.assertEqual(result.returncode, 2, f'{tool}: {command!r} was not blocked') self.assertIn('Blocked by command-safety hook', result.stderr) def assertAllowed(self, command, tool='Bash'): result = hook(command, tool) self.assertEqual(result.returncode, 0, f'{tool}: {command!r} was blocked: {result.stderr}') def test_blocks_destructive_bash_variants(self): for command in ('rm -rf build', 'rm -fr build', 'rm -r -f build', 'rm --recursive --force build', 'sudo rm -Rf /', 'cd x && rm -rf y', 'echo ok; rm -rf y', 'git reset --hard', 'git -C repo reset --hard HEAD~1', 'git clean -fdx', 'git clean --force', "bash -c 'rm -rf build'", 'bash -lc "git reset --hard"', 'eval "rm -rf build"', 'find . -name x | xargs rm -rf', 'FOO=1 /bin/rm -rf build'): with self.subTest(command=command): self.assertBlocked(command) def test_blocks_destructive_powershell_variants(self): for command in ('Remove-Item build -Recurse -Force', 'Remove-Item -Path build -Rec', 'rm -r build', 'ri build -recurse', 'Get-ChildItem x | Remove-Item -Recurse', 'git reset --hard', 'cmd /c "rd /s /q build"', 'pwsh -NoProfile -Command "Remove-Item build -Recurse"', 'format C:'): with self.subTest(command=command): self.assertBlocked(command, 'PowerShell') def test_allows_ordinary_commands(self): for command in ('rm build/file.txt', 'rm -r build', 'git reset HEAD file', 'git reset --soft HEAD~1', 'git clean -n', 'git status', 'echo "rm -rf is dangerous"', 'git commit -m "avoid rm -rf; use trash"', 'ls -rf'): with self.subTest(command=command): self.assertAllowed(command) self.assertAllowed('Remove-Item build/file.txt', 'PowerShell') self.assertAllowed('Remove-Item build -Recurse:$false', 'PowerShell') def test_unknown_shell_checks_both_dialects(self): self.assertBlocked('rm -r build', 'shell') self.assertBlocked('rm -rf build', 'shell') def test_fails_open_on_unusable_input(self): for payload in ('', 'not json', '[]', '{"tool_input": "rm -rf /"}', '{"tool_input": {"command": 5}}'): with self.subTest(payload=payload): result = subprocess.run([sys.executable, str(SAFETY), '--hook'], input=payload, capture_output=True, encoding='utf-8', timeout=20) self.assertEqual(result.returncode, 0, result.stderr) class CommandCheckTests(unittest.TestCase): def setUp(self): directory = tempfile.TemporaryDirectory() self.addCleanup(directory.cleanup) self.workspace = Path(directory.name).resolve() def test_passes_safe_command_inside_workspace(self): result = check(f'cat "{self.workspace / "file.txt"}"', self.workspace) self.assertEqual(result.returncode, 0, result.stderr) self.assertIn('PASS command safety', result.stdout) def test_rejects_destructive_command(self): result = check('git reset --hard', self.workspace) self.assertEqual(result.returncode, 1) self.assertIn('Blocked potentially destructive command', result.stderr) def test_rejects_absolute_path_outside_workspace(self): outside = self.workspace.parent / 'elsewhere.txt' result = check(f'cat "{outside}"', self.workspace) self.assertEqual(result.returncode, 1) self.assertIn('outside the workspace', result.stderr) def test_ignores_cmd_switches(self): self.assertEqual(check('cmd /c dir', self.workspace).returncode, 0) class WrapperTests(unittest.TestCase): def run_wrapper(self, arguments, payload=None): return subprocess.run(arguments, input=payload, capture_output=True, encoding='utf-8', timeout=60) def test_wrappers_block_in_hook_mode_and_check_in_cli_mode(self): event = json.dumps({'tool_name': 'Bash', 'tool_input': {'command': 'rm -rf build'}}) wrappers = [] bash = shutil.which('bash') if os.name == 'nt': # System32\bash.exe is WSL; use Git Bash like the other Windows tests. candidate = Path(os.environ.get('ProgramFiles', 'C:/Program Files')) / 'Git/bin/bash.exe' bash = str(candidate) if candidate.exists() else None if bash: wrappers.append(('bash', [bash, str(SCRIPTS / 'validate-command-safety.sh')])) for name in ('pwsh', 'powershell'): executable = shutil.which(name) if executable: wrappers.append((name, [executable, '-NoProfile', '-ExecutionPolicy', 'Bypass', '-File', str(SCRIPTS / 'Validate-CommandSafety.ps1')])) if not wrappers: self.skipTest('No supported shell is available.') for name, command in wrappers: with self.subTest(shell=name): blocked = self.run_wrapper(command, event) self.assertEqual(blocked.returncode, 2, blocked.stderr) allowed = self.run_wrapper(command, json.dumps({'tool_name': 'Bash', 'tool_input': {'command': 'git status'}})) self.assertEqual(allowed.returncode, 0, allowed.stderr) cli = command + (['-Command', 'git reset --hard'] if name != 'bash' else ['git reset --hard']) self.assertEqual(self.run_wrapper(cli).returncode, 1) if __name__ == '__main__': unittest.main()