Files
MyAiConfiguration/scripts/tests/test-command-safety.py
T
Julian LechnerandClaude Opus 5.5 79694fbaa2 fix(config): resolve Python reliably, add command-safety hook, harden CI
- Resolve Python 3.11+ through shared Resolve-Python.ps1/resolve-python.sh,
  which probe python, python3 and py -3 and skip the Windows Store alias.
  Build and capability checks fail early with an actionable message; doctor
  reports missing Python and the skipped hooks.
- Fix check-capabilities.sh comparing only the major version.
- Register Validate-CommandSafety as a PreToolUse hook for Claude and Codex;
  shared logic in command-safety.py catches rm -rf variants, git reset --hard,
  git clean -f, Remove-Item -Recurse, del/rd /s /q and nested shells.
- Replace duplicated placeholder chains in both builds with
  adapters/placeholders.tsv.
- Restore shell parity: add test-capabilities.sh, rename credentials.ps1 to
  with-credential.ps1 and qmd-warm.sh to start-qmd-warm.sh.
- CI: build once and pass generated/ as an artifact, lint Python with ruff
  and JavaScript modules with node --check, require SHA pins for all actions.
- Add evals for all own skills and update documentation.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-05 09:34:54 +01:00

130 lines
6.3 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'):
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()