Files
clean-architecture-frontend…/.claude/hooks/test_readonly_bash.py
DongHyeonka 2d61bad023 feat(claude): reviewer 서브에이전트의 Bash를 읽기 전용 가드로 막는다
문제: reviewer는 Bash를 갖고 본문에 「읽기 명령만 쓴다」고만 적혀 있다. 모델이
그 줄을 어기면 리뷰 중에 작업 트리를 바꾸거나 git 상태를 옮길 수 있고, 막는 장치가 없다.

방법: reviewer 머리 칸에 PreToolUse(Bash) 가드를 건다. 가드는 허용 목록 방식이라
`git diff/log/show/grep`과 `python3 -I scripts/check-work-docs.py`만 통과하고, 그 밖의
명령·출력 돌리기·줄바꿈 뒤 명령은 rc 2로 막는다. 스크립트와 시험은 프로젝트 문서
저장소의 공용 사본을 고치지 않고 `.claude/hooks/`에 둔다. `.claude/*`를 무시하는
`.gitignore`에 `!.claude/hooks/`를 더해 함께 배포한다. 본문의 python 줄은 가드와 같게
`-I`를 붙였다. repo 훅 README 1절의 「막지 않는다」에 이 예외를 적는다.
`scripts/tests/test_agent_guard.py`는 가드 자체 시험을 돌리고, 머리 칸에 적힌 그대로의
인자로 본문의 허용 명령은 rc 0, 쓰는 명령은 rc 2인지 본다. Bash를 가진 에이전트는
가드를 걸거나 그 시험의 UNGUARDED에 까닭과 함께 적어야 한다. CI의 scripts/tests step이
이 시험을 돈다. `.gitignore` 시험 목록에 `!.claude/hooks/`를 더하고, 문서 작성 순서의
`check-work-docs.py` 호출도 가드 인자와 같게 `-I`를 붙인다.
- 버린 대안: `scripts/hooks/`에 두기. 그 폴더는 settings.json이 거는 알림 훅
  `hooks.py` 하나만 두는 곳이라 성격이 다르다.
- verify-app은 걸지 않았다. 원격 묶음 명령(`ssh desktop '<cd·flock·pnpm>'`)과 임시
  spec 쓰기를 명령 앞머리 하나로 좁힐 수 없다. arch-reviewer는 Bash가 없다.

위험·한계: 사고 방지용이다. 허용한 명령 안에서 일부러 돌아가는 것은 못 막는다.
`cd <폴더> && git diff`는 막히니 `git -C <폴더>`를 쓴다.

검증:
- python3 -I .claude/hooks/test_readonly_bash.py: 9 tests OK
- 가드 직접 입력: 허용 8개 rc 0, touch·>·줄바꿈 touch·checkout·stash·-I 없는 python·
  --output·cd 8개 rc 2
- 새 프로세스 guard_probe(reviewer, git log --oneline -3): rc 0, 가드가 막은 줄 3
- python3 -I -m unittest discover -s scripts/tests: 112 OK
- 변이 넷(머리 칸 가드 빼기, --git에서 diff 빼기, 본문의 -I 빼기, 가드 없는 Bash
  에이전트 더하기)이 각각 test_agent_guard.py의 시험 하나를 떨어뜨림
- scripts/verify.sh docs rc 0, scripts/verify.sh hooks rc 0
2026-12-03 02:48:48 +09:00

111 lines
5.7 KiB
Python

"""readonly_bash.py 시험. 돌리는 법: python3 -I .claude/hooks/test_readonly_bash.py
파일을 쓰거나 지우지 않고 네트워크를 쓰지 않는다. 가드를 프로세스로 불러 rc만 본다.
"""
import json
import os
import subprocess
import sys
import unittest
HERE = os.path.dirname(os.path.abspath(__file__))
HOOK = os.path.join(HERE, "readonly_bash.py")
PROJ = "/nonexistent/proj-시험"
ARGS = ["--git", "log,show,diff,rev-parse,status", "--cmd", "cd,ls,wc,grep,sha256sum,find,sed,awk,head,cat",
"--py", "--pyfile", "--run", "./verify.sh --check", "--write", "lead/work-methods/evidence"]
def rc(tool, inp, args=ARGS, raw=None):
env = dict(os.environ, CLAUDE_PROJECT_DIR=PROJ)
data = raw if raw is not None else json.dumps({"tool_name": tool, "tool_input": inp})
r = subprocess.run([sys.executable, "-I", HOOK] + args, input=data, capture_output=True, text=True, env=env)
return r.returncode
def bash(cmd, args=ARGS):
return rc("Bash", {"command": cmd}, args)
class ReadonlyBashTests(unittest.TestCase):
def test_read_commands_pass(self):
for cmd in ("git log --oneline -5",
"git -C /x/repo show --stat abc123 | head -20",
"cd /x && git --no-pager diff a..b -- f.md 2>/dev/null",
"git rev-parse 'abc^{tree}'; git status -sb",
"TZ=Asia/Seoul git log -1 --format=%ci",
"wc -c /x/a.md /x/b.md",
"grep -c \"a > b\" /x/f",
"grep -rn '`code`' /x 2>&1 | head -3",
"ls -la /x >/dev/null 2>&1",
"sha256sum /x/a < /dev/null",
"find /x -name '*.md' -newer /x/a",
"sed -n '3,9p' /x/f",
"awk -F'|' '{print $2}' /x/f",
"awk -F '|' '$3 == 5 {print $1}' /x/f",
"python3 -I -c 'import json; print(len(json.load(open(\"/x/a.json\"))))'",
"python3 -I tools/check_cards.py",
"python3 -I /x/tools/tests/test_a.py -v",
"./verify.sh --check all",
"ls /x\ngit log -1\n# 주석 줄 rm -rf /x\nwc -l /x/f"):
self.assertEqual(bash(cmd), 0, cmd)
def test_write_commands_blocked(self):
for cmd in ("git push origin main", "git commit -m x", "git fetch origin", "git -C /x checkout main",
"git -c core.pager=rm log", "git diff --output=/x/a", "git branch -D x", "git",
"rm -rf /x", "mv /x/a /x/b", "cp /x/a /x/b", "touch /x/a", "mkdir /x/d", "chmod +x /x/a",
"echo hi", "curl http://x", "ssh host ls", "bash -c 'ls'", "sh x.sh", "xargs rm", "tee /x/f",
"ls > /x/f", "ls >> /x/f", "ls 2> /x/err", "ls &> /x/f", "git log | tee /x/f",
"ls $(rm -rf /x)", "ls `rm -rf /x`", "grep \"$(rm x)\" /x/f", "cat <(rm x)",
"(cd /x; rm a)", "ls /x\nrm -rf /x/y", "ls /x \\\n&& rm -rf /x/y", "ls; rm x", "ls & rm x",
"ls || rm x", "ls | sh",
"find /x -name a -delete", "find /x -exec rm {} +", "sed -i s/a/b/ /x/f",
"sed -ni s/a/b/p /x/f", "awk '{print > \"/x/f\"}' /x/a", "awk '{system(\"rm x\")}' /x/a",
"python3 -c 'print(1)'", "python3 -I -c \"open('/x/f','w').write('1')\"",
"python3 -I -c 'import subprocess'", "python3 -I -m pip install x", "python3 -I -",
"python3 -I - <<'EOF'\nprint(1)\nEOF", "python3 x.py",
"GIT_EXTERNAL_DIFF=/x/evil git diff", "LD_PRELOAD=/x/a.so ls",
"./verify.sh --on host", "./verify.sh", "ls 'unterminated", "wc -l /x/f >",
"awk -f /x/prog.awk /x/a", "awk -F '|' '{print | \"sh\"}' /x/a"):
self.assertEqual(bash(cmd), 2, cmd)
def test_empty_command_passes(self):
self.assertEqual(bash(""), 0)
def test_only_listed_commands(self):
only_git = ["--git", "show"]
self.assertEqual(bash("git show abc", only_git), 0)
self.assertEqual(bash("git log", only_git), 2)
self.assertEqual(bash("ls", only_git), 2)
self.assertEqual(bash("python3 -I -c 'print(1)'", only_git), 2)
self.assertEqual(bash("python3 -I tools/a.py", only_git), 2)
def test_bad_config_blocks_everything(self):
self.assertEqual(bash("git log", ["--git", "log,push"]), 2)
self.assertEqual(bash("ls", ["--cmd", "ls,rm"]), 2)
self.assertEqual(bash("ls", ["--cmd", "ls", "--nope"]), 2)
self.assertEqual(bash("ls", ["--cmd", "ls", "--run", "a; b"]), 2)
self.assertEqual(bash("ls", ["--cmd"]), 2)
def test_unreadable_input_blocks(self):
self.assertEqual(rc("Bash", {}, raw="not json"), 2)
def test_write_only_into_listed_folder(self):
ok = PROJ + "/lead/work-methods/evidence/A-verify.md"
self.assertEqual(rc("Write", {"file_path": ok}), 0)
self.assertEqual(rc("Write", {"file_path": "lead/work-methods/evidence/A-verify.md"}), 0)
self.assertEqual(rc("Write", {"file_path": PROJ + "/lead/work-methods/evidence/../../handoff.md"}), 2)
self.assertEqual(rc("Write", {"file_path": PROJ + "/lead/work-methods/evidence-x/a.md"}), 2)
self.assertEqual(rc("Edit", {"file_path": PROJ + "/AGENTS.md"}), 2)
self.assertEqual(rc("Write", {"file_path": ""}), 2)
def test_write_not_checked_without_write_arg(self):
self.assertEqual(rc("Write", {"file_path": "/x/a"}, ["--cmd", "ls"]), 0)
def test_other_tools_pass(self):
self.assertEqual(rc("Read", {"file_path": "/x/a"}), 0)
self.assertEqual(rc("Grep", {"pattern": "a"}), 0)
if __name__ == "__main__":
unittest.main()