summaryrefslogtreecommitdiff
path: root/plugins
diff options
context:
space:
mode:
authorMohamed Hegazy <mhegazy@anthropic.com>2026-10-05 09:53:54 -0700
committerMohamed Hegazy <mhegazy@anthropic.com>2026-10-05 09:53:54 -0700
commita22217bb450a6cc00d7a161566e7cc7d96dbf63a (patch)
treed805eb1ed3ec8a89ea6466bad1da7e8007bae3db /plugins
parentd182ca456ca09d31d139f7d3818d1d333b103cce (diff)
security-guidance: leave nothing behind when git is killed (2.0.9 → 2.0.10)mhegazy/sg-temp-index-cleanup
With a very large git index the hook's git calls hit their time limits and are killed, so git cannot clean up. Each kill could leave an index-sized file in the temp directory, index.stash.<pid> files in .git, and a dead .git/index.lock that fails the user's next git add or commit. - `git stash create` and the work-tree diff run on a throwaway index copy. - Every git the hook spawns gets GIT_OPTIONAL_LOCKS=0. - Copies live in a private per-user folder and are removed together with the files git writes next to them. - Leftovers older than 30 minutes are swept, including existing ones. Co-Authored-By: Claude <noreply@anthropic.com>
Diffstat (limited to 'plugins')
-rw-r--r--plugins/security-guidance/.claude-plugin/plugin.json2
-rw-r--r--plugins/security-guidance/hooks/diffstate.py26
-rw-r--r--plugins/security-guidance/hooks/gitutil.py117
-rw-r--r--plugins/security-guidance/tests/test_git_index_locks.py288
-rw-r--r--plugins/security-guidance/tests/test_temp_index_cleanup.py166
5 files changed, 583 insertions, 16 deletions
diff --git a/plugins/security-guidance/.claude-plugin/plugin.json b/plugins/security-guidance/.claude-plugin/plugin.json
index 375e65a0..6ee520df 100644
--- a/plugins/security-guidance/.claude-plugin/plugin.json
+++ b/plugins/security-guidance/.claude-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "security-guidance",
- "version": "2.0.9",
+ "version": "2.0.10",
"description": "Security review for Claude-generated code. Pattern-based warnings on edits, LLM-powered diff review on Stop, and an agentic commit reviewer that catches injection, XSS, SSRF, hardcoded secrets, and 25+ other vulnerability classes.",
"author": {
"name": "David Dworken",
diff --git a/plugins/security-guidance/hooks/diffstate.py b/plugins/security-guidance/hooks/diffstate.py
index 8d0665dd..be839212 100644
--- a/plugins/security-guidance/hooks/diffstate.py
+++ b/plugins/security-guidance/hooks/diffstate.py
@@ -13,7 +13,7 @@ from _base import debug_log, _PV
from gitutil import (
GIT_CMD,
_git_dir, _git_toplevel, _git_status_porcelain,
- _git_rev_parse_head, _is_ancestor, _git_name_only,
+ _git_rev_parse_head, _is_ancestor, _git_name_only, _temp_index,
)
from session_state import with_locked_state
@@ -188,6 +188,13 @@ def capture_git_baseline(cwd):
Falls back to HEAD if the working tree is clean.
Returns the SHA string, or None if not in a git repo or if the repo has no commits.
+ `stash create` runs on a throwaway copy of the index (GIT_INDEX_FILE), so
+ its `index.lock` and `index.stash.<pid>` files land next to the copy, not
+ in `.git`: it cannot collide with a concurrent git command, and a timeout
+ kill cannot leave a lock that blocks the user's next one.
+ GIT_OPTIONAL_LOCKS does not cover stash. Copying the real index without a
+ lock is safe: git replaces it by atomic rename.
+
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
@@ -209,11 +216,16 @@ def capture_git_baseline(cwd):
debug_log("No commits in repo, skipping baseline capture")
return None
- result = subprocess.run(
- [*GIT_CMD, "stash", "create"],
- cwd=cwd, capture_output=True, timeout=15
- )
- sha = (result.stdout or b"").decode("utf-8", errors="replace").strip()
+ sha = ""
+ # untracked_paths=[]: a plain copy of the index, no `add -N` pass.
+ with _temp_index(cwd, untracked_paths=[]) as env:
+ # env is None when there is no index file to copy: treat as clean.
+ if env is not None:
+ result = subprocess.run(
+ [*GIT_CMD, "stash", "create"],
+ cwd=cwd, capture_output=True, timeout=15, env=env
+ )
+ sha = (result.stdout or b"").decode("utf-8", errors="replace").strip()
if sha:
return sha
@@ -450,7 +462,7 @@ def compute_v2_review_set(cwd, baseline_sha, head_at_capture, untracked_at_basel
dirty_now |= _git_name_only(repo, f"{head_at_capture}..HEAD") or set()
diff_base = head_at_capture
- # changed_since: tracked files vs the stash baseline (no temp index — the
+ # changed_since: tracked files vs the stash baseline (no `add -N` — the
# stash never contained untracked files anyway), then union with
# currently-untracked. The previous `include_untracked=True` arm cost a
# full `git add -N .` (slow in large repos) per call to surface
diff --git a/plugins/security-guidance/hooks/gitutil.py b/plugins/security-guidance/hooks/gitutil.py
index b6e8cd54..726f2ba1 100644
--- a/plugins/security-guidance/hooks/gitutil.py
+++ b/plugins/security-guidance/hooks/gitutil.py
@@ -44,6 +44,13 @@ SAFE_GIT_CONFIG = (
("core.hooksPath", "/dev/null"),
)
+# The hook's git runs in the background beside the session's own git. Without
+# this, `git status` holds .git/index.lock while it writes back a refreshed
+# index: a concurrent `git add` fails, and a timeout kill leaves the lock.
+SAFE_GIT_ENV = {
+ "GIT_OPTIONAL_LOCKS": "0",
+}
+
def git_config_env(pairs, base=None):
base = os.environ if base is None else base
@@ -61,6 +68,7 @@ def git_config_env(pairs, base=None):
def apply_safe_git_env():
os.environ.update(git_config_env(SAFE_GIT_CONFIG))
+ os.environ.update(SAFE_GIT_ENV)
def _git_rev_parse_head(cwd):
@@ -131,6 +139,85 @@ def _diff_pathspec(cwd, paths):
return ["--"] + rel if rel else []
+_TEMP_INDEX_PREFIX = "security_hook_idx_"
+# A live copy is in use for under a minute (a couple of bounded git calls), so
+# anything this old belongs to a run that was killed.
+_TEMP_INDEX_STALE_S = 1800
+# Unlinking index-sized files is slow; a large backlog drains over several
+# calls instead of stalling one hook past its timeout.
+_SWEEP_BUDGET_S = 2
+
+
+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.
+
+ Age is the newer of mtime and ctime: a copy keeps .git/index's mtime,
+ which may be days old, so mtime alone would delete a file that another
+ running hook is still using."""
+ import stat
+ import time
+ cutoff = time.time() - _TEMP_INDEX_STALE_S
+ deadline = time.monotonic() + _SWEEP_BUDGET_S
+ try:
+ names = os.listdir(dirpath)
+ except OSError:
+ return
+ for name in names:
+ if not name.startswith(_TEMP_INDEX_PREFIX):
+ continue
+ p = os.path.join(dirpath, name)
+ try:
+ st = os.lstat(p)
+ if not 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:
+ os.unlink(p)
+ if time.monotonic() > deadline:
+ return
+ except OSError:
+ pass
+
+
+def _hook_tmpdir():
+ """Private per-user directory for throwaway index copies, or None to use
+ the bare temp dir.
+
+ An index copy can be hundreds of MB and a killed hook cannot clean up, so
+ copies live in one 0700 directory and anything stale is swept on entry,
+ here and in the bare temp dir. The name is predictable and the temp dir
+ may be shared, so anything that is not a real directory we own is
+ refused. Windows has no uid and its temp dir is already per-user."""
+ import stat
+ import tempfile
+ base = tempfile.gettempdir()
+ uid = os.getuid() if hasattr(os, "getuid") else None
+ _sweep_stale_indexes(base, uid)
+ if uid is None:
+ return None
+ d = os.path.join(base, f"claude-security-guidance-{uid}")
+ try:
+ os.mkdir(d, 0o700)
+ except FileExistsError:
+ pass
+ except OSError:
+ return None
+ try:
+ st = os.lstat(d)
+ except OSError:
+ return None
+ if not stat.S_ISDIR(st.st_mode) or st.st_uid != uid:
+ return None
+ try:
+ os.chmod(d, 0o700)
+ except OSError:
+ pass
+ _sweep_stale_indexes(d, uid)
+ return d
+
+
@contextlib.contextmanager
def _temp_index(cwd, untracked_paths=None):
"""Yield an env dict pointing GIT_INDEX_FILE at a throwaway copy of the
@@ -143,7 +230,12 @@ def _temp_index(cwd, untracked_paths=None):
in untracked count). The default `add -N .` stats every file in the
worktree — slow in large repos vs fast targeted scan. v2 callers
already know the untracked set from `git status --porcelain`, so they
- pass it; v1 keeps the whole-tree scan since it has no prior list."""
+ pass it; v1 keeps the whole-tree scan since it has no prior list.
+
+ Cleanup removes `<tmp_index>*`, not just the copy: git writes
+ `<index>.lock` and `<index>.stash.<pid>` next to the index it is given and
+ cannot remove them itself when a subprocess timeout kills it."""
+ import glob
import shutil
import tempfile
@@ -152,9 +244,14 @@ def _temp_index(cwd, untracked_paths=None):
yield None
return
- tmp_fd, tmp_index = tempfile.mkstemp(prefix="security_hook_idx_")
+ tmp_fd, tmp_index = tempfile.mkstemp(prefix=_TEMP_INDEX_PREFIX,
+ dir=_hook_tmpdir())
os.close(tmp_fd)
try:
+ # copy2, not copyfile: the copy must keep .git/index's mtime. Git
+ # re-reads any file whose mtime is not older than the index file's;
+ # with a fresh mtime it would miss a same-size edit made in the same
+ # second as the last index write.
shutil.copy2(real_index, tmp_index)
env = {**os.environ, "GIT_INDEX_FILE": tmp_index}
if untracked_paths is None:
@@ -182,10 +279,11 @@ def _temp_index(cwd, untracked_paths=None):
)
yield env
finally:
- try:
- os.unlink(tmp_index)
- except OSError:
- pass
+ for p in glob.glob(glob.escape(tmp_index) + "*"):
+ try:
+ os.unlink(p)
+ except OSError:
+ pass
def _git_toplevel(cwd):
@@ -400,9 +498,12 @@ def _git_name_only(cwd, base, include_untracked=False):
return {p for p in stdout.split("\0") if p}
try:
- if not include_untracked:
+ # A work-tree diff rewrites the index under <index>.lock when entries
+ # are stat-stale (mtime changed, content same), GIT_OPTIONAL_LOCKS or
+ # not, so it runs on a throwaway copy; an a..b range never opens it.
+ if not include_untracked and ".." in base:
return _run(None)
- with _temp_index(cwd) as env:
+ with _temp_index(cwd, None if include_untracked else []) as env:
return _run(env)
except (subprocess.TimeoutExpired, FileNotFoundError, OSError, ValueError) as e:
debug_log(f"_git_name_only({base!r}) error: {e}")
diff --git a/plugins/security-guidance/tests/test_git_index_locks.py b/plugins/security-guidance/tests/test_git_index_locks.py
new file mode 100644
index 00000000..e35855d0
--- /dev/null
+++ b/plugins/security-guidance/tests/test_git_index_locks.py
@@ -0,0 +1,288 @@
+import os
+import shutil
+import subprocess
+import tempfile
+import time
+
+import pytest
+
+from conftest import (
+ GIT_ENV, VULN_PY, commit_file, bash_payload, edit_payload, git, make_repo,
+ metrics_of, run_hook, stop_payload, ups_payload,
+)
+
+import diffstate
+import gitutil
+
+
+@pytest.fixture
+def tmproot(tmp_path, monkeypatch):
+ """A temp dir of our own, and the environment restored afterwards
+ (apply_safe_git_env writes to os.environ)."""
+ d = tmp_path / "tmproot"
+ d.mkdir()
+ monkeypatch.setattr(tempfile, "tempdir", str(d))
+ saved = dict(os.environ)
+ os.environ.update(GIT_ENV)
+ yield d
+ os.environ.clear()
+ os.environ.update(saved)
+
+
+def _leftovers(root):
+ return sorted(
+ os.path.join(dirpath, f)
+ for dirpath, _, files in os.walk(root) for f in files
+ )
+
+
+def _index_copies_left(root):
+ """Index copies and the files git writes next to them. The whole hook may
+ also start the detached SDK bootstrap, which uses the temp dir too."""
+ return [p for p in _leftovers(root)
+ if os.path.basename(p).startswith(gitutil._TEMP_INDEX_PREFIX)]
+
+
+def _index_litter(git_dir):
+ return sorted(n for n in os.listdir(git_dir) if n.startswith("index") and n != "index")
+
+
+def _index_sig(git_dir):
+ st = os.stat(os.path.join(git_dir, "index"))
+ return (st.st_ino, st.st_mtime_ns, st.st_size)
+
+
+def _make_stat_stale(path):
+ """Move a tracked file's mtime, content unchanged: a stat mismatch that
+ git would normally write back to the index it read."""
+ t = os.stat(path).st_mtime + 2
+ os.utime(path, (t, t))
+
+
+def _is_stash_create(args):
+ return list(args[-2:]) == ["stash", "create"]
+
+
+class TestBaselineCapture:
+ def test_stash_create_gets_a_throwaway_index(self, tmp_path, tmproot, monkeypatch):
+ repo = make_repo(tmp_path / "repo", {"app.py": "x = 1\n"})
+ (repo / "app.py").write_text("x = 2\n")
+ before = _index_sig(repo / ".git")
+ seen = []
+ real_run = subprocess.run
+
+ def spy(args, **kw):
+ if _is_stash_create(args):
+ seen.append(kw["env"]["GIT_INDEX_FILE"])
+ return real_run(args, **kw)
+
+ monkeypatch.setattr(subprocess, "run", spy)
+ assert diffstate.capture_git_baseline(str(repo))
+ assert len(seen) == 1
+ assert os.path.realpath(seen[0]).startswith(os.path.realpath(tmproot) + os.sep)
+ assert _index_sig(repo / ".git") == before
+ assert _index_litter(repo / ".git") == []
+ assert _leftovers(tmproot) == []
+
+ def test_killed_stash_create_leaves_nothing(self, tmp_path, tmproot, monkeypatch):
+ repo = make_repo(tmp_path / "repo", {"app.py": "x = 1\n"})
+ (repo / "app.py").write_text("x = 2\n")
+ real_run = subprocess.run
+
+ def killed(args, **kw):
+ if _is_stash_create(args):
+ idx = kw["env"]["GIT_INDEX_FILE"]
+ for suffix in (".lock", ".stash.4242", ".stash.4242.lock"):
+ with open(idx + suffix, "wb") as f:
+ f.write(b"partial")
+ raise subprocess.TimeoutExpired(args, kw["timeout"])
+ return real_run(args, **kw)
+
+ monkeypatch.setattr(subprocess, "run", killed)
+ assert diffstate.capture_git_baseline(str(repo)) is None
+ assert _index_litter(repo / ".git") == []
+ assert _leftovers(tmproot) == []
+
+ def test_succeeds_while_index_lock_exists(self, tmp_path, tmproot):
+ repo = make_repo(tmp_path / "repo", {"app.py": "x = 1\n"})
+ (repo / "app.py").write_text("x = 2\n")
+ head = git(repo, "rev-parse", "HEAD").strip()
+ (repo / ".git" / "index.lock").touch()
+ sha = diffstate.capture_git_baseline(str(repo))
+ assert sha and sha != head
+ assert git(repo, "show", f"{sha}:app.py") == "x = 2\n"
+ assert _index_litter(repo / ".git") == ["index.lock"]
+
+ def test_dirty_tree_matches_a_plain_stash_create(self, tmp_path, tmproot):
+ repo = make_repo(tmp_path / "repo", {"app.py": "x = 1\n"})
+ (repo / "app.py").write_text("staged\n")
+ git(repo, "add", "app.py")
+ (repo / "app.py").write_text("staged\nunstaged\n")
+ gitutil.apply_safe_git_env()
+ ours = diffstate.capture_git_baseline(str(repo))
+ plain = git(repo, "stash", "create").strip()
+ assert git(repo, "show", f"{ours}:app.py") == "staged\nunstaged\n"
+ assert (git(repo, "rev-parse", f"{ours}^{{tree}}")
+ == git(repo, "rev-parse", f"{plain}^{{tree}}"))
+
+ def test_clean_tree_returns_head(self, tmp_path, tmproot):
+ repo = make_repo(tmp_path / "repo")
+ head = git(repo, "rev-parse", "HEAD").strip()
+ assert diffstate.capture_git_baseline(str(repo)) == head
+
+ def test_missing_index_returns_head(self, tmp_path, tmproot):
+ repo = make_repo(tmp_path / "repo")
+ head = git(repo, "rev-parse", "HEAD").strip()
+ (repo / ".git" / "index").unlink()
+ assert diffstate.capture_git_baseline(str(repo)) == head
+ assert _index_litter(repo / ".git") == []
+
+ def test_linked_worktree_uses_its_own_index(self, tmp_path, tmproot):
+ repo = make_repo(tmp_path / "repo", {"app.py": "x = 1\n"})
+ wt = tmp_path / "wt"
+ git(repo, "worktree", "add", "-q", "-b", "side", str(wt))
+ assert (wt / ".git").is_file()
+ wt_git_dir = repo / ".git" / "worktrees" / "wt"
+ (wt / "app.py").write_text("x = 3\n")
+ (wt_git_dir / "index.lock").touch()
+ sha = diffstate.capture_git_baseline(str(wt))
+ assert git(wt, "show", f"{sha}:app.py") == "x = 3\n"
+ assert _index_litter(wt_git_dir) == ["index.lock"]
+ assert _index_litter(repo / ".git") == []
+ assert _leftovers(tmproot) == []
+
+
+class TestRacilyCleanEdit:
+ def test_same_size_edit_in_the_second_the_index_was_written(self, tmp_path, tmproot):
+ """Every stat field git caches still matches, so git only notices by
+ comparing the file's mtime with the index file's own mtime."""
+ repo = make_repo(tmp_path / "repo", {"app.py": "x = 1\n"})
+ git(repo, "config", "core.trustctime", "false")
+ then = int(time.time()) - 100
+ os.utime(repo / "app.py", (then, then))
+ git(repo, "update-index", "--refresh")
+ (repo / "app.py").write_text("x = 2\n")
+ os.utime(repo / "app.py", (then, then))
+ os.utime(repo / ".git" / "index", (then, then))
+ gitutil.apply_safe_git_env()
+ sha = diffstate.capture_git_baseline(str(repo))
+ assert git(repo, "show", f"{sha}:app.py") == "x = 2\n"
+ assert gitutil._git_name_only(str(repo), "HEAD") == {"app.py"}
+ assert "+x = 2" in gitutil.get_git_diff(str(repo), "HEAD", untracked_paths=[])
+
+
+class TestReadOnlyGitLeavesTheRealIndexAlone:
+ def test_env_carries_optional_locks_off(self, tmp_path, tmproot):
+ repo = make_repo(tmp_path / "repo")
+ os.environ.pop("GIT_OPTIONAL_LOCKS", None)
+ gitutil.apply_safe_git_env()
+ assert os.environ["GIT_OPTIONAL_LOCKS"] == "0"
+ with gitutil._temp_index(str(repo), untracked_paths=[]) as env:
+ assert env["GIT_OPTIONAL_LOCKS"] == "0"
+
+ def test_status(self, tmp_path, tmproot):
+ repo = make_repo(tmp_path / "repo", {"app.py": "x = 1\n"})
+ (repo / "new.py").write_text("n = 1\n")
+ _make_stat_stale(repo / "app.py")
+ before = _index_sig(repo / ".git")
+ gitutil.apply_safe_git_env()
+ assert gitutil._git_status_porcelain(str(repo)) == (set(), {"new.py"})
+ assert _index_sig(repo / ".git") == before
+
+ def test_work_tree_diff(self, tmp_path, tmproot):
+ repo = make_repo(tmp_path / "repo", {"app.py": "x = 1\n", "b.py": "b = 1\n"})
+ (repo / "b.py").write_text("b = 2\n")
+ _make_stat_stale(repo / "app.py")
+ before = _index_sig(repo / ".git")
+ gitutil.apply_safe_git_env()
+ assert gitutil._git_name_only(str(repo), "HEAD") == {"b.py"}
+ assert _index_sig(repo / ".git") == before
+ assert _leftovers(tmproot) == []
+
+ def test_range_diff_needs_no_index_copy(self, tmp_path, tmproot, monkeypatch):
+ repo = make_repo(tmp_path / "repo", {"app.py": "x = 1\n"})
+ first = git(repo, "rev-parse", "HEAD").strip()
+ commit_file(repo, "app.py", "x = 2\n")
+
+ def no_copy(*a, **kw):
+ raise AssertionError("range diff copied the index")
+
+ monkeypatch.setattr(gitutil, "_temp_index", no_copy)
+ assert gitutil._git_name_only(str(repo), f"{first}..HEAD") == {"app.py"}
+
+
+@pytest.mark.skipif(os.name == "nt", reason="uses a /bin/sh git shim")
+class TestWholeHook:
+ def _shim(self, tmp_path, hook_env):
+ """Put a logging `git` first on PATH; returns (env, read_log)."""
+ real_git = shutil.which("git")
+ bindir = tmp_path / "bin"
+ bindir.mkdir()
+ log = tmp_path / "git.log"
+ shim = bindir / "git"
+ shim.write_text(
+ "#!/bin/sh\n"
+ f'printf "%s\\t%s\\t%s\\n" "$GIT_OPTIONAL_LOCKS" "$GIT_INDEX_FILE" "$*" >> "{log}"\n'
+ f'exec "{real_git}" "$@"\n'
+ )
+ shim.chmod(0o755)
+ tmproot = tmp_path / "tmproot"
+ tmproot.mkdir()
+ env = dict(hook_env)
+ env.pop("GIT_OPTIONAL_LOCKS", None)
+ env["PATH"] = f"{bindir}{os.pathsep}{env['PATH']}"
+ env["TMPDIR"] = str(tmproot)
+
+ prefix = " ".join(gitutil.GIT_CMD[1:]) + " "
+
+ def read_log():
+ """[(optional_locks, index_file, [subcommand, *args])] per call."""
+ calls = []
+ for ln in log.read_text().splitlines():
+ locks, index_file, argv = ln.split("\t", 2)
+ if argv.startswith(prefix):
+ argv = argv[len(prefix):]
+ calls.append((locks, index_file, argv.split()))
+ return calls
+
+ return env, tmproot, read_log
+
+ def test_every_git_call_of_a_turn(self, tmp_path, hook_env, stub_api):
+ repo = make_repo(tmp_path / "repo", {"app.py": "x = 1\n", "wip.py": "w = 1\n"})
+ env, tmproot, read_log = self._shim(tmp_path, hook_env)
+ (repo / "wip.py").write_text("w = 2\n")
+ _make_stat_stale(repo / "app.py")
+ before = _index_sig(repo / ".git")
+
+ run_hook(ups_payload(repo), env)
+ (repo / "app.py").write_text(VULN_PY)
+ (repo / "new.py").write_text(VULN_PY)
+ run_hook(edit_payload(repo, repo / "app.py", VULN_PY), env)
+ run_hook(edit_payload(repo, repo / "new.py", VULN_PY), env)
+ rc, so, se = run_hook(stop_payload(repo), env)
+ m = metrics_of(so)
+ assert m.get("skip_reason") is None and m["files_reviewed"] == 2, m
+
+ calls = read_log()
+ assert {"stash", "status", "diff", "add"} <= {sub[0] for _, _, sub in calls}
+ assert [c for c in calls if c[0] != "0"] == []
+ for _, index_file, sub in calls:
+ if sub[0] in ("stash", "add") or (
+ sub[0] == "diff" and not any(".." in a for a in sub)):
+ assert index_file.startswith(str(tmproot)), sub
+ assert _index_sig(repo / ".git") == before
+ assert _index_litter(repo / ".git") == []
+ assert _index_copies_left(tmproot) == []
+
+ def test_every_git_call_of_a_commit_review(self, tmp_path, hook_env, stub_api):
+ repo = make_repo(tmp_path / "repo", {"app.py": "x = 1\n"})
+ env, tmproot, read_log = self._shim(tmp_path, hook_env)
+ sha, out = commit_file(repo, "app.py", VULN_PY)
+ before = _index_sig(repo / ".git")
+ rc, so, se = run_hook(bash_payload(repo, "git commit -m change", stdout=out), env)
+ assert metrics_of(so).get("skip_reason") is None
+ calls = read_log()
+ assert calls and [c for c in calls if c[0] != "0"] == []
+ assert _index_sig(repo / ".git") == before
+ assert _index_litter(repo / ".git") == []
+ assert _index_copies_left(tmproot) == []
diff --git a/plugins/security-guidance/tests/test_temp_index_cleanup.py b/plugins/security-guidance/tests/test_temp_index_cleanup.py
new file mode 100644
index 00000000..f85a0bb2
--- /dev/null
+++ b/plugins/security-guidance/tests/test_temp_index_cleanup.py
@@ -0,0 +1,166 @@
+import os
+import stat
+import tempfile
+import time
+
+import pytest
+
+from conftest import GIT_ENV, make_repo
+
+import gitutil
+
+posix_only = pytest.mark.skipif(not hasattr(os, "getuid"), reason="needs a uid")
+
+
+@pytest.fixture
+def tmproot(tmp_path, monkeypatch):
+ """A temp dir of our own, so nothing here reads or sweeps the real one."""
+ d = tmp_path / "tmproot"
+ d.mkdir()
+ monkeypatch.setattr(tempfile, "tempdir", str(d))
+ for k, v in GIT_ENV.items():
+ monkeypatch.setenv(k, v)
+ return d
+
+
+def _leftovers(root):
+ return sorted(
+ os.path.join(dirpath, f)
+ for dirpath, _, files in os.walk(root) for f in files
+ )
+
+
+def _write(path):
+ with open(path, "w") as f:
+ f.write("x")
+ return path
+
+
+def _advance_clock(monkeypatch, seconds):
+ """ctime cannot be set, so files are aged by moving the clock instead."""
+ real = time.time
+ monkeypatch.setattr(time, "time", lambda: real() + seconds)
+
+
+class TestTempIndex:
+ @posix_only
+ def test_copy_lives_in_private_dir_and_is_removed(self, tmp_path, tmproot):
+ repo = make_repo(tmp_path / "repo")
+ with gitutil._temp_index(str(repo), untracked_paths=[]) as env:
+ idx = env["GIT_INDEX_FILE"]
+ private = tmproot / f"claude-security-guidance-{os.getuid()}"
+ assert os.path.dirname(idx) == str(private)
+ assert stat.S_IMODE(os.lstat(private).st_mode) == 0o700
+ assert os.path.isfile(idx)
+ assert _leftovers(tmproot) == []
+
+ def test_cleanup_removes_what_a_killed_git_leaves(self, tmp_path, tmproot):
+ repo = make_repo(tmp_path / "repo")
+ with gitutil._temp_index(str(repo), untracked_paths=[]) as env:
+ for suffix in (".lock", ".stash.12345", ".stash.12345.lock"):
+ _write(env["GIT_INDEX_FILE"] + suffix)
+ assert _leftovers(tmproot) == []
+
+ def test_cleanup_when_body_raises(self, tmp_path, tmproot):
+ repo = make_repo(tmp_path / "repo")
+ with pytest.raises(RuntimeError):
+ with gitutil._temp_index(str(repo), untracked_paths=[]):
+ raise RuntimeError("boom")
+ assert _leftovers(tmproot) == []
+
+ def test_live_copy_keeps_index_mtime_and_survives_a_sweep(self, tmp_path, tmproot):
+ repo = make_repo(tmp_path / "repo")
+ old = int(time.time()) - 7200
+ os.utime(repo / ".git" / "index", (old, old))
+ with gitutil._temp_index(str(repo), untracked_paths=[]) as env:
+ assert int(os.stat(env["GIT_INDEX_FILE"]).st_mtime) == old
+ gitutil._hook_tmpdir()
+ assert os.path.isfile(env["GIT_INDEX_FILE"])
+
+
+class TestSweep:
+ @posix_only
+ def test_reclaims_stale_files_in_both_dirs(self, tmproot, monkeypatch):
+ private = gitutil._hook_tmpdir()
+ stale = [
+ _write(os.path.join(d, name))
+ for d in (private, str(tmproot))
+ for name in ("security_hook_idx_dead", "security_hook_idx_dead.lock")
+ ]
+ _advance_clock(monkeypatch, 3600)
+ keep = [
+ _write(os.path.join(private, "security_hook_idx_live")),
+ _write(os.path.join(str(tmproot), "security_hook_idx_live")),
+ ]
+ for p in keep:
+ os.utime(p, (time.time(), time.time()))
+ keep.append(_write(os.path.join(str(tmproot), "unrelated")))
+ gitutil._hook_tmpdir()
+ assert [p for p in stale if os.path.exists(p)] == []
+ assert [p for p in keep if not os.path.exists(p)] == []
+
+ def test_backdated_mtime_alone_is_not_stale(self, tmproot):
+ p = _write(str(tmproot / "security_hook_idx_copy2"))
+ old = time.time() - 7200
+ os.utime(p, (old, old))
+ gitutil._hook_tmpdir()
+ assert os.path.exists(p)
+
+ @posix_only
+ def test_only_our_own_regular_files(self, tmproot, monkeypatch):
+ target = _write(str(tmproot / "target"))
+ os.symlink(target, tmproot / "security_hook_idx_link")
+ (tmproot / "security_hook_idx_dir").mkdir()
+ mine = _write(str(tmproot / "security_hook_idx_mine"))
+ _advance_clock(monkeypatch, 3600)
+ gitutil._sweep_stale_indexes(str(tmproot), os.getuid() + 1)
+ assert os.path.exists(mine)
+ gitutil._sweep_stale_indexes(str(tmproot), os.getuid())
+ assert not os.path.exists(mine)
+ assert os.path.lexists(tmproot / "security_hook_idx_link")
+ assert os.path.exists(target)
+ assert (tmproot / "security_hook_idx_dir").is_dir()
+
+ def test_large_backlog_is_drained_in_slices(self, tmproot, monkeypatch):
+ for i in range(3):
+ _write(str(tmproot / f"security_hook_idx_{i}"))
+ _advance_clock(monkeypatch, 3600)
+ monkeypatch.setattr(gitutil, "_SWEEP_BUDGET_S", -1)
+ gitutil._sweep_stale_indexes(str(tmproot), None)
+ assert len(_leftovers(tmproot)) == 2
+
+
+class TestPrivateDir:
+ @posix_only
+ def test_refuses_symlink_or_file_at_the_predictable_path(self, tmp_path, tmproot):
+ repo = make_repo(tmp_path / "repo")
+ predictable = tmproot / f"claude-security-guidance-{os.getuid()}"
+ elsewhere = tmp_path / "elsewhere"
+ elsewhere.mkdir()
+ os.symlink(elsewhere, predictable)
+ assert gitutil._hook_tmpdir() is None
+ with gitutil._temp_index(str(repo), untracked_paths=[]) as env:
+ assert os.path.dirname(env["GIT_INDEX_FILE"]) == str(tmproot)
+ assert list(elsewhere.iterdir()) == []
+ predictable.unlink()
+ predictable.write_text("")
+ assert gitutil._hook_tmpdir() is None
+
+ @posix_only
+ def test_refuses_a_directory_owned_by_someone_else(self, tmproot, monkeypatch):
+ uid = os.getuid()
+ (tmproot / f"claude-security-guidance-{uid + 1}").mkdir()
+ monkeypatch.setattr(os, "getuid", lambda: uid + 1)
+ assert gitutil._hook_tmpdir() is None
+
+ def test_without_getuid_uses_and_sweeps_the_bare_temp_dir(
+ self, tmp_path, tmproot, monkeypatch):
+ repo = make_repo(tmp_path / "repo")
+ monkeypatch.delattr(os, "getuid", raising=False)
+ stale = _write(str(tmproot / "security_hook_idx_dead"))
+ _advance_clock(monkeypatch, 3600)
+ assert gitutil._hook_tmpdir() is None
+ assert not os.path.exists(stale)
+ with gitutil._temp_index(str(repo), untracked_paths=[]) as env:
+ assert os.path.dirname(env["GIT_INDEX_FILE"]) == str(tmproot)
+ assert _leftovers(tmproot) == []