diff options
| author | Mohamed Hegazy <8000722+mhegazy@users.noreply.github.com> | 2026-10-21 16:58:27 -0700 |
|---|---|---|
| committer | GitHub <noreply@github.com> | 2026-10-21 16:58:27 -0700 |
| commit | 234c3a4a443e3aa79dfe9ac86e931d50fc43e6da (patch) | |
| tree | 032ac8b77aa59a23ce5aa6a456db41256baa1180 /plugins | |
| parent | d1adba47161a271799de7b548225d929310046bd (diff) | |
| parent | 2de59fe9d850775f9f516180d144becd4db2c3da (diff) | |
Merge pull request #6837 from anthropics/mhegazy/sg-index-copy-gitlinks
security-guidance: keep nested repositories out of the index copy
Diffstat (limited to 'plugins')
| -rw-r--r-- | plugins/security-guidance/hooks/diffstate.py | 3 | ||||
| -rw-r--r-- | plugins/security-guidance/hooks/gitutil.py | 192 | ||||
| -rw-r--r-- | plugins/security-guidance/tests/test_nested_repos.py | 265 |
3 files changed, 448 insertions, 12 deletions
diff --git a/plugins/security-guidance/hooks/diffstate.py b/plugins/security-guidance/hooks/diffstate.py index 9ebb2b1b..6532fb6c 100644 --- a/plugins/security-guidance/hooks/diffstate.py +++ b/plugins/security-guidance/hooks/diffstate.py @@ -366,7 +366,8 @@ def capture_git_baseline(cwd): 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. + # env is None when no usable index copy could be made: fall + # back to HEAD. if env is not None: result = subprocess.run( [*GIT_CMD, "stash", "create"], diff --git a/plugins/security-guidance/hooks/gitutil.py b/plugins/security-guidance/hooks/gitutil.py index d72f3fcf..73d7c611 100644 --- a/plugins/security-guidance/hooks/gitutil.py +++ b/plugins/security-guidance/hooks/gitutil.py @@ -57,9 +57,9 @@ GIT_CMD = [ # vendored checkout, an unpacked archive) is another repository with its # own config. To report it as modified, or to show its changes inline # (diff.submodule=diff), git starts a second git inside it, which reads - # that config and runs the commands it names. The hook stays out of it: - # such a directory is left out of the review set, and a commit that moves - # one shows as the two commit ids. + # that config and runs the commands it names. Such a directory is left + # out of the review set, and so is a commit that moves one. See also + # _drop_gitlinks for the commands that take no such setting. "-c", "diff.ignoreSubmodules=all", "-c", "diff.submodule=short", ] @@ -150,6 +150,35 @@ def _find_git_index(cwd): return None +def _find_git_index_and_top(cwd): + """_find_git_index plus the work tree's top directory, from one git + call. (None, None) when either is missing: no index file, a bare + repository, or a `cwd` inside the git directory.""" + try: + result = subprocess.run( + [*GIT_CMD, "rev-parse", "--git-dir", "--show-toplevel"], + cwd=cwd, capture_output=True, timeout=5 + ) + if result.returncode != 0: + return None, None + # Paths as bytes from git: decode by hand (see _find_git_index). + out = result.stdout.decode("utf-8", errors="replace") + parts = out[:-1].split("\n") if out.endswith("\n") else [] + if len(parts) != 2 or not all(parts): + # A newline in one of the paths: ask for them one at a time. + index_path, top = _find_git_index(cwd), _git_toplevel(cwd) + return (index_path, top) if index_path and top else (None, None) + git_dir, top = parts + if not os.path.isabs(git_dir): + git_dir = os.path.join(cwd, git_dir) + index_path = os.path.join(git_dir, "index") + if not os.path.isfile(index_path): + return None, None + return index_path, top + except (subprocess.TimeoutExpired, FileNotFoundError, OSError): + return None, None + + def _diff_pathspec(cwd, paths): """Convert absolute touched-paths to repo-relative pathspec args for git diff. Paths outside cwd (e.g. ~/.claude/…) are dropped. Returns the @@ -518,9 +547,11 @@ def _temp_index(cwd, untracked_paths=None): """Yield an env dict pointing GIT_INDEX_FILE at a throwaway copy of the repo's index with `git add --intent-to-add` applied, so untracked files show up in subsequent `git diff` calls without touching the user's real - index. Yields None if no index can be found (bare repo / not a repo) or - no copy slot came free; the caller should fall back to a plain diff. - Always cleans up the temp file. + index. The copy has no gitlink entry for a nested repository (see + _drop_gitlinks). Yields None if no index can be found (bare repo / not a + repo), no copy slot came free, or those entries could not be removed. + Callers then go on without the copy: the diff reads the real index, and + the baseline falls back to HEAD. Always cleans up the temp file. Perf: when `untracked_paths` is given, only those paths are added (O(n) in untracked count). The default `add -N .` stats every file in the @@ -531,7 +562,7 @@ def _temp_index(cwd, untracked_paths=None): 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.""" - real_index = _find_git_index(cwd) + real_index, top = _find_git_index_and_top(cwd) if not real_index: yield None return @@ -547,12 +578,12 @@ def _temp_index(cwd, untracked_paths=None): debug_log("no index copy slot came free; going without a copy") yield None return - with _copied_index(cwd, real_index, tmpdir, untracked_paths) as env: + with _copied_index(cwd, top, real_index, tmpdir, untracked_paths) as env: yield env @contextlib.contextmanager -def _copied_index(cwd, real_index, tmpdir, untracked_paths): +def _copied_index(cwd, top, real_index, tmpdir, untracked_paths): import shutil import tempfile @@ -574,6 +605,12 @@ def _copied_index(cwd, real_index, tmpdir, untracked_paths): except (OSError, NotImplementedError, AttributeError): shutil.copy2(real_index, tmp_index) env = {**os.environ, "GIT_INDEX_FILE": tmp_index} + # Before `git add` runs, since add reads the gitlinks its paths cover. + if not _drop_gitlinks(top, env, tmp_index): + debug_log("could not remove gitlinks from the index copy; going on " + "without the copy") + yield None + return if untracked_paths is None: add_args = ["."] elif untracked_paths: @@ -595,14 +632,147 @@ def _copied_index(cwd, real_index, tmpdir, untracked_paths): # 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. - _run_git_on_review_paths(["add", "--intent-to-add"], add_args, - timeout=10, cwd=cwd, env=env) + _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"}) + # A whole-tree add puts a nested repository back. + if untracked_paths is None and not _drop_gitlinks(top, env, tmp_index): + yield None + return yield env finally: _remove_copy(tmp_index) _live_copies.discard(tmp_index) +# An index entry stores its mode as four bytes; this is a gitlink's. +_GITLINK_MODE = b"\x00\x00\xe0\x00" +# Signature of the index extension that says most entries are in a second, +# shared file (core.splitIndex). +_SPLIT_INDEX_EXT = b"link" + + +def _may_have_gitlinks(index_path): + """False only when the index file at `index_path` cannot hold a gitlink + entry: neither a gitlink's mode bytes nor the split-index signature occur + anywhere in it. Either can occur by chance (in an object id, a file + size, a path), so True means "list the entries and see". Most + repositories have no gitlink, and for them this saves a git process on + every index copy.""" + keep = max(len(_GITLINK_MODE), len(_SPLIT_INDEX_EXT)) - 1 + try: + with open(index_path, "rb") as f: + tail = b"" + while True: + chunk = f.read(1 << 20) + if not chunk: + return False + data = tail + chunk + if _GITLINK_MODE in data or _SPLIT_INDEX_EXT in data: + return True + tail = data[-keep:] + except OSError: + return True + + +_GITLINK_LIST_TIMEOUT = 10 +# `git ls-files --sparse` (git 2.35) lists a sparse index as it is stored; +# without it git first expands the index to every path in the repository. +# Set to False once this git has refused the option. +_ls_files_sparse = True + + +def _gitlink_paths(top, env): + """Paths (bytes, relative to `top`) of the gitlink entries, at any depth, + in the index `env` names. None if they could not be listed. The listing + is read as it comes, so a large index costs time but not memory.""" + global _ls_files_sparse + cmd = [*GIT_CMD, "ls-files", "-s", "-z"] + (["--sparse"] if _ls_files_sparse else []) + p = subprocess.Popen(cmd, cwd=top, stdout=subprocess.PIPE, + stderr=subprocess.DEVNULL, env=env) + killer = threading.Timer(_GITLINK_LIST_TIMEOUT, p.kill) + killer.daemon = True + found = set() + tail = b"" + try: + killer.start() + while True: + chunk = p.stdout.read1(65536) + if not chunk: + break + data = tail + chunk + end = data.rfind(b"\0") + 1 + # "<mode> <object> <stage>\t<path>", NUL-terminated. Most chunks + # have no gitlink and are not split up. + if b"160000 " in data: + for rec in data[:end].split(b"\0"): + if rec.startswith(b"160000 "): + found.add(rec.split(b"\t", 1)[1]) + tail = data[end:] + rc = p.wait() + finally: + killer.cancel() + if p.poll() is None: + p.kill() + p.wait() + p.stdout.close() + if rc == 129 and _ls_files_sparse: + # Usage error: a git without --sparse. + _ls_files_sparse = False + return _gitlink_paths(top, env) + if rc != 0: + debug_log(f"git ls-files on the index copy failed (rc={rc})") + return None + return found + + +def _drop_gitlinks(top, env, tmp_index): + """Remove the gitlink (mode 160000) entry of every nested repository from + the index copy that `env` names, never from the real index, before + anything else runs on the copy. A gitlink marks a directory that is, or + can be, another repository (see diff.ignoreSubmodules in GIT_CMD): + `git stash create` takes no flag like IGNORE_SUBMODULES, and `git add` + reads the gitlinks its paths cover. An entry whose directory has no + `.git` stays: git starts nothing there, and without the entry an older + `git stash create` fails on the empty directory. `top` is the work + tree's top directory. Returns True on success, False on any failure; the + copy must not be used then.""" + try: + if not _may_have_gitlinks(tmp_index): + return True + gitlinks = _gitlink_paths(top, env) + if gitlinks is None: + return False + top_b = os.fsencode(top) + nested = sorted(p for p in gitlinks + if os.path.lexists(os.path.join(top_b, p, b".git"))) + if not nested: + return True + mtime_ns = os.stat(tmp_index).st_mtime_ns + # git writes a new file and renames it over the copy, so a copy that + # is a hard link to the real index leaves the real one as it was. + rm = subprocess.run( + [*GIT_CMD, "update-index", "--force-remove", "-z", "--stdin"], + cwd=top, input=b"".join(p + b"\0" for p in nested), + capture_output=True, timeout=10, env=env) + if rm.returncode != 0: + debug_log(f"git update-index on the index copy failed (rc={rm.returncode}): " + f"{rm.stderr[:200].decode('utf-8', errors='replace')}") + return False + # Keep the mtime the copy came with; see _copied_index. + os.utime(tmp_index, ns=(mtime_ns, mtime_ns)) + debug_log(f"gitlink entries (nested repositories) removed from the " + f"index copy: {len(nested)}; their contents are not reviewed") + return True + except (subprocess.TimeoutExpired, OSError, RuntimeError, ValueError) as e: + # RuntimeError: the timer thread could not start. + debug_log(f"removing gitlinks from the index copy failed: {e}") + return False + + def _git_toplevel(cwd): """Absolute repo root for `cwd`, or None if not in a work tree.""" try: diff --git a/plugins/security-guidance/tests/test_nested_repos.py b/plugins/security-guidance/tests/test_nested_repos.py index cb010018..3c93a580 100644 --- a/plugins/security-guidance/tests/test_nested_repos.py +++ b/plugins/security-guidance/tests/test_nested_repos.py @@ -9,6 +9,7 @@ from conftest import ( stop_payload, ups_payload, ) +import diffstate import gitutil @@ -160,3 +161,267 @@ def test_commit_range_diff_does_not_enter_nested_repo(outer, marker, git_env, tm assert not ext_marker.exists() and not marker.exists() assert "lib.py" not in (out or "") + + +def _record_during_turn(outer, marker, commit): + _add_nested_repo(outer, "vendor/pkg", marker) + (outer / "app.py").write_text(VULN_PY) + git(outer, "add", "-A") + if commit: + git(outer, "commit", "-q", "-m", "wip") + marker.unlink(missing_ok=True) # only what the hooks run counts + + +@pytest.mark.parametrize("finding", [False, True], ids=["no-finding", "finding"]) +@pytest.mark.parametrize("commit", [False, True], ids=["staged", "committed"]) +def test_nested_repo_recorded_during_the_turn_filter_not_run( + outer, marker, hook_env, stub_api, commit, finding): + stub_api.vulns = [STUB_VULN] if finding else [] + ran_at = [] + + def hook(name, payload): + rc, out, err = run_hook(payload, hook_env) + # 2 is a Stop that hands a finding back. + assert rc == (2 if finding and name.startswith("stop") else 0), (name, out, err) + if marker.exists(): + ran_at.append(name) + marker.unlink() + + hook("prompt 1", ups_payload(outer)) + _record_during_turn(outer, marker, commit) + hook("stop 1", stop_payload(outer)) + hook("prompt 2", ups_payload(outer)) + (outer / "app.py").write_text(VULN_PY + "# one more edit\n") + hook("stop 2", stop_payload(outer)) + hook("prompt 3", ups_payload(outer)) + + assert ran_at == [] + assert stub_api.calls # the turn's own edit is still reviewed + + +@pytest.mark.skipif(os.name == "nt", reason="'*' is not allowed in Windows file names") +@pytest.mark.parametrize("commit", [False, True], ids=["staged", "committed"]) +def test_glob_shaped_file_name_beside_recorded_nested_repo( + outer, marker, hook_env, stub_api, commit): + assert run_hook(ups_payload(outer), hook_env)[0] == 0 + _record_during_turn(outer, marker, commit) + (outer / "vendor" / "p*").write_text("x = 1\n") + (outer / "new.py").write_text(VULN_PY) + + rc, out, err = run_hook(stop_payload(outer), hook_env) + + assert not marker.exists(), marker.read_text() + assert stub_api.calls, (rc, out, err) + + +def _index_copies(): + return [f for _, _, files in os.walk(tempfile.gettempdir()) for f in files + if f.startswith(gitutil._TEMP_INDEX_PREFIX)] + + +def _index_entries(repo, env=None): + return subprocess.run( + ["git", "ls-files", "-s"], cwd=repo, capture_output=True, text=True, + env=env, check=True, + ).stdout + + +@pytest.mark.parametrize("subdir", ["", "src"]) +def test_index_copy_has_no_gitlinks_and_real_index_is_unchanged( + outer, marker, git_env, subdir): + (outer / "src").mkdir() + (outer / "src" / "a.py").write_text("x = 1\n") + _add_nested_repo(outer, "src/third party/dep", marker) + _record_nested_repo(outer, marker) + real = outer / ".git" / "index" + before = (real.read_bytes(), real.stat().st_mtime_ns) + + with gitutil._temp_index(str(outer / subdir), untracked_paths=[]) as env: + assert env is not None + assert len(_index_copies()) == 1 + copy = _index_entries(outer, env) + copy_mtime = os.stat(env["GIT_INDEX_FILE"]).st_mtime_ns + + assert "160000" not in copy + assert "app.py" in copy and "src/a.py" in copy + assert copy_mtime == before[1] + assert (real.read_bytes(), real.stat().st_mtime_ns) == before + assert _index_entries(outer).count("160000") == 2 + assert not marker.exists() + + +def test_baseline_and_diff_with_recorded_nested_repo(outer, marker, git_env): + nested = _record_nested_repo(outer, marker) + (nested / "lib.py").write_text("print('abc')\n") + (outer / "app.py").write_text(VULN_PY) + (outer / "new.py").write_text("x = 1\n") + + baseline = diffstate.capture_git_baseline(str(outer)) + diff = gitutil.get_git_diff(str(outer), "HEAD", untracked_paths=["new.py"]) + since = gitutil.get_git_diff(str(outer), baseline, untracked_paths=["new.py"]) + # The snapshot has no entry for the nested repository; the real index does. + tracked_since = gitutil.get_git_diff(str(outer), baseline, untracked_paths=[]) + names_since = gitutil._git_name_only(str(outer), baseline) + + # The baseline is a snapshot with the edit in it, not HEAD. + assert baseline and baseline != git(outer, "rev-parse", "HEAD").strip() + assert "app.py" in diff and "new.py" in diff and "vendor/pkg" not in diff + assert "new.py" in since and "app.py" not in since and "vendor/pkg" not in since + assert tracked_since == "" and "vendor/pkg" not in names_since + assert not marker.exists() + + +def test_whole_tree_index_copy_with_recorded_nested_repo(outer, marker, git_env): + nested = _record_nested_repo(outer, marker) + (nested / "lib.py").write_text("print('abc')\n") + (outer / "new.py").write_text("x = 1\n") + + with gitutil._temp_index(str(outer)) as env: + assert env is not None + copy = _index_entries(outer, env) + + assert "new.py" in copy and "160000" not in copy + assert not marker.exists() + + +def test_no_index_copy_when_gitlinks_cannot_be_removed( + outer, marker, git_env, monkeypatch): + _record_nested_repo(outer, marker) + (outer / "app.py").write_text(VULN_PY) + real_run = subprocess.run + + def run(cmd, *a, **kw): + if "update-index" in cmd: + return subprocess.CompletedProcess(cmd, 1, b"", b"no") + return real_run(cmd, *a, **kw) + + monkeypatch.setattr(gitutil.subprocess, "run", run) + + with gitutil._temp_index(str(outer), untracked_paths=[]) as env: + assert env is None + # Without the copy the baseline is HEAD. + assert diffstate.capture_git_baseline(str(outer)) == git(outer, "rev-parse", "HEAD").strip() + assert diffstate.last_baseline_fail == 2 + assert not marker.exists() + assert _index_copies() == [] + + +@pytest.mark.skipif(os.name == "nt", reason="':' and '*' are not allowed in Windows file names") +def test_untracked_file_name_is_not_read_as_a_pattern(outer, git_env): + name = ":(glob)**" + (outer / name).write_text("x = 1\n") + (outer / "other.py").write_text("x = 2\n") + + with gitutil._temp_index(str(outer), [name]) as env: + copy = _index_entries(outer, env) + + assert name in copy and "other.py" not in copy + + +def test_gitlink_without_a_repository_stays_in_the_copy(outer, marker, git_env): + """A submodule that is not checked out: an empty directory.""" + nested = _record_nested_repo(outer, marker) + # Moved, not deleted: git's object files are read-only on Windows. + nested.rename(outer.parent / "moved-away") + nested.mkdir() + (outer / "app.py").write_text(VULN_PY) + + with gitutil._temp_index(str(outer), untracked_paths=[]) as env: + copy = _index_entries(outer, env) + baseline = diffstate.capture_git_baseline(str(outer)) + + assert "160000" in copy + assert baseline and baseline != git(outer, "rev-parse", "HEAD").strip() + assert diffstate.last_baseline_fail == 0 + + +def test_gitlinks_listed_by_a_git_without_sparse_listing(outer, marker, git_env, monkeypatch): + _record_nested_repo(outer, marker) + real_popen = subprocess.Popen + seen = [] + + def popen(cmd, *a, **kw): + if "ls-files" in cmd and "-z" in cmd: # the plugin's own listing + seen.append("--sparse" in cmd) + if "--sparse" in cmd: + cmd = [*gitutil.GIT_CMD, "ls-files", "--no-such-option"] + return real_popen(cmd, *a, **kw) + + monkeypatch.setattr(gitutil.subprocess, "Popen", popen) + monkeypatch.setattr(gitutil, "_ls_files_sparse", True) + + for _ in range(2): + with gitutil._temp_index(str(outer), untracked_paths=[]) as env: + assert "160000" not in _index_entries(outer, env) + + assert seen == [True, False, False] + + +def test_no_index_copy_when_the_listing_cannot_be_watched(outer, marker, git_env, monkeypatch): + _record_nested_repo(outer, marker) + + def no_thread(self): + raise RuntimeError("can't start new thread") + + monkeypatch.setattr(gitutil.threading.Timer, "start", no_thread) + + with gitutil._temp_index(str(outer), untracked_paths=[]) as env: + assert env is None + assert _index_copies() == [] + + +def _listings(monkeypatch): + """Counts the plugin's own `git ls-files` runs.""" + real_popen = subprocess.Popen + seen = [] + + def popen(cmd, *a, **kw): + if "ls-files" in cmd and "-z" in cmd: + seen.append(cmd) + return real_popen(cmd, *a, **kw) + + monkeypatch.setattr(gitutil.subprocess, "Popen", popen) + return seen + + +def test_index_without_gitlinks_is_not_listed(outer, git_env, monkeypatch): + for i in range(300): + (outer / f"f{i}.py").write_text(f"x = {i}\n") + git(outer, "add", "-A") + seen = _listings(monkeypatch) + + with gitutil._temp_index(str(outer), untracked_paths=[]) as env: + assert env is not None + + assert seen == [] + + +@pytest.mark.parametrize("setup", [ + [], + [("config", "index.version", "4")], + [("config", "core.splitIndex", "true")], + [("config", "feature.manyFiles", "true")], +], ids=["default", "index-v4", "split-index", "many-files"]) +def test_gitlink_found_in_every_index_format(outer, marker, git_env, monkeypatch, setup): + for args in setup: + git(outer, *args) + for i in range(50): + (outer / f"f{i}.py").write_text(f"x = {i}\n") + git(outer, "add", "-A") + git(outer, "commit", "-q", "-m", "files") + nested = _record_nested_repo(outer, marker) + # One more index write after the gitlink went in. + (outer / "later.py").write_text("x = 1\n") + git(outer, "add", "later.py") + marker.unlink(missing_ok=True) + (nested / "lib.py").write_text("print('abc')\n") + (outer / "app.py").write_text(VULN_PY) + seen = _listings(monkeypatch) + + with gitutil._temp_index(str(outer), untracked_paths=[]) as env: + copy = _index_entries(outer, env) + baseline = diffstate.capture_git_baseline(str(outer)) + + assert seen and "160000" not in copy and "later.py" in copy + assert baseline != git(outer, "rev-parse", "HEAD").strip() + assert not marker.exists() |
