Skip to content

Commit d735973

Browse files
authored
Merge pull request #5582 from modelcontextprotocol/v2/fix/GHSA-9vjp-x34c-xg6v
fix(git): GHSA-9vjp-x34c-xg6v
2 parents 63a0dcc + 914e017 commit d735973

3 files changed

Lines changed: 252 additions & 4 deletions

File tree

‎src/git/README.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -185,6 +185,7 @@ A repository's configuration and hooks travel with it (an unpacked archive, a sh
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.
187187
- 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.
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`.
189190
- `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.
190191
- `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.

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

Lines changed: 44 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -363,7 +363,9 @@ def _apply_merge_autostash(repo: git.Repo) -> str:
363363
return ""
364364
stash_oid = autostash.read_text().strip()
365365
try:
366-
repo.git.stash("apply", stash_oid)
366+
# Through _rewrite_tree although nothing after it runs a driver today
367+
# (`git stash store` runs none): any later git command must be safe.
368+
_rewrite_tree(repo, "stash", "apply", stash_oid)
367369
note = "\nApplied autostash."
368370
except git.GitCommandError:
369371
repo.git.stash("store", "-m", "autostash", "-q", stash_oid)
@@ -512,6 +514,40 @@ def git_create_branch(
512514
return f"Created branch '{branch_name}' from {base_label}"
513515

514516

517+
def _rewrite_tree(repo: git.Repo, command: str, *args: str) -> str:
518+
"""Run `git <command> <args>`, which writes the working tree, then re-harden.
519+
520+
`harden_repo` reads the repository's configuration when the call opens
521+
the repository, but that configuration can depend on the working tree: an
522+
`[include]` or `[includeIf]` path into it (git skips one whose file is
523+
missing), a `.git/config` that is a link into it, or an `includeIf
524+
"onbranch:..."` that a branch switch satisfies. A command that writes the
525+
tree can so create or change configuration. Git reads configuration once
526+
per process, at start, so the command itself runs under what was read,
527+
but every git command after it in the same call reads afresh, and would
528+
find filter or merge drivers that were never overridden. Every command
529+
that writes the tree therefore goes through here, and the drivers are
530+
read again before any other git command runs, whether or not it failed:
531+
a failed merge has written files too, and its cleanup runs git next.
532+
533+
If that read fails, the overrides may be incomplete, so the call stops
534+
with a `GitError`, which a caller's `except GitCommandError` cleanup does
535+
not catch, and no further git command runs.
536+
"""
537+
try:
538+
return getattr(repo.git, command)(*args)
539+
finally:
540+
try:
541+
harden_repo(repo)
542+
except git.GitCommandError as e:
543+
raise git.GitError(
544+
"Stopped: the repository's configuration could not be read "
545+
f"again after git {command} changed the working tree. The working "
546+
f"tree was left as git {command} wrote it (a merge may still be in "
547+
f"progress), and no further git command was run: {e}"
548+
) from e
549+
550+
515551
def git_checkout(repo: git.Repo, branch_name: str) -> str:
516552
# Defense in depth: reject branch names starting with '-' to prevent flag injection,
517553
# even if a malicious ref with that name exists (e.g. via filesystem manipulation)
@@ -522,7 +558,7 @@ def git_checkout(repo: git.Repo, branch_name: str) -> str:
522558
repo.rev_parse(
523559
branch_name
524560
) # Validates branch_name is a real git ref, throws BadName if not
525-
repo.git.checkout(branch_name)
561+
_rewrite_tree(repo, "checkout", branch_name)
526562
# rev_parse accepts any revision, so branch_name may have been a sha, tag or
527563
# remote-tracking ref rather than a branch. Report what actually happened instead of
528564
# claiming a branch switch; a detached HEAD is easy to commit onto by mistake.
@@ -558,7 +594,9 @@ def _merge_failure(repo: git.Repo, error: git.GitCommandError, what: str) -> str
558594
conflicts = _git_text(
559595
repo, "diff", _NO_SUBMODULE_STATUS, "--name-only", "--diff-filter=U"
560596
).splitlines()
561-
repo.git.merge("--abort")
597+
# Through _rewrite_tree although it is the last git command here, so a git
598+
# command added after it reads drivers the restored tree defines.
599+
_rewrite_tree(repo, "merge", "--abort")
562600
if conflicts:
563601
return (
564602
f"{what} stopped on conflicts in: {', '.join(conflicts)}. {unchanged} "
@@ -633,7 +671,9 @@ def git_merge(
633671
# names what the caller asked for.
634672
mode = "--ff-only" if fast_forward_only else "--ff"
635673
try:
636-
repo.git.merge(
674+
_rewrite_tree(
675+
repo,
676+
"merge",
637677
mode,
638678
"--commit",
639679
"--no-squash",

‎src/git/tests/test_tree_config.py‎

Lines changed: 207 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,207 @@
1+
"""Configuration a tool call's own writes create is overridden like the rest.
2+
3+
`harden_repo` reads the repository's filter and merge drivers when a call
4+
opens the repository, but the configuration can depend on the working tree:
5+
an `[include]` path into it that git skips while the file is missing, a
6+
`.git/config` that is a link to a tracked file, or an `includeIf
7+
"onbranch:..."` that a checkout satisfies. A tool that writes the tree (a
8+
merge, a checkout) can so define a driver mid-call, and the git commands it
9+
runs next (a conflicting merge's `git diff` and `git merge --abort`) would run
10+
it. Every tree-writing command goes through `_rewrite_tree`, which reads the
11+
drivers again before anything else runs.
12+
13+
Each attack test plants a filter that records its run in a canary file
14+
(`Payload`, shared with test_repository_config.py), drives the real server
15+
through a client, and asserts the canary stays empty. The payloads are POSIX
16+
shell scripts, so those tests skip on Windows.
17+
"""
18+
19+
import os
20+
import sys
21+
from pathlib import Path
22+
from unittest import mock
23+
24+
import git
25+
import pytest
26+
from conftest import connect, make_repo, wire
27+
from test_repository_config import Payload, root_of
28+
29+
from mcp_server_git import server
30+
from mcp_server_git.server import _rewrite_tree, git_checkout, git_merge, harden_repo
31+
32+
posix_only = pytest.mark.skipif(
33+
sys.platform == "win32", reason="the payloads are POSIX shell scripts"
34+
)
35+
36+
CONFLICT = (
37+
"Error executing tool git_merge: Merge of 'feature' into 'main' stopped on "
38+
"conflicts in: m.txt. The merge was aborted and the repository is "
39+
"unchanged. Resolve the conflicts by hand."
40+
)
41+
42+
43+
def filter_config(payload: Payload) -> str:
44+
command = payload.command("filter")
45+
return f'[filter "x"]\n\tsmudge = {command}\n\tclean = {command}\n'
46+
47+
48+
def diverged(
49+
repo: git.Repo,
50+
feature_files: dict[str, str],
51+
base_files: dict[str, str] | None = None,
52+
) -> None:
53+
"""`feature` writes `feature_files` and conflicts with `main` in m.txt.
54+
55+
Both branches start from a commit of `base_files`. Every file is under
56+
`* filter=x`, which is harmless while `x` is undefined.
57+
"""
58+
root = root_of(repo)
59+
base_files = base_files or {}
60+
(root / ".gitattributes").write_text("* filter=x\n")
61+
(root / "m.txt").write_text("base\n")
62+
for name, text in base_files.items():
63+
(root / name).write_text(text)
64+
repo.index.add([".gitattributes", "m.txt", *base_files])
65+
repo.index.commit("base")
66+
repo.git.checkout("-b", "feature")
67+
(root / "m.txt").write_text("theirs\n")
68+
for name, text in feature_files.items():
69+
(root / name).write_text(text)
70+
repo.index.add(["m.txt", *feature_files])
71+
repo.index.commit("theirs")
72+
repo.git.checkout("main")
73+
(root / "m.txt").write_text("ours\n")
74+
repo.index.add(["m.txt"])
75+
repo.index.commit("ours")
76+
77+
78+
def include_evil_cfg(repo: git.Repo) -> None:
79+
"""Add `[include] path = ../evil.cfg` to the repository's own config."""
80+
with open(Path(repo.git_dir) / "config", "a") as config:
81+
config.write("[include]\n\tpath = ../evil.cfg\n")
82+
83+
84+
async def merge(repo: git.Repo, repository: Path | None) -> dict[str, object]:
85+
async with connect(repository) as session:
86+
result = await session.call_tool(
87+
"git_merge",
88+
{
89+
"repo_path": str(root_of(repo)),
90+
"source_branch": "feature",
91+
"fast_forward_only": False,
92+
},
93+
)
94+
return wire(result)
95+
96+
97+
@posix_only
98+
@pytest.mark.parametrize("confined", [False, True])
99+
@pytest.mark.anyio
100+
async def test_include_created_by_a_conflicting_merge_runs_nothing(
101+
tmp_path: Path, confined: bool
102+
) -> None:
103+
payload = Payload(tmp_path / "payload")
104+
repo = make_repo(tmp_path / "repo")
105+
diverged(repo, {"evil.cfg": filter_config(payload)})
106+
# The include names a file that only the merged branch adds.
107+
include_evil_cfg(repo)
108+
109+
result = await merge(repo, root_of(repo) if confined else None)
110+
111+
assert payload.runs() == []
112+
assert result["isError"] is True
113+
assert result["content"] == [{"type": "text", "text": CONFLICT}]
114+
assert not (root_of(repo) / "evil.cfg").exists()
115+
repo.close()
116+
117+
118+
@posix_only
119+
@pytest.mark.anyio
120+
async def test_config_linked_into_the_tree_and_rewritten_by_a_merge_runs_nothing(
121+
tmp_path: Path,
122+
) -> None:
123+
payload = Payload(tmp_path / "payload")
124+
repo = make_repo(tmp_path / "repo")
125+
root = root_of(repo)
126+
config = Path(repo.git_dir) / "config"
127+
# The repository's configuration is a tracked file; the merged branch
128+
# adds a filter to it.
129+
original = config.read_text()
130+
diverged(
131+
repo,
132+
{"repo.cfg": original + filter_config(payload)},
133+
{"repo.cfg": original},
134+
)
135+
config.unlink()
136+
os.symlink(root / "repo.cfg", config)
137+
138+
result = await merge(repo, None)
139+
140+
assert payload.runs() == []
141+
assert result["content"] == [{"type": "text", "text": CONFLICT}]
142+
repo.close()
143+
144+
145+
@posix_only
146+
def test_drivers_a_checkout_defines_are_overridden_for_the_rest_of_the_call(
147+
tmp_path: Path,
148+
) -> None:
149+
payload = Payload(tmp_path / "payload")
150+
repo = make_repo(tmp_path / "repo")
151+
root = root_of(repo)
152+
(root / ".gitattributes").write_text("* filter=x\n")
153+
repo.index.add([".gitattributes"])
154+
repo.index.commit("attributes")
155+
repo.git.checkout("-b", "feature")
156+
(root / "evil.cfg").write_text(filter_config(payload))
157+
repo.index.add(["evil.cfg"])
158+
repo.index.commit("config")
159+
repo.git.checkout("main")
160+
include_evil_cfg(repo)
161+
harden_repo(repo)
162+
163+
assert git_checkout(repo, "feature") == "Switched to branch 'feature'"
164+
# A later command in the same call, on a file the filter applies to.
165+
(root / "test.txt").write_text("changed\n")
166+
repo.git.add("test.txt")
167+
168+
assert payload.runs() == []
169+
repo.close()
170+
171+
172+
def test_a_failed_re_read_stops_the_call(repo: git.Repo) -> None:
173+
failure = git.GitCommandError(["git", "config"], 128)
174+
with (
175+
mock.patch.object(server, "harden_repo", side_effect=failure),
176+
pytest.raises(git.GitError) as raised,
177+
):
178+
_rewrite_tree(repo, "status")
179+
# Not a GitCommandError, which git_merge's cleanup would catch and then
180+
# run more git commands under incomplete overrides.
181+
assert not isinstance(raised.value, git.GitCommandError)
182+
assert "could not be read again after git status" in str(raised.value)
183+
184+
185+
def test_a_failed_re_read_after_a_conflicting_merge_runs_no_cleanup(
186+
tmp_path: Path,
187+
) -> None:
188+
repo = make_repo(tmp_path / "repo")
189+
diverged(repo, {})
190+
failure = git.GitCommandError(["git", "config"], 128)
191+
with (
192+
mock.patch.object(server, "harden_repo", side_effect=failure),
193+
pytest.raises(git.GitError) as raised,
194+
):
195+
git_merge(repo, "feature", fast_forward_only=False)
196+
# Not git_merge's cleanup (`_merge_failure`, a ValueError), which would
197+
# run more git commands under incomplete overrides.
198+
assert not isinstance(raised.value, (git.GitCommandError, ValueError))
199+
# The failed re-read, raised while the merge's own failure propagated.
200+
assert raised.value.__cause__ is failure
201+
merge_failure = failure.__context__
202+
assert isinstance(merge_failure, git.GitCommandError)
203+
assert "merge" in merge_failure.command
204+
assert "a merge may still be in progress" in str(raised.value)
205+
# `git merge --abort` never ran.
206+
assert (Path(repo.git_dir) / "MERGE_HEAD").exists()
207+
repo.close()

0 commit comments

Comments
 (0)