summaryrefslogtreecommitdiff
path: root/plugins
diff options
context:
space:
mode:
authorClaude <noreply@anthropic.com>2026-10-19 17:36:13 +0000
committerClaude <noreply@anthropic.com>2026-10-19 17:36:13 +0000
commit7a151516fa58fd0160bacaf8fb5966931170bb9c (patch)
treead809bb2b1b65b4210c6ea3821ed30e1ae7a150a /plugins
parentd4c95aa95d02188aac37f6b435dadaccde46d1f9 (diff)
security-guidance: stay out of repositories nested in the work treemhegazy/sg-nested-repos
A directory with its own .git inside the work tree (a submodule, a vendored checkout, an unpacked archive) was added to the throwaway index as a submodule entry, and git then started a second git inside it to see whether it had changed. Nothing in such a directory is reviewed. git status and work-tree git diff now ignore submodule entries, an untracked nested repository is no longer listed as a changed file or added to the index copy, and a commit that moves a submodule is always shown as its two commit ids.
Diffstat (limited to 'plugins')
-rw-r--r--plugins/security-guidance/hooks/gitutil.py32
-rw-r--r--plugins/security-guidance/tests/test_nested_repos.py162
2 files changed, 189 insertions, 5 deletions
diff --git a/plugins/security-guidance/hooks/gitutil.py b/plugins/security-guidance/hooks/gitutil.py
index bc4d753b..28ded7d4 100644
--- a/plugins/security-guidance/hooks/gitutil.py
+++ b/plugins/security-guidance/hooks/gitutil.py
@@ -48,11 +48,27 @@ GIT_CMD = [
"-c", "diff.noprefix=false",
"-c", "diff.srcPrefix=a/",
"-c", "diff.dstPrefix=b/",
+ # A directory with its own `.git` inside the work tree (a submodule, a
+ # 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.
+ "-c", "diff.ignoreSubmodules=all",
+ "-c", "diff.submodule=short",
]
+# diff.ignoreSubmodules is a default that the repository's own settings for
+# one submodule (.gitmodules, submodule.<name>.ignore) override. The option
+# cannot be overridden. Pass it to every `git status` and work-tree `git diff`.
+IGNORE_SUBMODULES = "--ignore-submodules=all"
+
SAFE_GIT_CONFIG = (
("core.fsmonitor", "false"),
("core.hooksPath", "/dev/null"),
+ ("diff.ignoreSubmodules", "all"),
+ ("diff.submodule", "short"),
)
# The hook's git runs in the background beside the session's own git. Without
@@ -448,8 +464,11 @@ def _copied_index(cwd, real_index, tmpdir, untracked_paths):
# `git status` and here would silently drop ALL untracked files
# from the diff. --ignore-missing only works with --dry-run, so
# filter to surviving paths (lexists so dangling symlinks count).
+ # A nested repository (`dir/`) would be added as a submodule
+ # entry; see diff.ignoreSubmodules in GIT_CMD.
surviving = [p for p in untracked_paths
- if os.path.lexists(os.path.join(cwd, p))]
+ if not p.endswith("/")
+ and os.path.lexists(os.path.join(cwd, p))]
add_args = ["--"] + surviving if surviving else None
else:
add_args = None
@@ -673,7 +692,7 @@ def _git_name_only(cwd, base, include_untracked=False):
def _run(env):
# core.quotePath=false comes from GIT_CMD globally (see definition).
result = subprocess.run(
- [*GIT_CMD, "diff", "--name-only", "-z", base],
+ [*GIT_CMD, "diff", IGNORE_SUBMODULES, "--name-only", "-z", base],
cwd=cwd, capture_output=True, timeout=30,
env=env,
)
@@ -714,7 +733,7 @@ def _git_status_porcelain(cwd):
try:
# core.quotePath=false comes from GIT_CMD globally (see definition).
r = subprocess.run(
- [*GIT_CMD, "status", "--porcelain=v1", "-uall", "-z"],
+ [*GIT_CMD, "status", IGNORE_SUBMODULES, "--porcelain=v1", "-uall", "-z"],
cwd=cwd, capture_output=True, timeout=30,
)
if r.returncode != 0:
@@ -732,7 +751,10 @@ def _git_status_porcelain(cwd):
continue
xy, path = e[:2], e[3:]
if xy == "??":
- untracked.add(path)
+ # With -uall only a nested repository is listed as `dir/`.
+ # It is not a file to review; see diff.ignoreSubmodules.
+ if not path.endswith("/"):
+ untracked.add(path)
else:
tracked.add(path)
# Rename/copy entries are XY old\0new\0 — second NUL field is
@@ -791,7 +813,7 @@ def get_git_diff(cwd, baseline_sha, full_context=False, paths=None, untracked_pa
return ""
# core.quotePath=false comes from GIT_CMD globally (see definition).
- cmd = [*GIT_CMD, "diff", "--no-color", "--no-ext-diff", "--no-textconv", baseline_sha] + (["--unified=99999"] if full_context else []) + pathspec
+ cmd = [*GIT_CMD, "diff", IGNORE_SUBMODULES, "--no-color", "--no-ext-diff", "--no-textconv", baseline_sha] + (["--unified=99999"] if full_context else []) + pathspec
try:
if untracked_paths is not None and not untracked_paths:
# Nothing to `add -N`, and the diff only reads the index.
diff --git a/plugins/security-guidance/tests/test_nested_repos.py b/plugins/security-guidance/tests/test_nested_repos.py
new file mode 100644
index 00000000..cb010018
--- /dev/null
+++ b/plugins/security-guidance/tests/test_nested_repos.py
@@ -0,0 +1,162 @@
+import os
+import subprocess
+import tempfile
+
+import pytest
+
+from conftest import (
+ GIT_ENV, STUB_VULN, VULN_PY, git, make_repo, metrics_of, run_hook,
+ stop_payload, ups_payload,
+)
+
+import gitutil
+
+
+def _add_nested_repo(parent, rel, marker):
+ """A directory with its own `.git` whose config names a filter command,
+ the way an unpacked archive or a vendored checkout can. The command leaves
+ a line in `marker` each time git runs it."""
+ nested = make_repo(parent / rel, {
+ "lib.py": "print('one')\n",
+ ".gitattributes": "* filter=probe\n",
+ })
+ git(nested, "config", "filter.probe.clean",
+ f"sh -c 'echo ran >> \"{marker.as_posix()}\"; cat'")
+ # Same size, so git has to read the file to tell whether it changed.
+ (nested / "lib.py").write_text("print('two')\n")
+ old = os.stat(nested / ".git" / "index").st_mtime - 3600
+ os.utime(nested / ".git" / "index", (old, old))
+ return nested
+
+
+@pytest.fixture
+def outer(tmp_path):
+ return make_repo(tmp_path / "outer", {"app.py": "print('hi')\n"})
+
+
+@pytest.fixture
+def marker(tmp_path):
+ return tmp_path / "filter-ran"
+
+
+def _turn(repo, hook_env, stub_api, during):
+ stub_api.vulns = [STUB_VULN]
+ assert run_hook(ups_payload(repo), hook_env)[0] == 0
+ during()
+ return run_hook(stop_payload(repo), hook_env)
+
+
+def test_untracked_nested_repo_filter_not_run(outer, marker, hook_env, stub_api):
+ def during():
+ _add_nested_repo(outer, "vendor/pkg", marker)
+ (outer / "app.py").write_text(VULN_PY)
+
+ rc, out, err = _turn(outer, hook_env, stub_api, during)
+
+ assert not marker.exists(), marker.read_text()
+ # The turn's own edit is still reviewed.
+ assert stub_api.calls, (rc, out, err)
+ assert "app.py" in out + err
+
+
+def test_untracked_nested_repo_alone_is_not_reviewed(outer, marker, hook_env, stub_api):
+ rc, out, err = _turn(
+ outer, hook_env, stub_api,
+ lambda: _add_nested_repo(outer, "vendor/pkg", marker))
+
+ assert not marker.exists(), marker.read_text()
+ assert not stub_api.calls
+ assert (metrics_of(out) or {}).get("skipped") is True
+
+
+@pytest.fixture
+def git_env(tmp_path, monkeypatch):
+ """For calling gitutil in this process: a temp dir of our own, and the
+ environment restored afterwards."""
+ d = tmp_path / "tmproot"
+ d.mkdir()
+ monkeypatch.setattr(tempfile, "tempdir", str(d))
+ saved = dict(os.environ)
+ os.environ.update(GIT_ENV)
+ yield
+ os.environ.clear()
+ os.environ.update(saved)
+
+
+def _record_nested_repo(outer, marker, gitmodules=None):
+ nested = _add_nested_repo(outer, "vendor/pkg", marker)
+ if gitmodules:
+ (outer / ".gitmodules").write_text(gitmodules)
+ git(outer, "add", "-A")
+ git(outer, "commit", "-q", "-m", "add vendor/pkg")
+ if marker.exists():
+ marker.unlink()
+ return nested
+
+
+def test_untracked_nested_repo_is_not_a_changed_file(outer, marker, git_env):
+ _add_nested_repo(outer, "vendor/pkg", marker)
+ (outer / "new.py").write_text("x = 1\n")
+
+ tracked, untracked = gitutil._git_status_porcelain(str(outer))
+
+ assert (tracked, untracked) == (set(), {"new.py"})
+
+
+def test_intent_to_add_skips_nested_repos(outer, marker, git_env):
+ _add_nested_repo(outer, "vendor/pkg", marker)
+ (outer / "new.py").write_text("x = 1\n")
+
+ with gitutil._temp_index(str(outer), ["new.py", "vendor/pkg/"]) as env:
+ assert env is not None
+ listed = subprocess.run(
+ ["git", "ls-files", "-s"], cwd=outer, capture_output=True,
+ text=True, env=env,
+ ).stdout
+
+ assert "new.py" in listed
+ assert "160000" not in listed
+ assert not marker.exists()
+
+
+# A repository can ask for one submodule to be checked whatever the default.
+GITMODULES_IGNORE_NONE = (
+ '[submodule "pkg"]\n\tpath = vendor/pkg\n\turl = ./vendor/pkg\n\tignore = none\n'
+)
+
+
+@pytest.mark.parametrize("gitmodules", [None, GITMODULES_IGNORE_NONE])
+def test_status_and_diff_leave_out_recorded_nested_repo(outer, marker, git_env, gitmodules):
+ nested = _record_nested_repo(outer, marker, gitmodules)
+ (nested / "lib.py").write_text("print('abc')\n")
+ (outer / "app.py").write_text(VULN_PY)
+
+ tracked, untracked = gitutil._git_status_porcelain(str(outer))
+ diff = gitutil.get_git_diff(str(outer), "HEAD", untracked_paths=[])
+ names = gitutil._git_name_only(str(outer), "HEAD")
+
+ assert tracked == {"app.py"}
+ assert names == {"app.py"}
+ assert "app.py" in diff and "vendor/pkg" not in diff
+ assert not marker.exists()
+
+
+def test_commit_range_diff_does_not_enter_nested_repo(outer, marker, git_env, tmp_path):
+ nested = _record_nested_repo(outer, marker, GITMODULES_IGNORE_NONE)
+ ext_marker = tmp_path / "ext-diff-ran"
+ git(nested, "config", "diff.external",
+ f"sh -c 'echo ran >> \"{ext_marker.as_posix()}\"'")
+ base = git(outer, "rev-parse", "HEAD").strip()
+ git(nested, "commit", "-q", "-am", "two")
+ git(outer, "commit", "-q", "-am", "move vendor/pkg")
+ for m in (marker, ext_marker):
+ if m.exists():
+ m.unlink()
+ # The user's own setting asks for a submodule's changes inline.
+ os.environ.update({"GIT_CONFIG_COUNT": "1", "GIT_CONFIG_KEY_0": "diff.submodule",
+ "GIT_CONFIG_VALUE_0": "diff"})
+
+ out = gitutil._git_diff_range(str(outer), base, "HEAD")
+
+ assert not ext_marker.exists() and not marker.exists()
+ assert "lib.py" not in (out or "")