diff options
| author | Claude <noreply@anthropic.com> | 2026-10-20 23:00:54 +0000 |
|---|---|---|
| committer | Claude <noreply@anthropic.com> | 2026-10-20 23:00:54 +0000 |
| commit | a00d13d77ba7bf13a9d2ae0db5f7e24aeb4b12b2 (patch) | |
| tree | 5f9de8c90afbf0397b32bd18926e071f4486fda5 /plugins/security-guidance/tests | |
| parent | beecef224291d252a87f58c5e83df28d15fe3450 (diff) | |
security-guidance: keep nested repositories out of the index copy
The hooks run `git stash create` (the turn baseline) and
`git add --intent-to-add` (untracked files) on a throwaway copy of the
index. A nested repository that the index records is a gitlink entry
there. `git stash create` takes no --ignore-submodules option and
`git add` reads the gitlinks its paths cover, so both started a second
git inside that directory.
Before anything runs on the copy, remove the gitlink entry of every
nested repository from the copy, never from the real index. If that
removal fails, do not use the copy at all: the baseline falls back to
HEAD and runs no stash create, and the diff reads the real index with
--ignore-submodules=all. A gitlink whose directory has no `.git` (a
submodule that is not checked out) stays; git starts nothing there.
Run the intent-to-add `git add` with literal pathspecs, in that one
call's environment only.
The index file is scanned for a gitlink's mode bytes first, so a
repository without one starts no extra git process.
Diffstat (limited to 'plugins/security-guidance/tests')
| -rw-r--r-- | plugins/security-guidance/tests/test_nested_repos.py | 265 |
1 files changed, 265 insertions, 0 deletions
diff --git a/plugins/security-guidance/tests/test_nested_repos.py b/plugins/security-guidance/tests/test_nested_repos.py index cb010018..574e5ef2 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) + import shutil + shutil.rmtree(nested) + 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() |
