diff options
| author | Mohamed Hegazy <mhegazy@anthropic.com> | 2026-10-15 16:31:04 +0000 |
|---|---|---|
| committer | Claude <noreply@anthropic.com> | 2026-10-15 16:31:04 +0000 |
| commit | 8876c9951efd618ef5a889dd1a6479bdb73b70bd (patch) | |
| tree | 0807071f9262de3351fd3aa58ddb89ae6a5eec76 /plugins | |
| parent | 8f814f49002ff824e8a9ba43cf96112dc7f5948d (diff) | |
security-guidance: skip the untracked-file listing when the Stop review is off
UserPromptSubmit listed every untracked file in the worktree and stored the
result in the session state on each prompt, for a snapshot that only the Stop
review reads. With ENABLE_STOP_REVIEW=0 or ENABLE_CODE_SECURITY_REVIEW=0 the
Stop hook skips before reading it, so the listing is now skipped too. The
stash baseline is still captured for the Write pattern filter.
When the review is switched back on, the next prompt takes a fresh snapshot,
including after an interrupted turn whose baseline is kept.
Refs #6612
Diffstat (limited to 'plugins')
3 files changed, 211 insertions, 22 deletions
diff --git a/plugins/security-guidance/hooks/diffstate.py b/plugins/security-guidance/hooks/diffstate.py index be839212..f50382e6 100644 --- a/plugins/security-guidance/hooks/diffstate.py +++ b/plugins/security-guidance/hooks/diffstate.py @@ -198,7 +198,8 @@ def capture_git_baseline(cwd): NOTE: `git stash create` does NOT capture untracked files. UPS pairs this SHA with a `_list_untracked()` snapshot stored as `untracked_at_baseline`, and `compute_v2_review_set` subtracts that set so pre-existing untracked - files are not reviewed as Claude-authored. + files are not reviewed as Claude-authored. UPS takes no snapshot while the + Stop review, its only reader, is switched off. """ # stdout is a SHA so text=True is safe on stdout, but a non-ASCII # filename in `git stash create`'s STDERR warning (e.g. a worktree diff --git a/plugins/security-guidance/hooks/security_reminder_hook.py b/plugins/security-guidance/hooks/security_reminder_hook.py index 580bb8a3..97ad466e 100755 --- a/plugins/security-guidance/hooks/security_reminder_hook.py +++ b/plugins/security-guidance/hooks/security_reminder_hook.py @@ -532,29 +532,38 @@ def handle_user_prompt_submit(input_data): sys.exit(0) session_id = input_data.get("session_id", "default") - # stash-create and ls-files both walk the worktree (~2-5s each in a very - # large repo). Run them concurrently so UPS latency stays ≈ max(both). - import concurrent.futures as _cf - with _cf.ThreadPoolExecutor(max_workers=2) as _ex: - _f_sha = _ex.submit(capture_git_baseline, cwd) - _f_ut = _ex.submit(_list_untracked, cwd) - sha = _f_sha.result() - # Always capture the untracked snapshot. `git stash create` returns - # empty when there are no TRACKED changes, but pre-existing untracked - # files still need to be excluded from the next Stop's review_set — - # otherwise an untracked-only working tree gets every untracked file - # reviewed on every turn until something tracked is dirtied. - untracked_now = _f_ut.result() or {} + # The untracked snapshot has one reader: the Stop-hook diff review, which + # skips before reading it when either of these switches is off (see + # handle_stop_hook). Listing the worktree on every prompt then buys + # nothing, so only the stash baseline (still read by the Write pattern + # filter) is captured. + snapshot_untracked = ENABLE_STOP_REVIEW and ENABLE_CODE_SECURITY_REVIEW + + def _capture(repo_cwd): + if not snapshot_untracked: + return capture_git_baseline(repo_cwd), None + # stash-create and ls-files both walk the worktree (~2-5s each in a + # very large repo). Run them concurrently so UPS latency stays + # ≈ max(both). + import concurrent.futures as _cf + with _cf.ThreadPoolExecutor(max_workers=2) as _ex: + _f_sha = _ex.submit(capture_git_baseline, repo_cwd) + _f_ut = _ex.submit(_list_untracked, repo_cwd) + # Taken whether or not the stash produced a SHA. `git stash + # create` returns empty when there are no TRACKED changes, but + # pre-existing untracked files still need to be excluded from the + # next Stop's review_set — otherwise an untracked-only working + # tree gets every untracked file reviewed on every turn until + # something tracked is dirtied. + return _f_sha.result(), _f_ut.result() or {} + + sha, untracked_now = _capture(cwd) if not sha and not _git_toplevel(cwd): hint = load_repo_hint(session_id) if hint: debug_log(f"UPS: cwd is not a git repo; using repo hint {hint!r}") cwd = hint - with _cf.ThreadPoolExecutor(max_workers=2) as _ex: - _f_sha = _ex.submit(capture_git_baseline, cwd) - _f_ut = _ex.submit(_list_untracked, cwd) - sha = _f_sha.result() - untracked_now = _f_ut.result() or {} + sha, untracked_now = _capture(cwd) head = _git_rev_parse_head(cwd) # If the previous turn's Stop hook never ran (user interrupt, follow-up @@ -573,14 +582,24 @@ def handle_user_prompt_submit(input_data): # we still need to capture a baseline. if state.get("touched_paths") and state.get("baseline_sha"): preserved["value"] = True + # A baseline captured while the Stop review was off has no + # snapshot beside it. Without one the next Stop would take every + # untracked file in the tree as written this turn. + if untracked_now is not None and "untracked_at_baseline" not in state: + state["untracked_at_baseline"] = untracked_now return if sha: state["baseline_sha"] = sha state["head_at_capture"] = head # untracked_at_baseline is independent of whether the stash produced - # a SHA — write it unconditionally so compute_v2_review_set's - # preexisting-untracked exclusion works in untracked-only trees. - state["untracked_at_baseline"] = untracked_now + # a SHA, so compute_v2_review_set's preexisting-untracked exclusion + # works in untracked-only trees. None means no snapshot was taken + # (Stop review off): drop the previous one, which belongs to an older + # baseline. + if untracked_now is None: + state.pop("untracked_at_baseline", None) + else: + state["untracked_at_baseline"] = untracked_now with_locked_state(session_id, _save) if preserved["value"]: diff --git a/plugins/security-guidance/tests/test_prompt_untracked_snapshot.py b/plugins/security-guidance/tests/test_prompt_untracked_snapshot.py new file mode 100644 index 00000000..be0fc1ee --- /dev/null +++ b/plugins/security-guidance/tests/test_prompt_untracked_snapshot.py @@ -0,0 +1,169 @@ +import json +import os +import shutil + +import pytest + +from conftest import ( + VULN_PY, edit_payload, make_repo, metrics_of, run_hook, stop_payload, ups_payload, +) + +OFF_SWITCHES = [ + pytest.param({"ENABLE_STOP_REVIEW": "0"}, id="stop-review-off"), + pytest.param({"ENABLE_CODE_SECURITY_REVIEW": "0"}, id="all-reviews-off"), +] +OLD = "import os\nos.system(cmd)\n" + + +@pytest.fixture +def on(hook_env, tmp_path): + """hook_env with the Stop review on, and a `git` first on PATH that + records each call before running it.""" + shim = tmp_path / "bin" + shim.mkdir() + log = tmp_path / "git.log" + log.write_text("") + (shim / "git").write_text( + f'#!/bin/sh\nprintf \'%s\\n\' "$*" >> "{log}"\nexec "{shutil.which("git")}" "$@"\n') + (shim / "git").chmod(0o755) + env = {k: v for k, v in hook_env.items() if k != "CLAUDE_CODE_REMOTE_SESSION_ID"} + env.update(HOME=str(tmp_path), PATH=f"{shim}{os.pathsep}{hook_env['PATH']}", + GIT_CALLS=str(log)) + return env + + +def _listed_untracked(env): + with open(env["GIT_CALLS"]) as f: + return any("ls-files --others" in line for line in f) + + +def _state(env, session_id="s1"): + path = os.path.join(env["SECURITY_WARNINGS_STATE_DIR"], + f"security_warnings_state_{session_id}.json") + with open(path) as f: + return json.load(f) + + +def _repo(tmp_path): + repo = make_repo(tmp_path / "repo", {"app.py": OLD}) + (repo / "notes.txt").write_text("scratch\n") + return repo + + +def _write_payload(cwd, file_path, content, session_id="s1"): + return { + "session_id": session_id, + "hook_event_name": "PostToolUse", + "tool_name": "Write", + "tool_input": {"file_path": str(file_path), "content": content}, + "tool_response": {}, + "cwd": str(cwd), + } + + +def _reviewed(stub_api): + n = len(stub_api.calls) + del stub_api.calls[:] + return n > 0 + + +pytestmark = pytest.mark.skipif(os.name == "nt", reason="the git recorder is a sh script") + + +class TestPrompt: + def test_review_on_takes_the_snapshot(self, tmp_path, on): + repo = _repo(tmp_path) + rc, _, _ = run_hook(ups_payload(repo), on) + assert rc == 0 + assert _listed_untracked(on) + assert list(_state(on)["untracked_at_baseline"]) == ["notes.txt"] + + @pytest.mark.parametrize("off", OFF_SWITCHES) + def test_review_off_does_not_list_the_worktree(self, tmp_path, on, off): + repo = _repo(tmp_path) + rc, _, _ = run_hook(ups_payload(repo), {**on, **off}) + assert rc == 0 + assert not _listed_untracked(on) + assert "untracked_at_baseline" not in _state(on) + + @pytest.mark.parametrize("off", OFF_SWITCHES) + def test_review_off_write_filter_still_knows_what_was_there(self, tmp_path, on, off): + """The stash baseline is still captured: a full-file Write that keeps + a risky call from before the prompt is not reported as new.""" + repo = _repo(tmp_path) + env = {**on, **off, "CLAUDE_PROJECT_DIR": str(repo)} + (repo / "app.py").write_text(OLD + "# edited before the prompt\n") + run_hook(ups_payload(repo), env) + + _rc, out, _ = run_hook(_write_payload(repo, repo / "app.py", OLD + "print('x')\n"), env) + assert "additionalContext" not in out + _rc, out, _ = run_hook(_write_payload( + repo, repo / "app.py", OLD + "import pickle\npickle.loads(data)\n"), env) + assert "pickle" in out and "os.system" not in out + + def test_review_off_uses_the_repo_hint_without_listing(self, tmp_path, on): + repo = _repo(tmp_path) + outside = tmp_path / "not-a-repo" + outside.mkdir() + (repo / "app.py").write_text(VULN_PY) + # The hint a commit review that resolved the repo leaves behind. + with open(os.path.join(on["SECURITY_WARNINGS_STATE_DIR"], + "security_warnings_state_s1.json"), "w") as f: + json.dump({"shown_warnings": [], "repo_root_hint": str(repo)}, f) + rc, _, _ = run_hook(ups_payload(outside), {**on, "ENABLE_STOP_REVIEW": "0"}) + assert rc == 0 + assert not _listed_untracked(on) + assert _state(on).get("baseline_sha") + + def test_review_off_drops_the_snapshot_of_an_older_baseline(self, tmp_path, on): + repo = _repo(tmp_path) + run_hook(ups_payload(repo), on) + assert "untracked_at_baseline" in _state(on) + run_hook(ups_payload(repo), {**on, "ENABLE_STOP_REVIEW": "0"}) + assert "untracked_at_baseline" not in _state(on) + + +class TestTurn: + def test_review_on_reviews_only_new_untracked_files(self, tmp_path, on, stub_api): + repo = _repo(tmp_path) + (repo / "old_vuln.py").write_text(VULN_PY) + run_hook(ups_payload(repo), on) + _rc, out, _ = run_hook(stop_payload(repo), on) + assert metrics_of(out)["skip_reason"] == 9 # empty review set + assert not _reviewed(stub_api) + + run_hook(ups_payload(repo), on) + (repo / "new_vuln.py").write_text(VULN_PY) + _rc, out, _ = run_hook(stop_payload(repo), on) + assert metrics_of(out)["files_reviewed"] == 1 + assert _reviewed(stub_api) + + @pytest.mark.parametrize("off", OFF_SWITCHES) + def test_review_switched_back_on_at_the_next_prompt(self, tmp_path, on, stub_api, off): + """Old untracked files are not reviewed as this turn's work.""" + repo = _repo(tmp_path) + (repo / "old_vuln.py").write_text(VULN_PY) + run_hook(ups_payload(repo), {**on, **off}) + run_hook(stop_payload(repo), {**on, **off}) + + run_hook(ups_payload(repo), on) + _rc, out, _ = run_hook(stop_payload(repo), on) + assert metrics_of(out)["skip_reason"] == 9 + assert not _reviewed(stub_api) + + def test_review_switched_back_on_after_an_interrupted_turn(self, tmp_path, on, stub_api): + """The interrupted turn's baseline is kept, so its edit is reviewed, + and the old untracked file beside it is not.""" + off = {**on, "ENABLE_STOP_REVIEW": "0"} + repo = _repo(tmp_path) + (repo / "old_vuln.py").write_text(VULN_PY) + run_hook(ups_payload(repo), off) + (repo / "app.py").write_text(VULN_PY) + run_hook(edit_payload(repo, repo / "app.py"), off) # no Stop: interrupted + baseline = _state(on)["baseline_sha"] + + run_hook(ups_payload(repo), on) + assert _state(on)["baseline_sha"] == baseline + _rc, out, _ = run_hook(stop_payload(repo), on) + assert metrics_of(out)["files_reviewed"] == 1 + assert _reviewed(stub_api) |
