From d893d97104b6d22ed96f0add5f2a9c7eee9e2452 Mon Sep 17 00:00:00 2001 From: cliffhall Date: Wed, 18 Nov 2026 13:01:19 -0500 Subject: [PATCH] fix(git): repeat the --repository check after a tool writes the working tree Under --repository the directories git uses were checked once per tool call, when the repository was opened. A command that writes the working tree can change the repository's configuration for the rest of the call: with .git/config linked to a tracked file, a merge that brings in core.worktree moved the working tree, and the `git merge --abort` after a conflict then wrote files outside the allowed repository. _rewrite_tree, which already re-reads the drivers after each such write, now also runs validate_opened_repo again when the call was opened under --repository, and stops the call before any other git command if the repository no longer passes. git_checkout, git_merge and git_commit take the allowed repository as an optional keyword argument and pass it down. Closes #5599 Co-Authored-By: Claude Fable 5.2 Signed-off-by: cliffhall --- src/git/README.md | 2 + src/git/src/mcp_server_git/server.py | 86 +++++++-- src/git/tests/test_tree_confinement.py | 257 +++++++++++++++++++++++++ 3 files changed, 330 insertions(+), 15 deletions(-) create mode 100644 src/git/tests/test_tree_confinement.py diff --git a/src/git/README.md b/src/git/README.md index 95d5a00875..b551d1ff57 100644 --- a/src/git/README.md +++ b/src/git/README.md @@ -180,6 +180,8 @@ A tool call's `repo_path` must be inside that repository, and so must the direct It also refuses a repository whose index (`.git/index`) names a path Git would read outside the working tree: an entry that is absolute, or has an empty, `.`, `..` or `.git` component (on Windows also one with a `:`, or with `\` as a separator), which is what `git add` refuses to write. Git reads an index as it finds it, so a hand-written one could otherwise make `git_diff_unstaged`, `git_diff` and `git_status` show files outside the repository. For the same reason, every Git command the server runs, with or without `--repository`, sets `core.untrackedCache` to `false`: the untracked cache is kept in the index and names the directories `git status` lists, so Git scans the working tree instead. +These checks run when a tool call opens the repository, and again after each Git command in the call that writes the working tree (`git_checkout`, `git_merge` and the `git merge --abort` after a conflict, and the autostash `git_commit` reapplies when it concludes a merge), since such a write can change the repository's configuration (a `.git/config` linked to a tracked file that gains a `core.worktree`). If the repository no longer passes, the call stops with an error before it runs another Git command, and the working tree stays as that command wrote it; a merge that conflicted is then still in progress rather than aborted. + ### A repository's own programs A repository's configuration and hooks travel with it (an unpacked archive, a shared folder, a vendored tree), so the server never runs a program they name, with or without `--repository`. Every Git command it runs overrides, through `GIT_CONFIG_COUNT`, the settings that would start one: diff --git a/src/git/src/mcp_server_git/server.py b/src/git/src/mcp_server_git/server.py index a6116db44b..556e85286e 100644 --- a/src/git/src/mcp_server_git/server.py +++ b/src/git/src/mcp_server_git/server.py @@ -459,7 +459,9 @@ def _has_staged_changes(repo: git.Repo) -> bool: return bool(repo.index.diff(repo.head.commit)) -def git_commit(repo: git.Repo, message: str) -> str: +def git_commit( + repo: git.Repo, message: str, *, allowed_repository: Path | None = None +) -> str: # repo.index.commit() writes a tree unconditionally, so without this check # a caller that forgot to stage gets a hash back for an empty commit and no # way to tell it apart from a real one. @@ -480,7 +482,7 @@ def git_commit(repo: git.Repo, message: str) -> str: commit = repo.index.commit(message, parent_commits=parents, skip_hooks=True) for name in ("MERGE_HEAD", "MERGE_MSG", "MERGE_MODE", "AUTO_MERGE"): (git_dir / name).unlink(missing_ok=True) - autostash_note = _apply_merge_autostash(repo) + autostash_note = _apply_merge_autostash(repo, allowed_repository) else: # skip_hooks: GitPython runs the repository's hooks itself, ignoring # the core.hooksPath override (`harden_repo`). @@ -489,7 +491,9 @@ def git_commit(repo: git.Repo, message: str) -> str: return f"Changes committed successfully with hash {commit.hexsha}{autostash_note}" -def _apply_merge_autostash(repo: git.Repo) -> str: +def _apply_merge_autostash( + repo: git.Repo, allowed_repository: Path | None = None +) -> str: """Reapply a `git merge --autostash` stash, as `git commit` does. Mirrors git's sequencer: apply the stash, store it in the stash list if @@ -503,7 +507,9 @@ def _apply_merge_autostash(repo: git.Repo) -> str: try: # Through _rewrite_tree although nothing after it runs a driver today # (`git stash store` runs none): any later git command must be safe. - _rewrite_tree(repo, "stash", "apply", stash_oid) + _rewrite_tree( + repo, "stash", "apply", stash_oid, allowed_repository=allowed_repository + ) note = "\nApplied autostash." except git.GitCommandError: repo.git.stash("store", "-m", "autostash", "-q", stash_oid) @@ -652,8 +658,13 @@ def git_create_branch( return f"Created branch '{branch_name}' from {base_label}" -def _rewrite_tree(repo: git.Repo, command: str, *args: str) -> str: - """Run `git `, which writes the working tree, then re-harden. +def _rewrite_tree( + repo: git.Repo, + command: str, + *args: str, + allowed_repository: Path | None = None, +) -> str: + """Run `git `, which writes the working tree, then re-check. `harden_repo` reads the repository's configuration when the call opens the repository, but that configuration can depend on the working tree: an @@ -671,6 +682,16 @@ def _rewrite_tree(repo: git.Repo, command: str, *args: str) -> str: If that read fails, the overrides may be incomplete, so the call stops with a `GitError`, which a caller's `except GitCommandError` cleanup does not catch, and no further git command runs. + + The same holds for where git operates (#5599). `open_repo` checked the + directories git uses against `allowed_repository` (`--repository`) before + the write, and the write can move them: a `.git/config` that is a link to + a tracked file gains a `core.worktree` naming a directory outside, and + the next git command that writes the tree (the `git merge --abort` after + a conflict) writes there instead. So `validate_opened_repo` runs again + too, after the drivers are read, as at open. A repository that no longer + passes stops the call the same way: no git command can be trusted to + stay inside, the cleanup included, so the tree stays as written. """ try: return getattr(repo.git, command)(*args) @@ -684,9 +705,22 @@ def _rewrite_tree(repo: git.Repo, command: str, *args: str) -> str: f"tree was left as git {command} wrote it (a merge may still be in " f"progress), and no further git command was run: {e}" ) from e + if allowed_repository is not None: + try: + validate_opened_repo(repo, Path(repo.working_dir), allowed_repository) + except (ValueError, OSError, git.GitError) as e: + raise git.GitError( + f"Stopped: after git {command} changed the working tree, the " + "repository no longer passes the --repository check. The " + f"working tree was left as git {command} wrote it (a merge may " + "still be in progress), and no further git command was run: " + f"{e}" + ) from e -def git_checkout(repo: git.Repo, branch_name: str) -> str: +def git_checkout( + repo: git.Repo, branch_name: str, *, allowed_repository: Path | None = None +) -> str: # Defense in depth: reject branch names starting with '-' to prevent flag injection, # even if a malicious ref with that name exists (e.g. via filesystem manipulation) if branch_name.startswith("-"): @@ -699,7 +733,9 @@ def git_checkout(repo: git.Repo, branch_name: str) -> str: # --quiet: without it, git checks each checked-out submodule of the new # branch for local changes, running git inside it under its own # configuration; the reply below does not use git's output. - _rewrite_tree(repo, "checkout", "--quiet", branch_name) + _rewrite_tree( + repo, "checkout", "--quiet", branch_name, allowed_repository=allowed_repository + ) # rev_parse accepts any revision, so branch_name may have been a sha, tag or # remote-tracking ref rather than a branch. Report what actually happened instead of # claiming a branch switch; a detached HEAD is easy to commit onto by mistake. @@ -717,7 +753,12 @@ def _git_stderr(error: git.GitCommandError) -> str: return message or str(error) -def _merge_failure(repo: git.Repo, error: git.GitCommandError, what: str) -> str: +def _merge_failure( + repo: git.Repo, + error: git.GitCommandError, + what: str, + allowed_repository: Path | None = None, +) -> str: """Why `git merge` failed, after undoing whatever it left behind. A merge that stops on conflicts, or fails to write its merge commit, @@ -737,7 +778,7 @@ def _merge_failure(repo: git.Repo, error: git.GitCommandError, what: str) -> str ).splitlines() # Through _rewrite_tree although it is the last git command here, so a git # command added after it reads drivers the restored tree defines. - _rewrite_tree(repo, "merge", "--abort") + _rewrite_tree(repo, "merge", "--abort", allowed_repository=allowed_repository) if conflicts: return ( f"{what} stopped on conflicts in: {', '.join(conflicts)}. {unchanged} " @@ -747,7 +788,11 @@ def _merge_failure(repo: git.Repo, error: git.GitCommandError, what: str) -> str def git_merge( - repo: git.Repo, source_branch: str, fast_forward_only: bool = True + repo: git.Repo, + source_branch: str, + fast_forward_only: bool = True, + *, + allowed_repository: Path | None = None, ) -> str: """Merge `source_branch` into the current branch, or change nothing. @@ -757,6 +802,9 @@ def git_merge( The conflicts are reported for the caller to resolve by hand. By default only a fast-forward is allowed; `fast_forward_only=False` lets git create a merge commit when the branches have diverged. + + `allowed_repository` is the `--repository` the call was opened under, + checked again after each write to the working tree (`_rewrite_tree`). """ # Defense in depth: reject sources starting with '-' to prevent flag # injection, even if a malicious ref with that name exists. @@ -825,10 +873,11 @@ def git_merge( "-m", f"Merge '{source_branch}' into '{target}'", source.hexsha, + allowed_repository=allowed_repository, ) except git.GitCommandError as e: what = f"Merge of '{source_branch}' into '{target}'" - raise ValueError(_merge_failure(repo, e, what)) from e + raise ValueError(_merge_failure(repo, e, what, allowed_repository)) from e merged = repo.head.commit if fast_forward: return f"Fast-forwarded '{target}' to '{source_branch}' ({merged.hexsha[:7]})" @@ -1597,7 +1646,7 @@ def diff( ) @reports_failures def commit(repo_path: str, message: str) -> str: - return git_commit(open_repo(repo_path), message) + return git_commit(open_repo(repo_path), message, allowed_repository=repository) @server.tool( name=GitTools.ADD.value, @@ -1684,7 +1733,9 @@ def create_branch( ) @reports_failures def checkout(repo_path: str, branch_name: str) -> str: - return git_checkout(open_repo(repo_path), branch_name) + return git_checkout( + open_repo(repo_path), branch_name, allowed_repository=repository + ) @server.tool( name=GitTools.MERGE.value, @@ -1715,7 +1766,12 @@ def merge( ), ] = True, ) -> str: - return git_merge(open_repo(repo_path), source_branch, fast_forward_only) + return git_merge( + open_repo(repo_path), + source_branch, + fast_forward_only, + allowed_repository=repository, + ) @server.tool( name=GitTools.SHOW.value, diff --git a/src/git/tests/test_tree_confinement.py b/src/git/tests/test_tree_confinement.py new file mode 100644 index 0000000000..bcaa669266 --- /dev/null +++ b/src/git/tests/test_tree_confinement.py @@ -0,0 +1,257 @@ +"""Under `--repository`, a tool call's own writes cannot move where git works. + +`open_repo` checks the directories git uses (`validate_opened_repo`) once, +when a call opens the repository. But a repository's configuration can depend +on its working tree: a `.git/config` that is a link to a tracked file changes +whenever a merge or a checkout rewrites that file. A branch that adds +`core.worktree = ` to it so moves the working tree in +the middle of a call, and the git commands the call runs next (the +`git merge --abort` after a conflict, which writes files) would work in that +directory (#5599, the follow-up to GHSA-9vjp-x34c-xg6v). Every tree-writing +command goes through `_rewrite_tree`, which runs the check again before any +other git command, and stops the call when the repository no longer passes. + +The tests drive the real server through a client and assert that a directory +outside the allowed repository is left exactly as it was. They link +`.git/config` to a tracked file, so they skip on Windows, where creating a +symbolic link needs a privilege; the tests of `_rewrite_tree` itself run +everywhere. +""" + +import os +import sys +from pathlib import Path +from unittest import mock + +import git +import pytest +from conftest import connect, make_repo, wire +from test_repository_config import root_of + +from mcp_server_git import server +from mcp_server_git.server import _rewrite_tree, git_checkout + +needs_symlinks = pytest.mark.skipif( + sys.platform == "win32", reason="creating a symbolic link needs a privilege" +) + +STOPPED = ( + "Error executing tool {tool}: Stopped: after git {command} changed the " + "working tree, the repository no longer passes the --repository check. The " + "working tree was left as git {command} wrote it (a merge may still be in " + "progress), and no further git command was run: Repository path '{root}' " + "uses '{outside}', which is outside the allowed repository '{root}'" +) + + +def outside_dir(tmp_path: Path) -> Path: + """A directory beside the repository, holding a file named like a tracked one.""" + outside = tmp_path / "outside" + outside.mkdir() + (outside / "m.txt").write_text("not the repository's\n") + return outside + + +def contents(directory: Path) -> dict[str, str]: + return {p.name: p.read_text() for p in directory.iterdir()} + + +def worktree_config(repo: git.Repo, outside: Path) -> str: + """The repository's configuration, with `core.worktree` naming `outside`.""" + original = (Path(repo.git_dir) / "config").read_text() + return f"{original}[core]\n\tworktree = {outside.as_posix()}\n" + + +def track_config(repo: git.Repo) -> None: + """Commit `m.txt` and `repo.cfg`, a copy of the repository's configuration.""" + root = root_of(repo) + (root / "m.txt").write_text("base\n") + (root / "repo.cfg").write_text((Path(repo.git_dir) / "config").read_text()) + repo.index.add(["m.txt", "repo.cfg"]) + repo.index.commit("base") + + +def link_config(repo: git.Repo) -> None: + """Make `.git/config` a link to the tracked `repo.cfg`. + + The link stays inside the repository, so the check at open allows it. + """ + config = Path(repo.git_dir) / "config" + config.unlink() + os.symlink(root_of(repo) / "repo.cfg", config) + + +def feature_moves_the_worktree(repo: git.Repo, outside: Path) -> None: + """Branch `feature` changes m.txt and adds `core.worktree` to repo.cfg.""" + root = root_of(repo) + moved = worktree_config(repo, outside) + repo.git.checkout("-b", "feature") + (root / "m.txt").write_text("theirs\n") + (root / "repo.cfg").write_text(moved) + repo.index.add(["m.txt", "repo.cfg"]) + repo.index.commit("theirs") + repo.git.checkout("main") + + +async def call(repo: git.Repo, tool: str, **arguments: object) -> dict[str, object]: + root = root_of(repo) + async with connect(root) as session: + result = await session.call_tool(tool, {"repo_path": str(root), **arguments}) + return wire(result) + + +def stopped( + repo: git.Repo, outside: Path, tool: str, command: str +) -> dict[str, object]: + text = STOPPED.format( + tool=tool, command=command, root=root_of(repo), outside=outside.resolve() + ) + return {"content": [{"type": "text", "text": text}], "isError": True} + + +@needs_symlinks +@pytest.mark.anyio +async def test_a_conflicting_merge_that_moves_the_worktree_is_not_aborted_outside( + tmp_path: Path, +) -> None: + outside = outside_dir(tmp_path) + before = contents(outside) + repo = make_repo(tmp_path / "repo") + root = root_of(repo) + track_config(repo) + feature_moves_the_worktree(repo, outside) + (root / "m.txt").write_text("ours\n") + repo.index.add(["m.txt"]) + repo.index.commit("ours") + link_config(repo) + + result = await call( + repo, "git_merge", source_branch="feature", fast_forward_only=False + ) + + # Without the second check, `git merge --abort` ran with the working tree + # at `outside`: it overwrote m.txt there and wrote repo.cfg beside it. + assert contents(outside) == before + assert result == stopped(repo, outside, "git_merge", "merge") + # Neither `git diff` nor `git merge --abort` ran: the merge is as git left it. + assert (Path(repo.git_dir) / "MERGE_HEAD").exists() + repo.close() + + +@needs_symlinks +@pytest.mark.anyio +async def test_a_fast_forward_that_moves_the_worktree_is_reported( + tmp_path: Path, +) -> None: + outside = outside_dir(tmp_path) + before = contents(outside) + repo = make_repo(tmp_path / "repo") + track_config(repo) + feature_moves_the_worktree(repo, outside) + link_config(repo) + + result = await call(repo, "git_merge", source_branch="feature") + + assert contents(outside) == before + assert result == stopped(repo, outside, "git_merge", "merge") + repo.close() + + +@needs_symlinks +@pytest.mark.anyio +async def test_a_checkout_that_moves_the_worktree_is_reported(tmp_path: Path) -> None: + outside = outside_dir(tmp_path) + before = contents(outside) + repo = make_repo(tmp_path / "repo") + track_config(repo) + feature_moves_the_worktree(repo, outside) + link_config(repo) + + result = await call(repo, "git_checkout", branch_name="feature") + + assert contents(outside) == before + assert result == stopped(repo, outside, "git_checkout", "checkout") + repo.close() + + +@needs_symlinks +@pytest.mark.anyio +async def test_an_autostash_that_moves_the_worktree_is_reported(tmp_path: Path) -> None: + outside = outside_dir(tmp_path) + before = contents(outside) + repo = make_repo(tmp_path / "repo") + root = root_of(repo) + track_config(repo) + repo.git.checkout("-b", "feature") + (root / "m.txt").write_text("theirs\n") + repo.index.add(["m.txt"]) + repo.index.commit("theirs") + repo.git.checkout("main") + # A merge left for git_commit to conclude, whose autostash holds the + # change to repo.cfg. The configuration is not linked to it yet, so the + # setup's own git commands stay in the repository. + (root / "repo.cfg").write_text(worktree_config(repo, outside)) + repo.git.merge("--autostash", "--no-ff", "--no-commit", "feature") + autostash = Path(repo.git_dir) / "MERGE_AUTOSTASH" + assert autostash.exists() + link_config(repo) + + result = await call(repo, "git_commit", message="merge feature") + + assert contents(outside) == before + assert result == stopped(repo, outside, "git_commit", "stash") + # Nothing ran after `git stash apply`: the autostash was not cleared. + assert autostash.exists() + repo.close() + + +@pytest.mark.anyio +async def test_an_ordinary_repository_merges_and_checks_out_as_before( + tmp_path: Path, +) -> None: + repo = make_repo(tmp_path / "repo") + root = root_of(repo) + repo.git.checkout("-b", "feature") + (root / "new.txt").write_text("new\n") + repo.index.add(["new.txt"]) + commit = repo.index.commit("new") + repo.git.checkout("main") + + merged = await call(repo, "git_merge", source_branch="feature") + switched = await call(repo, "git_checkout", branch_name="feature") + + text = f"Fast-forwarded 'main' to 'feature' ({commit.hexsha[:7]})" + assert merged["content"] == [{"type": "text", "text": text}] + assert switched["content"] == [ + {"type": "text", "text": "Switched to branch 'feature'"} + ] + repo.close() + + +def test_without_an_allowed_repository_nothing_is_checked(repo: git.Repo) -> None: + repo.git.branch("feature") + with mock.patch.object(server, "validate_opened_repo") as validate: + assert git_checkout(repo, "feature") == "Switched to branch 'feature'" + validate.assert_not_called() + + +@pytest.mark.parametrize( + "failure", + [ + # A git command of the check itself failing: reported as a GitError + # that is not a GitCommandError, which git_merge's cleanup would catch. + git.GitCommandError(["git", "rev-parse"], 128), + ValueError("uses '/elsewhere', which is outside the allowed repository"), + OSError("a git directory that cannot be listed"), + ], +) +def test_a_failed_check_stops_the_call(repo: git.Repo, failure: Exception) -> None: + with ( + mock.patch.object(server, "validate_opened_repo", side_effect=failure), + pytest.raises(git.GitError) as raised, + ): + _rewrite_tree(repo, "status", allowed_repository=root_of(repo)) + assert not isinstance(raised.value, git.GitCommandError) + assert raised.value.__cause__ is failure + assert "no longer passes the --repository check" in str(raised.value) + assert "after git status changed the working tree" in str(raised.value)