diff --git a/src/git/README.md b/src/git/README.md index bd2a3e06fc..6d051f8e99 100644 --- a/src/git/README.md +++ b/src/git/README.md @@ -176,7 +176,7 @@ python -m mcp_server_git `--repository` (`-r`) accepts any path inside a Git working tree. At startup the server walks up to the enclosing repository root, the way `git rev-parse --show-toplevel` does, so `--repository .` works when a shared config is launched from any subdirectory of the repository. A path inside the repository therefore allows tool calls anywhere in that repository, not only under the subdirectory given. A path that does not exist, or is not inside a Git repository, is logged as a one-line error at startup. -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. A linked worktree can still be the `--repository`, though its Git directory lives under the main repository's `.git`; 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. With `--repository` set, the server also refuses a repository whose Git directory: +A tool call's `repo_path` must be inside that repository, and so must the directories Git then uses for it: a repository nested inside whose `.git` file, `commondir` or `core.worktree` points outside is refused. The `--repository` root itself may use a Git directory outside it only when that directory names the root back. A linked worktree's Git directory lives under the main repository's `.git` (`.git/worktrees/`), and the main repository's record of the worktree names the root back. Only the worktree itself may use that directory, so a repository nested in the worktree whose `.git` names it, or the main repository's `.git`, is refused. A submodule checkout can be the `--repository` too, or any root whose Git directory's own `config` sets `core.worktree` back to it, as a submodule's (`.git/modules/` in the superproject) does. Any other root whose `.git` file or `commondir` names a directory outside it, including one made with `git init --separate-git-dir`, is refused on every call, and the server logs a warning saying so at startup. The root'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: - 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`, `index`, `HEAD` or anywhere else in it) that resolves outside both the allowed repository and that Git directory. A link that stays inside is followed, and what it leads to is checked the same way. A `hooks` directory linked elsewhere is allowed, since no hook runs. diff --git a/src/git/src/mcp_server_git/server.py b/src/git/src/mcp_server_git/server.py index 4354f0052b..b70fb2e6cd 100644 --- a/src/git/src/mcp_server_git/server.py +++ b/src/git/src/mcp_server_git/server.py @@ -1092,6 +1092,113 @@ def validate_repo_path(repo_path: Path, allowed_repository: Path | None) -> None ) +# The git directory and common directory of each `--repository` root, as +# `record_root_git_dirs` found them when its server was created, or None when +# the root may use no git directory outside itself. Fixing the pair then, rather +# than reopening the root on every call, keeps a `.git` or `commondir` written +# into the root afterwards from naming a different repository as its own. +_ROOT_GIT_DIRS: dict[Path, tuple[Path, Path] | None] = {} + + +class _RootGit(git.Git): + """`git.Git` run in its working directory as given, never env-expanded. + + `git.Git` expands `$NAME` and `~` in a str working directory whatever + `expand_vars` says, and runs in the current directory when the expansion + does not exist; it takes a `Path` as it is. + """ + + def __init__(self, working_dir: str | os.PathLike[str] | None = None) -> None: + super().__init__(None if working_dir is None else Path(working_dir)) + + +class _RootRepo(git.Repo): + """`git.Repo` whose git commands and object reads run through `_RootGit`. + + Set as the wrapper type, so the object database and the environment + `git.Repo` sets up use it too. + """ + + GitCommandWrapperType = _RootGit + + +def record_root_git_dirs(allowed_repository: Path) -> tuple[Path, Path] | None: + """Record the git directories the `--repository` root may use outside itself. + + A root's git directory and common directory are its own when both lie + inside it, or when the git directory outside names the root back, which + only its owner can write: + + - a linked worktree: its git directory is `/worktrees/`, + and that directory's `gitdir` file, which `git worktree add` writes in + the main repository, names the root's `.git`; + - a git directory that is its own common directory and whose own + `config` sets `core.worktree` to the root, as `git submodule` writes it + for a submodule checkout (`/.git/modules/`). + + Any other git directory outside the root (a `.git` file naming another + repository, a `commondir` outside, `git init --separate-git-dir`) is not + the root's own, since nothing outside the root confirms it: None is + recorded, and every call that would use it is refused. + """ + allowed = allowed_repository.resolve() + own: tuple[Path, Path] | None = None + try: + with _RootRepo(allowed, expand_vars=False) as repo: + harden_repo(repo) + git_dir, common_dir = ( + Path(p).resolve() + for p in repo.git.rev_parse( + "--path-format=absolute", "--git-dir", "--git-common-dir" + ).splitlines() + ) + seen_by_gitpython = ( + Path(repo.git_dir).resolve(), + Path(repo.common_dir).resolve(), + ) + if seen_by_gitpython == (git_dir, common_dir) and ( + (git_dir.is_relative_to(allowed) and common_dir.is_relative_to(allowed)) + or _is_linked_worktree_of(allowed, git_dir, common_dir) + or _is_submodule_of(repo, allowed, git_dir, common_dir) + ): + own = (git_dir, common_dir) + except (git.GitError, OSError, ValueError): + pass + _ROOT_GIT_DIRS[allowed_repository] = own + return own + + +def _is_linked_worktree_of(allowed: Path, git_dir: Path, common_dir: Path) -> bool: + """Whether `git_dir` is the main repository's record of worktree `allowed`.""" + if git_dir.parent != common_dir / "worktrees": + return False + try: + named = (git_dir / "gitdir").read_text(encoding="utf-8").strip() + except OSError: + return False + # Relative when written with `worktree.useRelativePaths`. + return (git_dir / named).resolve() == allowed / ".git" + + +def _is_submodule_of( + repo: git.Repo, allowed: Path, git_dir: Path, common_dir: Path +) -> bool: + """Whether `git_dir` is a submodule's git directory checked out at `allowed`. + + Only `git_dir`'s own `config` is read (`--file`, so no other scope and no + include contributes); `core.worktree` there is relative to `git_dir`. + """ + if git_dir != common_dir: + return False + try: + named = repo.git.config( + "--file", str(git_dir / "config"), "--get", "core.worktree" + ) + except git.GitCommandError: + return False + return (git_dir / named).resolve() == allowed + + def validate_opened_repo( repo: git.Repo, repo_path: Path, allowed_repository: Path | None ) -> None: @@ -1102,8 +1209,9 @@ def validate_opened_repo( a directory anywhere else, so the working tree, git directory and common directory git actually uses are checked too. The working tree must lie inside the allowed repository. The two git directories must lie inside it, - or be the allowed repository's own as a pair, opened from the allowed - repository itself: a linked worktree's git directory lives under the main + or be the allowed repository's own as a pair (`record_root_git_dirs`, + fixed when the server is created), opened from the allowed repository + itself: a linked worktree's git directory lives under the main repository's `.git`, outside the worktree it serves, and only that worktree may use it. A repository nested inside a linked worktree whose `.git` names the main repository's git directory is refused. @@ -1146,14 +1254,16 @@ def outside(used: Path) -> ValueError: p for p in git_dirs + common_dirs if not p.resolve().is_relative_to(allowed) ] if escaped: - with git.Repo(allowed, expand_vars=False) as allowed_repo: - own_git_dir = Path(allowed_repo.git_dir).resolve() - own_common_dir = Path(allowed_repo.common_dir).resolve() + if allowed_repository in _ROOT_GIT_DIRS: + own = _ROOT_GIT_DIRS[allowed_repository] + else: + own = record_root_git_dirs(allowed_repository) is_own = ( - bool(working_trees) + own is not None + and bool(working_trees) and all(Path(w).resolve() == allowed for w in working_trees) - and all(p.resolve() == own_git_dir for p in git_dirs) - and all(p.resolve() == own_common_dir for p in common_dirs) + and all(p.resolve() == own[0] for p in git_dirs) + and all(p.resolve() == own[1] for p in common_dirs) ) if not is_own: raise outside(escaped[0]) @@ -1711,6 +1821,15 @@ async def reject_unknown_tools( subscriptions=False, ) + # The git directories the root may use outside itself are fixed now, not + # read again from the root on each call. + if repository is not None and record_root_git_dirs(repository) is None: + logging.getLogger(__name__).warning( + f"{repository}: its Git directory is outside it and is not a " + "linked worktree's or a submodule's, so tool calls that use it " + "will be refused" + ) + def open_repo(repo_path: str) -> git.Repo: path = Path(repo_path) validate_repo_path(path, repository) diff --git a/src/git/tests/test_root_git_dir.py b/src/git/tests/test_root_git_dir.py new file mode 100644 index 0000000000..8ebe9c2a00 --- /dev/null +++ b/src/git/tests/test_root_git_dir.py @@ -0,0 +1,306 @@ +"""The `--repository` root's own git directories, fixed when the server starts. + +A root's git directory may lie outside it only when it is a linked worktree, +whose git directory the main repository records under `.git/worktrees/` with a +`gitdir` file naming the root back. Any other git directory outside the root, +whether the root's `.git` names it when the server starts or a `.git` or +`commondir` written into the root afterwards does, is not the root's own, so +each call that would use it is refused. Each test drives the server through an +in-process MCP client and asserts on what comes back. +""" + +from pathlib import Path +from typing import Any + +import git +import pytest +from conftest import connect, make_repo, rmtree, wire + +from mcp_server_git import server as git_server +from mcp_server_git.server import ( + _RootRepo, + create_server, + record_root_git_dirs, + validate_opened_repo, +) + +OUTSIDE_TEXT = "outside content\n" + + +def outside_repo(path: Path) -> git.Repo: + repo = make_repo(path) + (path / "outside.txt").write_text(OUTSIDE_TEXT) + repo.index.add(["outside.txt"]) + repo.index.commit("outside") + return repo + + +async def show(root: Path, repo_path: Path, revision: str) -> dict[str, Any]: + async with connect(root) as session: + return wire( + await session.call_tool( + "git_show", {"repo_path": str(repo_path), "revision": revision} + ) + ) + + +def refused(result: dict[str, Any], used: Path) -> bool: + text = result["content"][0]["text"] + return ( + result["isError"] is True + and f"uses '{used}'" in text + and "which is outside the allowed repository" in text + and OUTSIDE_TEXT not in text + ) + + +async def test_a_root_whose_git_file_names_another_repository_is_refused( + tmp_path: Path, +) -> None: + other = outside_repo(tmp_path / "other") + root = tmp_path / "root" + root.mkdir() + (root / ".git").write_text(f"gitdir: {other.git_dir}\n") + try: + result = await show(root, root, "HEAD:outside.txt") + assert refused(result, Path(other.git_dir).resolve()), result + # The other repository named directly is refused as before. + direct = await show(root, tmp_path / "other", "HEAD:outside.txt") + assert direct["isError"] is True + assert OUTSIDE_TEXT not in direct["content"][0]["text"] + finally: + other.close() + + +async def test_a_root_whose_git_dir_is_replaced_after_startup_is_refused( + tmp_path: Path, +) -> None: + other = outside_repo(tmp_path / "other") + root_repo = make_repo(tmp_path / "root") + root = tmp_path / "root" + root_repo.close() + try: + async with connect(root) as session: + before = wire( + await session.call_tool( + "git_show", {"repo_path": str(root), "revision": "HEAD:test.txt"} + ) + ) + assert before["isError"] is False + rmtree(root / ".git") + (root / ".git").write_text(f"gitdir: {other.git_dir}\n") + after = wire( + await session.call_tool( + "git_show", + {"repo_path": str(root), "revision": "HEAD:outside.txt"}, + ) + ) + assert refused(after, Path(other.git_dir).resolve()), after + finally: + other.close() + + +@pytest.mark.parametrize("when", ["before startup", "after startup"]) +async def test_a_root_whose_commondir_names_another_repository_is_refused( + tmp_path: Path, when: str +) -> None: + other = outside_repo(tmp_path / "other") + root_repo = make_repo(tmp_path / "root") + root = tmp_path / "root" + commondir = Path(root_repo.git_dir) / "commondir" + root_repo.close() + if when == "before startup": + commondir.write_text(f"{other.git_dir}\n") + try: + async with connect(root) as session: + if when == "after startup": + commondir.write_text(f"{other.git_dir}\n") + result = wire( + await session.call_tool( + "git_show", + {"repo_path": str(root), "revision": "HEAD:outside.txt"}, + ) + ) + assert refused(result, Path(other.git_dir).resolve()), result + finally: + other.close() + + +async def test_a_linked_worktree_root_is_served(tmp_path: Path) -> None: + main = make_repo(tmp_path / "main") + worktree = tmp_path / "worktree" + main.git.worktree("add", str(worktree)) + try: + result = await show(worktree, worktree, "HEAD:test.txt") + assert result["isError"] is False, result + finally: + main.close() + + +async def test_a_linked_worktree_root_with_relative_paths_is_served( + tmp_path: Path, +) -> None: + # `worktree.useRelativePaths` writes the `gitdir` file relative to the + # worktree's git directory; write it that way by hand, whatever git runs. + main = make_repo(tmp_path / "main") + worktree = tmp_path / "worktree" + main.git.worktree("add", str(worktree)) + gitdir = Path(main.git_dir) / "worktrees" / "worktree" / "gitdir" + gitdir.write_text("../../../../worktree/.git\n") + try: + result = await show(worktree, worktree, "HEAD:test.txt") + assert result["isError"] is False, result + finally: + main.close() + + +async def test_a_root_naming_another_worktrees_git_dir_is_refused( + tmp_path: Path, +) -> None: + # The other repository's linked worktree record names its own worktree, + # not this root, so the root cannot claim it. + other = outside_repo(tmp_path / "other") + other.git.worktree("add", str(tmp_path / "other-wt")) + record = Path(other.git_dir) / "worktrees" / "other-wt" + root = tmp_path / "root" + root.mkdir() + (root / ".git").write_text(f"gitdir: {record}\n") + try: + result = await show(root, root, "HEAD:outside.txt") + assert refused(result, record.resolve()), result + finally: + other.close() + + +async def test_a_worktree_record_without_its_gitdir_file_is_refused( + tmp_path: Path, +) -> None: + main = make_repo(tmp_path / "main") + worktree = tmp_path / "worktree" + main.git.worktree("add", str(worktree)) + record = Path(main.git_dir) / "worktrees" / "worktree" + (record / "gitdir").unlink() + try: + result = await show(worktree, worktree, "HEAD:test.txt") + assert refused(result, record.resolve()), result + finally: + main.close() + + +def test_the_root_is_recorded_on_first_use_without_a_server(tmp_path: Path) -> None: + # validate_opened_repo called directly, with no server created for the + # root, records the root's git directories then and holds it to them. + other = outside_repo(tmp_path / "other") + root = tmp_path / "root" + root.mkdir() + (root / ".git").write_text(f"gitdir: {other.git_dir}\n") + git_server._ROOT_GIT_DIRS.pop(root, None) + try: + with ( + git.Repo(root, expand_vars=False) as repo, + pytest.raises(ValueError, match="outside the allowed repository"), + ): + validate_opened_repo(repo, root, root) + assert git_server._ROOT_GIT_DIRS[root] is None + finally: + other.close() + + +def test_a_root_that_is_not_a_repository_records_nothing(tmp_path: Path) -> None: + assert record_root_git_dirs(tmp_path) is None + + +def add_submodule(tmp_path: Path) -> tuple[git.Repo, Path]: + """A superproject with a submodule checked out at `/mod`.""" + source = make_repo(tmp_path / "source") + source.close() + superproject = make_repo(tmp_path / "super") + superproject.git.execute( + [ + "git", + "-c", + "protocol.file.allow=always", + "submodule", + "add", + str(tmp_path / "source"), + "mod", + ] + ) + return superproject, tmp_path / "super" / "mod" + + +async def test_a_submodule_root_is_served(tmp_path: Path) -> None: + superproject, module = add_submodule(tmp_path) + try: + result = await show(module, module, "HEAD:test.txt") + assert result["isError"] is False, result + finally: + superproject.close() + + +async def test_a_root_naming_another_submodules_git_dir_is_refused( + tmp_path: Path, +) -> None: + # The submodule's git directory sets `core.worktree` to the submodule's + # own checkout, not this root, so the root cannot claim it. + superproject, _ = add_submodule(tmp_path) + modules = (tmp_path / "super" / ".git" / "modules" / "mod").resolve() + root = tmp_path / "root" + root.mkdir() + (root / ".git").write_text(f"gitdir: {modules}\n") + try: + result = await show(root, root, "HEAD:test.txt") + assert result["isError"] is True, result + assert git_server._ROOT_GIT_DIRS[root] is None + finally: + superproject.close() + + +async def test_a_root_whose_git_dir_is_not_its_own_is_logged_at_startup( + tmp_path: Path, caplog: pytest.LogCaptureFixture +) -> None: + other = outside_repo(tmp_path / "other") + root = tmp_path / "root" + root.mkdir() + (root / ".git").write_text(f"gitdir: {other.git_dir}\n") + try: + with caplog.at_level("WARNING", logger="mcp_server_git.server"): + await show(root, root, "HEAD:test.txt") + assert any( + "is not a linked worktree's or a submodule's" in record.getMessage() + for record in caplog.records + ) + finally: + other.close() + + +@pytest.mark.parametrize("target", ["another repository", "nothing"]) +def test_a_root_named_like_an_environment_variable_is_recorded_as_itself( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, target: str +) -> None: + # A linked worktree root whose directory name is literally `$NAME`: its + # git directories are recorded from the root itself, not from wherever + # `$NAME` expands to. + other = outside_repo(tmp_path / "other") + other.close() + named = tmp_path / "other" if target == "another repository" else tmp_path / "x" + monkeypatch.setenv("GHSA_ROOT_NAME", str(named)) + main = make_repo(tmp_path / "main") + worktree = tmp_path / "$GHSA_ROOT_NAME" + main.git.worktree("add", str(worktree)) + record = (Path(main.git_dir) / "worktrees" / "$GHSA_ROOT_NAME").resolve() + try: + create_server(worktree) + assert git_server._ROOT_GIT_DIRS[worktree] == ( + record, + Path(main.git_dir).resolve(), + ) + # The repository the recording opens runs its commands, and reads + # its objects, in the root itself. + with _RootRepo(worktree.resolve(), expand_vars=False) as opened: + toplevel = Path(opened.git.rev_parse("--show-toplevel")).resolve() + assert toplevel == worktree.resolve() + assert opened.odb.info(opened.head.commit.binsha).type == b"commit" + assert opened.head.commit.hexsha == main.head.commit.hexsha + finally: + main.close()