Skip to content

Commit e7f2595

Browse files
cliffhallclaude
andcommitted
fix(git): check the directories git opens for a repository
Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: cliffhall <[email protected]>
1 parent 7599f59 commit e7f2595

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
@@ -136,6 +136,8 @@ python -m mcp_server_git
136136

137137
`--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.
138138

139+
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`.
140+
139141
### Usage with Claude Desktop
140142

141143
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
@@ -369,6 +370,64 @@ def validate_repo_path(repo_path: Path, allowed_repository: Path | None) -> None
369370
)
370371

371372

373+
def validate_opened_repo(
374+
repo: git.Repo, repo_path: Path, allowed_repository: Path | None
375+
) -> None:
376+
"""Validate that the directories git opened are within the allowed repository.
377+
378+
`validate_repo_path` checks only the path the caller passed. Git can then
379+
follow a `.git` file (`gitdir:`), a `commondir` file or `core.worktree` to
380+
a directory anywhere else, so the working tree, git directory and common
381+
directory git actually uses are checked too. The working tree must lie
382+
inside the allowed repository. The two git directories must lie inside it
383+
or be the allowed repository's own: a linked worktree's git directory
384+
lives under the main repository's `.git`, outside the worktree it serves.
385+
386+
Both git's answer (`rev-parse`, which the tools' git commands follow) and
387+
GitPython's (which some tools read directly) are checked: GitPython does
388+
not apply `core.worktree`, so the two can differ.
389+
"""
390+
if allowed_repository is None:
391+
return
392+
393+
allowed = allowed_repository.resolve()
394+
395+
def outside(used: Path) -> ValueError:
396+
return ValueError(
397+
f"Repository path '{repo_path}' uses '{used}', which is outside the "
398+
f"allowed repository '{allowed_repository}'"
399+
)
400+
401+
git_dir, common_dir, bare = repo.git.rev_parse(
402+
"--path-format=absolute",
403+
"--git-dir",
404+
"--git-common-dir",
405+
"--is-bare-repository",
406+
).splitlines()
407+
working_trees = [] if bare == "true" else [repo.git.rev_parse("--show-toplevel")]
408+
if repo.working_tree_dir is not None:
409+
working_trees.append(str(repo.working_tree_dir))
410+
for working_tree in map(Path, working_trees):
411+
if not working_tree.resolve().is_relative_to(allowed):
412+
raise outside(working_tree)
413+
414+
escaped = [
415+
p
416+
for p in map(Path, (git_dir, common_dir, repo.git_dir, repo.common_dir))
417+
if not p.resolve().is_relative_to(allowed)
418+
]
419+
if not escaped:
420+
return
421+
with git.Repo(allowed) as allowed_repo:
422+
own = {
423+
Path(allowed_repo.git_dir).resolve(),
424+
Path(allowed_repo.common_dir).resolve(),
425+
}
426+
for p in escaped:
427+
if p.resolve() not in own:
428+
raise outside(p)
429+
430+
372431
def git_branch(
373432
repo: git.Repo,
374433
branch_type: str,
@@ -524,7 +583,13 @@ async def reject_unknown_tools(
524583
def open_repo(repo_path: str) -> git.Repo:
525584
path = Path(repo_path)
526585
validate_repo_path(path, repository)
527-
return git.Repo(path)
586+
repo = git.Repo(path)
587+
try:
588+
validate_opened_repo(repo, path, repository)
589+
except Exception:
590+
repo.close()
591+
raise
592+
return repo
528593

529594
@server.tool(
530595
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
@@ -1175,6 +1176,111 @@ async def test_restricted_server_rejects_symlink_escape(tmp_path: Path, repo: gi
11751176
other.close()
11761177

11771178

1179+
def uses_outside(result: dict[str, Any], used: Path, allowed: Path) -> bool:
1180+
"""The result is the error for a repository git opened outside `allowed`."""
1181+
text = result["content"][0]["text"]
1182+
return (
1183+
result["isError"] is True
1184+
and f"uses '{used}'" in text
1185+
and f"which is outside the allowed repository '{allowed}'" in text
1186+
)
1187+
1188+
1189+
async def test_restricted_server_rejects_gitdir_file_pointing_outside(
1190+
tmp_path: Path, repo: git.Repo
1191+
):
1192+
# A `.git` file inside the allowed repository passes the path check, but
1193+
# git follows its `gitdir:` line to the repository it names. Neither a read
1194+
# nor a write may reach that repository.
1195+
root = root_of(repo)
1196+
other = make_repo(tmp_path / "other")
1197+
nested = root / "nested"
1198+
nested.mkdir()
1199+
(nested / ".git").write_text(f"gitdir: {other.git_dir}\n")
1200+
try:
1201+
shown = await call(
1202+
root, "git_show", {"repo_path": str(nested), "revision": "HEAD"}
1203+
)
1204+
assert uses_outside(shown, Path(other.git_dir), root)
1205+
branched = await call(
1206+
root,
1207+
"git_create_branch",
1208+
{"repo_path": str(nested), "branch_name": "escaped"},
1209+
)
1210+
assert uses_outside(branched, Path(other.git_dir), root)
1211+
assert "escaped" not in {head.name for head in other.heads}
1212+
finally:
1213+
other.close()
1214+
1215+
1216+
async def test_restricted_server_rejects_commondir_pointing_outside(
1217+
tmp_path: Path, repo: git.Repo
1218+
):
1219+
# A worktree-style git directory inside the allowed repository whose
1220+
# `commondir` names another repository's `.git` reads that repository's
1221+
# objects and refs.
1222+
root = root_of(repo)
1223+
other = make_repo(tmp_path / "other")
1224+
other.git.worktree("add", str(tmp_path / "other-wt"))
1225+
admin = root / "admin"
1226+
shutil.copytree(
1227+
Path(other.git_dir) / "worktrees" / "other-wt",
1228+
admin,
1229+
ignore=shutil.ignore_patterns("*.ipc"), # git's fsmonitor socket
1230+
)
1231+
(admin / "commondir").write_text(f"{other.git_dir}\n")
1232+
nested = root / "nested"
1233+
nested.mkdir()
1234+
(nested / ".git").write_text(f"gitdir: {admin}\n")
1235+
try:
1236+
result = await call(root, "git_log", {"repo_path": str(nested)})
1237+
assert uses_outside(result, Path(other.git_dir), root)
1238+
finally:
1239+
other.close()
1240+
1241+
1242+
async def test_restricted_server_rejects_worktree_config_pointing_outside(
1243+
tmp_path: Path, repo: git.Repo
1244+
):
1245+
# `core.worktree` in a nested repository moves its working tree, and every
1246+
# checkout or add with it, to wherever the setting names.
1247+
root = root_of(repo)
1248+
elsewhere = tmp_path / "elsewhere"
1249+
elsewhere.mkdir()
1250+
nested = make_repo(root / "nested")
1251+
with nested.config_writer() as config:
1252+
config.set_value("core", "worktree", str(elsewhere))
1253+
nested.close()
1254+
result = await call(root, "git_status", {"repo_path": str(root / "nested")})
1255+
assert uses_outside(result, elsewhere, root)
1256+
1257+
1258+
async def test_restricted_server_serves_a_linked_worktree(tmp_path: Path):
1259+
# A linked worktree's git directory lives under the main repository's
1260+
# `.git`, outside the worktree, and is still the allowed repository's own.
1261+
main = make_repo(tmp_path / "main")
1262+
worktree = tmp_path / "worktree"
1263+
main.git.worktree("add", str(worktree))
1264+
try:
1265+
result = await call(worktree, "git_status", {"repo_path": str(worktree)})
1266+
assert result["isError"] is False
1267+
finally:
1268+
main.close()
1269+
1270+
1271+
async def test_restricted_server_accepts_nested_bare_repository(repo: git.Repo):
1272+
# A bare repository has no working tree; its git directory is inside.
1273+
root = root_of(repo)
1274+
bare = git.Repo.init(root / "bare.git", bare=True)
1275+
bare.close()
1276+
result = await call(
1277+
root,
1278+
"git_branch",
1279+
{"repo_path": str(root / "bare.git"), "branch_type": "local"},
1280+
)
1281+
assert result["isError"] is False
1282+
1283+
11781284
async def test_restricted_server_accepts_nested_repository(repo: git.Repo):
11791285
# Characterization: the restriction is a path containment check, so a
11801286
# separate repository nested inside the allowed one is served.

0 commit comments

Comments
 (0)