From ccc72ad01a030f879b1e66ebfe14dced0be0965e Mon Sep 17 00:00:00 2001 From: cliffhall Date: Fri, 4 Dec 2026 22:51:31 -0500 Subject: [PATCH] fix(git): harden working tree file handling Co-Authored-By: Claude Opus 5.5 Signed-off-by: cliffhall --- src/git/README.md | 2 +- src/git/src/mcp_server_git/server.py | 67 ++++++++++++++++++++--- src/git/tests/test_root_identity.py | 80 ++++++++++++++++++++++++++++ 3 files changed, 140 insertions(+), 9 deletions(-) create mode 100644 src/git/tests/test_root_identity.py diff --git a/src/git/README.md b/src/git/README.md index dfedceb2f7..bec510dca0 100644 --- a/src/git/README.md +++ b/src/git/README.md @@ -178,7 +178,7 @@ python -m mcp_server_git With `--repository` set, the server's `instructions` (in the `initialize` result for a 2025-11-25 client, and the `server/discover` result for a 2026-07-28 client) name that repository root, with symbolic links resolved, and tell the model to pass exactly that path as `repo_path`: for example, `This server is confined to the Git repository at /home/me/project. Pass exactly that path as repo_path to every tool and prompt: a path outside that repository is refused.` A client that gives the server's instructions to its model therefore needs no path in the user's prompt. `repo_path` is still required on every tool and prompt. Without `--repository` the server sends no instructions. -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. The `--repository` root itself may use a Git directory outside it only when that directory names the root back. A linked worktree's Git directory lives under the main repository's `.git` (`.git/worktrees/`), and the main repository's record of the worktree names the root back. Only the worktree itself may use that directory, so a repository nested in the worktree whose `.git` names it, or the main repository's `.git`, is refused. A submodule checkout can be the `--repository` too, or any root whose Git directory's own `config` sets `core.worktree` back to it, as a submodule's (`.git/modules/` in the superproject) does. Any other root whose `.git` file or `commondir` names a directory outside it, including one made with `git init --separate-git-dir`, is refused on every call, and the server logs a warning saying so at startup. The root's Git directory and common directory are fixed when the server starts: if the root's `.git` is later replaced, or gains a `commondir`, so that Git would use a different directory outside the root, the call is refused. With `--repository` set, the server also refuses a repository whose Git directory: +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. The `--repository` root itself may use a Git directory outside it only when that directory names the root back. A linked worktree's Git directory lives under the main repository's `.git` (`.git/worktrees/`), and the main repository's record of the worktree names the root back. Only the worktree itself may use that directory, so a repository nested in the worktree whose `.git` names it, or the main repository's `.git`, is refused. A submodule checkout can be the `--repository` too, or any root whose Git directory's own `config` sets `core.worktree` back to it, as a submodule's (`.git/modules/` in the superproject) does. Any other root whose `.git` file or `commondir` names a directory outside it, including one made with `git init --separate-git-dir`, is refused on every call, and the server logs a warning saying so at startup. The root itself is fixed when the server starts, as the directory its path resolved to then (the path the `instructions` name): if that path is later a symbolic link, another directory or nothing, because the root was renamed or removed, each call made after that is refused rather than served from whatever is there now, until the server is restarted. A replacement that happens while a call is in progress is not covered: that call can still reach what replaced the root. The root's Git directory and common directory are fixed when the server starts too: if the root's `.git` is later replaced, or gains a `commondir`, so that Git would use a different directory outside the root, the call is refused. With `--repository` set, the server also refuses a repository whose Git directory: - holds a file with more than one hard link, anywhere in it or in what a link in it leads to (other than a linked `hooks` directory), outside its object stores (`objects`, and a submodule's under `modules`). Git appends to a reflog in place, and rewrites files such as `MERGE_MSG` and `COMMIT_EDITMSG` in place, so such a file hard-linked to a file elsewhere would take that write there. A local clone hard-links the object store it clones, which is allowed, so a link that leads into or onto an object store holding such files is refused instead. - names alternate object stores (`objects/info/alternates` or `objects/info/http-alternates` with any entry), wherever they are. A clone made with `--reference` or `--shared` therefore cannot be used under `--repository`; `git repack -a -d` and then deleting `objects/info/alternates` makes it self-contained. diff --git a/src/git/src/mcp_server_git/server.py b/src/git/src/mcp_server_git/server.py index fefdeea0fa..e039fcb017 100644 --- a/src/git/src/mcp_server_git/server.py +++ b/src/git/src/mcp_server_git/server.py @@ -22,6 +22,7 @@ import logging import os import re +import stat import sys import tempfile import threading @@ -1125,6 +1126,49 @@ def git_show(repo: git.Repo, revision: str) -> str: return "".join(output) +# Each `--repository` root as it was when its server was created: the path it +# resolved to, and the identity (device, inode) of the directory there. Keyed +# by the configured path. Resolving the configured path again on each call +# would follow the root renamed away and a link, or another directory, put in +# its place, and serve whatever repository then sits there. +_ROOTS: dict[Path, tuple[Path, tuple[int, int]]] = {} + + +def record_root(allowed_repository: Path) -> Path: + """Fix the `--repository` root: resolve it and record its identity.""" + resolved = allowed_repository.resolve() + st = os.stat(resolved) + _ROOTS[allowed_repository] = (resolved, (st.st_dev, st.st_ino)) + return resolved + + +def fixed_root(allowed_repository: Path) -> Path: + """The `--repository` root as fixed at startup, still the same directory. + + Raises ValueError when the path the root resolved to is no longer the + directory that was there (a link now, or another directory), so that a + call made after the root was replaced does not reach what replaced it. A + replacement that races a call already past this check is not caught: the + call goes on to use the path by name. A root not yet recorded (a check called + with no server created) is recorded now. + """ + if allowed_repository not in _ROOTS: + return record_root(allowed_repository) + resolved, identity = _ROOTS[allowed_repository] + try: + st = os.lstat(resolved) + same = not stat.S_ISLNK(st.st_mode) and (st.st_dev, st.st_ino) == identity + except OSError: + same = False + if not same: + raise ValueError( + f"The allowed repository '{resolved}' is no longer the directory " + "the server started with; restart the server to use the directory " + "now at this path" + ) + return resolved + + def validate_repo_path(repo_path: Path, allowed_repository: Path | None) -> None: """Validate that repo_path is within the allowed repository path. @@ -1136,10 +1180,11 @@ def validate_repo_path(repo_path: Path, allowed_repository: Path | None) -> None if allowed_repository is None: return # No restriction configured - # Resolve both paths to handle symlinks and relative paths + # The root as fixed at startup, never the configured path resolved again. + resolved_allowed = fixed_root(allowed_repository) + # Resolve repo_path to handle symlinks and relative paths try: resolved_repo = repo_path.resolve() - resolved_allowed = allowed_repository.resolve() except (OSError, RuntimeError): raise ValueError(f"Invalid path: {repo_path}") @@ -1201,7 +1246,7 @@ def record_root_git_dirs(allowed_repository: Path) -> tuple[Path, Path] | None: the root's own, since nothing outside the root confirms it: None is recorded, and every call that would use it is refused. """ - allowed = allowed_repository.resolve() + allowed = fixed_root(allowed_repository) own: tuple[Path, Path] | None = None try: with _RootRepo(allowed, expand_vars=False) as repo: @@ -1299,7 +1344,7 @@ def validate_opened_repo( if allowed_repository is None: return - allowed = allowed_repository.resolve() + allowed = fixed_root(allowed_repository) def outside(kind: str) -> ValueError: return ValueError( @@ -2121,13 +2166,14 @@ def server_instructions(repository: Path | None) -> str | None: Confined by `--repository`, the server tells the model the one `repo_path` it accepts before the model's first call, so it does not have to guess one and read the allowed repository back from a refusal (#5610). - The path named is the one `validate_repo_path` compares against (resolved), - so the exact string passes. Unconfined, any repository is in scope and - there is nothing to name, so the server sends none. + The path named is the one `validate_repo_path` compares against (the root + as fixed at startup, `fixed_root`), so the exact string passes. Unconfined, + any repository is in scope and there is nothing to name, so the server + sends none. """ if repository is None: return None - root = repository.resolve() + root = fixed_root(repository) return ( f"This server is confined to the Git repository at {root}. Pass " "exactly that path as repo_path to every tool and prompt: a path " @@ -2155,6 +2201,11 @@ async def reject_unknown_tools( raise MCPError(code=INVALID_PARAMS, message=f"Unknown tool: {name}") return await call_next(ctx) + # The root is fixed now, its path and the directory there; each call + # checks against this, never the configured path resolved again. + if repository is not None: + record_root(repository) + server = MCPServer( "mcp-git", version=SERVER_VERSION, diff --git a/src/git/tests/test_root_identity.py b/src/git/tests/test_root_identity.py new file mode 100644 index 0000000000..601b76fa81 --- /dev/null +++ b/src/git/tests/test_root_identity.py @@ -0,0 +1,80 @@ +"""The `--repository` root is fixed when the server starts: its path and the +directory at that path. + +Each call compares the path it is given against the root as resolved at +startup, and refuses once that path is no longer the same directory: the root +renamed away and a symbolic link, or another directory, put in its place. +Resolving the configured path again on each call would follow the swap and +serve whatever repository now sits there. Each test drives the server through +an in-process MCP client and asserts on what comes back. +""" + +from pathlib import Path +from typing import Any + +import pytest +from conftest import connect, make_repo, text_result, wire + +ROOT_TEXT = "root content\n" +OTHER_TEXT = "other content\n" + + +def repo_with(path: Path, text: str) -> None: + repo = make_repo(path) + (path / "f.txt").write_text(text, newline="\n") + repo.index.add(["f.txt"]) + repo.index.commit("f") + repo.close() + + +def swap_symlink(root: Path, other: Path) -> None: + root.rename(root.with_name("held")) + root.symlink_to(other, target_is_directory=True) + + +def swap_directory(root: Path, other: Path) -> None: + root.rename(root.with_name("held")) + other.rename(root) + + +def swap_removed(root: Path, other: Path) -> None: + root.rename(root.with_name("held")) + + +@pytest.mark.parametrize("swap", [swap_symlink, swap_directory, swap_removed]) +async def test_root_swapped_between_calls_is_refused(tmp_path: Path, swap: Any): + root = tmp_path / "root" + other = tmp_path / "other" + repo_with(root, ROOT_TEXT) + repo_with(other, OTHER_TEXT) + show = {"repo_path": str(root), "revision": "HEAD:f.txt"} + async with connect(root) as session: + first = await session.call_tool("git_show", show) + assert wire(first) == text_result(ROOT_TEXT) + + swap(root, other) + + for tool, arguments in ( + ("git_show", show), + ("git_status", {"repo_path": str(root)}), + ): + result = wire(await session.call_tool(tool, arguments)) + assert result["isError"], tool + text = result["content"][0]["text"] + assert OTHER_TEXT not in text + assert "is no longer the directory the server started with" in text + + +async def test_root_reached_through_a_symlink_keeps_working(tmp_path: Path): + # `--repository` given as a link to the root: the root is the directory + # the link resolved to at startup, which stays the same directory. + root = tmp_path / "root" + repo_with(root, ROOT_TEXT) + link = tmp_path / "link" + link.symlink_to(root, target_is_directory=True) + async with connect(link) as session: + for repo_path in (link, root): + result = await session.call_tool( + "git_show", {"repo_path": str(repo_path), "revision": "HEAD:f.txt"} + ) + assert wire(result) == text_result(ROOT_TEXT)