Skip to content

Commit b711f8d

Browse files
authored
Merge pull request #5333 from modelcontextprotocol/v2/fix/GHSA-w766-5x43-whvw
fix(git): GHSA-w766-5x43-whvw
2 parents cb3c7fe + e7f2595 commit b711f8d

3 files changed

Lines changed: 177 additions & 4 deletions

File tree

‎src/git/README.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -139,6 +139,8 @@ python -m mcp_server_git
139139
140140
`--repository` (`-r`) accepts any path inside a Git working tree. At startup the server walks up to the enclosing repository root, the way `git rev-parse --show-toplevel` does, so `--repository .` works when a shared config is launched from any subdirectory of the repository. A path inside the repository therefore allows tool calls anywhere in that repository, not only under the subdirectory given. A path that does not exist, or is not inside a Git repository, is logged as a one-line error at startup.
141141

142+
A tool call's `repo_path` must be inside that repository, and so must the directories Git then uses for it: a repository nested inside whose `.git` file, `commondir` or `core.worktree` points outside is refused. A linked worktree can still be the `--repository`, though its Git directory lives under the main repository's `.git`.
143+
142144
### Usage with Claude Desktop
143145

144146
Add this to your `claude_desktop_config.json`:

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

Lines changed: 69 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,8 @@
11
# The git MCP server: tools that read and change a Git repository through
2-
# GitPython. Repository confinement (`--repository`, `validate_repo_path`) and
3-
# the flag-injection guards live beside the handlers because every tool call
4-
# must pass them before any git command runs.
2+
# GitPython. Repository confinement (`--repository`, `validate_repo_path` on the
3+
# path given, `validate_opened_repo` on the directories git then uses) and the
4+
# flag-injection guards live beside the handlers because every tool call must
5+
# pass them before any git command runs.
56
#
67
# Built on the MCP Python SDK's high-level `MCPServer` (#5174), the API these
78
# reference servers are meant to teach: each tool is a typed function, and the
@@ -414,6 +415,64 @@ def validate_repo_path(repo_path: Path, allowed_repository: Path | None) -> None
414415
)
415416

416417

418+
def validate_opened_repo(
419+
repo: git.Repo, repo_path: Path, allowed_repository: Path | None
420+
) -> None:
421+
"""Validate that the directories git opened are within the allowed repository.
422+
423+
`validate_repo_path` checks only the path the caller passed. Git can then
424+
follow a `.git` file (`gitdir:`), a `commondir` file or `core.worktree` to
425+
a directory anywhere else, so the working tree, git directory and common
426+
directory git actually uses are checked too. The working tree must lie
427+
inside the allowed repository. The two git directories must lie inside it
428+
or be the allowed repository's own: a linked worktree's git directory
429+
lives under the main repository's `.git`, outside the worktree it serves.
430+
431+
Both git's answer (`rev-parse`, which the tools' git commands follow) and
432+
GitPython's (which some tools read directly) are checked: GitPython does
433+
not apply `core.worktree`, so the two can differ.
434+
"""
435+
if allowed_repository is None:
436+
return
437+
438+
allowed = allowed_repository.resolve()
439+
440+
def outside(used: Path) -> ValueError:
441+
return ValueError(
442+
f"Repository path '{repo_path}' uses '{used}', which is outside the "
443+
f"allowed repository '{allowed_repository}'"
444+
)
445+
446+
git_dir, common_dir, bare = repo.git.rev_parse(
447+
"--path-format=absolute",
448+
"--git-dir",
449+
"--git-common-dir",
450+
"--is-bare-repository",
451+
).splitlines()
452+
working_trees = [] if bare == "true" else [repo.git.rev_parse("--show-toplevel")]
453+
if repo.working_tree_dir is not None:
454+
working_trees.append(str(repo.working_tree_dir))
455+
for working_tree in map(Path, working_trees):
456+
if not working_tree.resolve().is_relative_to(allowed):
457+
raise outside(working_tree)
458+
459+
escaped = [
460+
p
461+
for p in map(Path, (git_dir, common_dir, repo.git_dir, repo.common_dir))
462+
if not p.resolve().is_relative_to(allowed)
463+
]
464+
if not escaped:
465+
return
466+
with git.Repo(allowed) as allowed_repo:
467+
own = {
468+
Path(allowed_repo.git_dir).resolve(),
469+
Path(allowed_repo.common_dir).resolve(),
470+
}
471+
for p in escaped:
472+
if p.resolve() not in own:
473+
raise outside(p)
474+
475+
417476
def git_branch(
418477
repo: git.Repo,
419478
branch_type: str,
@@ -569,7 +628,13 @@ async def reject_unknown_tools(
569628
def open_repo(repo_path: str) -> git.Repo:
570629
path = Path(repo_path)
571630
validate_repo_path(path, repository)
572-
return git.Repo(path)
631+
repo = git.Repo(path)
632+
try:
633+
validate_opened_repo(repo, path, repository)
634+
except Exception:
635+
repo.close()
636+
raise
637+
return repo
573638

574639
@server.tool(
575640
name=GitTools.STATUS.value,

‎src/git/tests/test_protocol.py‎

Lines changed: 106 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99
"""
1010

1111
import json
12+
import shutil
1213
import re
1314
import threading
1415
import time
@@ -1226,6 +1227,111 @@ async def test_restricted_server_rejects_symlink_escape(tmp_path: Path, repo: gi
12261227
other.close()
12271228

12281229

1230+
def uses_outside(result: dict[str, Any], used: Path, allowed: Path) -> bool:
1231+
"""The result is the error for a repository git opened outside `allowed`."""
1232+
text = result["content"][0]["text"]
1233+
return (
1234+
result["isError"] is True
1235+
and f"uses '{used}'" in text
1236+
and f"which is outside the allowed repository '{allowed}'" in text
1237+
)
1238+
1239+
1240+
async def test_restricted_server_rejects_gitdir_file_pointing_outside(
1241+
tmp_path: Path, repo: git.Repo
1242+
):
1243+
# A `.git` file inside the allowed repository passes the path check, but
1244+
# git follows its `gitdir:` line to the repository it names. Neither a read
1245+
# nor a write may reach that repository.
1246+
root = root_of(repo)
1247+
other = make_repo(tmp_path / "other")
1248+
nested = root / "nested"
1249+
nested.mkdir()
1250+
(nested / ".git").write_text(f"gitdir: {other.git_dir}\n")
1251+
try:
1252+
shown = await call(
1253+
root, "git_show", {"repo_path": str(nested), "revision": "HEAD"}
1254+
)
1255+
assert uses_outside(shown, Path(other.git_dir), root)
1256+
branched = await call(
1257+
root,
1258+
"git_create_branch",
1259+
{"repo_path": str(nested), "branch_name": "escaped"},
1260+
)
1261+
assert uses_outside(branched, Path(other.git_dir), root)
1262+
assert "escaped" not in {head.name for head in other.heads}
1263+
finally:
1264+
other.close()
1265+
1266+
1267+
async def test_restricted_server_rejects_commondir_pointing_outside(
1268+
tmp_path: Path, repo: git.Repo
1269+
):
1270+
# A worktree-style git directory inside the allowed repository whose
1271+
# `commondir` names another repository's `.git` reads that repository's
1272+
# objects and refs.
1273+
root = root_of(repo)
1274+
other = make_repo(tmp_path / "other")
1275+
other.git.worktree("add", str(tmp_path / "other-wt"))
1276+
admin = root / "admin"
1277+
shutil.copytree(
1278+
Path(other.git_dir) / "worktrees" / "other-wt",
1279+
admin,
1280+
ignore=shutil.ignore_patterns("*.ipc"), # git's fsmonitor socket
1281+
)
1282+
(admin / "commondir").write_text(f"{other.git_dir}\n")
1283+
nested = root / "nested"
1284+
nested.mkdir()
1285+
(nested / ".git").write_text(f"gitdir: {admin}\n")
1286+
try:
1287+
result = await call(root, "git_log", {"repo_path": str(nested)})
1288+
assert uses_outside(result, Path(other.git_dir), root)
1289+
finally:
1290+
other.close()
1291+
1292+
1293+
async def test_restricted_server_rejects_worktree_config_pointing_outside(
1294+
tmp_path: Path, repo: git.Repo
1295+
):
1296+
# `core.worktree` in a nested repository moves its working tree, and every
1297+
# checkout or add with it, to wherever the setting names.
1298+
root = root_of(repo)
1299+
elsewhere = tmp_path / "elsewhere"
1300+
elsewhere.mkdir()
1301+
nested = make_repo(root / "nested")
1302+
with nested.config_writer() as config:
1303+
config.set_value("core", "worktree", str(elsewhere))
1304+
nested.close()
1305+
result = await call(root, "git_status", {"repo_path": str(root / "nested")})
1306+
assert uses_outside(result, elsewhere, root)
1307+
1308+
1309+
async def test_restricted_server_serves_a_linked_worktree(tmp_path: Path):
1310+
# A linked worktree's git directory lives under the main repository's
1311+
# `.git`, outside the worktree, and is still the allowed repository's own.
1312+
main = make_repo(tmp_path / "main")
1313+
worktree = tmp_path / "worktree"
1314+
main.git.worktree("add", str(worktree))
1315+
try:
1316+
result = await call(worktree, "git_status", {"repo_path": str(worktree)})
1317+
assert result["isError"] is False
1318+
finally:
1319+
main.close()
1320+
1321+
1322+
async def test_restricted_server_accepts_nested_bare_repository(repo: git.Repo):
1323+
# A bare repository has no working tree; its git directory is inside.
1324+
root = root_of(repo)
1325+
bare = git.Repo.init(root / "bare.git", bare=True)
1326+
bare.close()
1327+
result = await call(
1328+
root,
1329+
"git_branch",
1330+
{"repo_path": str(root / "bare.git"), "branch_type": "local"},
1331+
)
1332+
assert result["isError"] is False
1333+
1334+
12291335
async def test_restricted_server_accepts_nested_repository(repo: git.Repo):
12301336
# Characterization: the restriction is a path containment check, so a
12311337
# separate repository nested inside the allowed one is served.

0 commit comments

Comments
 (0)