diff --git a/src/git/README.md b/src/git/README.md index 2f88d37451..818ccf731a 100644 --- a/src/git/README.md +++ b/src/git/README.md @@ -180,6 +180,7 @@ With `--repository` set, the server's `instructions` (in the `initialize` result 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: +- 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. - holds a symbolic link (at `objects`, `refs`, `logs`, `index`, `HEAD`, `hooks` or anywhere else in it) that resolves outside the repository's Git directories: that Git directory, or, for a linked worktree, the main repository's `.git` it shares. A link into the working tree is refused too, since Git writes through a link and a checkout can change what a working-tree path holds first. A link that stays inside is followed, and what it leads to is checked the same way. `hooks` is no exception, although no hook runs: a `hooks` directory or hook script linked elsewhere, such as to a shared hooks directory or to a script in the working tree, is refused (Git's `core.hooksPath` setting shares hooks without a link). - holds a Windows directory junction that resolves outside those Git directories, anywhere in it. A junction is judged like a symbolic link: one that stays inside is followed and what it leads to is checked. diff --git a/src/git/src/mcp_server_git/server.py b/src/git/src/mcp_server_git/server.py index 8eb4bdc944..f3cf2dc201 100644 --- a/src/git/src/mcp_server_git/server.py +++ b/src/git/src/mcp_server_git/server.py @@ -1357,6 +1357,8 @@ def outside(kind: str) -> ValueError: for directory in admitted: _check_git_dir_contents(repo_path, directory, admitted) + _check_shared_files(repo_path, {p.resolve() for p in git_dirs + common_dirs}) + if bare != "true": _check_index_entries(repo, repo_path) @@ -1403,6 +1405,102 @@ def _check_index_entries(repo: git.Repo, repo_path: Path) -> None: ) +def _check_shared_files(repo_path: Path, admitted: Collection[Path]) -> None: + """Refuse a file in a git directory that shares its contents with another. + + Git writes some files in a git directory in place: it appends to a reflog + (`logs/HEAD`, `logs/refs/...`), and truncates and rewrites `MERGE_MSG`, + `MERGE_HEAD`, `MERGE_MODE`, `COMMIT_EDITMSG` and `FETCH_HEAD`. A file + hard-linked to one elsewhere takes that write there. (The rest it writes + to a lock file renamed over the old one, which leaves another link + alone.) So a regular file with more than one hard link is refused in + each git directory in `admitted` (the repository's git directory and + common directory, resolved), and in whatever a link or junction in it + leads to, as git follows those. + + Object stores (`_in_object_store`) are exempt: a local clone hard-links + every file of the store it clones, and git only ever adds a file to a + store, by rename. The exemption holds only where git never writes in + place, so a link that leads into a store holding shared files, or onto a + directory holding such a store, is refused too, as is a link to a shared + file. + + A real `hooks` directory is part of the git directory, so its files are + checked like any other (without following a link in it); a `hooks` that + is a link or junction is not followed. + """ + + def refused(entry: str, why: str) -> ValueError: + return ValueError( + f"Repository path '{repo_path}' has '{entry}' in its git directory, " + f"{why}: not allowed with --repository" + ) + + # Directory links, and the store directories holding shared files, + # judged against each other once the walk has seen them all. + linked: list[tuple[str, Path]] = [] + shared: set[Path] = set() + # Each directory to scan, and whether links in it are followed. + pending = [(d, True) for d in admitted] + visited = set(admitted) + while pending: + current, follow = pending.pop() + in_store = _in_object_store(current, admitted) + try: + with os.scandir(current) as scan: + entries = list(scan) + except OSError as err: + raise refused(str(current), f"which cannot be read ({err.strerror})") + for entry in entries: + if entry.is_symlink() or entry.is_dir(): + target = Path(entry.path).resolve() + if not follow and (entry.is_symlink() or target != Path(entry.path)): + continue + if current in admitted and entry.name == "hooks": + if target != Path(entry.path): + continue + follow_inside = False + else: + follow_inside = follow + if target.is_dir(): + if target != Path(entry.path): + linked.append((entry.path, target)) + if target not in visited: + visited.add(target) + pending.append((target, follow_inside)) + elif target.is_file() and target.stat().st_nlink > 1: + raise refused(entry.path, "which leads to a shared file") + elif os.lstat(entry.path).st_nlink > 1: + if not in_store: + raise refused(entry.path, "a file with more than one hard link") + shared.add(current) + for entry_path, target in linked: + if any(s.is_relative_to(target) or target.is_relative_to(s) for s in shared): + raise refused(entry_path, "which leads to a shared object store") + + +def _in_object_store(path: Path, admitted: Collection[Path]) -> bool: + """Whether directory `path` lies in an object store of a git directory. + + The store is `objects` at the top of an admitted git directory, or at the + top of a submodule's under its `modules` (`git submodule add` of a local + path hard-links that one too); nothing under a `logs` directory, where git + appends, counts. Judged within the innermost admitted directory holding + `path`: a git directory placed inside another's store (a linked + worktree's at `/objects/`) is not a store itself, so the + files git writes in place at its top are checked. + """ + holders = [d for d in admitted if path.is_relative_to(d)] + if not holders: + return False + parts = path.relative_to(max(holders, key=lambda d: len(d.parts))).parts + return ( + bool(parts) + and "logs" not in parts + and (parts[0] == "objects" or (parts[0] == "modules" and "objects" in parts)) + ) + + # Files in a git directory that name more object stores for git to read: an # alternate's objects are read as the repository's own, from wherever it is. _ALTERNATES = ("alternates", "http-alternates") diff --git a/src/git/tests/test_shared_files.py b/src/git/tests/test_shared_files.py new file mode 100644 index 0000000000..0e5b7c949e --- /dev/null +++ b/src/git/tests/test_shared_files.py @@ -0,0 +1,290 @@ +"""A file in a git directory that shares its contents with another, under `--repository`. + +Git appends to a reflog in place, and rewrites the merge and commit message +files (`MERGE_MSG`, `COMMIT_EDITMSG`, ...) in place, so such a file +hard-linked to a file elsewhere takes git's write there. `_check_shared_files` +refuses a regular file with more than one hard link in a git directory, +except in an object store, which a local clone hard-links and git never +writes in place; a link that would lead a write onto such a store is refused +too. The refusal names the entry found in the git directory. + +The tests drive the real server through a client, except where only this +check's own answer is in question. The controls keep a local clone, a +submodule cloned from a local path, and a `hooks` linked to a shared +directory (which this check does not walk) working. +""" + +import os +from pathlib import Path +from typing import Any + +import git +import pytest +from conftest import connect, make_repo, rmtree, wire + +from mcp_server_git.server import _check_shared_files + +ORIGINAL = "ORIGINAL-OUTSIDE-CONTENT\n" + +needs_symlinks = pytest.mark.skipif( + os.name == "nt", reason="creating a symbolic link needs a privilege" +) + + +def root_of(repo: git.Repo) -> Path: + assert repo.working_dir is not None + return Path(repo.working_dir) + + +async def call( + repository: Path, tool: str, arguments: dict[str, Any] +) -> dict[str, Any]: + async with connect(repository) as session: + return wire(await session.call_tool(tool, arguments)) + + +def refuses(result: dict[str, Any], entry: Path) -> bool: + """The result is the refusal naming `entry` in the git directory.""" + text = result["content"][0]["text"] + return ( + result["isError"] is True + and f"has '{entry}' in its git directory" in text + and "not allowed with --repository" in text + ) + + +def has_shared_file(directory: Path) -> bool: + return any(p.stat().st_nlink > 1 for p in directory.rglob("*") if p.is_file()) + + +@pytest.mark.parametrize("entry", ["logs/HEAD", "logs/refs/heads/main"]) +async def test_hard_linked_reflog_is_refused( + tmp_path: Path, repo: git.Repo, entry: str +): + root = root_of(repo) + outside = tmp_path / "outside.txt" + outside.write_text(ORIGINAL) + reflog = Path(repo.git_dir).resolve() / entry + reflog.unlink() + os.link(outside, reflog) + (root / "new.txt").write_text("new\n") + repo.git.add("new.txt") + result = await call( + root, "git_commit", {"repo_path": str(root), "message": "payload"} + ) + assert outside.read_text() == ORIGINAL + assert refuses(result, reflog), result + + +async def test_hard_linked_reflog_is_refused_before_a_checkout( + tmp_path: Path, repo: git.Repo +): + root = root_of(repo) + outside = tmp_path / "outside.txt" + outside.write_text(ORIGINAL) + repo.git.branch("other") + reflog = Path(repo.git_dir).resolve() / "logs" / "HEAD" + reflog.unlink() + os.link(outside, reflog) + result = await call( + root, "git_checkout", {"repo_path": str(root), "branch_name": "other"} + ) + assert outside.read_text() == ORIGINAL + assert refuses(result, reflog), result + assert repo.active_branch.name == "main" + + +async def test_local_clone_is_accepted(tmp_path: Path, repo: git.Repo): + # A local clone hard-links every file of the source's object store. + repo.git.gc("-q") + (root_of(repo) / "loose.txt").write_text("loose\n") + repo.git.add("loose.txt") + repo.git.commit("-qm", "loose object") + clone = git.Repo.clone_from(root_of(repo), tmp_path / "clone") + try: + assert has_shared_file(Path(clone.git_dir) / "objects") + clone_root = root_of(clone) + with clone.config_writer() as config: + config.set_value("user", "name", "Test User") + config.set_value("user", "email", "test@example.com") + (clone_root / "new.txt").write_text("new\n") + async with connect(clone_root) as session: + for tool, arguments in ( + ("git_status", {}), + ("git_add", {"files": ["new.txt"]}), + ("git_commit", {"message": "in the clone"}), + ("git_create_branch", {"branch_name": "side"}), + ("git_checkout", {"branch_name": "side"}), + ("git_log", {}), + ): + result = wire( + await session.call_tool( + tool, {"repo_path": str(clone_root), **arguments} + ) + ) + assert result["isError"] is False, (tool, result) + finally: + clone.close() + + +async def test_submodule_cloned_from_a_local_path_is_accepted( + tmp_path: Path, repo: git.Repo +): + # `git submodule add` of a local path hard-links the submodule's objects + # into `.git/modules//objects` of the superproject. + make_repo(tmp_path / "source").close() + root = root_of(repo) + repo.git.execute( + [ + "git", + "-c", + "protocol.file.allow=always", + "submodule", + "add", + "-q", + str(tmp_path / "source"), + "sm", + ] + ) + repo.git.commit("-qm", "add submodule") + assert has_shared_file(Path(repo.git_dir) / "modules") + for repo_path in (root, root / "sm"): + result = await call(root, "git_status", {"repo_path": str(repo_path)}) + assert result["isError"] is False, (repo_path, result) + + +@needs_symlinks +async def test_link_onto_a_shared_object_store_is_refused( + tmp_path: Path, repo: git.Repo +): + # The exemption holds only for the store itself: a link to a shared + # object file is refused, whether it leads into the store, onto the + # directory holding it, or to the file. + clone = git.Repo.clone_from(root_of(repo), tmp_path / "clone") + clone_root = root_of(clone) + git_dir = Path(clone.git_dir).resolve() + clone.close() + shared = next( + p + for p in (git_dir / "objects").rglob("*") + if p.is_file() and p.stat().st_nlink > 1 + ) + for name, target, is_dir in ( + ("into-store", shared.parent, True), + ("onto-git-dir", git_dir, True), + ("onto-file", shared, False), + ): + link = git_dir / name + link.symlink_to(target, target_is_directory=is_dir) + result = await call(clone_root, "git_status", {"repo_path": str(clone_root)}) + assert refuses(result, link), (name, result) + link.unlink() + + +@needs_symlinks +async def test_links_without_shared_files_are_accepted(repo: git.Repo): + # With no shared object file, a link back to the git directory is as + # before. + root = root_of(repo) + git_dir = Path(repo.git_dir) + (git_dir / "loop").symlink_to(git_dir, target_is_directory=True) + result = await call(root, "git_status", {"repo_path": str(root)}) + assert result["isError"] is False, result + + +@needs_symlinks +async def test_worktree_git_dir_inside_an_object_store_is_not_exempt( + tmp_path: Path, repo: git.Repo +): + # A linked worktree's git directory moved to `/objects/nested` + # holds files git rewrites in place (`MERGE_MSG`); they are judged from + # that git directory, where they are not in a store. + root = root_of(repo) + outside = tmp_path / "outside.txt" + outside.write_text(ORIGINAL) + nested = root / "nested" + repo.git.worktree("add", "-q", "-b", "wtb", str(nested)) + git_dir = Path(repo.git_dir).resolve() + moved = git_dir / "objects" / "nested" + (git_dir / "worktrees" / "nested").rename(moved) + (nested / ".git").write_text(f"gitdir: {moved}\n") + (moved / "commondir").write_text("../..\n") + repo.git.branch("other") + os.link(outside, moved / "MERGE_MSG") + result = await call( + root, + "git_merge", + { + "repo_path": str(nested), + "source_branch": "other", + "fast_forward_only": False, + }, + ) + assert outside.read_text() == ORIGINAL + assert refuses(result, moved / "MERGE_MSG"), result + + +@needs_symlinks +def test_hooks_linked_to_a_shared_directory_is_not_walked( + tmp_path: Path, repo: git.Repo +): + # A shared hooks directory elsewhere may hold anything, a hard-linked + # file or a directory that cannot be read; this check does not walk it. + shared_hooks = tmp_path / "shared-hooks" + shared_hooks.mkdir() + (tmp_path / "original").write_text("x\n") + os.link(tmp_path / "original", shared_hooks / "pre-commit") + git_dir = Path(repo.git_dir).resolve() + hooks = git_dir / "hooks" + rmtree(hooks) + hooks.symlink_to(shared_hooks, target_is_directory=True) + _check_shared_files(root_of(repo), {git_dir}) + + +@needs_symlinks +async def test_hard_link_in_a_real_hooks_directory_is_refused( + tmp_path: Path, repo: git.Repo +): + # A real hooks directory is part of the git directory, so its files are + # checked like any other. + root = root_of(repo) + git_dir = Path(repo.git_dir).resolve() + (tmp_path / "original").write_text("x\n") + linked = git_dir / "hooks" / "pre-commit" + linked.parent.mkdir(exist_ok=True) + linked.unlink(missing_ok=True) + os.link(tmp_path / "original", linked) + result = await call(root, "git_status", {"repo_path": str(root)}) + assert refuses(result, linked), result + + +@needs_symlinks +def test_links_in_a_real_hooks_directory_are_not_followed( + tmp_path: Path, repo: git.Repo +): + # Only the files of a real hooks directory are checked; a link in it + # leads somewhere this check does not walk. + shared = tmp_path / "shared" + shared.mkdir() + (tmp_path / "original").write_text("x\n") + os.link(tmp_path / "original", shared / "pre-commit") + git_dir = Path(repo.git_dir).resolve() + (git_dir / "hooks" / "shared").symlink_to(shared, target_is_directory=True) + _check_shared_files(root_of(repo), {git_dir}) + + +@pytest.mark.skipif( + os.name == "nt" or os.geteuid() == 0, + reason="needs POSIX permissions that bind the caller", +) +async def test_unreadable_directory_is_refused_not_crashed(repo: git.Repo): + root = root_of(repo) + unreadable = Path(repo.git_dir).resolve() / "hooks" / "locked" + unreadable.mkdir(parents=True) + unreadable.chmod(0) + try: + result = await call(root, "git_status", {"repo_path": str(root)}) + finally: + unreadable.chmod(0o700) + assert refuses(result, unreadable), result + assert "which cannot be read" in result["content"][0]["text"]