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', shell=None): payload = json.dumps({'hook_event_name': 'PreToolUse', 'tool_name': tool, 'tool_input': {'command': command}}) extra = ['--shell', shell] if shell else [] return subprocess.run([sys.executable, str(SAFETY), '--hook', *extra], 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_commands_hidden_in_control_flow_and_wrapper_options(self): for command in ('if [ -d build ]; then rm -rf build; fi', 'for d in a b; do rm -rf "$d"; done', 'while true; do git reset --hard; done', '(rm -rf x)', '{ git reset --hard; }', '! rm -rf x', 'find . -print0 | xargs -0 rm -rf', 'sudo -E rm -rf /x', 'env -i git reset --hard', 'timeout 30 rm -rf x', 'nice -n 5 rm -rf x', 'rm -rf ${dir}', 'echo ${#arr[@]}; rm -rf x', "sudo -u bob bash -c 'rm -rf x'"): with self.subTest(command=command): self.assertBlocked(command) for command in ('Get-ChildItem bin -Recurse | ForEach-Object { Remove-Item $_ -Recurse -Force }', 'gci bin | % { ri $_ -Recurse }', 'foreach ($d in $dirs) { Remove-Item $d -Recurse }'): with self.subTest(command=command): self.assertBlocked(command, 'PowerShell') def test_blocks_commands_after_comments_escapes_and_line_continuations(self): for command in ("echo hi # don't touch\nrm -rf build", 'echo "\\""; git reset --hard', "echo 'a\\'; rm -rf x", 'rm \\\n -rf build', 'git reset \\\n --hard'): with self.subTest(command=command): self.assertBlocked(command) self.assertBlocked('Remove-Item build `\n -Recurse -Force', 'PowerShell') def test_blocks_git_and_find_forms_that_discard_work(self): for command in ('git checkout -- .', 'git checkout -- src/app.ts', 'git checkout HEAD -- a.txt', 'git checkout .', 'git restore .', 'git restore --worktree src', 'git push --force', 'git push -f origin main', 'git push --force-with-lease', 'git push origin +main', 'git stash clear', 'find . -name "*.tmp" -delete'): with self.subTest(command=command): self.assertBlocked(command) for command in ('git checkout main', 'git checkout -b feat/x', 'git restore --staged file.txt', 'git push', 'git push origin main', 'git stash list', 'find . -name "*.tmp"'): with self.subTest(command=command): self.assertAllowed(command) def test_heredoc_bodies_are_text_not_commands(self): for command in ("cat > c.sh <<'EOF'\nrm -rf \"$tmp\"\nEOF", 'git commit -F - < a.txt <