summaryrefslogtreecommitdiff
path: root/plugins
diff options
context:
space:
mode:
authorMohamed Hegazy <8000722+mhegazy@users.noreply.github.com>2026-11-12 16:10:24 -0800
committerGitHub <noreply@github.com>2026-11-12 16:10:24 -0800
commitca69627d20f9c42ae6d10ae2aee8f3226d9e2e02 (patch)
treeb06d4249351ce8310a64e15c124ad11a231b1c54 /plugins
parent23c304a6387ed2fa207ceff27646d8514ee75235 (diff)
parent141a7256071c54e00afaee4c9f6455ed745be841 (diff)
Merge pull request #7093 from anthropics/mhegazy/sg-ordinary-checkouts
security-guidance: only run git in ordinary checkouts
Diffstat (limited to 'plugins')
-rw-r--r--plugins/security-guidance/hooks/diffstate.py9
-rw-r--r--plugins/security-guidance/hooks/gitutil.py55
-rw-r--r--plugins/security-guidance/tests/test_bare_repo_toplevel.py161
3 files changed, 221 insertions, 4 deletions
diff --git a/plugins/security-guidance/hooks/diffstate.py b/plugins/security-guidance/hooks/diffstate.py
index 6a3d9b81..cd3205e6 100644
--- a/plugins/security-guidance/hooks/diffstate.py
+++ b/plugins/security-guidance/hooks/diffstate.py
@@ -19,7 +19,7 @@ from _base import debug_log, make_state_dir, portable_output, _PV
import gitutil
from gitutil import (
GIT_CMD,
- _git_dir, _git_toplevel, _git_status_porcelain,
+ _git_dir, _git_toplevel, _found_through_bare_folder, _git_status_porcelain,
_git_rev_parse_head, _is_ancestor, _git_name_only, _temp_index,
_secret_rename_origins, index_entry_count,
)
@@ -581,6 +581,9 @@ def capture_git_baseline(cwd):
global last_baseline_fail, last_index_entries
last_baseline_fail = 0
last_index_entries = None
+ if _found_through_bare_folder(cwd):
+ debug_log("Not an ordinary checkout, skipping baseline capture")
+ return None
try:
# HEAD's commit and its tree in one call: the commit is the answer
# for a clean tree, the tree is what the snapshot is compared with.
@@ -1313,6 +1316,8 @@ def _list_untracked(cwd):
gitutil.py already follow the lenient pattern; this function and
capture_git_baseline / _git_name_only / _git_status_porcelain were
the holdouts."""
+ if _found_through_bare_folder(cwd):
+ return {}
try:
repo = _git_toplevel(cwd) or cwd
started_ns = time.time_ns()
@@ -1386,7 +1391,7 @@ def compute_v2_review_set(cwd, baseline_sha, head_at_capture, untracked_at_basel
if not isinstance(untracked_at_baseline, dict):
untracked_at_baseline = {}
- tracked_dirty, untracked = _git_status_porcelain(repo)
+ tracked_dirty, untracked = (None, None) if _found_through_bare_folder(cwd) else _git_status_porcelain(repo)
if tracked_dirty is None:
return [], "HEAD", repo, [], {"dirty_now_count": -1, "changed_since_count": -1, "review_set_count": 0}
diff --git a/plugins/security-guidance/hooks/gitutil.py b/plugins/security-guidance/hooks/gitutil.py
index 36732482..184dba6d 100644
--- a/plugins/security-guidance/hooks/gitutil.py
+++ b/plugins/security-guidance/hooks/gitutil.py
@@ -18,6 +18,7 @@ import contextlib
import errno
import os
import re
+import stat
import subprocess
import sys
import tempfile
@@ -110,6 +111,7 @@ SAFE_GIT_CONFIG = (
("diff.ignoreSubmodules", "all"),
("diff.submodule", "short"),
("log.showSignature", "false"),
+ ("safe.bareRepository", "explicit"),
)
# The hook's git runs in the background beside the session's own git. Without
@@ -963,6 +965,50 @@ def _drop_gitlinks(top, env, tmp_index):
return False
+def _looks_like_git_dir(path):
+ """git's own test for a repository directory, near enough: objects and refs
+ it can enter, and a HEAD that is a link into refs/ or a file holding a ref
+ or a SHA. Anything else named HEAD stays unopened: a named pipe would block."""
+ # With a commondir file, objects and refs are in the folder that it names.
+ if not (os.path.lexists(os.path.join(path, "commondir"))
+ or ((os.access(os.path.join(path, "objects"), os.X_OK)
+ or os.environ.get("GIT_OBJECT_DIRECTORY"))
+ and os.access(os.path.join(path, "refs"), os.X_OK))):
+ return False
+ head_path = os.path.join(path, "HEAD")
+ try:
+ mode = os.lstat(head_path).st_mode
+ if stat.S_ISLNK(mode):
+ return os.readlink(head_path).startswith("refs/") # git does not follow it
+ if not stat.S_ISREG(mode):
+ return False
+ with open(head_path, "rb") as f:
+ head = f.read(64)
+ except OSError:
+ return False
+ return bool(re.match(rb"ref:\s*refs/|[0-9a-fA-F]{40}", head))
+
+
+def _found_through_bare_folder(cwd):
+ """True when git, searching up from `cwd`, would take a folder with no
+ `.git` entry for the repository. Git versions before 2.38 have no
+ safe.bareRepository, so this is what keeps them to ordinary checkouts.
+ A repository the caller named through the environment is not searched for."""
+ if os.environ.get("GIT_DIR"):
+ return False
+ d = os.path.realpath(cwd or os.curdir)
+ while True:
+ entry = os.path.join(d, ".git")
+ if os.path.isfile(entry) or _looks_like_git_dir(entry):
+ return False # git passes over an empty `.git` folder or a broken link
+ if _looks_like_git_dir(d):
+ return os.path.basename(d) != ".git"
+ parent = os.path.dirname(d)
+ if parent == d:
+ return False
+ d = parent
+
+
def _git_toplevel(cwd):
"""Absolute repo root for `cwd`, or None if not in a work tree."""
try:
@@ -976,7 +1022,7 @@ def _git_toplevel(cwd):
if r.returncode != 0:
return None
path = r.stdout.decode("utf-8", errors="replace").strip()
- return path if path else None
+ return path if path and not _found_through_bare_folder(cwd) else None
except (subprocess.TimeoutExpired, FileNotFoundError, OSError):
return None
@@ -995,7 +1041,10 @@ def _git_toplevel_and_head(cwd):
return None, None
# See #2099: the first line is a PATH, so decode the bytes manually.
top, _, head = r.stdout.decode("utf-8", errors="replace").strip().rpartition("\n")
- return (top.strip() or None), (head.strip() or None)
+ top = top.strip()
+ if not top or _found_through_bare_folder(cwd):
+ return None, None
+ return top, (head.strip() or None)
def _git_head_at(cwd, epoch):
@@ -1026,6 +1075,8 @@ def _git_dir(repo_root):
if a different worktree later pushes it. Returns None on failure so
callers can degrade (push-sweep state is best-effort).
"""
+ if _found_through_bare_folder(repo_root):
+ return None
try:
# See #2099: stdout is a PATH (shared gitdir), may be non-ASCII.
# Decode bytes manually to avoid cp1252 reader-thread crash.
diff --git a/plugins/security-guidance/tests/test_bare_repo_toplevel.py b/plugins/security-guidance/tests/test_bare_repo_toplevel.py
new file mode 100644
index 00000000..158f1054
--- /dev/null
+++ b/plugins/security-guidance/tests/test_bare_repo_toplevel.py
@@ -0,0 +1,161 @@
+"""The plugin only treats ordinary checkouts as repositories to run git in."""
+import os
+import subprocess
+
+import pytest
+
+from conftest import GIT_ENV, git, make_repo
+
+import diffstate
+import gitutil
+
+
+def _run(cwd, *args):
+ return subprocess.run(["git", *args], cwd=cwd, capture_output=True, text=True,
+ env={**os.environ, **GIT_ENV}, check=True).stdout
+
+
+@pytest.fixture
+def carried(tmp_path):
+ d = tmp_path / "project" / "src"
+ d.mkdir(parents=True)
+ _run(d, "init", "-q", "-b", "main", "--bare", ".")
+ _run(d, "config", "core.bare", "false")
+ _run(d, "config", "core.worktree", ".")
+ return d
+
+
+def test_folder_without_its_own_git_entry_is_not_a_repo(carried):
+ assert gitutil._git_toplevel(str(carried)) is None
+ assert gitutil._git_toplevel_and_head(str(carried)) == (None, None)
+
+
+def test_ordinary_checkout(tmp_path):
+ r = make_repo(tmp_path / "repo")
+ assert os.path.samefile(gitutil._git_toplevel(str(r)), r)
+
+
+def test_linked_worktree_of_a_bare_repo(tmp_path):
+ src = make_repo(tmp_path / "repo")
+ bare = tmp_path / "store.git"
+ _run(tmp_path, "clone", "-q", "--bare", str(src), str(bare))
+ wt = tmp_path / "wt"
+ _run(bare, "worktree", "add", "-q", str(wt), "main")
+ assert os.path.samefile(gitutil._git_toplevel(str(wt)), wt)
+
+
+def test_repo_named_by_the_environment(carried, monkeypatch):
+ monkeypatch.setenv("GIT_DIR", str(carried))
+ assert gitutil._git_toplevel(str(carried)) is not None
+
+
+# The tests run without apply_safe_git_env, so git here finds these folders the
+# way git before 2.38 does.
+@pytest.fixture
+def carried_with_filter(carried, tmp_path):
+ marker = tmp_path / "filter-ran"
+ (carried / "app.py").write_text("print('inner')\n")
+ (carried / ".gitattributes").write_text("* filter=probe\n")
+ _run(carried, "add", ".gitattributes", "app.py")
+ _run(carried, "commit", "-q", "-m", "inner")
+ _run(carried, "config", "filter.probe.clean", f"sh -c 'echo x >> \"{marker.as_posix()}\"; cat'")
+ (carried / "app.py").write_text("print('chang')\n") # same size, so git has to hash it
+ return carried, marker
+
+
+def _assert_stays_out(d, marker):
+ assert diffstate.capture_git_baseline(str(d)) is None
+ assert diffstate._list_untracked(str(d)) == {}
+ paths, _base, _repo, untracked, metrics = diffstate.compute_v2_review_set(str(d), "HEAD", None)
+ assert (paths, untracked, metrics["review_set_count"]) == ([], [], 0)
+ assert not marker.exists()
+
+
+def test_prompt_and_stop_git_stay_out_of_the_folder(carried_with_filter):
+ d, marker = carried_with_filter
+ _run(d, "status", "--porcelain")
+ assert marker.exists() # the filter does run for a plain git status here
+ marker.unlink()
+ _assert_stays_out(d, marker)
+
+
+def test_folder_whose_work_tree_is_a_real_checkout(tmp_path):
+ project = make_repo(tmp_path / "project")
+ d = project / "carried"
+ d.mkdir()
+ _run(d, "init", "-q", "-b", "main", "--bare", ".")
+ _run(d, "config", "core.bare", "false")
+ _run(d, "config", "core.worktree", "..")
+ assert gitutil._git_toplevel(str(d)) is None
+
+
+def test_no_plugin_records_in_the_folder(carried):
+ assert gitutil._git_dir(str(carried)) is None
+
+
+def test_subfolder_of_the_folder(carried):
+ sub = carried / "sub"
+ sub.mkdir()
+ assert gitutil._found_through_bare_folder(str(sub))
+
+
+def test_git_dir_with_a_work_tree_elsewhere(tmp_path):
+ gd = tmp_path / "gd"
+ wt = tmp_path / "wtree"
+ gd.mkdir()
+ wt.mkdir()
+ _run(gd, "init", "-q", "-b", "main")
+ _run(gd, "config", "core.worktree", str(wt))
+ assert not gitutil._found_through_bare_folder(str(gd))
+ assert os.path.samefile(gitutil._git_toplevel(str(gd)), wt)
+
+
+def test_inside_a_dot_git_directory(tmp_path):
+ r = make_repo(tmp_path / "repo")
+ assert not gitutil._found_through_bare_folder(str(r / ".git"))
+
+
+def test_project_folder_named_like_a_repository(tmp_path):
+ r = make_repo(tmp_path / "repo")
+ d = r / "docs"
+ (d / "objects").mkdir(parents=True)
+ (d / "refs").mkdir()
+ (d / "HEAD").write_text("notes\n")
+ assert not gitutil._found_through_bare_folder(str(d))
+
+
+def test_head_text_that_is_not_a_ref(tmp_path):
+ r = make_repo(tmp_path / "repo")
+ d = r / "docs"
+ (d / "objects").mkdir(parents=True)
+ (d / "refs").mkdir()
+ (d / "HEAD").write_text("ref: see the notes\n")
+ assert not gitutil._found_through_bare_folder(str(d))
+
+
+@pytest.mark.skipif(os.name == "nt", reason="symbolic links")
+def test_head_that_is_a_link_into_refs(carried):
+ (carried / "HEAD").unlink()
+ os.symlink("refs/heads/main", carried / "HEAD")
+ assert gitutil._found_through_bare_folder(str(carried))
+
+
+@pytest.mark.skipif(os.name == "nt", reason="named pipes")
+def test_head_that_is_a_named_pipe_is_not_opened(tmp_path):
+ d = tmp_path / "pipe"
+ (d / "objects").mkdir(parents=True)
+ (d / "refs").mkdir()
+ os.mkfifo(d / "HEAD")
+ assert not gitutil._looks_like_git_dir(str(d))
+
+
+def test_commondir_layout(carried):
+ (carried / "commondir").write_text("../store\n")
+ (carried / "objects").rename(carried.parent / "objects")
+ (carried / "refs").rename(carried.parent / "refs")
+ assert gitutil._found_through_bare_folder(str(carried))
+
+
+def test_empty_git_folder_does_not_hide_the_repository(carried):
+ (carried / ".git").mkdir()
+ assert gitutil._found_through_bare_folder(str(carried))