|
| 1 | +"""Configuration a tool call's own writes create is overridden like the rest. |
| 2 | +
|
| 3 | +`harden_repo` reads the repository's filter and merge drivers when a call |
| 4 | +opens the repository, but the configuration can depend on the working tree: |
| 5 | +an `[include]` path into it that git skips while the file is missing, a |
| 6 | +`.git/config` that is a link to a tracked file, or an `includeIf |
| 7 | +"onbranch:..."` that a checkout satisfies. A tool that writes the tree (a |
| 8 | +merge, a checkout) can so define a driver mid-call, and the git commands it |
| 9 | +runs next (a conflicting merge's `git diff` and `git merge --abort`) would run |
| 10 | +it. Every tree-writing command goes through `_rewrite_tree`, which reads the |
| 11 | +drivers again before anything else runs. |
| 12 | +
|
| 13 | +Each attack test plants a filter that records its run in a canary file |
| 14 | +(`Payload`, shared with test_repository_config.py), drives the real server |
| 15 | +through a client, and asserts the canary stays empty. The payloads are POSIX |
| 16 | +shell scripts, so those tests skip on Windows. |
| 17 | +""" |
| 18 | + |
| 19 | +import os |
| 20 | +import sys |
| 21 | +from pathlib import Path |
| 22 | +from unittest import mock |
| 23 | + |
| 24 | +import git |
| 25 | +import pytest |
| 26 | +from conftest import connect, make_repo, wire |
| 27 | +from test_repository_config import Payload, root_of |
| 28 | + |
| 29 | +from mcp_server_git import server |
| 30 | +from mcp_server_git.server import _rewrite_tree, git_checkout, git_merge, harden_repo |
| 31 | + |
| 32 | +posix_only = pytest.mark.skipif( |
| 33 | + sys.platform == "win32", reason="the payloads are POSIX shell scripts" |
| 34 | +) |
| 35 | + |
| 36 | +CONFLICT = ( |
| 37 | + "Error executing tool git_merge: Merge of 'feature' into 'main' stopped on " |
| 38 | + "conflicts in: m.txt. The merge was aborted and the repository is " |
| 39 | + "unchanged. Resolve the conflicts by hand." |
| 40 | +) |
| 41 | + |
| 42 | + |
| 43 | +def filter_config(payload: Payload) -> str: |
| 44 | + command = payload.command("filter") |
| 45 | + return f'[filter "x"]\n\tsmudge = {command}\n\tclean = {command}\n' |
| 46 | + |
| 47 | + |
| 48 | +def diverged( |
| 49 | + repo: git.Repo, |
| 50 | + feature_files: dict[str, str], |
| 51 | + base_files: dict[str, str] | None = None, |
| 52 | +) -> None: |
| 53 | + """`feature` writes `feature_files` and conflicts with `main` in m.txt. |
| 54 | +
|
| 55 | + Both branches start from a commit of `base_files`. Every file is under |
| 56 | + `* filter=x`, which is harmless while `x` is undefined. |
| 57 | + """ |
| 58 | + root = root_of(repo) |
| 59 | + base_files = base_files or {} |
| 60 | + (root / ".gitattributes").write_text("* filter=x\n") |
| 61 | + (root / "m.txt").write_text("base\n") |
| 62 | + for name, text in base_files.items(): |
| 63 | + (root / name).write_text(text) |
| 64 | + repo.index.add([".gitattributes", "m.txt", *base_files]) |
| 65 | + repo.index.commit("base") |
| 66 | + repo.git.checkout("-b", "feature") |
| 67 | + (root / "m.txt").write_text("theirs\n") |
| 68 | + for name, text in feature_files.items(): |
| 69 | + (root / name).write_text(text) |
| 70 | + repo.index.add(["m.txt", *feature_files]) |
| 71 | + repo.index.commit("theirs") |
| 72 | + repo.git.checkout("main") |
| 73 | + (root / "m.txt").write_text("ours\n") |
| 74 | + repo.index.add(["m.txt"]) |
| 75 | + repo.index.commit("ours") |
| 76 | + |
| 77 | + |
| 78 | +def include_evil_cfg(repo: git.Repo) -> None: |
| 79 | + """Add `[include] path = ../evil.cfg` to the repository's own config.""" |
| 80 | + with open(Path(repo.git_dir) / "config", "a") as config: |
| 81 | + config.write("[include]\n\tpath = ../evil.cfg\n") |
| 82 | + |
| 83 | + |
| 84 | +async def merge(repo: git.Repo, repository: Path | None) -> dict[str, object]: |
| 85 | + async with connect(repository) as session: |
| 86 | + result = await session.call_tool( |
| 87 | + "git_merge", |
| 88 | + { |
| 89 | + "repo_path": str(root_of(repo)), |
| 90 | + "source_branch": "feature", |
| 91 | + "fast_forward_only": False, |
| 92 | + }, |
| 93 | + ) |
| 94 | + return wire(result) |
| 95 | + |
| 96 | + |
| 97 | +@posix_only |
| 98 | +@pytest.mark.parametrize("confined", [False, True]) |
| 99 | +@pytest.mark.anyio |
| 100 | +async def test_include_created_by_a_conflicting_merge_runs_nothing( |
| 101 | + tmp_path: Path, confined: bool |
| 102 | +) -> None: |
| 103 | + payload = Payload(tmp_path / "payload") |
| 104 | + repo = make_repo(tmp_path / "repo") |
| 105 | + diverged(repo, {"evil.cfg": filter_config(payload)}) |
| 106 | + # The include names a file that only the merged branch adds. |
| 107 | + include_evil_cfg(repo) |
| 108 | + |
| 109 | + result = await merge(repo, root_of(repo) if confined else None) |
| 110 | + |
| 111 | + assert payload.runs() == [] |
| 112 | + assert result["isError"] is True |
| 113 | + assert result["content"] == [{"type": "text", "text": CONFLICT}] |
| 114 | + assert not (root_of(repo) / "evil.cfg").exists() |
| 115 | + repo.close() |
| 116 | + |
| 117 | + |
| 118 | +@posix_only |
| 119 | +@pytest.mark.anyio |
| 120 | +async def test_config_linked_into_the_tree_and_rewritten_by_a_merge_runs_nothing( |
| 121 | + tmp_path: Path, |
| 122 | +) -> None: |
| 123 | + payload = Payload(tmp_path / "payload") |
| 124 | + repo = make_repo(tmp_path / "repo") |
| 125 | + root = root_of(repo) |
| 126 | + config = Path(repo.git_dir) / "config" |
| 127 | + # The repository's configuration is a tracked file; the merged branch |
| 128 | + # adds a filter to it. |
| 129 | + original = config.read_text() |
| 130 | + diverged( |
| 131 | + repo, |
| 132 | + {"repo.cfg": original + filter_config(payload)}, |
| 133 | + {"repo.cfg": original}, |
| 134 | + ) |
| 135 | + config.unlink() |
| 136 | + os.symlink(root / "repo.cfg", config) |
| 137 | + |
| 138 | + result = await merge(repo, None) |
| 139 | + |
| 140 | + assert payload.runs() == [] |
| 141 | + assert result["content"] == [{"type": "text", "text": CONFLICT}] |
| 142 | + repo.close() |
| 143 | + |
| 144 | + |
| 145 | +@posix_only |
| 146 | +def test_drivers_a_checkout_defines_are_overridden_for_the_rest_of_the_call( |
| 147 | + tmp_path: Path, |
| 148 | +) -> None: |
| 149 | + payload = Payload(tmp_path / "payload") |
| 150 | + repo = make_repo(tmp_path / "repo") |
| 151 | + root = root_of(repo) |
| 152 | + (root / ".gitattributes").write_text("* filter=x\n") |
| 153 | + repo.index.add([".gitattributes"]) |
| 154 | + repo.index.commit("attributes") |
| 155 | + repo.git.checkout("-b", "feature") |
| 156 | + (root / "evil.cfg").write_text(filter_config(payload)) |
| 157 | + repo.index.add(["evil.cfg"]) |
| 158 | + repo.index.commit("config") |
| 159 | + repo.git.checkout("main") |
| 160 | + include_evil_cfg(repo) |
| 161 | + harden_repo(repo) |
| 162 | + |
| 163 | + assert git_checkout(repo, "feature") == "Switched to branch 'feature'" |
| 164 | + # A later command in the same call, on a file the filter applies to. |
| 165 | + (root / "test.txt").write_text("changed\n") |
| 166 | + repo.git.add("test.txt") |
| 167 | + |
| 168 | + assert payload.runs() == [] |
| 169 | + repo.close() |
| 170 | + |
| 171 | + |
| 172 | +def test_a_failed_re_read_stops_the_call(repo: git.Repo) -> None: |
| 173 | + failure = git.GitCommandError(["git", "config"], 128) |
| 174 | + with ( |
| 175 | + mock.patch.object(server, "harden_repo", side_effect=failure), |
| 176 | + pytest.raises(git.GitError) as raised, |
| 177 | + ): |
| 178 | + _rewrite_tree(repo, "status") |
| 179 | + # Not a GitCommandError, which git_merge's cleanup would catch and then |
| 180 | + # run more git commands under incomplete overrides. |
| 181 | + assert not isinstance(raised.value, git.GitCommandError) |
| 182 | + assert "could not be read again after git status" in str(raised.value) |
| 183 | + |
| 184 | + |
| 185 | +def test_a_failed_re_read_after_a_conflicting_merge_runs_no_cleanup( |
| 186 | + tmp_path: Path, |
| 187 | +) -> None: |
| 188 | + repo = make_repo(tmp_path / "repo") |
| 189 | + diverged(repo, {}) |
| 190 | + failure = git.GitCommandError(["git", "config"], 128) |
| 191 | + with ( |
| 192 | + mock.patch.object(server, "harden_repo", side_effect=failure), |
| 193 | + pytest.raises(git.GitError) as raised, |
| 194 | + ): |
| 195 | + git_merge(repo, "feature", fast_forward_only=False) |
| 196 | + # Not git_merge's cleanup (`_merge_failure`, a ValueError), which would |
| 197 | + # run more git commands under incomplete overrides. |
| 198 | + assert not isinstance(raised.value, (git.GitCommandError, ValueError)) |
| 199 | + # The failed re-read, raised while the merge's own failure propagated. |
| 200 | + assert raised.value.__cause__ is failure |
| 201 | + merge_failure = failure.__context__ |
| 202 | + assert isinstance(merge_failure, git.GitCommandError) |
| 203 | + assert "merge" in merge_failure.command |
| 204 | + assert "a merge may still be in progress" in str(raised.value) |
| 205 | + # `git merge --abort` never ran. |
| 206 | + assert (Path(repo.git_dir) / "MERGE_HEAD").exists() |
| 207 | + repo.close() |
0 commit comments