Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion src/git/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -189,7 +189,7 @@ A Git directory or common directory inside the allowed repository must also lie

A refusal names only the `repo_path` given and the kind of directory refused (a working tree or Git directory outside the allowed repository), or the link or junction found in the Git directory, never where Git resolved it.

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.
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; or an unmerged entry (one recorded during a conflict) below a symbolic link in the working tree (on Windows also a directory junction), which Git's diff of a conflicted file reads through the link. Git reads an index as it finds it, so a hand-written one could otherwise make `git_diff_unstaged`, `git_diff`, `git_status` and the prompts show files outside the repository. An entry that is not unmerged is accepted below a link, since Git shows it as deleted rather than read it: a repository that replaced a tracked directory with a link holds such entries until it commits. 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.

Expand Down
88 changes: 76 additions & 12 deletions src/git/src/mcp_server_git/server.py
Original file line number Diff line number Diff line change
Expand Up @@ -1405,7 +1405,7 @@ def outside(kind: str) -> ValueError:
_check_shared_files(repo_path, {p.resolve() for p in git_dirs + common_dirs})

if bare != "true":
_check_index_entries(repo, repo_path)
_check_index_entries(repo, repo_path, Path(working_trees[0]))


def _unsafe_index_entry(entry: bytes, windows: bool = os.name == "nt") -> bool:
Expand All @@ -1429,25 +1429,89 @@ def _unsafe_index_entry(entry: bytes, windows: bool = os.name == "nt") -> bool:
return False


def _check_index_entries(repo: git.Repo, repo_path: Path) -> None:
# A directory junction's reparse tag. `stat` defines the name only on Windows,
# the one platform whose `lstat` reports `st_reparse_tag`.
_IO_REPARSE_TAG_MOUNT_POINT = 0xA0000003


def _linked_component(path: bytes) -> bool | None:
"""What a leading component of an index entry is in the working tree.
True for a symbolic link, or on Windows a directory junction (which
`lstat` does not follow either, and reports by its reparse tag); False for
an ordinary directory, below which the entry's next component is checked;
None for anything else, missing included, below which git reads nothing.
"""
try:
status = os.lstat(path)
except OSError:
return None
if (
stat.S_ISLNK(status.st_mode)
or getattr(status, "st_reparse_tag", 0) == _IO_REPARSE_TAG_MOUNT_POINT
):
return True
return False if stat.S_ISDIR(status.st_mode) else None


def _behind_a_link(
working_tree: bytes, entry: bytes, checked: dict[bytes, bool | None]
) -> bool:
"""Whether a leading component of `entry` is a link in `working_tree`.
`checked` holds each prefix already looked at, so an index with many
entries in one directory costs one `lstat` per directory, not per entry.
"""
prefix = b""
for component in entry.split(b"/")[:-1]:
prefix = prefix + b"/" + component if prefix else component
if prefix not in checked:
checked[prefix] = _linked_component(os.path.join(working_tree, prefix))
linked = checked[prefix]
if linked is not False:
return bool(linked)
return False


def _check_index_entries(repo: git.Repo, repo_path: Path, working_tree: Path) -> None:
"""Refuse an index naming a path outside the working tree.
The index is read through `git ls-files`, so a split index's shared part
and a sparse index's collapsed directories are listed as git uses them.
`:(top)` lists the whole index wherever GitPython runs git from.
Every entry is judged by its spelling (`_unsafe_index_entry`). An unmerged
entry (stage 1, 2 or 3) is also refused when a leading component of it is
a symbolic link in the working tree: git's combined diff of an entry with
stages 2 and 3 reads its file through the link, wherever that points. A
stage-0 entry behind a link is left alone. Git checks the path before it
reads one (it shows the entry as deleted), and a repository that replaced
a tracked directory with a link holds such entries until it commits. Git
makes no unmerged entry behind a link itself: a merge that meets one moves
the link aside.
"""
listed = repo.git.ls_files(
"-z", "--full-name", "--", ":(top)", stdout_as_string=False
"-z", "--stage", "--full-name", "--", ":(top)", stdout_as_string=False
)
for entry in listed.split(b"\0"):
if entry and _unsafe_index_entry(entry):
# repr: the name is the repository's own, and escaped it carries
# no line breaks or terminal control sequences into the result.
name = entry.decode("utf-8", errors="replace")
raise ValueError(
f"Repository path '{repo_path}' has an index entry {name!r} "
"that git would read outside the working tree"
)
root = os.fsencode(working_tree)
checked: dict[bytes, bool | None] = {}
for record in listed.split(b"\0"):
if not record:
continue
# `<mode> <object> <stage>\t<path>`: the path is everything after the tab.
info, _, entry = record.partition(b"\t")
if _unsafe_index_entry(entry):
reason = "that git would read outside the working tree"
elif not info.endswith(b" 0") and _behind_a_link(root, entry, checked):
reason = "that git would read through a symbolic link in the working tree"
else:
continue
# repr: the name is the repository's own, and escaped it carries
# no line breaks or terminal control sequences into the result.
name = entry.decode("utf-8", errors="replace")
raise ValueError(
f"Repository path '{repo_path}' has an index entry {name!r} {reason}"
)


def _check_shared_files(repo_path: Path, admitted: Collection[Path]) -> None:
Expand Down
173 changes: 172 additions & 1 deletion src/git/tests/test_index_entries.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,14 +16,16 @@
import time
from pathlib import Path
from typing import Any
from unittest import mock

import git
import pytest
from conftest import connect, make_repo, wire
from conftest import connect, make_repo, rmtree, wire
from mcp.shared.exceptions import MCPError
from mcp.types import INVALID_PARAMS
from test_eras import MODERN
from test_eras import connect as connect_era
from test_junction import junction, windows_only

from mcp_server_git.server import _unsafe_index_entry

Expand Down Expand Up @@ -259,3 +261,172 @@ async def test_untracked_cache_naming_outside_is_ignored(tmp_path: Path):
def test_unsafe_index_entry(entry: bytes, posix: bool, windows: bool):
assert _unsafe_index_entry(entry, windows=False) is posix
assert _unsafe_index_entry(entry, windows=True) is windows


# An unmerged entry behind a symbolic link.
#
# The spelling of `link/secret.txt` is fine, but with `link` a symbolic link in
# the working tree, git's combined diff (`git diff` on an entry with stages 2
# and 3) reads the file through it, wherever it points. Git checks the path
# when it writes the file and when it compares a stage-0 entry, which it shows
# as deleted; the combined diff does not. So an unmerged entry whose leading
# component is a link is refused, and a stage-0 one, which a repository that
# replaced a directory with a link holds until it commits, is not.

BEHIND = "that git would read through a symbolic link in the working tree"


def unmerged(repo: git.Repo, path: str, stages: str = "123") -> None:
"""Record `path` as unmerged in `repo`'s index, at each stage in `stages`."""

def git_in(*args: str, stdin: str) -> str:
# Bytes, not text: a text-mode pipe on Windows would write each "\n"
# as "\r\n", which git would take as part of the path.
return (
subprocess.run(
["git", *args],
cwd=repo.working_dir,
input=stdin.encode(),
capture_output=True,
check=True,
)
.stdout.decode()
.strip()
)

lines = ""
for stage in stages:
blob = git_in("hash-object", "-w", "--stdin", stdin=f"stage {stage}\n")
lines += f"100644 {blob} {stage}\t{path}\n"
git_in("update-index", "--index-info", stdin=lines)


def linked_repo(tmp_path: Path) -> Path:
"""A repository whose working tree holds `link`, a link to `outside`."""
outside_marker(tmp_path)
root = tmp_path / "repo"
make_repo(root).close()
(root / "link").symlink_to(tmp_path / "outside", target_is_directory=True)
return root


@pytest.mark.parametrize(("tool", "extra"), TOOLS)
async def test_unmerged_entry_behind_a_symlink_is_refused(
tmp_path: Path, tool: str, extra: dict[str, Any]
):
root = linked_repo(tmp_path)
with git.Repo(root) as repo:
unmerged(repo, "link/secret.txt")
# Unchecked, git reads the outside file: the precondition.
assert MARKER in repo.git.diff()
result = await call(root, tool, {"repo_path": str(root), **extra})
assert result["isError"] is True
text = result["content"][0]["text"]
assert f"has an index entry 'link/secret.txt' {BEHIND}" in text
assert MARKER not in text


async def test_unmerged_entry_behind_a_nested_symlink_is_refused(tmp_path: Path):
root = linked_repo(tmp_path)
(root / "dir").mkdir()
(root / "dir" / "deeper").symlink_to(tmp_path / "outside", target_is_directory=True)
with git.Repo(root) as repo:
# Two entries under the same ordinary directory, the plain one listed
# first (the index is sorted): `dir` is looked up once for both.
unmerged(repo, "dir/a-plain.txt")
unmerged(repo, "dir/deeper/secret.txt")
looked_up: list[bytes] = []
lstat = os.lstat

def recording_lstat(path: Any, *args: Any, **kwargs: Any) -> os.stat_result:
looked_up.append(os.fsencode(path))
return lstat(path, *args, **kwargs)

with mock.patch("mcp_server_git.server.os.lstat", recording_lstat):
result = await call(root, "git_diff_unstaged", {"repo_path": str(root)})
# By name: git may spell the working tree differently from `root`.
assert [os.path.basename(p) for p in looked_up].count(b"dir") == 1
assert result["isError"] is True
text = result["content"][0]["text"]
assert f"'dir/deeper/secret.txt' {BEHIND}" in text
assert MARKER not in text


@pytest.mark.parametrize("prompt", ["git_commit_message", "git_summarize_changes"])
async def test_prompts_refuse_an_unmerged_entry_behind_a_symlink(
tmp_path: Path, prompt: str
):
root = linked_repo(tmp_path)
with git.Repo(root) as repo:
unmerged(repo, "link/secret.txt")
async with connect_era(MODERN, root) as client:
with pytest.raises(MCPError) as excinfo:
await client.get_prompt(prompt, {"repo_path": str(root)})
assert excinfo.value.error.code == INVALID_PARAMS
assert BEHIND in excinfo.value.error.message
assert MARKER not in excinfo.value.error.message


async def test_directory_replaced_by_a_symlink_is_accepted(tmp_path: Path):
# The ordinary state the rule leaves alone: `link/secret.txt` committed,
# then the directory replaced by a link and not yet committed. Git shows
# the stage-0 entry as deleted and reads nothing through the link.
outside_marker(tmp_path)
root = tmp_path / "repo"
with make_repo(root) as repo:
(root / "link").mkdir()
(root / "link" / "secret.txt").write_text("tracked\n")
repo.git.add("link")
repo.git.commit("-m", "link")
rmtree(root / "link")
(root / "link").symlink_to(tmp_path / "outside", target_is_directory=True)
result = await call(root, "git_diff_unstaged", {"repo_path": str(root)})
assert result["isError"] is False
text = result["content"][0]["text"]
assert "deleted file mode" in text
assert MARKER not in text


async def test_conflicts_git_makes_are_accepted(tmp_path: Path):
# One side replaces a directory with a link, the other edits a file in
# it: git keeps the directory and moves the link aside (`link~HEAD`), so
# its unmerged entries are not behind a link. An entry under a regular
# file or a missing directory reads nothing either.
outside_marker(tmp_path)
root = tmp_path / "repo"
with make_repo(root) as repo:
(root / "link").mkdir()
(root / "link" / "secret.txt").write_text("base\n")
repo.git.add("link")
repo.git.commit("-m", "base")
repo.git.checkout("-b", "theirs")
(root / "link" / "secret.txt").write_text("theirs\n")
repo.git.commit("-am", "theirs")
repo.git.checkout("main")
repo.git.rm("-r", "-q", "link")
(root / "link").symlink_to(tmp_path / "outside", target_is_directory=True)
repo.git.add("link")
repo.git.commit("-m", "link")
with pytest.raises(git.GitCommandError):
repo.git.merge("theirs")
assert "link/secret.txt" in repo.git.ls_files("-u")
assert (root / "link").is_dir() and not (root / "link").is_symlink()
unmerged(repo, "test.txt/under-a-file.txt")
unmerged(repo, "missing/file.txt")
result = await call(root, "git_status", {"repo_path": str(root)})
assert result["isError"] is False
assert MARKER not in result["content"][0]["text"]


@windows_only
async def test_unmerged_entry_behind_a_junction_is_refused(tmp_path: Path):
# A directory junction is not a symbolic link to Python, but `lstat`
# reports it by its reparse tag, and the path is read through it alike.
outside_marker(tmp_path)
root = tmp_path / "repo"
with make_repo(root) as repo:
junction(root / "link", tmp_path / "outside")
unmerged(repo, "link/secret.txt")
result = await call(root, "git_status", {"repo_path": str(root)})
assert result["isError"] is True
assert f"'link/secret.txt' {BEHIND}" in result["content"][0]["text"]