diff options
| author | Mohamed Hegazy <mhegazy@anthropic.com> | 2026-11-04 20:36:00 +0000 |
|---|---|---|
| committer | Claude <noreply@anthropic.com> | 2026-11-04 21:33:13 +0000 |
| commit | 8ae757f137060bf97e7c9fa2876fb444633b1316 (patch) | |
| tree | 20682d2d15d27f4d06f0b9ad95464f2c3d6f6020 /plugins | |
| parent | 1280a036e8e4d44dfe81f9728f8dfa6917687195 (diff) | |
security-guidance: name new files the Stop review could not see
When git add -N fails on both tries or times out, wake Claude once per
set of files with their names, so the review no longer ends as "no
changes". A timed-out add now keeps the tracked files' diff, so a
timeout on every turn cannot stop their reviews. Private object
directory cleanup no longer chmods through a link.
Fixes #6996
Co-authored-by: mhegazy <mhegazy@anthropic.com>
Diffstat (limited to 'plugins')
| -rw-r--r-- | plugins/security-guidance/hooks/gitutil.py | 24 | ||||
| -rwxr-xr-x | plugins/security-guidance/hooks/security_reminder_hook.py | 83 | ||||
| -rw-r--r-- | plugins/security-guidance/tests/test_add_failure_metric.py | 200 |
3 files changed, 265 insertions, 42 deletions
diff --git a/plugins/security-guidance/hooks/gitutil.py b/plugins/security-guidance/hooks/gitutil.py index 029fcb9d..7fa75ec1 100644 --- a/plugins/security-guidance/hooks/gitutil.py +++ b/plugins/security-guidance/hooks/gitutil.py @@ -300,8 +300,9 @@ _path_list_too_long = set() # timeout, 4 the retry with a private object directory worked. A git that # speaks another language reports a failed retry as 2. With 1 to 3 the new # files are not in the diff, so a turn that only added files looks like a turn -# with no changes; a timeout loses the whole diff. -_add_failed = {"code": 0} +# with no changes. `left_out` says so for the last get_git_diff alone: the code +# stays set through a fallback diff that worked. +_add_failed = {"code": 0, "left_out": False} # Next to an index copy: where a retried `git add -N` stores the empty blob. _OBJECTS_DIR_SUFFIX = ".objects" @@ -547,8 +548,10 @@ def _remove_objects_dir(path): import stat def writable_then_retry(func, p, _exc): - os.chmod(p, stat.S_IWRITE) - func(p) + # Not a link: chmod would follow it to whatever it points at. + if func in (os.unlink, os.rmdir) and not os.path.islink(p): + os.chmod(p, stat.S_IWRITE) + func(p) try: shutil.rmtree(path, onerror=writable_then_retry) @@ -623,11 +626,7 @@ def _hook_tmpdir(): def _note_add_failure(kind, paths): _add_failed["code"] = kind * 100000 + min(len(paths), 99999) - - -def _new_files_left_out(): - """True if a failed `git add -N` kept new files out of this run's diff.""" - return _add_failed["code"] // 100000 in (1, 2, 3) + _add_failed["left_out"] = kind != 4 def _env_with_private_objects(env, cwd, objects_dir): @@ -675,15 +674,17 @@ def _add_new_files(cwd, paths, env, tmp_index): try: failed = add(env) except subprocess.TimeoutExpired: + # No retry: git is slow here, not refused. The diff goes on for the + # tracked files, so a timeout on every turn cannot stop their reviews. _note_add_failure(3, paths) - raise + return if not failed: return debug_log(f"git add -N failed: {failed.stderr[:200].decode('utf-8', errors='replace')}") # Whatever happens to the retry, the diff goes on for the tracked files. try: objects_dir = tmp_index + _OBJECTS_DIR_SUFFIX - os.mkdir(objects_dir) + os.mkdir(objects_dir, 0o700) retry_failed = add(_env_with_private_objects(env, cwd, objects_dir)) if retry_failed: debug_log(f"git add -N retry failed: {retry_failed.stderr[:200].decode('utf-8', errors='replace')}") @@ -1533,6 +1534,7 @@ def get_git_diff(cwd, baseline_sha, full_context=False, paths=None, untracked_pa MAX_FILE_DIFF_BYTES is cut down to its added lines. """ _path_list_too_long.clear() + _add_failed["left_out"] = False pathspec = _diff_pathspec(cwd, paths) if paths and not pathspec: # Caller restricted to specific paths but none are inside this repo diff --git a/plugins/security-guidance/hooks/security_reminder_hook.py b/plugins/security-guidance/hooks/security_reminder_hook.py index 232bc08b..516365a6 100755 --- a/plugins/security-guidance/hooks/security_reminder_hook.py +++ b/plugins/security-guidance/hooks/security_reminder_hook.py @@ -219,6 +219,9 @@ CONTINUATION_SUFFIX = ( "response." ) +# New files named in the notice for a failed `git add -N`. +_LEFT_OUT_NAMES_SHOWN = 5 + # Extra keys emit_metrics appends to every row this invocation emits. _TAIL_METRICS: Dict[str, Any] = {} # Of those, the ones that go after the others whenever they were set: a row @@ -1416,6 +1419,44 @@ def _review_failure_reason(status): return ("reply", "the model's reply could not be read", "") +def _left_out_files_notice(session_id, repo_root, untracked, diff_output): + """(one line for the terminal, text for Claude) naming the source files a + failed `git add -N` kept out of this Stop review, or None. + + Each set of files gets one notice a session: the wake ends in another Stop + that fails the same way, and a notice there would wake Claude for ever. So + no notice unless the mark is saved. Paths are JSON quoted in ASCII: a file + name can hold a line break. + """ + in_diff = set(extract_file_paths_from_diff(diff_output or "")) + + def has_content(p): + try: + return os.path.getsize(os.path.join(repo_root, p)) > 0 + except OSError: + return False + + names = sorted(p for p in untracked or () + if p not in in_diff and _is_reviewable_source(p) and has_content(p)) + if not names: + return None + key = "new_files_left_out:" + hashlib.sha256( + "\0".join(names).encode("utf-8", "replace")).hexdigest()[:16] + if not atomic_check_and_mark_warning(session_id, key): + return None + if key not in load_state(session_id).get("shown_warnings", ()): + return None + _TAIL_METRICS["add_fail_told"] = len(names) + shown = ", ".join(json.dumps(p) for p in names[:_LEFT_OUT_NAMES_SHOWN]) + if len(names) > _LEFT_OUT_NAMES_SHOWN: + shown += f" and {len(names) - _LEFT_OUT_NAMES_SHOWN} more" + return (f"Security review left out new files: {shown}. Log: {DEBUG_LOG_FILE}", + f"The security review did not see these new files, so it did not " + f"review them: {shown}. git could not add them to the review's " + f"diff. Tell the user this in one sentence, and that details are " + f"in {DEBUG_LOG_FILE}.") + + def _exit_review_failed(kind, session_id, metrics, status, pushed="no"): """End a commit ("Commit") or push ("Push") review that got no verdict. @@ -2485,10 +2526,29 @@ def handle_stop_hook(input_data): _TAIL_METRICS["warn_fired_mask"] = warn_fired_mask v2_metrics = {} + left_out = False + restore_paths = touched_paths + + def _left_out_notice(): + # Asked for as the row goes out: the mark must not outlive a hook + # killed during the review. + if not left_out: + return None + return _left_out_files_notice(session_id, repo_root, untracked, diff_output) + + def _left_out_wake(): + """emit_metrics arguments that wake Claude to say new files were left out.""" + notice = _left_out_notice() + if not notice: + return {} + return {"rewake_summary": notice[0], "hook_event_name": hook_event_name, + "additional_context": (PROVENANCE_BANNER + "\n\n" + notice[1] + + CONTINUATION_SUFFIX + "\n")} def _skip(reason, restore=False, **extra): if restore: - restore_unreviewed_stop_state(session_id, touched_paths, snap_baseline) + restore_unreviewed_stop_state(session_id, restore_paths, snap_baseline) + wake = _left_out_wake() # CC truncates metrics to 10 keys by # insertion order. v2_metrics (3) must precede sweep (3) so the v2 # diagnostics survive when extra adds touched_paths_count + ip_* keys. @@ -2500,8 +2560,8 @@ def handle_stop_hook(input_data): if gitutil._unparsed_diff_headers else {}), **({"secret_shaped_skipped": len(gitutil._secret_shaped_skipped)} if gitutil._secret_shaped_skipped else {}), - }) - sys.exit(0) + }, **wake) + sys.exit(2 if wake else 0) # Limit stop hook firings per asyncRewake loop to prevent infinite loops. # fire_count auto-expires after STOP_LOOP_STATE_TTL_SEC so a stale count @@ -2648,9 +2708,9 @@ def handle_stop_hook(input_data): # put back, listed as touched so the next prompt keeps this baseline even # if an edit tool never wrote them. A review of the tracked files goes on # without them, rather than repeating that review every turn. - left_out = gitutil._new_files_left_out() + left_out = gitutil._add_failed["left_out"] if left_out: - touched_paths = list(touched_paths) + [ + restore_paths = list(touched_paths) + [ os.path.join(repo_root, p) for p in untracked or ()] if not diff_output or not diff_output.strip(): @@ -2796,6 +2856,7 @@ def handle_stop_hook(input_data): # untracked_baseline_n is the signal for whether the UPS-time # untracked-snapshot capture actually ran. sweep_trimmed = {k: v for k, v in sweep.items() if k != "warn_unresolved_mask"} + left_out_notice = _left_out_notice() # Guidance goes to stderr plus top-level decision/reason (see # emit_metrics). exit(2) preserved as the asyncRewake "force fix" # signal — that's the documented mechanism. @@ -2817,8 +2878,9 @@ def handle_stop_hook(input_data): **({"secret_shaped_skipped": len(gitutil._secret_shaped_skipped)} if gitutil._secret_shaped_skipped else {}), }, rewake_summary=_format_vulns_summary(vulns), - additional_context=(PROVENANCE_BANNER + "\n\n" - + concrete_guidance + CONTINUATION_SUFFIX + "\n"), + additional_context=(PROVENANCE_BANNER + "\n\n" + concrete_guidance + + ("\n\n" + left_out_notice[1] if left_out_notice else "") + + CONTINUATION_SUFFIX + "\n"), hook_event_name=hook_event_name) sys.exit(2) @@ -2826,11 +2888,12 @@ def handle_stop_hook(input_data): if stop_review_failed: debug_log(f"Stop hook: review got no verdict " f"({_review_failure_reason(llm.last_review_status())[1]})") - restore_unreviewed_stop_state(session_id, touched_paths, snap_baseline) + restore_unreviewed_stop_state(session_id, restore_paths, snap_baseline) else: debug_log("Stop hook: no security issues found") if is_subagent: record_reviewed_diff(session_id, diff_hash) + wake = _left_out_wake() # CC keeps the first 20 metric keys (10 in older versions), in insertion # order, after the pv and usage keys emit_metrics puts first. The previous # **sweep,**v2_metrics tail meant the 3 v2_metrics keys were always sliced @@ -2852,8 +2915,8 @@ def handle_stop_hook(input_data): if gitutil._unparsed_diff_headers else {}), **({"secret_shaped_skipped": len(gitutil._secret_shaped_skipped)} if gitutil._secret_shaped_skipped else {}), - }) - sys.exit(0) + }, **wake) + sys.exit(2 if wake else 0) _SDK_BOOTSTRAP_THROTTLE = os.path.join(_resolve_state_dir(), ".sdk_bootstrap_spawned") diff --git a/plugins/security-guidance/tests/test_add_failure_metric.py b/plugins/security-guidance/tests/test_add_failure_metric.py index 8e539e9b..81685ec1 100644 --- a/plugins/security-guidance/tests/test_add_failure_metric.py +++ b/plugins/security-guidance/tests/test_add_failure_metric.py @@ -1,8 +1,9 @@ """`git add --intent-to-add` puts new files in the Stop review's diff. A user who cannot write the object store gets a retry with a private object directory; a failure that stays leaves the new files for a later review, unless the turn's -tracked files were reviewed. The Stop row says -what happened.""" +tracked files were reviewed, and tells Claude which files were left out. The +Stop row says what happened.""" +import json import os import shutil import subprocess @@ -12,11 +13,12 @@ from types import SimpleNamespace import pytest from conftest import ( - GIT_ENV, VULN_PY, edit_payload, git, make_repo, metrics_of, run_hook, + GIT_ENV, STUB_VULN, VULN_PY, edit_payload, git, make_repo, metrics_of, run_hook, stop_payload, ups_payload, ) import gitutil +import security_reminder_hook as hook def _cannot_write_read_only_dirs(): @@ -110,21 +112,23 @@ class TestPathspecSettings: @pytest.mark.skipif(os.name == "nt", reason="the stand-in git is a shell script") -class TestAddThatKeepsFailing: - def _git_that_refuses_add(self, tmp_path): - d = tmp_path / "shim" - d.mkdir() - real = shutil.which("git") - shim = d / "git" - shim.write_text('#!/bin/sh\nfor a in "$@"; do\n' - ' [ "$a" = --intent-to-add ] && { echo "fatal: refused" >&2; exit 128; }\n' - f'done\nexec "{real}" "$@"\n') - shim.chmod(0o755) - return d +def _env_refusing_add(tmp_path, hook_env, unless="false"): + """`hook_env` with a git that fails `add -N` unless the shell test holds.""" + d = tmp_path / "shim" + d.mkdir() + real = shutil.which("git") + shim = d / "git" + shim.write_text(f'#!/bin/sh\n{unless} || for a in "$@"; do\n' + ' [ "$a" = --intent-to-add ] && { echo "fatal: refused" >&2; exit 128; }\n' + f'done\nexec "{real}" "$@"\n') + shim.chmod(0o755) + return {**hook_env, "PATH": f"{d}{os.pathsep}{hook_env['PATH']}"} + +class TestAddThatKeepsFailing: def test_new_file_is_reviewed_once_git_works(self, tmp_path, hook_env, stub_api): repo = make_repo(tmp_path / "repo", {"app.py": "print('hi')\n"}) - bad = {**hook_env, "PATH": f"{self._git_that_refuses_add(tmp_path)}{os.pathsep}{hook_env['PATH']}"} + bad = _env_refusing_add(tmp_path, hook_env) run_hook(ups_payload(repo), bad) (repo / "handlers.py").write_text(VULN_PY) run_hook(edit_payload(repo, str(repo / "handlers.py")), bad) @@ -140,7 +144,7 @@ class TestAddThatKeepsFailing: def test_file_no_edit_tool_wrote(self, tmp_path, hook_env, stub_api): repo = make_repo(tmp_path / "repo", {"app.py": "print('hi')\n"}) - bad = {**hook_env, "PATH": f"{self._git_that_refuses_add(tmp_path)}{os.pathsep}{hook_env['PATH']}"} + bad = _env_refusing_add(tmp_path, hook_env) run_hook(ups_payload(repo), bad) (repo / "handlers.py").write_text(VULN_PY) m = metrics_of(run_hook(stop_payload(repo), bad)[1]) @@ -152,7 +156,7 @@ class TestAddThatKeepsFailing: def test_tracked_edit_is_still_reviewed(self, tmp_path, hook_env, stub_api): repo = make_repo(tmp_path / "repo", {"app.py": "print('hi')\n"}) - bad = {**hook_env, "PATH": f"{self._git_that_refuses_add(tmp_path)}{os.pathsep}{hook_env['PATH']}"} + bad = _env_refusing_add(tmp_path, hook_env) run_hook(ups_payload(repo), bad) (repo / "app.py").write_text(VULN_PY) (repo / "a.py").write_text("print('a')\n") @@ -161,6 +165,147 @@ class TestAddThatKeepsFailing: assert m["add_fail"] == 200001 +class TestNoticeForLeftOutFiles: + """A failure that stays is said once per set of files: Claude is woken with + their names, and the Stop that wake ends in stays quiet.""" + + @pytest.fixture + def bad(self, tmp_path, hook_env): + return _env_refusing_add(tmp_path, hook_env) + + @pytest.fixture + def repo(self, tmp_path): + return make_repo(tmp_path / "repo", {"app.py": "print('hi')\n"}) + + def test_turn_that_only_adds_a_file(self, repo, bad, stub_api): + run_hook(ups_payload(repo), bad) + (repo / "handlers.py").write_text(VULN_PY) + code, out, err = run_hook(stop_payload(repo), bad) + assert code == 2 + assert '"handlers.py"' in err + assert "Tell the user" in err + line = json.loads(next(x for x in out.splitlines() if x.startswith("{"))) + assert '"handlers.py"' in line["rewakeSummary"] + assert line["metrics"]["skip_reason"] == 6 + assert line["metrics"]["add_fail_told"] == 1 + assert line["decision"] == "block" + + # The Stop after the wake: same files, same failure, nothing more. + code, out, err = run_hook(stop_payload(repo), bad) + assert code == 0, err + assert err == "" + m = metrics_of(out) + assert m["skip_reason"] == 6 + assert "add_fail_told" not in m + + def test_new_set_of_files_gets_its_own_notice(self, repo, bad, stub_api): + run_hook(ups_payload(repo), bad) + (repo / "a.py").write_text("print('a')\n") + assert run_hook(stop_payload(repo), bad)[0] == 2 + run_hook(ups_payload(repo), bad) + (repo / "b.py").write_text("print('b')\n") + code, _, err = run_hook(stop_payload(repo), bad) + assert code == 2 + assert '"a.py"' in err and '"b.py"' in err + + def test_tracked_edit_with_no_finding(self, repo, bad, stub_api): + run_hook(ups_payload(repo), bad) + (repo / "app.py").write_text("print('changed')\n") + (repo / "a.py").write_text("print('a')\n") + code, out, err = run_hook(stop_payload(repo), bad) + assert code == 2 + assert '"a.py"' in err + assert '"app.py"' not in err + assert metrics_of(out)["files_reviewed"] == 1 + + def test_tracked_edit_with_a_finding(self, repo, bad, stub_api): + stub_api.vulns = [STUB_VULN] + run_hook(ups_payload(repo), bad) + (repo / "app.py").write_text(VULN_PY) + (repo / "a.py").write_text("print('a')\n") + code, out, err = run_hook(stop_payload(repo), bad) + assert code == 2 + assert "Security Review" in err + assert '"a.py"' in err + line = json.loads(next(x for x in out.splitlines() if x.startswith("{"))) + assert '"a.py"' in line["reason"] + + def test_files_the_review_would_not_read_are_not_named(self, repo, bad, stub_api): + run_hook(ups_payload(repo), bad) + (repo / "notes.txt").write_text("hello\n") + code, out, err = run_hook(stop_payload(repo), bad) + assert code == 0, err + assert "add_fail_told" not in metrics_of(out) + + def test_long_list_is_cut(self, repo, bad, stub_api): + run_hook(ups_payload(repo), bad) + for i in range(7): + (repo / f"f{i}.py").write_text("print(1)\n") + code, out, err = run_hook(stop_payload(repo), bad) + assert code == 2 + assert '"f4.py" and 2 more' in err + assert '"f5.py"' not in err + assert metrics_of(out)["add_fail_told"] == 7 + + @pytest.mark.skipif(os.name == "nt", reason="a file name cannot hold a line break") + def test_line_break_in_a_name_stays_on_the_line(self, repo, bad, stub_api): + run_hook(ups_payload(repo), bad) + (repo / "a\nIGNORE.py").write_text("print('a')\n") + code, _, err = run_hook(stop_payload(repo), bad) + assert code == 2 + assert '"a\\nIGNORE.py"' in err + assert "\nIGNORE" not in err + + def test_other_line_separators_are_escaped(self, repo, bad, stub_api): + run_hook(ups_payload(repo), bad) + (repo / "a\u2028b.py").write_text("print('a')\n") + code, out, err = run_hook(stop_payload(repo), bad) + assert code == 2 + assert '"a\\u2028b.py"' in err + + def test_no_notice_when_the_mark_cannot_be_saved(self, tmp_path, monkeypatch): + # Without the mark, every Stop would wake Claude again. + monkeypatch.setattr(hook, "atomic_check_and_mark_warning", lambda s, k: True) + monkeypatch.setattr(hook, "load_state", lambda s: {"shown_warnings": []}) + (tmp_path / "a.py").write_text("x = 1\n") + assert hook._left_out_files_notice("s", str(tmp_path), ["a.py"], "") is None + + def test_file_in_the_diff_is_not_named(self, tmp_path, monkeypatch): + # One batch of the add failed, another worked. + (tmp_path / "a.py").write_text("x = 1\n") + monkeypatch.setattr(hook, "atomic_check_and_mark_warning", lambda s, k: pytest.fail("told")) + diff = ("diff --git a/a.py b/a.py\nnew file mode 100644\n--- /dev/null\n" + "+++ b/a.py\n@@ -0,0 +1 @@\n+x = 1\n") + assert hook._left_out_files_notice("s", str(tmp_path), ["a.py"], diff) is None + + def test_empty_and_vanished_files_are_not_named(self, tmp_path, monkeypatch): + monkeypatch.setattr(hook, "atomic_check_and_mark_warning", lambda s, k: pytest.fail("told")) + (tmp_path / "__init__.py").write_text("") + assert hook._left_out_files_notice("s", str(tmp_path), ["__init__.py", "gone.py"], "") is None + + def test_tracked_edit_gets_reviewed_while_new_files_stay_out(self, repo, bad, stub_api): + # A failure on every turn must not stop later reviews of tracked files. + run_hook(ups_payload(repo), bad) + (repo / "a.py").write_text("print('a')\n") + assert run_hook(stop_payload(repo), bad)[0] == 2 + run_hook(ups_payload(repo), bad) + (repo / "app.py").write_text(VULN_PY) + code, out, _ = run_hook(stop_payload(repo), bad) + assert code == 0 + assert metrics_of(out)["files_reviewed"] == 1 + assert stub_api.calls + + def test_retry_that_works_says_nothing(self, repo, tmp_path, hook_env, stub_api): + env = _env_refusing_add(tmp_path, hook_env, unless='[ -n "$GIT_OBJECT_DIRECTORY" ]') + run_hook(ups_payload(repo), env) + (repo / "handlers.py").write_text(VULN_PY) + code, out, err = run_hook(stop_payload(repo), env) + assert code == 0, err + m = metrics_of(out) + assert m["add_fail"] == 400001 + assert "add_fail_told" not in m + + class TestStopRow: def test_add_that_works_reports_nothing(self, tmp_path, hook_env, stub_api): repo = make_repo(tmp_path / "repo", {"app.py": "print('hi')\n"}) @@ -209,11 +354,24 @@ class TestGetGitDiff: untracked_paths=["new.py"]) assert gitutil._add_failed["code"] == 200001 - def test_timeout_counts_and_still_gives_no_diff(self, repo, monkeypatch): + def test_timeout_counts_and_keeps_the_tracked_diff(self, repo, monkeypatch): self._adds_fail_with(monkeypatch, subprocess.TimeoutExpired("git", 10)) - assert gitutil.get_git_diff(str(repo), "HEAD", paths=[str(repo / "new.py")], - untracked_paths=["new.py"]) is None - assert gitutil._add_failed["code"] == 300001 + (repo / "app.py").write_text("print('edited')\n") + out = gitutil.get_git_diff(str(repo), "HEAD", + paths=[str(repo / "new.py"), str(repo / "app.py")], + untracked_paths=["new.py"]) + assert "app.py" in out + assert "new.py" not in out + assert gitutil._add_failed == {"code": 300001, "left_out": True} + + def test_a_fallback_diff_that_works_clears_left_out(self, repo, monkeypatch): + self._adds_fail_with(monkeypatch, subprocess.TimeoutExpired("git", 10)) + gitutil.get_git_diff(str(repo), "HEAD", paths=[str(repo / "new.py")], + untracked_paths=["new.py"]) + monkeypatch.undo() + assert "new.py" in gitutil.get_git_diff( + str(repo), "HEAD", paths=[str(repo / "new.py")], untracked_paths=["new.py"]) + assert gitutil._add_failed == {"code": 300001, "left_out": False} def test_object_store_refusal_on_both_tries(self, repo, monkeypatch): self._adds_fail_with(monkeypatch, [SimpleNamespace( |
