CI / CI configuration security checks (push) Successful in 6s
CI / Python tests and compilation (push) Failing after 12s
CI / QMD unit tests (push) Skipped
CI / Capabilities and shell quality (push) Successful in 1m50s
CI / Build and inspect generated packages (push) Skipped
CI / Bash integration and installation guards (push) Skipped
CI / Installed client configuration smoke tests (push) Skipped
CI / PowerShell tests on Ubuntu (push) Failing after 7m24s
206 lines
11 KiB
Python
206 lines
11 KiB
Python
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 - <<EOF\nfix: avoid git reset --hard\nEOF',
|
|
'cat <<-END\n\trm -rf x\n\tEND'):
|
|
with self.subTest(command=command):
|
|
self.assertAllowed(command)
|
|
self.assertBlocked('cat > a.txt <<EOF\nhello\nEOF\nrm -rf build')
|
|
self.assertBlocked('cat <<EOF; rm -rf build\nbody\nEOF')
|
|
|
|
def test_allows_comments_and_hashes_that_are_not_commands(self):
|
|
for command in ('ls # rm -rf x', 'git commit -m "fix #12; rm -rf is bad"', 'echo a#b', 'echo "\\"rm -rf x\\""'):
|
|
with self.subTest(command=command):
|
|
self.assertAllowed(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_shell_override_checks_codex_windows_powershell_text_reported_as_bash(self):
|
|
for command in ('rm -r build', 'Remove-Item build -Recurse', 'ri build -recurse', 'rm -rf build'):
|
|
with self.subTest(command=command):
|
|
self.assertEqual(2, hook(command, 'Bash', 'unknown').returncode)
|
|
self.assertEqual(0, hook('rm -r build', 'Bash').returncode, 'Claude Git Bash keeps the POSIX meaning of rm -r')
|
|
self.assertEqual(0, hook('Get-ChildItem build', 'Bash', 'unknown').returncode)
|
|
|
|
def test_unknown_shell_checks_both_dialects(self):
|
|
self.assertBlocked('rm -r build', 'shell')
|
|
self.assertBlocked('rm -rf build', 'shell')
|
|
|
|
def test_allowed_shell_search_gets_the_search_reminder_in_the_same_process(self):
|
|
with tempfile.TemporaryDirectory() as directory:
|
|
home = Path(directory)
|
|
(home / '.my-ai-configuration/qmd').mkdir(parents=True)
|
|
(home / '.my-ai-configuration/qmd/qmd-search.mjs').write_text('')
|
|
env = dict(os.environ, HOME=str(home), USERPROFILE=str(home))
|
|
|
|
def run(command, session='s1'):
|
|
payload = json.dumps({'session_id': session, 'tool_name': 'Bash', 'tool_input': {'command': command}})
|
|
return subprocess.run([sys.executable, str(SAFETY), '--hook'], input=payload, capture_output=True,
|
|
encoding='utf-8', timeout=20, env=env)
|
|
|
|
result = run('rg Tile')
|
|
self.assertEqual(result.returncode, 0, result.stderr)
|
|
self.assertIn('additionalContext', result.stdout)
|
|
self.assertEqual('', run('git status', 's2').stdout)
|
|
blocked = run('rm -rf build && rg x', 's3')
|
|
self.assertEqual(blocked.returncode, 2)
|
|
self.assertEqual('', blocked.stdout)
|
|
|
|
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)
|
|
# Codex hook commands pass -Shell; the wrapper must stay in hook mode and read the event.
|
|
codex = json.dumps({'tool_name': 'Bash', 'tool_input': {'command': 'rm -r build'}})
|
|
self.assertEqual(2, self.run_wrapper(command + ['-Shell', 'unknown'], codex).returncode, name)
|
|
|
|
|
|
if __name__ == '__main__':
|
|
unittest.main()
|