From 63b3f50e486689c2fabf07110b94aaa7695a4dd6 Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Fri, 13 Nov 2026 01:53:43 +0900 Subject: [PATCH] =?UTF-8?q?test(harness):=20rm=20=EA=B0=80=EB=93=9C=20?= =?UTF-8?q?=EC=8B=9C=ED=97=98=EC=9D=B4=20checkout=20=EC=9C=84=EC=B9=98?= =?UTF-8?q?=EC=99=80=20=EC=83=81=EA=B4=80=EC=97=86=EC=9D=B4=20=EA=B0=99?= =?UTF-8?q?=EC=9D=80=20=ED=8C=90=EC=A0=95=EC=9D=84=20=EB=82=B8=EB=8B=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 문제: test_rm_whole_checkout_or_sibling_is_blocked가 이 repo의 checkout을 cwd로 쓴다. H12는 /tmp 아래 rm을 일부러 허용하므로, checkout이 /tmp 아래(scratchpad worktree)에 있으면 `rm -rf ./*`가 통과해 main에서도 시험이 실패한다. main checkout 안의 worktree에서는 main checkout 허용 때문에 통과해 expectedFailure로 돌렸다. 같은 코드가 놓인 자리에 따라 통과·실패·예상 실패로 갈린다. 고른 방법: 시험이 /tmp 밖(/var/tmp, 못 쓰면 HOME)에 빈 checkout과 그 안의 worktree(.claude/worktrees/w)를 직접 만들어 cwd로 넘긴다. checkout에서는 자신·옆 폴더 삭제가 막히는지 보고, worktree의 알려진 빈틈은 늘 expectedFailure로 둔다. 두 곳에서 `rm -rf build`가 통과하는 시험을 더해, 막히는 이유가 위치를 몰라서가 아님을 확인한다. /tmp 밖 폴더를 못 찾으면 건너뛰지 않고 오류로 멈춘다. 버린 대안: /tmp 아래면 건너뛰기(/tmp에서 이 판정을 시험하지 못한다), H12 허용 폴더를 환경 변수로 바꾸게 하기(시험 때문에 훅 입력을 늘린다). 위험: 시험이 /var/tmp(또는 HOME)에 h12-test-* 임시 폴더를 만들고 끝나면 지운다. 시험 프로세스가 중간에 죽으면 그 폴더가 남을 수 있다. 훅 동작은 바꾸지 않아 플러그인 버전은 그대로 둔다. 검증: main(8583353)을 /tmp 아래 worktree에서 돌리면 이 시험이 실패하는 것을 먼저 봤다. 고친 뒤 /tmp 아래 worktree와 원래 위치 아래 worktree 두 곳에서 scripts/check.sh 통과. 훅을 두 가지로 망가뜨리면(허용 폴더 자신 허용, cwd 상위 폴더 허용) 새 시험이 실패한다. --- plugins/harness/tests/test_hooks.py | 70 ++++++++++++++++++++++++----- 1 file changed, 58 insertions(+), 12 deletions(-) diff --git a/plugins/harness/tests/test_hooks.py b/plugins/harness/tests/test_hooks.py index 3e7dce4..71a1cd8 100644 --- a/plugins/harness/tests/test_hooks.py +++ b/plugins/harness/tests/test_hooks.py @@ -6,6 +6,7 @@ """ import json import os +import shutil import subprocess import sys import tempfile @@ -13,11 +14,8 @@ import unittest SCRIPTS = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "scripts") REPO = os.path.dirname(os.path.dirname(os.path.dirname(SCRIPTS))) -_COMMON = subprocess.run(["git", "-C", REPO, "rev-parse", "--path-format=absolute", "--git-common-dir"], - capture_output=True, text=True).stdout.strip() -# main checkout 안에 만든 worktree(.claude/worktrees/…)에서 도는가. 이때 H12 허용 폴더에 main checkout이 들어가 -# worktree 자신(`rm -rf ./*`)이나 옆 worktree(`../x`)를 지우는 것이 통과한다(알려진 빈틈, 전역 훅과 같이 고친다) -NESTED_WORKTREE = bool(_COMMON) and os.path.realpath(REPO).startswith(os.path.dirname(os.path.realpath(_COMMON)) + "/") +# 시험용 checkout을 둘 /tmp 밖 후보. H12는 /tmp 아래 rm을 일부러 허용하므로 /tmp 안에서는 작업 폴더 판정이 안 보인다 +OUTSIDE_TMP_BASES = ("/var/tmp", os.path.expanduser("~")) def run(script, args=(), payload=None, env=None, cwd=None): @@ -33,9 +31,23 @@ def bash(command, cwd=REPO): "tool_input": {"command": command}, "cwd": cwd} -class GuardBashTest(unittest.TestCase): - """H12. 여기 사례는 판정의 대표만 둔다. 많은 사례는 소유자 기계 전역 훅 시험에 있다.""" +def git(cwd, *args): + """시험용 git. 사용자 설정(서명·훅·기본 브랜치)에 따라 결과가 달라지지 않게 부른다.""" + subprocess.run(["git", "-c", "user.name=t", "-c", "user.email=t@example.com", "-c", "commit.gpgsign=false", + "-c", "core.hooksPath=/dev/null", "-c", "init.defaultBranch=main", "-C", cwd, *args], + check=True, capture_output=True, text=True, timeout=30) + +def outside_tmp_base(): + """OUTSIDE_TMP_BASES 중 쓸 수 있는 첫 폴더. 없으면 시험을 건너뛰지 않고 오류로 멈춘다.""" + for base in OUTSIDE_TMP_BASES: + real = os.path.realpath(base) + if os.path.isdir(real) and os.access(real, os.W_OK) and not (real + "/").startswith("/tmp/"): + return real + raise RuntimeError("/tmp 밖에 시험용 checkout을 만들 곳이 없다: %s" % ", ".join(OUTSIDE_TMP_BASES)) + + +class H12Asserts: ALWAYS = {"HARNESS_H12": "always"} def assert_blocked(self, command, cwd=REPO): @@ -47,6 +59,10 @@ class GuardBashTest(unittest.TestCase): r = run("guard_bash.py", payload=bash(command, cwd), env=self.ALWAYS) self.assertEqual(r.returncode, 0, "통과해야 한다: %s\n%s" % (command, r.stderr)) + +class GuardBashTest(H12Asserts, unittest.TestCase): + """H12. 여기 사례는 판정의 대표만 둔다. 많은 사례는 소유자 기계 전역 훅 시험에 있다.""" + def test_force_push_to_hosting_remote_is_blocked(self): for c in ("git push --force origin main", "git push -f", "git push origin +feature/x", "git push --force-with-lease origin claude/x", "git push --mirror origin", @@ -67,11 +83,6 @@ class GuardBashTest(unittest.TestCase): "ssh build 'rm -rf ~/workspace/some-repo'"): self.assert_blocked(c) - @(unittest.expectedFailure if NESTED_WORKTREE else (lambda f: f)) - def test_rm_whole_checkout_or_sibling_is_blocked(self): - for c in ("rm -rf ./*", "rm -rf ../other-repo/src"): - self.assert_blocked(c) - def test_rm_inside_project_tmp_and_known_vars_pass(self): for c in ("rm -rf build dist", "rm -rf /tmp/some-build-x", 'T=$(mktemp -d) && rm -rf "$T"', "S=/tmp/x; rm -rf $S/out", 'rm -rf "${OUT:?}/build"', "ssh build 'rm -rf ~/x-logs'"): @@ -109,6 +120,41 @@ class GuardBashTest(unittest.TestCase): self.assertEqual(r.returncode, 1) +class GuardRmCheckoutTest(H12Asserts, unittest.TestCase): + """H12가 작업 폴더 안 삭제는 통과시키고 작업 폴더 자신·옆 폴더 삭제는 막는지. + + 이 repo의 checkout을 cwd로 쓰면 결과가 checkout 위치에 따라 달라진다(/tmp 아래면 /tmp 허용에 걸려 통과하고, + main checkout 안의 worktree면 main checkout 허용에 걸려 통과한다). 그래서 /tmp 밖에 checkout과 그 안의 + worktree를 직접 만들어 cwd로 넘긴다. + """ + + @classmethod + def setUpClass(cls): + base = tempfile.mkdtemp(prefix="h12-test-", dir=outside_tmp_base()) + cls.addClassCleanup(shutil.rmtree, base, True) + cls.checkout = os.path.join(base, "repo") + git(base, "init", "-q", cls.checkout) + git(cls.checkout, "commit", "-q", "--allow-empty", "-m", "init") + cls.worktree = os.path.join(cls.checkout, ".claude", "worktrees", "w") + git(cls.checkout, "worktree", "add", "-q", "--detach", cls.worktree) + + def test_rm_inside_checkout_and_worktree_passes(self): + # 둘 다 허용 폴더로 잡힌다. 아래 시험이 막히는 것은 위치를 몰라서가 아니라 대상이 넓어서다 + for cwd in (self.checkout, self.worktree): + self.assert_passed("rm -rf build", cwd=cwd) + + def test_rm_whole_checkout_or_sibling_is_blocked(self): + for c in ("rm -rf ./*", "rm -rf ../other-repo/src"): + self.assert_blocked(c, cwd=self.checkout) + + @unittest.expectedFailure + def test_rm_nested_worktree_itself_or_sibling_is_blocked(self): + """알려진 빈틈: main checkout 안의 worktree에서는 허용 폴더에 main checkout이 들어가 worktree 자신이나 + 옆 worktree를 지우는 것이 통과한다. 전역 훅과 같이 고친다. 고치면 이 시험의 expectedFailure를 뗀다.""" + for c in ("rm -rf ./*", "rm -rf ../other-worktree"): + self.assert_blocked(c, cwd=self.worktree) + + class NudgeSecretsTest(unittest.TestCase): def nudge(self, content, tool="Write"): key = "content" if tool == "Write" else "new_string"