kuri-tool-guard/tests/test_terminal_guards.py
XLion 06a7f93d18
refactor(kuri-tool-guard): modularise monolithic __init__.py and tests
Split the 1341-line __init__.py into 5 focused modules:
  _state.py    - home root helpers, mutable poll state
  _parser.py   - shell tokenizer (independent)
  _predicates.py - terminal predicates + bounded output
  _guards.py   - all 9 guard implementations + AST helpers
  __init__.py  - thin entry point + dispatcher + re-exports

Split the 2226-line test_guard.py into 14 dedicated files:
  13 test_*.py files + tests/_support.py (shared helpers)

Key changes:
- Package-relative imports throughout (Hermes loader compatible)
- No top-level module pollution (hermes_plugins.kuri_tool_guard.* only)
- Typechecked via ty with symlink alias for hyphenated dir name
- All 10 guard policies, messages, and block/allow behaviour preserved
- 338 tests (336 original + 2 new: isolation + loader contract)
- ty, ruff, bandit, vulture all pass in just verify
2026-07-31 02:23:02 +08:00

298 lines
11 KiB
Python

"""Tests for kuri-tool-guard — terminal guard orchestration and middleware."""
from __future__ import annotations
import tempfile
import unittest
from pathlib import Path
from unittest.mock import MagicMock
from tests._support import load_mod, submodule
class TestTerminalGuardCombined(unittest.TestCase):
"""Test _match_terminal_predicate — the orchestration layer."""
def setUp(self):
self.mod = load_mod()
self.pred = submodule(self.mod, "_predicates")
# ── Should block (return a reason string) ───────────────────
def test_block_cat_read(self):
self.assertIsNotNone(self.pred._match_terminal_predicate("cat /proc/version"))
def test_block_cat_file_write(self):
"""cat pipeline with redirect to real file."""
self.assertIsNotNone(self.pred._match_terminal_predicate("cat file | grep x > output"))
def test_block_cat_heredoc(self):
"""cat heredoc with redirect — cat predicate catches it."""
self.assertIsNotNone(self.pred._match_terminal_predicate("cat <<'EOF' > /tmp/x"))
def test_block_heredoc_direct(self):
self.assertIsNotNone(self.pred._match_terminal_predicate("<<'EOF' > /tmp/x"))
def test_block_echo(self):
self.assertIsNotNone(self.pred._match_terminal_predicate("echo 'x' > /tmp/x"))
def test_block_printf(self):
self.assertIsNotNone(self.pred._match_terminal_predicate("printf 'x' > /tmp/x"))
def test_block_bare_redirect(self):
self.assertIsNotNone(self.pred._match_terminal_predicate("> /tmp/x"))
def test_block_tee(self):
self.assertIsNotNone(self.pred._match_terminal_predicate("echo foo | tee /tmp/x"))
# ── Should NOT block ───────────────────────────────────────
def test_pass_ls(self):
self.assertIsNone(self.pred._match_terminal_predicate("ls -la"))
def test_pass_grep(self):
self.assertIsNone(self.pred._match_terminal_predicate("grep foo /tmp/x"))
def test_pass_echo_no_redirect(self):
self.assertIsNone(self.pred._match_terminal_predicate("echo 'hello'"))
def test_pass_echo_devnull(self):
self.assertIsNone(self.pred._match_terminal_predicate("echo 'hi' > /dev/null"))
def test_pass_printf_gt_in_format(self):
self.assertIsNone(self.pred._match_terminal_predicate("printf '%s > %s' a b"))
def test_pass_stderr_to_stdout(self):
self.assertIsNone(self.pred._match_terminal_predicate("cmd 2>&1"))
def test_pass_cat_pipe_no_write(self):
self.assertIsNone(self.pred._match_terminal_predicate("cat file | grep bar"))
class TestTerminalGuardMiddleware(unittest.TestCase):
"""Test _guard_terminal and _on_pre_tool_call for terminal."""
def setUp(self):
self.mod = load_mod()
def test_register(self):
ctx = MagicMock()
self.mod.register(ctx)
ctx.register_hook.assert_called_once_with(
"pre_tool_call",
self.mod._on_pre_tool_call,
)
# ── Blocks ─────────────────────────────────────────────────
def test_blocks_cat_read(self):
result = self.mod._on_pre_tool_call(
tool_name="terminal",
args={"command": "cat /etc/hostname"},
)
self.assertIsNotNone(result)
self.assertEqual(result["action"], "block")
self.assertIn("cat", result["message"])
self.assertIn("read_file", result["message"])
def test_blocks_cat_stderr_only(self):
"""cat file 2>/dev/null — stdout still terminal."""
result = self.mod._on_pre_tool_call(
tool_name="terminal",
args={"command": "cat file 2>/dev/null"},
)
self.assertIsNotNone(result)
self.assertEqual(result["action"], "block")
self.assertIn("cat", result["message"])
def test_blocks_cat_fd_redirect(self):
"""cat file >&2 — stdout to stderr terminal."""
result = self.mod._on_pre_tool_call(
tool_name="terminal",
args={"command": "cat file >&2"},
)
self.assertIsNotNone(result)
self.assertEqual(result["action"], "block")
self.assertIn("cat", result["message"])
def test_blocks_cat_env_var(self):
"""FOO=1 cat file — env var, terminal output."""
result = self.mod._on_pre_tool_call(
tool_name="terminal",
args={"command": "FOO=1 cat file"},
)
self.assertIsNotNone(result)
self.assertEqual(result["action"], "block")
self.assertIn("cat", result["message"])
def test_blocks_cat_path_command(self):
"""/bin/cat file — path command, terminal."""
result = self.mod._on_pre_tool_call(
tool_name="terminal",
args={"command": "/bin/cat file"},
)
self.assertIsNotNone(result)
self.assertEqual(result["action"], "block")
def test_blocks_cat_pipe_file_write(self):
"""cat file | grep x > output — pipeline writes to file (shell-write msg)."""
result = self.mod._on_pre_tool_call(
tool_name="terminal",
args={"command": "cat file | grep x > output"},
)
self.assertIsNotNone(result)
self.assertEqual(result["action"], "block")
self.assertIn("patch", result["message"])
self.assertNotIn("read_file", result["message"])
def test_blocks_cat_pipe_tee(self):
"""cat file | tee output — blocked by tee guard (shell-write msg)."""
result = self.mod._on_pre_tool_call(
tool_name="terminal",
args={"command": "cat file | tee output"},
)
self.assertIsNotNone(result)
self.assertEqual(result["action"], "block")
def test_blocks_cat_devnull_with_stderr(self):
"""cat file >/dev/null 2>errors.log — stderr writes file."""
result = self.mod._on_pre_tool_call(
tool_name="terminal",
args={"command": "cat file >/dev/null 2>errors.log"},
)
self.assertIsNotNone(result)
self.assertEqual(result["action"], "block")
self.assertIn("patch", result["message"])
def test_blocks_echo_redirect(self):
result = self.mod._on_pre_tool_call(
tool_name="terminal",
args={"command": "echo 'x' > /tmp/x"},
)
self.assertIsNotNone(result)
self.assertEqual(result["action"], "block")
self.assertIn("不允許", result["message"])
def test_blocks_printf_redirect(self):
result = self.mod._on_pre_tool_call(
tool_name="terminal",
args={"command": "printf 'x' > /tmp/x"},
)
self.assertIsNotNone(result)
self.assertEqual(result["action"], "block")
self.assertIn("不允許", result["message"])
def test_blocks_heredoc_direct(self):
result = self.mod._on_pre_tool_call(
tool_name="terminal",
args={"command": "<<'EOF' > /tmp/x"},
)
self.assertIsNotNone(result)
self.assertEqual(result["action"], "block")
# ── Passes ─────────────────────────────────────────────────
def test_passes_safe_command(self):
result = self.mod._on_pre_tool_call(
tool_name="terminal",
args={"command": "ls -la"},
)
self.assertIsNone(result)
def test_passes_echo_devnull(self):
result = self.mod._on_pre_tool_call(
tool_name="terminal",
args={"command": "echo 'hi' > /dev/null"},
)
self.assertIsNone(result)
# ── Cat passes (pipeline / devnull) ────────────────────────────
def test_passes_cat_pipe_head(self):
"""cat file | head — legitimate pipeline, allow."""
result = self.mod._on_pre_tool_call(
tool_name="terminal",
args={"command": "cat file | head"},
)
self.assertIsNone(result)
def test_passes_cat_devnull(self):
"""cat file >/dev/null — stdout discarded, allow."""
result = self.mod._on_pre_tool_call(
tool_name="terminal",
args={"command": "cat file >/dev/null"},
)
self.assertIsNone(result)
def test_passes_cat_devnull_explicit(self):
"""cat file 1>/dev/null — explicit stdout discard, allow."""
result = self.mod._on_pre_tool_call(
tool_name="terminal",
args={"command": "cat file 1>/dev/null"},
)
self.assertIsNone(result)
def test_passes_cat_devnull_amp(self):
"""cat file &>/dev/null — combined discard, allow."""
result = self.mod._on_pre_tool_call(
tool_name="terminal",
args={"command": "cat file &>/dev/null"},
)
self.assertIsNone(result)
def test_passes_cat_pipe_devnull(self):
"""cat file | head >/dev/null — pipeline to discard, allow."""
result = self.mod._on_pre_tool_call(
tool_name="terminal",
args={"command": "cat file | head >/dev/null"},
)
self.assertIsNone(result)
def test_passes_not_cat_cmd(self):
"""printf with 'cat' arg — not a cat command, allow."""
result = self.mod._on_pre_tool_call(
tool_name="terminal",
args={"command": "printf 'cat file\\n'"},
)
self.assertIsNone(result)
# ── Cat process substitution redirect ──
def test_passes_cat_proc_sub_redirect(self):
"""cat file > >(head) — process sub, allow."""
result = self.mod._on_pre_tool_call(
tool_name="terminal",
args={"command": "cat file > >(head)"},
)
self.assertIsNone(result)
def test_passes_cat_proc_sub_redirect_grep(self):
"""cat file > >(grep pattern) — process sub, allow."""
result = self.mod._on_pre_tool_call(
tool_name="terminal",
args={"command": "cat file > >(grep pattern)"},
)
self.assertIsNone(result)
# ── Edge cases ─────────────────────────────────────────────
def test_empty_command(self):
result = self.mod._on_pre_tool_call(
tool_name="terminal",
args={"command": ""},
)
self.assertIsNone(result)
def test_non_dict_args(self):
result = self.mod._on_pre_tool_call(
tool_name="terminal",
args=None,
)
self.assertIsNone(result)
def test_missing_command(self):
result = self.mod._on_pre_tool_call(
tool_name="terminal",
args={"path": str(Path(tempfile.gettempdir()) / "x")},
)
self.assertIsNone(result)