Skip to content

Commit 13a14ce

Browse files
cliffhallclaude
andcommitted
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Signed-off-by: cliffhall <cliff@futurescale.com>
1 parent 0837be8 commit 13a14ce

3 files changed

Lines changed: 114 additions & 12 deletions

File tree

‎src/git/README.md‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -188,9 +188,9 @@ A repository's configuration and hooks travel with it (an unpacked archive, a sh
188188
- `commit.gpgSign` and `merge.verifySignatures` are `false`, and `git_merge` passes `--no-gpg-sign` and `--no-verify-signatures`. Each `branch.<name>.mergeOptions` the repository's own configuration sets is emptied, since Git reads it as command-line options. `submodule.recurse` and `merge.autoStash` are `false`, and `core.pager` is `cat`.
189189
- `git_status`, `git_diff_unstaged` and `git_diff` pass `--ignore-submodules=dirty`, because looking for changes inside a submodule runs Git under the submodule's own configuration. A submodule whose checked-out commit moved is still reported; changes inside one are not, so run the tool on the submodule's path to see them.
190190
- `diff.submodule` is `short`, so a diff reports a submodule whose commit moved as a `Subproject commit` line rather than running a nested `git diff` inside it, which would not carry the flags above.
191-
- `git_add` and `git_checkout` let Git check whether a checked-out submodule changed, which runs Git inside it under its own configuration. The filter and merge drivers each checked-out submodule (and each submodule inside one) defines are emptied too, the same way as the repository's own.
191+
- `git_add` lets Git check whether a checked-out submodule changed, which runs Git inside it under its own configuration, so the filter and merge drivers each checked-out submodule (and each submodule inside one) defines are emptied too, the same way as the repository's own. `git_checkout` passes `--quiet`, which skips that check.
192192

193-
This needs Git 2.31 or later; with an older Git every tool call fails with an error saying so, rather than run unprotected.
193+
This needs Git 2.33 or later; with an older Git every tool call fails with an error saying so, rather than run unprotected.
194194

195195
### Commit identity
196196

‎src/git/src/mcp_server_git/server.py‎

Lines changed: 38 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -118,7 +118,8 @@ def _git_text(repo: git.Repo, command: str, *args: str) -> str:
118118
# honoring it would let the repository run code as the server's user on a
119119
# read-only call such as git_status. The overrides go in through
120120
# GIT_CONFIG_COUNT (git 2.31+), which outranks every config file and is
121-
# inherited by the git processes git itself starts, submodules included.
121+
# inherited by the git processes git itself starts, submodules included from
122+
# git 2.33 (`_MIN_SUBMODULE_GIT`).
122123
#
123124
# - `core.fsmonitor` is run on every index refresh (status, diff, add).
124125
# - `core.hooksPath` pointing at the null device leaves no hook to find, so
@@ -191,6 +192,12 @@ def _config_env(entries: list[tuple[str, str]]) -> dict[str, str]:
191192
return env
192193

193194

195+
# Git 2.31 and 2.32 drop GIT_CONFIG_COUNT from the environment of the git
196+
# they run inside a submodule (fixed upstream in 2.33), so none of the
197+
# overrides would reach it.
198+
_MIN_SUBMODULE_GIT = (2, 33)
199+
200+
194201
def _submodule_drivers(repo: git.Repo) -> set[str]:
195202
"""The filter and merge driver keys each checked-out submodule defines.
196203
@@ -201,18 +208,33 @@ def _submodule_drivers(repo: git.Repo) -> set[str]:
201208
too once their names are known. A submodule is found at each gitlink in
202209
the index, then inside it at each of its own, the way git descends.
203210
Listing them runs only `git config` and `git ls-files`, which start no
204-
program. A gitlink whose directory git cannot open as a repository is
205-
skipped: the nested git cannot open it either, so it runs nothing there.
211+
program. Each submodule is opened the way the nested git opens it, with
212+
`GIT_DIR=.git` in its directory, so no upward search or ownership check
213+
makes the two disagree. A submodule whose configuration or index git
214+
cannot read is skipped: the nested git cannot read it either, and stops
215+
before it runs anything there.
216+
217+
Raises `git.GitError` on git older than `_MIN_SUBMODULE_GIT`, whose
218+
nested git would not inherit the overrides.
206219
"""
220+
if repo.git.version_info[:2] < _MIN_SUBMODULE_GIT:
221+
raise git.GitError(
222+
"Git 2.33 or later is required: older git does not pass the "
223+
"configuration overrides to the git it runs inside a submodule"
224+
)
207225
drivers: set[str] = set()
208226
if repo.working_tree_dir is None:
209227
return drivers
210-
pending = [Path(repo.working_tree_dir)]
228+
# The opened repository's own index, then each submodule's.
229+
pending = [(Path(repo.working_tree_dir), repo.git)]
211230
seen: set[Path] = set()
212231
while pending:
213-
top = pending.pop()
214-
# -z prints `<mode> <object> <stage>\t<path>\0` for each entry.
215-
listing = repo.git(C=str(top)).ls_files("-z", "--stage")
232+
top, top_git = pending.pop()
233+
try:
234+
# -z prints `<mode> <object> <stage>\t<path>\0` for each entry.
235+
listing = top_git.ls_files("-z", "--stage")
236+
except git.GitCommandError:
237+
continue # an index git cannot read
216238
for entry in listing.split("\0"):
217239
info, _, path = entry.partition("\t")
218240
if not info.startswith("160000 "):
@@ -224,8 +246,11 @@ def _submodule_drivers(repo: git.Repo) -> set[str]:
224246
if resolved in seen:
225247
continue
226248
seen.add(resolved)
249+
# The nested git runs with GIT_DIR=.git in the submodule.
250+
sub_git = git.Git(submodule)
251+
sub_git.update_environment(**repo.git.environment(), GIT_DIR=".git")
227252
try:
228-
listed = repo.git(C=str(submodule)).config(
253+
listed = sub_git.config(
229254
"--show-scope", "-z", "--get-regexp", _LISTED_KEYS
230255
)
231256
except git.GitCommandError:
@@ -235,7 +260,7 @@ def _submodule_drivers(repo: git.Repo) -> set[str]:
235260
key = field.partition("\n")[0]
236261
if key != "core.hookspath" and scope not in _TRUSTED_SCOPES:
237262
drivers.add(key)
238-
pending.append(submodule)
263+
pending.append((submodule, sub_git))
239264
return drivers
240265

241266

@@ -564,7 +589,10 @@ def git_checkout(repo: git.Repo, branch_name: str) -> str:
564589
repo.rev_parse(
565590
branch_name
566591
) # Validates branch_name is a real git ref, throws BadName if not
567-
repo.git.checkout(branch_name)
592+
# --quiet: without it, git checks each checked-out submodule of the new
593+
# branch for local changes, running git inside it under its own
594+
# configuration; the reply below does not use git's output.
595+
repo.git.checkout("--quiet", branch_name)
568596
# rev_parse accepts any revision, so branch_name may have been a sha, tag or
569597
# remote-tracking ref rather than a branch. Report what actually happened instead of
570598
# claiming a branch switch; a detached HEAD is easy to commit onto by mistake.

‎src/git/tests/test_submodule_config.py‎

Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -238,6 +238,33 @@ async def test_nested_submodule_filters_never_run(repo: git.Repo, canary: Canary
238238
assert canary.runs() == []
239239

240240

241+
@posix_only
242+
async def test_checkout_never_looks_inside_a_submodule_the_branch_adds(
243+
repo: git.Repo, canary: Canary
244+
):
245+
# The current branch has no gitlink at `vendor`, so hardening does not
246+
# list its drivers; the target branch records one. git_checkout must not
247+
# look inside it once the new index is written.
248+
vendor = make_repo(root_of(repo) / "vendor")
249+
commit_file(vendor, ".gitattributes", "*.txt filter=evil\n")
250+
vendor.git.config("filter.evil.clean", canary.command("filter"))
251+
sha = vendor.head.commit.hexsha
252+
vendor.close()
253+
repo.git.checkout("-q", "-b", "with-vendor")
254+
record_gitlink(repo, "vendor", sha)
255+
repo.git.commit("-m", "add vendor")
256+
repo.git.checkout("-q", "main")
257+
os.utime(root_of(repo) / "vendor" / "test.txt", (1_000_000_000, 1_000_000_000))
258+
path = root_of(repo)
259+
260+
result = await call(
261+
"git_checkout", {"repo_path": str(path), "branch_name": "with-vendor"}, path
262+
)
263+
264+
assert result["isError"] is False, result
265+
assert canary.runs() == []
266+
267+
241268
async def test_git_add_still_stages_a_moved_submodule(repo: git.Repo):
242269
sm = embed(repo, "sm")
243270
commit_file(sm, "test.txt", "changed\n")
@@ -314,3 +341,50 @@ def test_bare_repository_has_no_submodules(tmp_path: Path):
314341
bare = git.Repo.init(tmp_path / "bare.git", bare=True)
315342
assert _submodule_drivers(bare) == set()
316343
bare.close()
344+
345+
346+
def test_skips_a_submodule_whose_index_git_cannot_read(repo: git.Repo):
347+
# One broken submodule does not stop every tool: the nested git cannot
348+
# read that index either, so it runs nothing there.
349+
sm = embed(repo, "sm")
350+
sm.git.config("filter.evil.clean", "x")
351+
sm.close()
352+
(root_of(repo) / "sm" / ".git" / "index").write_bytes(b"not an index")
353+
354+
assert _submodule_drivers(repo) == {"filter.evil.clean"}
355+
356+
357+
async def test_tools_still_work_beside_a_broken_submodule(repo: git.Repo):
358+
embed(repo, "sm").close()
359+
(root_of(repo) / "sm" / ".git" / "index").write_bytes(b"not an index")
360+
361+
result = await call("git_status", {"repo_path": str(root_of(repo))})
362+
363+
assert result["isError"] is False, result
364+
365+
366+
def test_opens_a_submodule_as_the_nested_git_does(
367+
tmp_path: Path, repo: git.Repo, monkeypatch: pytest.MonkeyPatch
368+
):
369+
# The nested git opens a submodule with GIT_DIR=.git, which skips the
370+
# ownership check; so does the listing. Simulated here: every repository
371+
# is taken to belong to someone else, and only the opened one is trusted.
372+
sm = embed(repo, "sm")
373+
sm.git.config("filter.evil.clean", "x")
374+
sm.close()
375+
global_config = tmp_path / "global-config"
376+
global_config.write_text(f"[safe]\n\tdirectory = {root_of(repo).as_posix()}\n")
377+
monkeypatch.setenv("GIT_CONFIG_GLOBAL", str(global_config))
378+
monkeypatch.setenv("GIT_TEST_ASSUME_DIFFERENT_OWNER", "1")
379+
with pytest.raises(git.GitCommandError, match="dubious ownership"):
380+
git.Git(root_of(repo) / "sm").ls_files()
381+
382+
assert _submodule_drivers(repo) == {"filter.evil.clean"}
383+
384+
385+
def test_refuses_git_older_than_2_33(repo: git.Repo, monkeypatch: pytest.MonkeyPatch):
386+
# Git 2.31 and 2.32 do not pass GIT_CONFIG_COUNT to the git they run
387+
# inside a submodule, so the overrides would not reach it.
388+
monkeypatch.setattr(git.Git, "version_info", property(lambda self: (2, 32, 0)))
389+
with pytest.raises(git.GitError, match="Git 2.33 or later is required"):
390+
harden_repo(repo)

0 commit comments

Comments
 (0)