diff options
| author | Mohamed Hegazy <mhegazy@anthropic.com> | 2026-10-27 20:20:27 +0000 |
|---|---|---|
| committer | Claude <noreply@anthropic.com> | 2026-10-27 20:20:27 +0000 |
| commit | 1280a036e8e4d44dfe81f9728f8dfa6917687195 (patch) | |
| tree | 4d9f110c7cd84fe5bc99908af154786d36853dfc /plugins | |
| parent | f8c5e7a1dcb71b10cb74586224b5401f3de5db28 (diff) | |
security-guidance: keep new files in the Stop review when git add -N fails
Retry the add with a private object directory for users who cannot write the object store. Drop the pathspec settings git refuses alongside literal pathspecs, which hid new files since 2.0.16. When a failure stays and nothing is reviewed, keep the files for a later turn.
Diffstat (limited to 'plugins')
| -rw-r--r-- | plugins/security-guidance/hooks/gitutil.py | 134 | ||||
| -rwxr-xr-x | plugins/security-guidance/hooks/security_reminder_hook.py | 13 | ||||
| -rw-r--r-- | plugins/security-guidance/tests/test_add_failure_metric.py | 203 |
3 files changed, 305 insertions, 45 deletions
diff --git a/plugins/security-guidance/hooks/gitutil.py b/plugins/security-guidance/hooks/gitutil.py index ec51e3c6..029fcb9d 100644 --- a/plugins/security-guidance/hooks/gitutil.py +++ b/plugins/security-guidance/hooks/gitutil.py @@ -295,13 +295,17 @@ _path_list_too_long = set() # A failed `git add --intent-to-add` during this hook run, for the Stop hook's # metrics: kind * 100000 + the paths the add was given. One number because a -# review row is near CC's key cap. A failed add leaves the new files out of the -# diff, so a turn that only added files looks like a turn with no changes; a -# timeout loses the whole diff. kind: 1 git could not write the empty blob to -# the object store, 2 any other git error, 3 timeout. A git that speaks another -# language counts as 2. +# review row is near CC's key cap. kind: 1 git could not write the empty blob +# to the object store and the retry failed too, 2 any other git error, 3 +# 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} +# Next to an index copy: where a retried `git add -N` stores the empty blob. +_OBJECTS_DIR_SUFFIX = ".objects" + def _too_many_args(e): """The OS refused to start the command because its arguments are too @@ -398,8 +402,9 @@ def _owner_is_gone(name): def _sweep_stale_indexes(dirpath, uid): - """Delete index copies in `dirpath` that a killed run left behind. Only - regular files owned by `uid` (None: no ownership check) are touched. + """Delete index copies in `dirpath` that a killed run left behind, and + their private object directories. Only regular files and directories owned + by `uid` (None: no ownership check) are touched. A copy goes as soon as the hook that made it is gone: a killed hook can leave one per run, and index-sized files fill a disk long before the age @@ -422,12 +427,16 @@ def _sweep_stale_indexes(dirpath, uid): p = os.path.join(dirpath, name) try: st = os.lstat(p) - if not stat.S_ISREG(st.st_mode): + is_dir = stat.S_ISDIR(st.st_mode) and name.endswith(_OBJECTS_DIR_SUFFIX) + if not (is_dir or stat.S_ISREG(st.st_mode)): continue if uid is not None and st.st_uid != uid: continue if max(st.st_mtime, st.st_ctime) < cutoff or _owner_is_gone(name): - os.unlink(p) + if is_dir: + _remove_objects_dir(p) + else: + os.unlink(p) if time.monotonic() > deadline: return except OSError: @@ -531,6 +540,22 @@ def _copy_slot(tmpdir, index_bytes=0): os.close(held) +def _remove_objects_dir(path): + """Remove a private object directory. git writes objects read-only, which + stops Windows from deleting them.""" + import shutil + import stat + + def writable_then_retry(func, p, _exc): + os.chmod(p, stat.S_IWRITE) + func(p) + + try: + shutil.rmtree(path, onerror=writable_then_retry) + except OSError: + pass + + def _remove_copy(tmp_index): """Remove an index copy and the files git wrote next to it.""" import glob @@ -539,6 +564,7 @@ def _remove_copy(tmp_index): os.unlink(p) except OSError: pass + _remove_objects_dir(tmp_index + _OBJECTS_DIR_SUFFIX) def remove_copies_on_termination(): @@ -599,6 +625,77 @@ 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) + + +def _env_with_private_objects(env, cwd, objects_dir): + """`env` for a git that writes objects to `objects_dir` and still reads + the repository's own, wherever git says they are (a linked worktree shares + them). A path holding the list separator is left out, since git would + split it; the add then fails only if it has to read an object.""" + out = {**env, "GIT_OBJECT_DIRECTORY": objects_dir} + try: + r = subprocess.run([*GIT_CMD, "rev-parse", "--git-path", "objects"], + cwd=cwd, capture_output=True, timeout=5, env=env) + except (subprocess.TimeoutExpired, OSError): + return out + own = os.path.join(cwd, os.fsdecode(r.stdout).strip()) + if r.returncode == 0 and os.pathsep not in own: + out["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = os.pathsep.join( + p for p in (own, env.get("GIT_ALTERNATE_OBJECT_DIRECTORIES")) if p) + return out + + +def _add_new_files(cwd, paths, env, tmp_index): + """`git add --intent-to-add` the untracked `paths` to the index copy `env` + names, so the diff shows them. The add has to store the empty blob, so a + user who cannot write the object store gets a second try that stores it in + a private directory next to the copy. Nothing needs that blob afterwards: + `git diff` reads these files from the work tree. `git stash create` would + fail on such an index, and only runs on a copy with nothing added. + + No stdout used here (only returncode matters), but text=True still spawns + reader threads that decode stderr — git error messages can reference + non-ASCII filenames and crash on cp1252. See #2099. Drop text=True so bytes + stay raw.""" + # The paths are file names, not patterns, for this git add only: an + # untracked file named `:(glob)**` must add only itself. git refuses that + # together with a glob or icase setting from the user's environment. + env = {k: v for k, v in env.items() + if k not in ("GIT_GLOB_PATHSPECS", "GIT_ICASE_PATHSPECS")} + env["GIT_LITERAL_PATHSPECS"] = "1" + + def add(add_env): + results = _run_git_on_review_paths( + ["add", "--intent-to-add"], paths, timeout=10, cwd=cwd, env=add_env) + return next((r for r in results if r.returncode != 0), None) + + try: + failed = add(env) + except subprocess.TimeoutExpired: + _note_add_failure(3, paths) + raise + 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) + 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')}") + except (subprocess.TimeoutExpired, OSError) as e: + debug_log(f"git add -N retry failed: {e}") + retry_failed = True + if retry_failed: + _note_add_failure(1 if b"empty blob" in failed.stderr else 2, paths) + else: + _note_add_failure(4, paths) + + @contextlib.contextmanager def _temp_index(cwd, untracked_paths=None): """Yield an env dict pointing GIT_INDEX_FILE at a throwaway copy of the @@ -685,24 +782,7 @@ def _copied_index(cwd, top, real_index, tmpdir, untracked_paths): else: add_args = None if add_args: - # No stdout used here (only returncode matters), but text=True - # still spawns reader threads that decode stderr — git error - # messages can reference non-ASCII filenames and crash on - # cp1252. See #2099. Drop text=True so bytes stay raw. - try: - results = _run_git_on_review_paths( - ["add", "--intent-to-add"], add_args, timeout=10, cwd=cwd, - # The paths are file names, not patterns, for this git add - # only: an untracked file named `:(glob)**` must add only - # itself. - env={**env, "GIT_LITERAL_PATHSPECS": "1"}) - except subprocess.TimeoutExpired: - _note_add_failure(3, add_args) - raise - failed = next((r for r in results if r.returncode != 0), None) - if failed: - _note_add_failure(1 if b"empty blob" in failed.stderr else 2, add_args) - debug_log(f"git add -N failed: {failed.stderr[:200].decode('utf-8', errors='replace')}") + _add_new_files(cwd, add_args, env, tmp_index) # A whole-tree add puts a nested repository back. if untracked_paths is None and not _drop_gitlinks(top, env, tmp_index): yield None diff --git a/plugins/security-guidance/hooks/security_reminder_hook.py b/plugins/security-guidance/hooks/security_reminder_hook.py index 3efe344e..232bc08b 100755 --- a/plugins/security-guidance/hooks/security_reminder_hook.py +++ b/plugins/security-guidance/hooks/security_reminder_hook.py @@ -2644,6 +2644,15 @@ def handle_stop_hook(input_data): if not baseline_sha: baseline_sha = "HEAD" + # New files a failed `git add -N` hid: when nothing gets reviewed they are + # 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() + if left_out: + touched_paths = list(touched_paths) + [ + os.path.join(repo_root, p) for p in untracked or ()] + if not diff_output or not diff_output.strip(): if "gave_up" in gitutil._path_list_too_long: debug_log("Stop hook: changed paths do not fit the git commands, skipping") @@ -2652,7 +2661,7 @@ def handle_stop_hook(input_data): debug_log("Stop hook: no source code files among the changed paths") _skip(7) debug_log("Stop hook: no changes since baseline") - _skip(6) + _skip(6, restore=left_out) diff_hash = hashlib.sha256(diff_output.encode("utf-8", "replace")).hexdigest() if snap.get("reviewed_diff_hash") == diff_hash: @@ -2663,7 +2672,7 @@ def handle_stop_hook(input_data): diff_files = parse_diff_into_files(diff_output) if not diff_files: debug_log("Stop hook: no source code files in diff") - _skip(7) + _skip(7, restore=left_out) # Mirror commit-review: hard-bail only on pathological diffs (>300 files, # usually a bad baseline), otherwise prioritize by security-risk path diff --git a/plugins/security-guidance/tests/test_add_failure_metric.py b/plugins/security-guidance/tests/test_add_failure_metric.py index 3a86a8ac..8e539e9b 100644 --- a/plugins/security-guidance/tests/test_add_failure_metric.py +++ b/plugins/security-guidance/tests/test_add_failure_metric.py @@ -1,6 +1,10 @@ -"""A failed `git add --intent-to-add` leaves new files out of the Stop review's -diff. The review goes on as before; the Stop row says that it happened.""" +"""`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.""" import os +import shutil import subprocess import tempfile from types import SimpleNamespace @@ -8,8 +12,8 @@ from types import SimpleNamespace import pytest from conftest import ( - GIT_ENV, VULN_PY, make_repo, metrics_of, run_hook, stop_payload, - ups_payload, + GIT_ENV, VULN_PY, edit_payload, git, make_repo, metrics_of, run_hook, + stop_payload, ups_payload, ) import gitutil @@ -43,15 +47,16 @@ class TestObjectStoreNotWritable: def test_turn_that_only_adds_a_file(self, tmp_path, hook_env, stub_api, read_only_objects): repo = make_repo(tmp_path / "repo", {"app.py": "print('hi')\n"}) read_only_objects(repo) + before = sorted(p for p in (repo / ".git" / "objects").rglob("*")) run_hook(ups_payload(repo), hook_env) (repo / "handlers.py").write_text(VULN_PY) m = metrics_of(run_hook(stop_payload(repo), hook_env)[1]) - assert m["skip_reason"] == 6, m - assert m["review_set_count"] == 1 - assert m["add_fail"] == 100001 - assert not stub_api.calls + assert m["files_reviewed"] == 1, m + assert m["add_fail"] == 400001 + assert stub_api.calls + assert sorted(p for p in (repo / ".git" / "objects").rglob("*")) == before - def test_tracked_edit_is_still_reviewed(self, tmp_path, hook_env, stub_api, read_only_objects): + def test_tracked_edit_and_new_files(self, tmp_path, hook_env, stub_api, read_only_objects): repo = make_repo(tmp_path / "repo", {"app.py": "print('hi')\n"}) read_only_objects(repo) run_hook(ups_payload(repo), hook_env) @@ -60,21 +65,103 @@ class TestObjectStoreNotWritable: (repo / "b.py").write_text("print('b')\n") m = metrics_of(run_hook(stop_payload(repo), hook_env)[1]) assert not m.get("skipped"), m - assert m["files_reviewed"] == 1 - assert m["add_fail"] == 100002 + assert m["files_reviewed"] == 3 + assert m["add_fail"] == 400002 + def test_linked_worktree_and_packed_repo(self, tmp_path, hook_env, stub_api, read_only_objects): + repo = make_repo(tmp_path / "repo", {"app.py": "print('hi')\n"}) + git(repo, "repack", "-adq") + wt = tmp_path / "wt" + git(repo, "worktree", "add", "-q", "-b", "side", str(wt)) + read_only_objects(repo) + run_hook(ups_payload(wt), hook_env) + (wt / "handlers.py").write_text(VULN_PY) + m = metrics_of(run_hook(stop_payload(wt), hook_env)[1]) + assert m["files_reviewed"] == 1, m + assert m["add_fail"] == 400001 -class TestStopRow: - def test_other_git_error(self, tmp_path, hook_env, stub_api): - # git refuses --literal-pathspecs together with a user's icase setting. + def test_private_directory_is_gone_afterwards(self, tmp_path, monkeypatch, read_only_objects): + d = tmp_path / "tmproot" + d.mkdir() + monkeypatch.setattr(tempfile, "tempdir", str(d)) + for k, v in GIT_ENV.items(): + monkeypatch.setenv(k, v) + repo = make_repo(tmp_path / "repo", {"app.py": "print('hi')\n"}) + read_only_objects(repo) + (repo / "new.py").write_text("print('new')\n") + out = gitutil.get_git_diff(str(repo), "HEAD", paths=[str(repo / "new.py")], + untracked_paths=["new.py"]) + gitutil._add_failed["code"] = 0 + assert "new.py" in out + assert not [p for p in d.rglob("*") if gitutil._TEMP_INDEX_PREFIX in p.name] + + +class TestPathspecSettings: + @pytest.mark.parametrize("name", ["GIT_ICASE_PATHSPECS", "GIT_GLOB_PATHSPECS"]) + def test_new_file_is_reviewed(self, tmp_path, hook_env, stub_api, name): + # git refuses --literal-pathspecs together with these two. repo = make_repo(tmp_path / "repo", {"app.py": "print('hi')\n"}) - env = {**hook_env, "GIT_ICASE_PATHSPECS": "1"} + env = {**hook_env, name: "1"} run_hook(ups_payload(repo), env) (repo / "handlers.py").write_text(VULN_PY) m = metrics_of(run_hook(stop_payload(repo), env)[1]) + assert m["files_reviewed"] == 1, m + assert "add_fail" not in m + + +@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 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']}"} + run_hook(ups_payload(repo), bad) + (repo / "handlers.py").write_text(VULN_PY) + run_hook(edit_payload(repo, str(repo / "handlers.py")), bad) + m = metrics_of(run_hook(stop_payload(repo), bad)[1]) + assert m["skip_reason"] == 6, m + assert m["add_fail"] == 200001 + assert not stub_api.calls + + run_hook(ups_payload(repo), hook_env) + m = metrics_of(run_hook(stop_payload(repo), hook_env)[1]) + assert m["files_reviewed"] == 1, m + assert stub_api.calls + + 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']}"} + run_hook(ups_payload(repo), bad) + (repo / "handlers.py").write_text(VULN_PY) + m = metrics_of(run_hook(stop_payload(repo), bad)[1]) assert m["skip_reason"] == 6, m + + run_hook(ups_payload(repo), hook_env) + m = metrics_of(run_hook(stop_payload(repo), hook_env)[1]) + assert m["files_reviewed"] == 1, m + + 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']}"} + run_hook(ups_payload(repo), bad) + (repo / "app.py").write_text(VULN_PY) + (repo / "a.py").write_text("print('a')\n") + m = metrics_of(run_hook(stop_payload(repo), bad)[1]) + assert m["files_reviewed"] == 1, m assert m["add_fail"] == 200001 + +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"}) run_hook(ups_payload(repo), hook_env) @@ -128,7 +215,7 @@ class TestGetGitDiff: untracked_paths=["new.py"]) is None assert gitutil._add_failed["code"] == 300001 - def test_object_store_refusal(self, repo, monkeypatch): + def test_object_store_refusal_on_both_tries(self, repo, monkeypatch): self._adds_fail_with(monkeypatch, [SimpleNamespace( returncode=128, stderr=b"fatal: cannot create an empty blob in the object database")]) @@ -136,8 +223,92 @@ class TestGetGitDiff: untracked_paths=["new.py"]) assert gitutil._add_failed["code"] == 100001 + def test_retry_reads_the_repositorys_objects_and_writes_elsewhere(self, repo, monkeypatch): + seen = [] + real = gitutil._run_git_on_review_paths + + def run(args, paths, timeout, **kwargs): + if args[0] != "add": + return real(args, paths, timeout, **kwargs) + seen.append(kwargs["env"]) + return real(args, paths, timeout, **kwargs) if len(seen) > 1 else [ + SimpleNamespace(returncode=128, stderr=b"nope")] + + monkeypatch.setattr(gitutil, "_run_git_on_review_paths", run) + out = gitutil.get_git_diff(str(repo), "HEAD", paths=[str(repo / "new.py")], + untracked_paths=["new.py"]) + assert "new.py" in out + assert "GIT_OBJECT_DIRECTORY" not in seen[0] + assert seen[1]["GIT_OBJECT_DIRECTORY"].endswith(".objects") + assert os.path.samefile(seen[1]["GIT_ALTERNATE_OBJECT_DIRECTORIES"], + repo / ".git" / "objects") + assert gitutil._add_failed["code"] == 400001 + + def test_retry_timeout_keeps_the_tracked_diff(self, repo, monkeypatch): + (repo / "app.py").write_text("print('changed')\n") + real = gitutil._run_git_on_review_paths + adds = [] + + def run(args, paths, timeout, **kwargs): + if args[0] != "add": + return real(args, paths, timeout, **kwargs) + adds.append(args) + if len(adds) > 1: + raise subprocess.TimeoutExpired("git", 10) + return [SimpleNamespace(returncode=128, stderr=b"fatal: nope")] + + monkeypatch.setattr(gitutil, "_run_git_on_review_paths", run) + out = gitutil.get_git_diff(str(repo), "HEAD", untracked_paths=["new.py"]) + assert "app.py" in out + assert gitutil._add_failed["code"] == 200001 + def test_a_later_add_that_works_keeps_the_failure(self, repo, monkeypatch): gitutil._add_failed["code"] = 300001 gitutil.get_git_diff(str(repo), "HEAD", paths=[str(repo / "new.py")], untracked_paths=["new.py"]) assert gitutil._add_failed["code"] == 300001 + + +class TestLeftovers: + def _private_dir(self, parent, name): + d = parent / name + (d / "e6").mkdir(parents=True) + blob = d / "e6" / "9de29" + blob.write_bytes(b"x") + blob.chmod(0o444) + return d + + def test_removed_with_its_copy(self, tmp_path): + copy = tmp_path / "security_hook_idx_pid1_abcdefgh" + copy.write_bytes(b"i") + self._private_dir(tmp_path, copy.name + ".objects") + gitutil._remove_copy(str(copy)) + assert not list(tmp_path.iterdir()) + + @pytest.mark.skipif(os.name == "nt", reason="no pid check on Windows") + def test_killed_hooks_directory_is_swept(self, tmp_path): + p = subprocess.Popen(["git", "--version"], stdout=subprocess.DEVNULL) + p.wait() + self._private_dir(tmp_path, f"security_hook_idx_pid{p.pid}_abcdefgh.objects") + gitutil._sweep_stale_indexes(str(tmp_path), None) + assert not list(tmp_path.iterdir()) + + def test_live_hooks_directory_stays(self, tmp_path): + self._private_dir(tmp_path, f"security_hook_idx_pid{os.getpid()}_abcdefgh.objects") + gitutil._sweep_stale_indexes(str(tmp_path), None) + assert list(tmp_path.iterdir()) + + def test_other_directories_stay(self, tmp_path): + (tmp_path / "security_hook_idx_pid1_abcdefgh.other").mkdir() + gitutil._sweep_stale_indexes(str(tmp_path), None) + assert list(tmp_path.iterdir()) + + @pytest.mark.skipif(os.name == "nt", reason="needs symlinks") + def test_link_at_the_private_directory_is_not_followed(self, tmp_path): + victim = tmp_path / "victim" + victim.mkdir() + (victim / "keep").write_text("x") + copy = tmp_path / "security_hook_idx_pid1_abcdefgh" + (tmp_path / (copy.name + ".objects")).symlink_to(victim) + gitutil._remove_copy(str(copy)) + assert (victim / "keep").exists() |
