From 386113b13cf28f7e814feebf9f27f66a022e22f1 Mon Sep 17 00:00:00 2001 From: cliffhall Date: Fri, 27 Nov 2026 00:31:29 -0500 Subject: [PATCH 1/7] fix(git): GHSA-5pwg-5xfw-x322 Co-Authored-By: Claude Opus 5.5 Signed-off-by: cliffhall --- src/git/src/mcp_server_git/server.py | 68 +++++++++++- src/git/tests/test_alternates_race.py | 143 ++++++++++++++++++++++++++ 2 files changed, 209 insertions(+), 2 deletions(-) create mode 100644 src/git/tests/test_alternates_race.py diff --git a/src/git/src/mcp_server_git/server.py b/src/git/src/mcp_server_git/server.py index 9aea4cfb3c..571541ba9b 100644 --- a/src/git/src/mcp_server_git/server.py +++ b/src/git/src/mcp_server_git/server.py @@ -22,6 +22,8 @@ import logging import os import re +import sys +import tempfile import threading from collections.abc import Callable, Iterator from contextlib import contextmanager @@ -43,6 +45,9 @@ from .transport import run +if sys.platform == "win32": # pragma: no cover # the coverage gate runs on Linux + import _winapi + # The version this server reports in serverInfo, read from the installed # distribution's metadata (pyproject.toml) so it cannot drift from the # published version (#360). Without it the SDK reports its own `mcp` version. @@ -887,13 +892,27 @@ def git_merge( ) -def git_show(repo: git.Repo, revision: str) -> str: +def git_show( + repo: git.Repo, revision: str, allowed_repository: Path | None = None +) -> str: + """Show `revision`: a commit with its patch, a blob's text or a tree's names. + + Under `--repository` (`allowed_repository` set) git reads objects through + `_own_object_store`, so only the repository's own objects are shown. + """ # Defense in depth: reject revisions starting with '-' to prevent flag injection, # even if a malicious ref with that name exists (e.g. via filesystem manipulation) if revision.startswith("-"): raise FlagInjectionError( f"Invalid revision: '{revision}' - cannot start with '-'" ) + if allowed_repository is None: + return _show(repo, revision) + with _own_object_store(repo): + return _show(repo, revision) + + +def _show(repo: git.Repo, revision: str) -> str: obj = repo.rev_parse(revision) if isinstance(obj, git.Blob): return obj.data_stream.read().decode("utf-8", errors="replace") @@ -1083,6 +1102,51 @@ def _check_index_entries(repo: git.Repo, repo_path: Path) -> None: _ALTERNATES = ("alternates", "http-alternates") +@contextmanager +def _own_object_store(repo: git.Repo) -> Iterator[None]: + """Run `repo`'s git on its own objects only, whatever its alternates say. + + `_check_git_dir_contents` refuses an alternates entry when the repository + is opened, but the file can be rewritten before git reads an object, and + git has no setting that turns alternates off. So git is pointed + (`GIT_OBJECT_DIRECTORY`) at a new, private directory holding a link to + each of the repository's loose-object directories and to its `pack` + directory, and nothing else: git reads the alternates list from that + directory's `info/alternates`, which does not exist. Links are followed + for reading. Nothing is written there, so this is for reading objects + only. On Windows the links are directory junctions, which need no + privilege. + + GitPython's persistent `git cat-file` processes are stopped before and + after, so none reads with the environment it does not belong to. + """ + objects = Path(repo.common_dir) / "objects" + own = Path(tempfile.mkdtemp(prefix="mcp-git-objects-")) + links: list[Path] = [] + try: + for name in [f"{i:02x}" for i in range(256)] + ["pack"]: + link = own / name + if sys.platform != "win32": + os.symlink(objects / name, link, target_is_directory=True) + else: # pragma: no cover # Windows only; the coverage gate runs on Linux + _winapi.CreateJunction(str(objects / name), str(link)) + links.append(link) + repo.git.clear_cache() + with repo.git.custom_environment(GIT_OBJECT_DIRECTORY=str(own)): + try: + yield + finally: + repo.git.clear_cache() + finally: + # Each link is removed as a link, so what it names is never touched. + for link in links: + if sys.platform != "win32": + os.unlink(link) + else: # pragma: no cover # Windows only; the coverage gate runs on Linux + os.rmdir(link) + os.rmdir(own) + + def _check_git_dir_contents( repo_path: Path, directory: Path, @@ -1806,7 +1870,7 @@ def merge( ) @reports_failures def show(repo_path: str, revision: str) -> str: - return git_show(open_repo(repo_path), revision) + return git_show(open_repo(repo_path), revision, allowed_repository=repository) @server.tool( name=GitTools.BRANCH.value, diff --git a/src/git/tests/test_alternates_race.py b/src/git/tests/test_alternates_race.py new file mode 100644 index 0000000000..be6a11a4f7 --- /dev/null +++ b/src/git/tests/test_alternates_race.py @@ -0,0 +1,143 @@ +"""git_show reads only the repository's own objects under `--repository`. + +`_check_git_dir_contents` refuses an alternate object store when a repository +is opened, but the alternates file is an ordinary file in the git directory, +so its contents can change between that check and the object reads that +follow it. Under `--repository`, `git_show` therefore runs git on an object +directory of its own (`_own_object_store`) whose alternates list is always +empty, so what the repository's alternates file says while git reads objects +no longer matters. + +The tests are deterministic rather than a race: the check is wrapped so that +it plants an alternates entry right after it has passed, which is the state +git would see if a write landed in that window. Without `--repository`, +alternates keep working, since a `--shared` or `--reference` clone is a +supported repository there. +""" + +from collections.abc import Callable, Iterator +from contextlib import contextmanager +from pathlib import Path +from typing import Any +from unittest import mock + +import git +import pytest +from conftest import connect, make_repo, wire + +from mcp_server_git import server + +MARKER = "ONLY_IN_THE_OTHER_REPOSITORY\n" + + +def objects_of(repo: git.Repo) -> Path: + return Path(repo.common_dir) / "objects" + + +@pytest.fixture +def other(tmp_path: Path) -> git.Repo: + """A repository outside the allowed one, with a commit of its own.""" + repo = make_repo(tmp_path / "other") + assert repo.working_dir is not None + (Path(repo.working_dir) / "only-here.txt").write_text(MARKER) + repo.index.add(["only-here.txt"]) + repo.index.commit("only in the other repository") + return repo + + +@contextmanager +def alternates_planted_after_check(alternates: Path, entry: str) -> Iterator[None]: + """Write `entry` to `alternates` each time the git-directory check passes.""" + check: Callable[..., None] = server._check_git_dir_contents + + def check_then_plant(*args: Any, **kwargs: Any) -> None: + check(*args, **kwargs) + alternates.write_text(entry) + + with mock.patch.object(server, "_check_git_dir_contents", check_then_plant): + yield + + +async def show(repository: Path | None, repo_path: Path, revision: str) -> Any: + async with connect(repository) as session: + return wire( + await session.call_tool( + "git_show", {"repo_path": str(repo_path), "revision": revision} + ) + ) + + +@pytest.mark.parametrize("revision", ["{blob}", "{commit}", "{commit}:"]) +async def test_restricted_git_show_ignores_alternates_written_after_the_check( + test_repository: git.Repo, other: git.Repo, revision: str +): + root = Path(test_repository.working_dir or "") + alternates = objects_of(test_repository) / "info" / "alternates" + alternates.parent.mkdir(parents=True, exist_ok=True) + rev = revision.format( + blob=other.git.rev_parse("HEAD:only-here.txt"), + commit=other.head.commit.hexsha, + ) + + with alternates_planted_after_check(alternates, f"{objects_of(other)}\n"): + result = await show(root, root, rev) + + # The entry really was in place when git_show read objects. + assert alternates.read_text() == f"{objects_of(other)}\n" + assert result["isError"] is True + text = result["content"][0]["text"] + assert "ONLY_IN_THE_OTHER_REPOSITORY" not in text + assert "only-here.txt" not in text + + +async def test_restricted_git_show_still_reads_the_repositorys_own_objects( + test_repository: git.Repo, +): + root = Path(test_repository.working_dir or "") + (root / "packed.txt").write_text("PACKED\n") + test_repository.index.add(["packed.txt"]) + test_repository.index.commit("packed") + test_repository.git.gc("--quiet") # moves every object into a pack + (root / "loose.txt").write_text("LOOSE\n") + test_repository.index.add(["loose.txt"]) + test_repository.index.commit("loose") + + for revision, expected in [ + ("HEAD:packed.txt", "PACKED"), + ("HEAD:loose.txt", "LOOSE"), + ("HEAD", "+LOOSE"), + ("HEAD~1", "+PACKED"), + ]: + result = await show(root, root, revision) + assert result["isError"] is False, result + assert expected in result["content"][0]["text"] + + +async def test_restricted_git_show_leaves_no_object_directory_behind( + test_repository: git.Repo, tmp_path: Path +): + root = Path(test_repository.working_dir or "") + scratch = tmp_path / "scratch" + scratch.mkdir() + with mock.patch("tempfile.tempdir", str(scratch)): + ok = await show(root, root, "HEAD") + failed = await show(root, root, "0" * 40) + assert ok["isError"] is False + assert failed["isError"] is True + assert list(scratch.iterdir()) == [] + + +async def test_unrestricted_git_show_follows_alternates( + test_repository: git.Repo, other: git.Repo +): + # Without --repository, a clone made with --shared or --reference reads + # its objects from the store it names, as git does. + root = Path(test_repository.working_dir or "") + alternates = objects_of(test_repository) / "info" / "alternates" + alternates.parent.mkdir(parents=True, exist_ok=True) + alternates.write_text(f"{objects_of(other)}\n") + + result = await show(None, root, other.git.rev_parse("HEAD:only-here.txt")) + + assert result["isError"] is False + assert result["content"][0]["text"] == MARKER From f4174562f7912409ceb8d0ab930dbd93fd557242 Mon Sep 17 00:00:00 2001 From: cliffhall Date: Fri, 27 Nov 2026 01:12:03 -0500 Subject: [PATCH 2/7] fix(git): GHSA-5pwg-5xfw-x322 Co-Authored-By: Claude Opus 5.5 Signed-off-by: cliffhall --- src/git/src/mcp_server_git/server.py | 79 +++++++---- src/git/tests/test_alternates_race.py | 197 ++++++++++++++++++++------ 2 files changed, 212 insertions(+), 64 deletions(-) diff --git a/src/git/src/mcp_server_git/server.py b/src/git/src/mcp_server_git/server.py index 571541ba9b..624167a35f 100644 --- a/src/git/src/mcp_server_git/server.py +++ b/src/git/src/mcp_server_git/server.py @@ -26,7 +26,8 @@ import tempfile import threading from collections.abc import Callable, Iterator -from contextlib import contextmanager +from contextlib import ExitStack, contextmanager +from contextvars import ContextVar from enum import Enum from functools import wraps from importlib.metadata import version @@ -892,27 +893,13 @@ def git_merge( ) -def git_show( - repo: git.Repo, revision: str, allowed_repository: Path | None = None -) -> str: - """Show `revision`: a commit with its patch, a blob's text or a tree's names. - - Under `--repository` (`allowed_repository` set) git reads objects through - `_own_object_store`, so only the repository's own objects are shown. - """ +def git_show(repo: git.Repo, revision: str) -> str: # Defense in depth: reject revisions starting with '-' to prevent flag injection, # even if a malicious ref with that name exists (e.g. via filesystem manipulation) if revision.startswith("-"): raise FlagInjectionError( f"Invalid revision: '{revision}' - cannot start with '-'" ) - if allowed_repository is None: - return _show(repo, revision) - with _own_object_store(repo): - return _show(repo, revision) - - -def _show(repo: git.Repo, revision: str) -> str: obj = repo.rev_parse(revision) if isinstance(obj, git.Blob): return obj.data_stream.read().decode("utf-8", errors="replace") @@ -1112,10 +1099,15 @@ def _own_object_store(repo: git.Repo) -> Iterator[None]: (`GIT_OBJECT_DIRECTORY`) at a new, private directory holding a link to each of the repository's loose-object directories and to its `pack` directory, and nothing else: git reads the alternates list from that - directory's `info/alternates`, which does not exist. Links are followed - for reading. Nothing is written there, so this is for reading objects - only. On Windows the links are directory junctions, which need no - privilege. + directory's `info/alternates`, which does not exist. On Windows the links + are directory junctions, which need no privilege. + + Git follows the links for writing too: a new loose object is written to + a temporary file in its own `xx` directory and renamed there, and a pack + in `pack`, so what git writes lands in the repository's store. A link to + a missing directory could not be written through, so each loose-object + directory the store lacks is created first, as git would on its first + write to it. GitPython's persistent `git cat-file` processes are stopped before and after, so none reads with the environment it does not belong to. @@ -1125,6 +1117,7 @@ def _own_object_store(repo: git.Repo) -> Iterator[None]: links: list[Path] = [] try: for name in [f"{i:02x}" for i in range(256)] + ["pack"]: + (objects / name).mkdir(exist_ok=True) link = own / name if sys.platform != "win32": os.symlink(objects / name, link, target_is_directory=True) @@ -1147,6 +1140,31 @@ def _own_object_store(repo: git.Repo) -> Iterator[None]: os.rmdir(own) +# What a tool call or prompt has to undo when it ends: `open_repo` enters a +# repository's `_own_object_store` here, since most tools never close the +# repository they open. +_CALL: ContextVar[ExitStack | None] = ContextVar("_CALL", default=None) + + +@contextmanager +def _one_call() -> Iterator[None]: + """Scope one tool call or prompt; what it entered in `_CALL` ends with it.""" + with ExitStack() as stack: + token = _CALL.set(stack) + try: + yield + finally: + _CALL.reset(token) + + +def _read_own_objects_for_call(repo: git.Repo) -> None: + """Run `repo`'s git through `_own_object_store` until the call ends.""" + stack = _CALL.get() + if stack is None: + raise RuntimeError("a repository opened under --repository needs _one_call()") + stack.enter_context(_own_object_store(repo)) + + def _check_git_dir_contents( repo_path: Path, directory: Path, @@ -1460,7 +1478,7 @@ def reports_failures(fn: Callable[_P, str]) -> Callable[_P, str]: @wraps(fn) def wrapper(*args: _P.args, **kwargs: _P.kwargs) -> str: - with _GIT_LOCK, reported_to_model(): + with _GIT_LOCK, _one_call(), reported_to_model(): return fn(*args, **kwargs) return wrapper @@ -1615,6 +1633,9 @@ def open_repo(repo_path: str) -> git.Repo: # confinement checks' included, runs a program it names. harden_repo(repo) validate_opened_repo(repo, path, repository) + if repository is not None: + # Last, once the directories it links to have been checked. + _read_own_objects_for_call(repo) except Exception: repo.close() raise @@ -1631,7 +1652,12 @@ def open_repo(repo_path: str) -> git.Repo: def commit_message( repo_path: Annotated[str, Field(description="The path to the Git repository.")], ) -> str: - with _GIT_LOCK, reported_as_invalid_params(), open_repo(repo_path) as repo: + with ( + _GIT_LOCK, + _one_call(), + reported_as_invalid_params(), + open_repo(repo_path) as repo, + ): return commit_message_prompt(repo) @server.prompt( @@ -1654,7 +1680,12 @@ def summarize_changes( ), ] = None, ) -> str: - with _GIT_LOCK, reported_as_invalid_params(), open_repo(repo_path) as repo: + with ( + _GIT_LOCK, + _one_call(), + reported_as_invalid_params(), + open_repo(repo_path) as repo, + ): return summarize_changes_prompt(repo, target) @server.tool( @@ -1870,7 +1901,7 @@ def merge( ) @reports_failures def show(repo_path: str, revision: str) -> str: - return git_show(open_repo(repo_path), revision, allowed_repository=repository) + return git_show(open_repo(repo_path), revision) @server.tool( name=GitTools.BRANCH.value, diff --git a/src/git/tests/test_alternates_race.py b/src/git/tests/test_alternates_race.py index be6a11a4f7..560e48eea1 100644 --- a/src/git/tests/test_alternates_race.py +++ b/src/git/tests/test_alternates_race.py @@ -1,18 +1,20 @@ -"""git_show reads only the repository's own objects under `--repository`. +"""Under `--repository`, git reads only the repository's own objects. `_check_git_dir_contents` refuses an alternate object store when a repository is opened, but the alternates file is an ordinary file in the git directory, so its contents can change between that check and the object reads that -follow it. Under `--repository`, `git_show` therefore runs git on an object -directory of its own (`_own_object_store`) whose alternates list is always -empty, so what the repository's alternates file says while git reads objects -no longer matters. +follow it. Under `--repository`, `open_repo` therefore runs git, for the rest +of the tool call or prompt, on an object directory of its own +(`_own_object_store`) whose alternates list is always empty, so what the +repository's alternates file says while git reads objects no longer matters. The tests are deterministic rather than a race: the check is wrapped so that it plants an alternates entry right after it has passed, which is the state -git would see if a write landed in that window. Without `--repository`, -alternates keep working, since a `--shared` or `--reference` clone is a -supported repository there. +git would see if a write landed in that window. Each route that reads an +object a caller names is driven that way. Writes go through the same object +directory, so the tools that write objects are shown to still land them in +the repository's store. Without `--repository`, alternates keep working, +since a `--shared` or `--reference` clone is a supported repository there. """ from collections.abc import Callable, Iterator @@ -24,24 +26,30 @@ import git import pytest from conftest import connect, make_repo, wire +from mcp.shared.exceptions import MCPError from mcp_server_git import server MARKER = "ONLY_IN_THE_OTHER_REPOSITORY\n" +MESSAGE = "only in the other repository" def objects_of(repo: git.Repo) -> Path: return Path(repo.common_dir) / "objects" +def root_of(repo: git.Repo) -> Path: + assert repo.working_dir is not None + return Path(repo.working_dir) + + @pytest.fixture def other(tmp_path: Path) -> git.Repo: """A repository outside the allowed one, with a commit of its own.""" repo = make_repo(tmp_path / "other") - assert repo.working_dir is not None - (Path(repo.working_dir) / "only-here.txt").write_text(MARKER) + (root_of(repo) / "only-here.txt").write_text(MARKER) repo.index.add(["only-here.txt"]) - repo.index.commit("only in the other repository") + repo.index.commit(MESSAGE) return repo @@ -58,42 +66,92 @@ def check_then_plant(*args: Any, **kwargs: Any) -> None: yield -async def show(repository: Path | None, repo_path: Path, revision: str) -> Any: +async def call(repository: Path | None, tool: str, arguments: dict[str, Any]) -> Any: async with connect(repository) as session: - return wire( - await session.call_tool( - "git_show", {"repo_path": str(repo_path), "revision": revision} + return wire(await session.call_tool(tool, arguments)) + + +async def summarize(repository: Path, repo_path: Path, target: str) -> str: + """The git_summarize_changes prompt's text, or the error it was refused with.""" + async with connect(repository) as session: + try: + result = await session.get_prompt( + "git_summarize_changes", + {"repo_path": str(repo_path), "target": target}, ) - ) + except MCPError as e: + return f"refused: {e}" + return str(wire(result)) + +# Each route that reads objects a caller names: the tool and its arguments, +# with {blob} and {commit} standing for the other repository's objects. +ROUTES = [ + ("git_show", {"revision": "{blob}"}), + ("git_show", {"revision": "{commit}"}), + ("git_show", {"revision": "{commit}:"}), + ("git_diff", {"target": "{commit}"}), + ("git_log", {}), + ("git_checkout", {"branch_name": "{commit}"}), + ("git_create_branch", {"branch_name": "new", "base_branch": "{commit}"}), +] -@pytest.mark.parametrize("revision", ["{blob}", "{commit}", "{commit}:"]) -async def test_restricted_git_show_ignores_alternates_written_after_the_check( - test_repository: git.Repo, other: git.Repo, revision: str + +@pytest.mark.parametrize( + ("tool", "arguments"), ROUTES, ids=[f"{t}-{a}" for t, a in ROUTES] +) +async def test_restricted_tools_ignore_alternates_written_after_the_check( + test_repository: git.Repo, other: git.Repo, tool: str, arguments: dict[str, str] ): - root = Path(test_repository.working_dir or "") + root = root_of(test_repository) + git_dir = Path(test_repository.git_dir) alternates = objects_of(test_repository) / "info" / "alternates" alternates.parent.mkdir(parents=True, exist_ok=True) - rev = revision.format( - blob=other.git.rev_parse("HEAD:only-here.txt"), - commit=other.head.commit.hexsha, - ) + commit = other.head.commit.hexsha + names = {"blob": other.git.rev_parse("HEAD:only-here.txt"), "commit": commit} + if tool == "git_log": + # A branch naming the other repository's commit, checked out. + (git_dir / "refs" / "heads" / "elsewhere").write_text(f"{commit}\n") + (git_dir / "HEAD").write_text("ref: refs/heads/elsewhere\n") with alternates_planted_after_check(alternates, f"{objects_of(other)}\n"): - result = await show(root, root, rev) + result = await call( + root, + tool, + {"repo_path": str(root)} + | {k: v.format(**names) for k, v in arguments.items()}, + ) - # The entry really was in place when git_show read objects. + # The entry really was in place when the tool read objects. assert alternates.read_text() == f"{objects_of(other)}\n" assert result["isError"] is True text = result["content"][0]["text"] assert "ONLY_IN_THE_OTHER_REPOSITORY" not in text + assert MESSAGE not in text assert "only-here.txt" not in text + assert not (root / "only-here.txt").exists() + assert not (git_dir / "refs" / "heads" / "new").exists() -async def test_restricted_git_show_still_reads_the_repositorys_own_objects( +async def test_restricted_prompt_ignores_alternates_written_after_the_check( + test_repository: git.Repo, other: git.Repo +): + root = root_of(test_repository) + alternates = objects_of(test_repository) / "info" / "alternates" + alternates.parent.mkdir(parents=True, exist_ok=True) + + with alternates_planted_after_check(alternates, f"{objects_of(other)}\n"): + text = await summarize(root, root, other.head.commit.hexsha) + + assert alternates.read_text() == f"{objects_of(other)}\n" + assert text.startswith("refused: ") + assert "ONLY_IN_THE_OTHER_REPOSITORY" not in text + + +async def test_restricted_tools_still_read_the_repositorys_own_objects( test_repository: git.Repo, ): - root = Path(test_repository.working_dir or "") + root = root_of(test_repository) (root / "packed.txt").write_text("PACKED\n") test_repository.index.add(["packed.txt"]) test_repository.index.commit("packed") @@ -102,42 +160,101 @@ async def test_restricted_git_show_still_reads_the_repositorys_own_objects( test_repository.index.add(["loose.txt"]) test_repository.index.commit("loose") - for revision, expected in [ - ("HEAD:packed.txt", "PACKED"), - ("HEAD:loose.txt", "LOOSE"), - ("HEAD", "+LOOSE"), - ("HEAD~1", "+PACKED"), + for tool, arguments, expected in [ + ("git_show", {"revision": "HEAD:packed.txt"}, "PACKED"), + ("git_show", {"revision": "HEAD:loose.txt"}, "LOOSE"), + ("git_show", {"revision": "HEAD"}, "+LOOSE"), + ("git_show", {"revision": "HEAD~1"}, "+PACKED"), + ("git_diff", {"target": "HEAD~2"}, "+PACKED"), + ("git_log", {}, "packed"), ]: - result = await show(root, root, revision) + result = await call(root, tool, {"repo_path": str(root)} | arguments) assert result["isError"] is False, result assert expected in result["content"][0]["text"] + assert "+LOOSE" in await summarize(root, root, "HEAD~1") -async def test_restricted_git_show_leaves_no_object_directory_behind( +async def test_restricted_writes_land_in_the_repositorys_own_store(tmp_path: Path): + # A repository with no loose-object directories yet, so every object the + # tools write is the first in its directory. + repo = git.Repo.init(tmp_path / "fresh") + root = root_of(repo) + for config in [("user.name", "t"), ("user.email", "t@example.com")]: + repo.git.config(*config) + (root / "a.txt").write_text("A\n") + (root / "b.txt").write_text("B\n") + + for tool, arguments in [ + ("git_add", {"files": ["a.txt"]}), + ("git_commit", {"message": "first"}), + ("git_create_branch", {"branch_name": "side"}), + ("git_checkout", {"branch_name": "side"}), + ("git_add", {"files": ["b.txt"]}), + ("git_commit", {"message": "on side"}), + ("git_checkout", {"branch_name": "main"}), + ]: + result = await call(root, tool, {"repo_path": str(root)} | arguments) + assert result["isError"] is False, (tool, result) + (root / "c.txt").write_text("C\n") + repo.index.add(["c.txt"]) + repo.index.commit("on main") + # git itself writes the merge commit, through the private directory. + result = await call( + root, + "git_merge", + {"repo_path": str(root), "source_branch": "side", "fast_forward_only": False}, + ) + assert result["isError"] is False, result + + head = repo.git.rev_parse("HEAD") + assert "with merge commit" in result["content"][0]["text"] + # Every object is in the repository's own store, read by a git that runs + # outside the server: fsck fails on any object HEAD reaches but lacks. + assert len(repo.git.rev_list("--objects", "HEAD").splitlines()) >= 9 + repo.git.fsck("--no-dangling") + assert repo.commit(head).parents[1].message.rstrip() == "on side" + + +async def test_restricted_calls_leave_no_object_directory_behind( test_repository: git.Repo, tmp_path: Path ): - root = Path(test_repository.working_dir or "") + root = root_of(test_repository) scratch = tmp_path / "scratch" scratch.mkdir() with mock.patch("tempfile.tempdir", str(scratch)): - ok = await show(root, root, "HEAD") - failed = await show(root, root, "0" * 40) + ok = await call(root, "git_show", {"repo_path": str(root), "revision": "HEAD"}) + failed = await call( + root, "git_show", {"repo_path": str(root), "revision": "0" * 40} + ) + await summarize(root, root, "HEAD") assert ok["isError"] is False assert failed["isError"] is True assert list(scratch.iterdir()) == [] +def test_a_restricted_repository_is_opened_only_inside_a_call( + test_repository: git.Repo, +): + # Outside `_one_call()` there is nothing to end the private store with. + with pytest.raises(RuntimeError, match="needs _one_call"): + server._read_own_objects_for_call(test_repository) + + async def test_unrestricted_git_show_follows_alternates( test_repository: git.Repo, other: git.Repo ): # Without --repository, a clone made with --shared or --reference reads # its objects from the store it names, as git does. - root = Path(test_repository.working_dir or "") + root = root_of(test_repository) alternates = objects_of(test_repository) / "info" / "alternates" alternates.parent.mkdir(parents=True, exist_ok=True) alternates.write_text(f"{objects_of(other)}\n") - result = await show(None, root, other.git.rev_parse("HEAD:only-here.txt")) + result = await call( + None, + "git_show", + {"repo_path": str(root), "revision": other.git.rev_parse("HEAD:only-here.txt")}, + ) assert result["isError"] is False assert result["content"][0]["text"] == MARKER From f9a8bf74f86d0071e70054e6970d99daf0b77d35 Mon Sep 17 00:00:00 2001 From: cliffhall Date: Fri, 27 Nov 2026 01:32:12 -0500 Subject: [PATCH 3/7] fix(git): GHSA-5pwg-5xfw-x322 Co-Authored-By: Claude Opus 5.5 Signed-off-by: cliffhall --- src/git/src/mcp_server_git/server.py | 43 +++++++++++++++++++---- src/git/tests/test_alternates_race.py | 49 +++++++++++++++++++++++++++ 2 files changed, 86 insertions(+), 6 deletions(-) diff --git a/src/git/src/mcp_server_git/server.py b/src/git/src/mcp_server_git/server.py index 624167a35f..2c859747d1 100644 --- a/src/git/src/mcp_server_git/server.py +++ b/src/git/src/mcp_server_git/server.py @@ -1090,7 +1090,7 @@ def _check_index_entries(repo: git.Repo, repo_path: Path) -> None: @contextmanager -def _own_object_store(repo: git.Repo) -> Iterator[None]: +def _own_object_store(repo: git.Repo, *, writes: bool = False) -> Iterator[None]: """Run `repo`'s git on its own objects only, whatever its alternates say. `_check_git_dir_contents` refuses an alternates entry when the repository @@ -1102,12 +1102,17 @@ def _own_object_store(repo: git.Repo) -> Iterator[None]: directory's `info/alternates`, which does not exist. On Windows the links are directory junctions, which need no privilege. + A link to a directory the store lacks yet reads as absent, so a call + that only reads writes nothing to the repository, and works on a store + it cannot write to. + Git follows the links for writing too: a new loose object is written to a temporary file in its own `xx` directory and renamed there, and a pack in `pack`, so what git writes lands in the repository's store. A link to - a missing directory could not be written through, so each loose-object - directory the store lacks is created first, as git would on its first - write to it. + a missing directory cannot be written through, so for a call that + `writes`, each loose-object directory the store lacks is created first, + as git would on its first write to it. One that cannot be created is + left out: a write into it would fail in the store itself as well. GitPython's persistent `git cat-file` processes are stopped before and after, so none reads with the environment it does not belong to. @@ -1117,7 +1122,11 @@ def _own_object_store(repo: git.Repo) -> Iterator[None]: links: list[Path] = [] try: for name in [f"{i:02x}" for i in range(256)] + ["pack"]: - (objects / name).mkdir(exist_ok=True) + if writes: + try: + (objects / name).mkdir(exist_ok=True) + except OSError: + pass link = own / name if sys.platform != "win32": os.symlink(objects / name, link, target_is_directory=True) @@ -1144,6 +1153,8 @@ def _own_object_store(repo: git.Repo) -> Iterator[None]: # repository's `_own_object_store` here, since most tools never close the # repository they open. _CALL: ContextVar[ExitStack | None] = ContextVar("_CALL", default=None) +# Whether the running tool can write objects (`writes_objects`). +_WRITES: ContextVar[bool] = ContextVar("_WRITES", default=False) @contextmanager @@ -1162,7 +1173,7 @@ def _read_own_objects_for_call(repo: git.Repo) -> None: stack = _CALL.get() if stack is None: raise RuntimeError("a repository opened under --repository needs _one_call()") - stack.enter_context(_own_object_store(repo)) + stack.enter_context(_own_object_store(repo, writes=_WRITES.get())) def _check_git_dir_contents( @@ -1484,6 +1495,20 @@ def wrapper(*args: _P.args, **kwargs: _P.kwargs) -> str: return wrapper +def writes_objects(fn: Callable[_P, str]) -> Callable[_P, str]: + """Mark a tool that writes to the repository, so its object store can be.""" + + @wraps(fn) + def wrapper(*args: _P.args, **kwargs: _P.kwargs) -> str: + token = _WRITES.set(True) + try: + return fn(*args, **kwargs) + finally: + _WRITES.reset(token) + + return wrapper + + READ_ONLY = ToolAnnotations( read_only_hint=True, destructive_hint=False, @@ -1742,6 +1767,7 @@ def diff( structured_output=False, ) @reports_failures + @writes_objects def commit(repo_path: str, message: str) -> str: return git_commit(open_repo(repo_path), message, allowed_repository=repository) @@ -1752,6 +1778,7 @@ def commit(repo_path: str, message: str) -> str: structured_output=False, ) @reports_failures + @writes_objects def add(repo_path: str, files: Annotated[list[str], Field(min_length=1)]) -> str: return git_add(open_repo(repo_path), files) @@ -1762,6 +1789,7 @@ def add(repo_path: str, files: Annotated[list[str], Field(min_length=1)]) -> str structured_output=False, ) @reports_failures + @writes_objects def reset(repo_path: str) -> str: return git_reset(open_repo(repo_path)) @@ -1829,6 +1857,7 @@ def log( structured_output=False, ) @reports_failures + @writes_objects def create_branch( repo_path: str, branch_name: str, @@ -1852,6 +1881,7 @@ def create_branch( structured_output=False, ) @reports_failures + @writes_objects def checkout(repo_path: str, branch_name: str) -> str: return git_checkout( open_repo(repo_path), branch_name, allowed_repository=repository @@ -1868,6 +1898,7 @@ def checkout(repo_path: str, branch_name: str) -> str: structured_output=False, ) @reports_failures + @writes_objects def merge( repo_path: str, source_branch: Annotated[ diff --git a/src/git/tests/test_alternates_race.py b/src/git/tests/test_alternates_race.py index 560e48eea1..73efd86e95 100644 --- a/src/git/tests/test_alternates_race.py +++ b/src/git/tests/test_alternates_race.py @@ -17,6 +17,8 @@ since a `--shared` or `--reference` clone is a supported repository there. """ +import os +import sys from collections.abc import Callable, Iterator from contextlib import contextmanager from pathlib import Path @@ -215,6 +217,53 @@ async def test_restricted_writes_land_in_the_repositorys_own_store(tmp_path: Pat assert repo.commit(head).parents[1].message.rstrip() == "on side" +async def test_restricted_read_only_calls_write_nothing_to_the_store( + test_repository: git.Repo, +): + # A link to a loose-object directory the store lacks reads as absent, so + # a call that only reads creates none of them. + root = root_of(test_repository) + objects = objects_of(test_repository) + before = sorted(p.name for p in objects.iterdir()) + for tool, arguments in [ + ("git_status", {}), + ("git_log", {}), + ("git_show", {"revision": "HEAD"}), + ("git_diff", {"target": "HEAD"}), + ("git_branch", {"branch_type": "local"}), + ]: + result = await call(root, tool, {"repo_path": str(root)} | arguments) + assert result["isError"] is False, (tool, result) + await summarize(root, root, "HEAD") + assert sorted(p.name for p in objects.iterdir()) == before + + +@pytest.mark.skipif( + sys.platform == "win32" or os.geteuid() == 0, + reason="needs a directory that chmod can make unwritable", +) +async def test_restricted_server_works_on_a_store_it_cannot_write( + test_repository: git.Repo, +): + root = root_of(test_repository) + objects = objects_of(test_repository) + objects.chmod(0o555) + try: + for tool, arguments, expected in [ + ("git_status", {}, "Repository status"), + ("git_log", {}, "initial commit"), + ("git_show", {"revision": "HEAD:test.txt"}, "test"), + # A tool that writes but adds no object: the loose-object + # directories it cannot create are left out. + ("git_create_branch", {"branch_name": "side"}, "side"), + ]: + result = await call(root, tool, {"repo_path": str(root)} | arguments) + assert result["isError"] is False, (tool, result) + assert expected in result["content"][0]["text"] + finally: + objects.chmod(0o755) + + async def test_restricted_calls_leave_no_object_directory_behind( test_repository: git.Repo, tmp_path: Path ): From a2ae0ae6777a1a96242035ab00fec4d8329dde07 Mon Sep 17 00:00:00 2001 From: cliffhall Date: Fri, 27 Nov 2026 01:49:27 -0500 Subject: [PATCH 4/7] fix(git): GHSA-5pwg-5xfw-x322 Co-Authored-By: Claude Opus 5.5 Signed-off-by: cliffhall --- src/git/src/mcp_server_git/server.py | 38 ++++++++++----- src/git/tests/test_alternates_race.py | 68 ++++++++++++++++++++++++++- 2 files changed, 92 insertions(+), 14 deletions(-) diff --git a/src/git/src/mcp_server_git/server.py b/src/git/src/mcp_server_git/server.py index 2c859747d1..d271b65362 100644 --- a/src/git/src/mcp_server_git/server.py +++ b/src/git/src/mcp_server_git/server.py @@ -1102,17 +1102,20 @@ def _own_object_store(repo: git.Repo, *, writes: bool = False) -> Iterator[None] directory's `info/alternates`, which does not exist. On Windows the links are directory junctions, which need no privilege. - A link to a directory the store lacks yet reads as absent, so a call - that only reads writes nothing to the repository, and works on a store - it cannot write to. + A loose-object directory the repository lacks yet gets no entry for a + call that only reads, so git finds nothing there, as in the store + itself: such a call writes nothing to the repository, and works on a + store it cannot write to. (`_GIT_LOCK` keeps another call from creating + one meanwhile.) Git follows the links for writing too: a new loose object is written to a temporary file in its own `xx` directory and renamed there, and a pack - in `pack`, so what git writes lands in the repository's store. A link to - a missing directory cannot be written through, so for a call that - `writes`, each loose-object directory the store lacks is created first, - as git would on its first write to it. One that cannot be created is - left out: a write into it would fail in the store itself as well. + in `pack`, so what git writes lands in the repository's store. Git would + create a missing `xx` inside the private directory, where the object + would be lost, so for a call that `writes`, every name has an entry: + each directory the repository lacks is created first, as git would on + its first write to it, and one that cannot be created is held by an + empty file, so that a write into it fails as it would in the store. GitPython's persistent `git cat-file` processes are stopped before and after, so none reads with the environment it does not belong to. @@ -1120,19 +1123,26 @@ def _own_object_store(repo: git.Repo, *, writes: bool = False) -> Iterator[None] objects = Path(repo.common_dir) / "objects" own = Path(tempfile.mkdtemp(prefix="mcp-git-objects-")) links: list[Path] = [] + placeholders: list[Path] = [] try: for name in [f"{i:02x}" for i in range(256)] + ["pack"]: + target = objects / name + entry = own / name if writes: try: - (objects / name).mkdir(exist_ok=True) + target.mkdir(exist_ok=True) except OSError: pass - link = own / name + if not target.is_dir(): + if writes: + entry.touch() + placeholders.append(entry) + continue if sys.platform != "win32": - os.symlink(objects / name, link, target_is_directory=True) + os.symlink(target, entry, target_is_directory=True) else: # pragma: no cover # Windows only; the coverage gate runs on Linux - _winapi.CreateJunction(str(objects / name), str(link)) - links.append(link) + _winapi.CreateJunction(str(target), str(entry)) + links.append(entry) repo.git.clear_cache() with repo.git.custom_environment(GIT_OBJECT_DIRECTORY=str(own)): try: @@ -1146,6 +1156,8 @@ def _own_object_store(repo: git.Repo, *, writes: bool = False) -> Iterator[None] os.unlink(link) else: # pragma: no cover # Windows only; the coverage gate runs on Linux os.rmdir(link) + for placeholder in placeholders: + os.unlink(placeholder) os.rmdir(own) diff --git a/src/git/tests/test_alternates_race.py b/src/git/tests/test_alternates_race.py index 73efd86e95..a715ae742f 100644 --- a/src/git/tests/test_alternates_race.py +++ b/src/git/tests/test_alternates_race.py @@ -238,6 +238,65 @@ async def test_restricted_read_only_calls_write_nothing_to_the_store( assert sorted(p.name for p in objects.iterdir()) == before +@contextmanager +def private_store_seen_by( + tool_function: str, seen: dict[str, set[str]] +) -> Iterator[None]: + """Record the private object directory's entries while `tool_function` runs. + + Each entry is recorded as its name, with `/` after a link to a directory + and nothing after a placeholder file, so the result is the same whether + the platform links with symbolic links or with junctions. + """ + original = getattr(server, tool_function) + + def recording(repo: git.Repo, *args: Any, **kwargs: Any) -> str: + own = Path(repo.git.environment()["GIT_OBJECT_DIRECTORY"]) + seen[tool_function] = { + p.name + ("/" if p.is_dir() else "") for p in own.iterdir() + } + return original(repo, *args, **kwargs) + + with mock.patch.object(server, tool_function, recording): + yield + + +async def test_restricted_private_store_links_only_what_the_call_can_use( + tmp_path: Path, +): + # A repository with only a few loose-object directories. A read links + # just those (on Windows a junction cannot name a missing directory); a + # write has an entry for every name, so git never creates one inside the + # private directory, where what it wrote would be lost. + repo = make_repo(tmp_path / "few") + root = root_of(repo) + (root / "a.txt").write_text("A\n") + repo.index.add(["a.txt"]) + repo.index.commit("one") + objects = objects_of(repo) + existing = {p.name for p in objects.iterdir() if len(p.name) == 2} + assert 0 < len(existing) < 256 + every = {f"{i:02x}/" for i in range(256)} | {"pack/"} + + seen: dict[str, set[str]] = {} + with ( + private_store_seen_by("git_status", seen), + private_store_seen_by("git_create_branch", seen), + ): + status = await call(root, "git_status", {"repo_path": str(root)}) + branch = await call( + root, "git_create_branch", {"repo_path": str(root), "branch_name": "b"} + ) + + assert status["isError"] is False and branch["isError"] is False + assert seen["git_status"] == {f"{n}/" for n in existing} | {"pack/"} + assert seen["git_create_branch"] == every + # The write call created the directories it linked, as git would. + assert {p.name for p in objects.iterdir() if len(p.name) == 2} == { + f"{i:02x}" for i in range(256) + } + + @pytest.mark.skipif( sys.platform == "win32" or os.geteuid() == 0, reason="needs a directory that chmod can make unwritable", @@ -247,6 +306,7 @@ async def test_restricted_server_works_on_a_store_it_cannot_write( ): root = root_of(test_repository) objects = objects_of(test_repository) + seen: dict[str, set[str]] = {} objects.chmod(0o555) try: for tool, arguments, expected in [ @@ -257,9 +317,15 @@ async def test_restricted_server_works_on_a_store_it_cannot_write( # directories it cannot create are left out. ("git_create_branch", {"branch_name": "side"}, "side"), ]: - result = await call(root, tool, {"repo_path": str(root)} | arguments) + with private_store_seen_by("git_create_branch", seen): + result = await call(root, tool, {"repo_path": str(root)} | arguments) assert result["isError"] is False, (tool, result) assert expected in result["content"][0]["text"] + # Each directory the write call could not create is held by a file, + # so a write into it fails instead of landing in the private store. + missing = {f"{i:02x}" for i in range(256)} - {p.name for p in objects.iterdir()} + assert missing + assert missing <= seen["git_create_branch"] finally: objects.chmod(0o755) From 00abeccf376b146b66a4a536e86abc12dabaee36 Mon Sep 17 00:00:00 2001 From: cliffhall Date: Fri, 27 Nov 2026 02:30:31 -0500 Subject: [PATCH 5/7] fix(git): link a linked worktree's objects by their resolved path Co-Authored-By: Claude Opus 5.5 Signed-off-by: cliffhall --- src/git/src/mcp_server_git/server.py | 4 ++- src/git/tests/test_alternates_race.py | 42 +++++++++++++++++++++++---- 2 files changed, 40 insertions(+), 6 deletions(-) diff --git a/src/git/src/mcp_server_git/server.py b/src/git/src/mcp_server_git/server.py index d271b65362..efaf5d5b23 100644 --- a/src/git/src/mcp_server_git/server.py +++ b/src/git/src/mcp_server_git/server.py @@ -1120,7 +1120,9 @@ def _own_object_store(repo: git.Repo, *, writes: bool = False) -> Iterator[None] GitPython's persistent `git cat-file` processes are stopped before and after, so none reads with the environment it does not belong to. """ - objects = Path(repo.common_dir) / "objects" + # Resolved: a linked worktree's common directory reads `/../..`, + # and a junction's target is not a path Windows collapses `..` in. + objects = Path(repo.common_dir).resolve() / "objects" own = Path(tempfile.mkdtemp(prefix="mcp-git-objects-")) links: list[Path] = [] placeholders: list[Path] = [] diff --git a/src/git/tests/test_alternates_race.py b/src/git/tests/test_alternates_race.py index a715ae742f..3504404377 100644 --- a/src/git/tests/test_alternates_race.py +++ b/src/git/tests/test_alternates_race.py @@ -62,7 +62,7 @@ def alternates_planted_after_check(alternates: Path, entry: str) -> Iterator[Non def check_then_plant(*args: Any, **kwargs: Any) -> None: check(*args, **kwargs) - alternates.write_text(entry) + alternates.write_text(entry, newline="\n") with mock.patch.object(server, "_check_git_dir_contents", check_then_plant): yield @@ -126,7 +126,7 @@ async def test_restricted_tools_ignore_alternates_written_after_the_check( # The entry really was in place when the tool read objects. assert alternates.read_text() == f"{objects_of(other)}\n" - assert result["isError"] is True + assert result["isError"] is True, result text = result["content"][0]["text"] assert "ONLY_IN_THE_OTHER_REPOSITORY" not in text assert MESSAGE not in text @@ -179,7 +179,8 @@ async def test_restricted_tools_still_read_the_repositorys_own_objects( async def test_restricted_writes_land_in_the_repositorys_own_store(tmp_path: Path): # A repository with no loose-object directories yet, so every object the # tools write is the first in its directory. - repo = git.Repo.init(tmp_path / "fresh") + # Named, since git's default branch name is configurable. + repo = git.Repo.init(tmp_path / "fresh", initial_branch="main") root = root_of(repo) for config in [("user.name", "t"), ("user.email", "t@example.com")]: repo.git.config(*config) @@ -297,6 +298,37 @@ async def test_restricted_private_store_links_only_what_the_call_can_use( } +async def test_restricted_private_store_of_a_linked_worktree_names_real_paths( + tmp_path: Path, +): + # GitPython gives a linked worktree's common directory as + # `/../..`. A junction's target is not a path Windows collapses + # `..` in, so each link names the main repository's objects directly. + main = make_repo(tmp_path / "main") + worktree = tmp_path / "worktree" + main.git.worktree("add", str(worktree)) + expected = (Path(main.git_dir).resolve() / "objects").resolve() + targets: list[Path] = [] + original = server.git_status + + def recording(repo: git.Repo) -> str: + own = Path(repo.git.environment()["GIT_OBJECT_DIRECTORY"]) + targets.extend(Path(os.readlink(p)) for p in own.iterdir()) + return original(repo) + + try: + with mock.patch.object(server, "git_status", recording): + result = await call(worktree, "git_status", {"repo_path": str(worktree)}) + finally: + main.close() + + assert result["isError"] is False, result + assert targets + for target in targets: + assert ".." not in target.parts, target + assert Path(str(target).removeprefix("\\\\?\\")).parent == expected + + @pytest.mark.skipif( sys.platform == "win32" or os.geteuid() == 0, reason="needs a directory that chmod can make unwritable", @@ -363,7 +395,7 @@ async def test_unrestricted_git_show_follows_alternates( root = root_of(test_repository) alternates = objects_of(test_repository) / "info" / "alternates" alternates.parent.mkdir(parents=True, exist_ok=True) - alternates.write_text(f"{objects_of(other)}\n") + alternates.write_text(f"{objects_of(other)}\n", newline="\n") result = await call( None, @@ -371,5 +403,5 @@ async def test_unrestricted_git_show_follows_alternates( {"repo_path": str(root), "revision": other.git.rev_parse("HEAD:only-here.txt")}, ) - assert result["isError"] is False + assert result["isError"] is False, result assert result["content"][0]["text"] == MARKER From 3a9143021c55224b756a9dd96398cda2747089a2 Mon Sep 17 00:00:00 2001 From: cliffhall Date: Fri, 27 Nov 2026 02:43:22 -0500 Subject: [PATCH 6/7] test(git): write the marker blob with LF line endings on every platform Co-Authored-By: Claude Opus 5.5 Signed-off-by: cliffhall --- src/git/tests/test_alternates_race.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/git/tests/test_alternates_race.py b/src/git/tests/test_alternates_race.py index 3504404377..f5088ec122 100644 --- a/src/git/tests/test_alternates_race.py +++ b/src/git/tests/test_alternates_race.py @@ -49,7 +49,7 @@ def root_of(repo: git.Repo) -> Path: def other(tmp_path: Path) -> git.Repo: """A repository outside the allowed one, with a commit of its own.""" repo = make_repo(tmp_path / "other") - (root_of(repo) / "only-here.txt").write_text(MARKER) + (root_of(repo) / "only-here.txt").write_text(MARKER, newline="\n") repo.index.add(["only-here.txt"]) repo.index.commit(MESSAGE) return repo From eb9c526b84e3a8d5f3e9a436c2e4d26d3ac25eb0 Mon Sep 17 00:00:00 2001 From: cliffhall Date: Fri, 27 Nov 2026 03:00:04 -0500 Subject: [PATCH 7/7] test(git): compare the planted alternates entry as bytes Co-Authored-By: Claude Opus 5.5 Signed-off-by: cliffhall --- src/git/tests/test_alternates_race.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/git/tests/test_alternates_race.py b/src/git/tests/test_alternates_race.py index f5088ec122..e9dac111fc 100644 --- a/src/git/tests/test_alternates_race.py +++ b/src/git/tests/test_alternates_race.py @@ -125,7 +125,7 @@ async def test_restricted_tools_ignore_alternates_written_after_the_check( ) # The entry really was in place when the tool read objects. - assert alternates.read_text() == f"{objects_of(other)}\n" + assert alternates.read_bytes() == f"{objects_of(other)}\n".encode() assert result["isError"] is True, result text = result["content"][0]["text"] assert "ONLY_IN_THE_OTHER_REPOSITORY" not in text @@ -145,7 +145,7 @@ async def test_restricted_prompt_ignores_alternates_written_after_the_check( with alternates_planted_after_check(alternates, f"{objects_of(other)}\n"): text = await summarize(root, root, other.head.commit.hexsha) - assert alternates.read_text() == f"{objects_of(other)}\n" + assert alternates.read_bytes() == f"{objects_of(other)}\n".encode() assert text.startswith("refused: ") assert "ONLY_IN_THE_OTHER_REPOSITORY" not in text