Skip to content

Commit d76bf7f

Browse files
committed
Merge branch 'v2/fix/GHSA-pm7p-vphh-2cg7' into v2/fix/GHSA-8wv7-r664-7594
# Conflicts: # src/git/src/mcp_server_git/server.py
2 parents 3667b32 + f777ce6 commit d76bf7f

6 files changed

Lines changed: 932 additions & 9 deletions

File tree

‎src/git/README.md‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -184,8 +184,11 @@ A repository's configuration and hooks travel with it (an unpacked archive, a sh
184184

185185
- `core.fsmonitor` is `false`, and `core.hooksPath` points at the null device, so no hook runs; `git_commit` also skips the hooks GitPython would run itself (`pre-commit`, `commit-msg`, `post-commit`).
186186
- Diffs pass `--no-ext-diff` and `--no-textconv`, so `diff.external`, `diff.<driver>.command` and `diff.<driver>.textconv` are ignored.
187-
- Each filter driver (`filter.<name>.clean`, `smudge`, `process`) and merge driver (`merge.<name>.driver`) that the repository's own configuration defines is emptied: files are staged and checked out unfiltered, and a file a merge driver would have merged is a conflict, which `git_merge` aborts. Drivers from your global or system configuration, such as Git LFS's, keep working.
187+
- Each filter driver (`filter.<name>.clean`, `smudge`, `process`) and merge driver (`merge.<name>.driver`) that the repository's own configuration defines is emptied, including one with an empty name (`[filter ""]`, selected by `filter=`): files are staged and checked out unfiltered, and a file a merge driver would have merged is a conflict, which `git_merge` aborts. Drivers from your global or system configuration, such as Git LFS's, keep working.
188+
- The repository's configuration can depend on its working tree (an `[include]` or `[includeIf]` path into it, or a `.git/config` linked to a tracked file), so a tool that writes the working tree (`git_checkout`, `git_merge`, and the `git merge --abort` after a conflict) reads the drivers again before it runs any other Git command, and a driver that the files it wrote define is emptied as well.
188189
- `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`.
190+
- Git never fetches a missing object from a promisor remote by itself (`GIT_NO_LAZY_FETCH=1`), since that fetch runs the transport program the repository's configuration names (`remote.<name>.uploadpack`, `core.sshCommand`). In a partial clone, or any repository that declares a promisor remote, a tool that needs an object that is not on disk reports it missing. A Git too old to honor the variable (before 2.45.1, other than the maintenance releases 2.39.4, 2.40.2, 2.41.1, 2.42.2, 2.43.4 and 2.44.1 made with it) refuses a repository that declares a promisor remote (`remote.<name>.promisor`, `remote.<name>.partialCloneFilter` or `extensions.partialClone`, with or without a remote name).
191+
- `maintenance.auto` is `false` and `gc.auto` is `0`, so no tool starts Git's automatic maintenance (which `git merge` runs when it finishes), whose garbage collection would run the commands a repository's `gc.recentObjectsHook` names. Repositories the server works in are not garbage-collected automatically; your own Git commands still do it.
189192
- `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.
190193
- `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.
191194
- `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.

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

Lines changed: 110 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -134,6 +134,15 @@ def _git_text(repo: git.Repo, command: str, *args: str) -> str:
134134
# - `diff.submodule` set to `diff` makes git diff run a nested git diff inside
135135
# each changed submodule, without `_DIFF_FLAGS`, so the submodule's own
136136
# `diff.external` and textconv drivers would run; `short` starts nothing.
137+
# - `maintenance.auto` keeps a merge (or any other command that ends in
138+
# `git maintenance run --auto`) from starting git's automatic maintenance,
139+
# whose cruft repacks (git 2.42+) run each command the repository's
140+
# `gc.recentObjectsHook` names. Stopping the launch covers every task,
141+
# including a geometric repack the repository enables, which its own
142+
# `maintenance.<task>.auto` gates; `gc.auto` is a backstop for the gc task
143+
# only, so it does not replace `maintenance.auto`.
144+
# That hook cannot be emptied like a driver: it is multi-valued, and an
145+
# empty override adds a value rather than replacing the repository's.
137146
#
138147
# External diff programs and textconv filters are turned off per command
139148
# (`_DIFF_FLAGS`), and filter and merge drivers per repository (`_LISTED_KEYS`).
@@ -147,6 +156,8 @@ def _git_text(repo: git.Repo, command: str, *args: str) -> str:
147156
("status.submoduleSummary", "false"),
148157
("merge.autoStash", "false"),
149158
("diff.submodule", "short"),
159+
("maintenance.auto", "false"),
160+
("gc.auto", "0"),
150161
)
151162

152163
# A filter driver (`filter.<name>.clean`/`smudge`/`process`, applied by
@@ -160,9 +171,11 @@ def _git_text(repo: git.Repo, command: str, *args: str) -> str:
160171
# `commit.gpgSign` says). Drivers and options from the user's global or
161172
# system configuration (git-lfs, say) are the user's own and keep working.
162173
# `harden_repo` lists these keys, and `core.hooksPath`, whose command-scope
163-
# value shows that git applied the overrides.
174+
# value shows that git applied the overrides. A driver's name may be empty
175+
# (`[filter ""]`, read back as `filter..clean`, selected by `filter=`), so
176+
# the name is matched with `.*`, not `.+`.
164177
_LISTED_KEYS = (
165-
r"^(core\.hookspath|filter\..+\.(clean|smudge|process)|merge\..+\.driver"
178+
r"^(core\.hookspath|filter\..*\.(clean|smudge|process)|merge\..*\.driver"
166179
r"|branch\..+\.mergeoptions)$"
167180
)
168181

@@ -181,6 +194,50 @@ def _git_text(repo: git.Repo, command: str, *args: str) -> str:
181194
# `submodule.<name>.ignore`, which the repository could set to `none`.
182195
_NO_SUBMODULE_STATUS = "--ignore-submodules=dirty"
183196

197+
# A repository that declares a promisor remote has git fetch any object it is
198+
# missing from that remote, by itself, on a read-only command (git show, git
199+
# status with HEAD's tree gone). The fetch runs a transport program the
200+
# repository's configuration names (`remote.<name>.uploadpack`,
201+
# `core.sshCommand`, an `ext::` URL), and no override can pin it by name,
202+
# since the remote's name is the repository's choice; `protocol.allow=never`
203+
# is no help either, as a repository-level `protocol.<name>.allow` outranks
204+
# it. GIT_NO_LAZY_FETCH=1 turns the fetch off, so a missing object is an
205+
# error. Git honors it from 2.45.1 and the maintenance releases made with it
206+
# (2.39.4, 2.40.2, ..., 2.44.1), mapped here as minor -> first patch; an
207+
# older git ignores it, so `harden_repo` refuses a repository with a promisor
208+
# remote there. Any of these keys declares one; git also reads a
209+
# `remote.promisor` with no remote name, as a promisor remote named "".
210+
_NO_LAZY_FETCH_SINCE = {39: 4, 40: 2, 41: 1, 42: 2, 43: 4, 44: 1, 45: 1}
211+
_PROMISOR_KEYS = (
212+
r"^(extensions\.partialclone|remote\.(.+\.)?(promisor|partialclonefilter))$"
213+
)
214+
215+
216+
def _honors_no_lazy_fetch(version: tuple[int, ...]) -> bool:
217+
"""Whether git at `version` honors GIT_NO_LAZY_FETCH."""
218+
major, minor, patch = (tuple(version) + (0, 0, 0))[:3]
219+
if (major, minor) > (2, 45):
220+
return True
221+
since = _NO_LAZY_FETCH_SINCE.get(minor) if major == 2 else None
222+
return since is not None and patch >= since
223+
224+
225+
def _refuse_promisor_remote(repo: git.Repo) -> None:
226+
"""Refuse a repository with a promisor remote, for a git that would fetch."""
227+
try:
228+
repo.git.config("--get-regexp", _PROMISOR_KEYS)
229+
except git.GitCommandError as e:
230+
# Exit 1 is "nothing matched": no promisor remote, nothing to fetch.
231+
if e.status == 1:
232+
return
233+
raise
234+
raise git.GitError(
235+
"Git 2.45.1 or later (or 2.39.4, 2.40.2, 2.41.1, 2.42.2, 2.43.4, "
236+
"2.44.1) is required for a repository with a promisor remote (a "
237+
"partial clone): an older git fetches missing objects from it, and "
238+
"the fetch runs a program the repository's configuration names"
239+
)
240+
184241

185242
def _config_env(entries: list[tuple[str, str]]) -> dict[str, str]:
186243
"""GIT_CONFIG_COUNT variables for `entries`, after any the user set."""
@@ -276,10 +333,13 @@ def harden_repo(repo: git.Repo) -> None:
276333
overrides each with an empty command. The same read checks that git
277334
applied the overrides: git older than 2.31 ignores GIT_CONFIG_COUNT, and
278335
is refused rather than run unprotected; so is git older than 2.33 for a
279-
repository with a checked-out submodule (`_submodule_drivers`).
336+
repository with a checked-out submodule (`_submodule_drivers`). Lazy
337+
fetching is turned off (GIT_NO_LAZY_FETCH), and a repository with a
338+
promisor remote is refused on a git too old to honor that
339+
(`_PROMISOR_KEYS`).
280340
"""
281341
entries = list(HARDENED_CONFIG)
282-
repo.git.update_environment(**_config_env(entries))
342+
repo.git.update_environment(GIT_NO_LAZY_FETCH="1", **_config_env(entries))
283343
try:
284344
listed = repo.git.config("--show-scope", "-z", "--get-regexp", _LISTED_KEYS)
285345
except git.GitCommandError as e:
@@ -308,6 +368,8 @@ def harden_repo(repo: git.Repo) -> None:
308368
if drivers:
309369
entries += [(key, "") for key in sorted(drivers)]
310370
repo.git.update_environment(**_config_env(entries))
371+
if not _honors_no_lazy_fetch(repo.git.version_info):
372+
_refuse_promisor_remote(repo)
311373

312374

313375
def git_status(repo: git.Repo) -> str:
@@ -434,7 +496,9 @@ def _apply_merge_autostash(repo: git.Repo) -> str:
434496
return ""
435497
stash_oid = autostash.read_text().strip()
436498
try:
437-
repo.git.stash("apply", stash_oid)
499+
# Through _rewrite_tree although nothing after it runs a driver today
500+
# (`git stash store` runs none): any later git command must be safe.
501+
_rewrite_tree(repo, "stash", "apply", stash_oid)
438502
note = "\nApplied autostash."
439503
except git.GitCommandError:
440504
repo.git.stash("store", "-m", "autostash", "-q", stash_oid)
@@ -583,6 +647,40 @@ def git_create_branch(
583647
return f"Created branch '{branch_name}' from {base_label}"
584648

585649

650+
def _rewrite_tree(repo: git.Repo, command: str, *args: str) -> str:
651+
"""Run `git <command> <args>`, which writes the working tree, then re-harden.
652+
653+
`harden_repo` reads the repository's configuration when the call opens
654+
the repository, but that configuration can depend on the working tree: an
655+
`[include]` or `[includeIf]` path into it (git skips one whose file is
656+
missing), a `.git/config` that is a link into it, or an `includeIf
657+
"onbranch:..."` that a branch switch satisfies. A command that writes the
658+
tree can so create or change configuration. Git reads configuration once
659+
per process, at start, so the command itself runs under what was read,
660+
but every git command after it in the same call reads afresh, and would
661+
find filter or merge drivers that were never overridden. Every command
662+
that writes the tree therefore goes through here, and the drivers are
663+
read again before any other git command runs, whether or not it failed:
664+
a failed merge has written files too, and its cleanup runs git next.
665+
666+
If that read fails, the overrides may be incomplete, so the call stops
667+
with a `GitError`, which a caller's `except GitCommandError` cleanup does
668+
not catch, and no further git command runs.
669+
"""
670+
try:
671+
return getattr(repo.git, command)(*args)
672+
finally:
673+
try:
674+
harden_repo(repo)
675+
except git.GitCommandError as e:
676+
raise git.GitError(
677+
"Stopped: the repository's configuration could not be read "
678+
f"again after git {command} changed the working tree. The working "
679+
f"tree was left as git {command} wrote it (a merge may still be in "
680+
f"progress), and no further git command was run: {e}"
681+
) from e
682+
683+
586684
def git_checkout(repo: git.Repo, branch_name: str) -> str:
587685
# Defense in depth: reject branch names starting with '-' to prevent flag injection,
588686
# even if a malicious ref with that name exists (e.g. via filesystem manipulation)
@@ -596,7 +694,7 @@ def git_checkout(repo: git.Repo, branch_name: str) -> str:
596694
# --quiet: without it, git checks each checked-out submodule of the new
597695
# branch for local changes, running git inside it under its own
598696
# configuration; the reply below does not use git's output.
599-
repo.git.checkout("--quiet", branch_name)
697+
_rewrite_tree(repo, "checkout", "--quiet", branch_name)
600698
# rev_parse accepts any revision, so branch_name may have been a sha, tag or
601699
# remote-tracking ref rather than a branch. Report what actually happened instead of
602700
# claiming a branch switch; a detached HEAD is easy to commit onto by mistake.
@@ -632,7 +730,9 @@ def _merge_failure(repo: git.Repo, error: git.GitCommandError, what: str) -> str
632730
conflicts = _git_text(
633731
repo, "diff", _NO_SUBMODULE_STATUS, "--name-only", "--diff-filter=U"
634732
).splitlines()
635-
repo.git.merge("--abort")
733+
# Through _rewrite_tree although it is the last git command here, so a git
734+
# command added after it reads drivers the restored tree defines.
735+
_rewrite_tree(repo, "merge", "--abort")
636736
if conflicts:
637737
return (
638738
f"{what} stopped on conflicts in: {', '.join(conflicts)}. {unchanged} "
@@ -707,7 +807,9 @@ def git_merge(
707807
# names what the caller asked for.
708808
mode = "--ff-only" if fast_forward_only else "--ff"
709809
try:
710-
repo.git.merge(
810+
_rewrite_tree(
811+
repo,
812+
"merge",
711813
mode,
712814
"--commit",
713815
"--no-squash",
Lines changed: 145 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,145 @@
1+
"""No tool starts git's automatic maintenance in a repository it opens.
2+
3+
`git merge` ends in `git maintenance run --auto`, which runs `git gc` when
4+
the repository's own configuration says it is due (`gc.auto`,
5+
`gc.autoPackLimit`). That gc's cruft repack runs every command the
6+
repository's `gc.recentObjectsHook` names, so a repository could run a
7+
program as the server's user through git_merge. `HARDENED_CONFIG` pins
8+
`maintenance.auto` and `gc.auto` off; these tests plant a repository that
9+
forces a gc on the next merge, with a hook that records its own run in a
10+
canary file, and assert the canary is never written.
11+
12+
The hook is a POSIX shell script, so the tests that run it skip on Windows;
13+
the check of the pinned values runs everywhere.
14+
"""
15+
16+
import os
17+
import shlex
18+
import stat
19+
import subprocess
20+
import sys
21+
from pathlib import Path
22+
23+
import git
24+
import pytest
25+
from conftest import connect, wire
26+
27+
from mcp_server_git.server import harden_repo
28+
29+
posix_only = pytest.mark.skipif(
30+
sys.platform == "win32", reason="the hook is a POSIX shell script"
31+
)
32+
# gc.recentObjectsHook arrived in git 2.42; an older git never runs it.
33+
needs_hook = pytest.mark.skipif(
34+
git.Git().version_info < (2, 42), reason="gc.recentObjectsHook needs git 2.42"
35+
)
36+
37+
38+
def root_of(repo: git.Repo) -> Path:
39+
assert repo.working_dir is not None
40+
return Path(repo.working_dir)
41+
42+
43+
def commit_file(repo: git.Repo, name: str, content: str) -> None:
44+
(root_of(repo) / name).write_text(content, newline="\n")
45+
repo.git.add(name)
46+
repo.git.commit("-m", f"write {name}")
47+
48+
49+
def plant_due_gc(repo: git.Repo, canary: Path, *, diverge: bool) -> None:
50+
"""Make the next merge of `feature` run a gc that asks the hook.
51+
52+
Two packs make gc due under `gc.auto=1` and `gc.autoPackLimit=1`, and
53+
their sizes (6 or 3 objects against 4) are within a factor of two, so a
54+
git whose maintenance repacks geometrically finds them due too. An old
55+
unreachable loose object makes the cruft repack consult
56+
`gc.recentObjectsHook`. `diverge` adds a commit on `main`, so the merge
57+
is not a fast-forward.
58+
"""
59+
# Each commit comes before the pack it lands in: a commit runs automatic
60+
# maintenance too, which could consolidate packs already made.
61+
repo.git.branch("feature")
62+
if diverge:
63+
commit_file(repo, "main.txt", "main\n")
64+
repo.git.repack("-a", "-d")
65+
repo.git.checkout("feature")
66+
(root_of(repo) / "feature-1.txt").write_text("one\n", newline="\n")
67+
(root_of(repo) / "feature-2.txt").write_text("two\n", newline="\n")
68+
repo.git.add("feature-1.txt", "feature-2.txt")
69+
repo.git.commit("-m", "feature")
70+
repo.git.checkout("main")
71+
repo.git.repack("-d")
72+
73+
hook = canary.parent / "hook.sh"
74+
hook.write_text(f"#!/bin/sh\necho ran >> {shlex.quote(str(canary))}\n")
75+
hook.chmod(hook.stat().st_mode | stat.S_IEXEC)
76+
with repo.config_writer() as config:
77+
config.set_value("gc", "auto", "1")
78+
config.set_value("gc", "autoPackLimit", "1")
79+
config.set_value("gc", "autoDetach", "false")
80+
config.set_value("gc", "recentObjectsHook", shlex.quote(str(hook)))
81+
82+
sha = (
83+
subprocess.run(
84+
["git", "hash-object", "-w", "--stdin"],
85+
cwd=root_of(repo),
86+
input=b"stale\n",
87+
capture_output=True,
88+
check=True,
89+
)
90+
.stdout.decode()
91+
.strip()
92+
)
93+
loose = Path(repo.git_dir) / "objects" / sha[:2] / sha[2:]
94+
os.utime(loose, (0, 0))
95+
96+
97+
@posix_only
98+
@pytest.mark.parametrize("fast_forward_only", [True, False])
99+
@pytest.mark.parametrize("pinned", [False, True], ids=["roots", "repository"])
100+
async def test_merge_never_runs_the_recent_objects_hook(
101+
tmp_path: Path, repo: git.Repo, fast_forward_only: bool, pinned: bool
102+
):
103+
canary = tmp_path / "canary"
104+
plant_due_gc(repo, canary, diverge=not fast_forward_only)
105+
106+
async with connect(root_of(repo) if pinned else None) as session:
107+
result = wire(
108+
await session.call_tool(
109+
"git_merge",
110+
{
111+
"repo_path": str(root_of(repo)),
112+
"source_branch": "feature",
113+
"fast_forward_only": fast_forward_only,
114+
},
115+
)
116+
)
117+
118+
assert result["isError"] is False, result
119+
assert (root_of(repo) / "feature-1.txt").exists()
120+
assert not canary.exists()
121+
122+
123+
@posix_only
124+
@needs_hook
125+
@pytest.mark.parametrize("diverge", [False, True], ids=["fast-forward", "merge"])
126+
def test_the_planted_repository_runs_the_hook_without_the_overrides(
127+
tmp_path: Path, repo: git.Repo, diverge: bool
128+
):
129+
# The control: the same merge under plain git does run the hook, so the
130+
# test above fails if the overrides go missing.
131+
canary = tmp_path / "canary"
132+
plant_due_gc(repo, canary, diverge=diverge)
133+
repo.git.merge("--ff", "--no-edit", "feature")
134+
assert canary.read_text() == "ran\n"
135+
136+
137+
def test_harden_repo_turns_automatic_maintenance_off(repo: git.Repo):
138+
with repo.config_writer() as config:
139+
config.set_value("gc", "auto", "1")
140+
config.set_value("maintenance", "auto", "true")
141+
harden_repo(repo)
142+
assert repo.git.config("--show-scope", "--get", "gc.auto") == "command\t0"
143+
assert (
144+
repo.git.config("--show-scope", "--get", "maintenance.auto") == "command\tfalse"
145+
)

0 commit comments

Comments
 (0)