|
| 1 | +"""A Windows junction in a git directory is held to `--repository` (#5520). |
| 2 | +
|
| 3 | +`_check_git_dir_contents` refuses a symbolic link in a git directory that |
| 4 | +resolves outside the allowed repository. A Windows directory junction is not a |
| 5 | +symbolic link to Python (`DirEntry.is_symlink()` is false for one, and |
| 6 | +`is_dir()` true), yet git follows it like one, so the walk used to enter a |
| 7 | +junction's target as an ordinary directory without judging where it was. The |
| 8 | +walk now judges every directory by where it resolves. |
| 9 | +
|
| 10 | +Two sets of tests, both through the real server and a client: |
| 11 | +
|
| 12 | +- **Real junctions**, made with `mklink /J` (which needs no privilege). They |
| 13 | + run only on Windows, which is the `Test git (Windows)` CI leg. |
| 14 | +- **Junction-like entries** on every platform: `os.scandir` is wrapped so a |
| 15 | + symbolic link reports itself the way a junction does. A POSIX host cannot |
| 16 | + make a junction, and the per-file coverage gate runs on Linux, so these are |
| 17 | + what fail there when the fix is taken out. |
| 18 | +""" |
| 19 | + |
| 20 | +import os |
| 21 | +import subprocess |
| 22 | +import sys |
| 23 | +from collections.abc import Callable, Iterator |
| 24 | +from contextlib import contextmanager |
| 25 | +from pathlib import Path |
| 26 | +from typing import Any |
| 27 | +from unittest import mock |
| 28 | + |
| 29 | +import git |
| 30 | +import pytest |
| 31 | +from conftest import connect, make_repo, rmtree, wire |
| 32 | + |
| 33 | +windows_only = pytest.mark.skipif( |
| 34 | + sys.platform != "win32", reason="junctions exist only on Windows" |
| 35 | +) |
| 36 | + |
| 37 | +Link = Callable[[Path, Path], None] |
| 38 | + |
| 39 | + |
| 40 | +def root_of(repo: git.Repo) -> Path: |
| 41 | + assert repo.working_dir is not None |
| 42 | + return Path(repo.working_dir) |
| 43 | + |
| 44 | + |
| 45 | +async def status(repository: Path, repo_path: Path) -> dict[str, Any]: |
| 46 | + """`git_status` on `repo_path` from a server restricted to `repository`.""" |
| 47 | + async with connect(repository) as session: |
| 48 | + return wire( |
| 49 | + await session.call_tool("git_status", {"repo_path": str(repo_path)}) |
| 50 | + ) |
| 51 | + |
| 52 | + |
| 53 | +def uses_outside(result: dict[str, Any], used: Path, allowed: Path) -> bool: |
| 54 | + """The result is the error for a repository git opened outside `allowed`.""" |
| 55 | + text = result["content"][0]["text"] |
| 56 | + return ( |
| 57 | + result["isError"] is True |
| 58 | + and f"uses '{used}'" in text |
| 59 | + and f"which is outside the allowed repository '{allowed}'" in text |
| 60 | + ) |
| 61 | + |
| 62 | + |
| 63 | +def junction(link: Path, target: Path) -> None: |
| 64 | + """Make `link` a directory junction to `target` (Windows only).""" |
| 65 | + subprocess.run( |
| 66 | + ["cmd", "/c", "mklink", "/J", str(link), str(target)], |
| 67 | + check=True, |
| 68 | + capture_output=True, |
| 69 | + ) |
| 70 | + |
| 71 | + |
| 72 | +def symlink(link: Path, target: Path) -> None: |
| 73 | + link.symlink_to(target, target_is_directory=True) |
| 74 | + |
| 75 | + |
| 76 | +class JunctionLike: |
| 77 | + """A symbolic link's `DirEntry`, answering as a junction's does.""" |
| 78 | + |
| 79 | + def __init__(self, entry: "os.DirEntry[str]") -> None: |
| 80 | + self._entry = entry |
| 81 | + self.name = entry.name |
| 82 | + self.path = entry.path |
| 83 | + |
| 84 | + def is_symlink(self) -> bool: |
| 85 | + return False |
| 86 | + |
| 87 | + def is_dir(self) -> bool: |
| 88 | + return True |
| 89 | + |
| 90 | + |
| 91 | +class JunctionLikeScan: |
| 92 | + """`os.scandir`'s iterator, with each directory link made junction-like.""" |
| 93 | + |
| 94 | + def __init__(self, scan: Any) -> None: |
| 95 | + self._scan = scan |
| 96 | + |
| 97 | + def __enter__(self) -> Iterator[Any]: |
| 98 | + return iter(self) |
| 99 | + |
| 100 | + def __exit__(self, *exc: object) -> None: |
| 101 | + self._scan.close() |
| 102 | + |
| 103 | + def __iter__(self) -> Iterator[Any]: |
| 104 | + for entry in self._scan: |
| 105 | + if entry.is_symlink() and entry.is_dir(): |
| 106 | + yield JunctionLike(entry) |
| 107 | + else: |
| 108 | + yield entry |
| 109 | + |
| 110 | + |
| 111 | +@contextmanager |
| 112 | +def links_scan_as_junctions() -> Iterator[None]: |
| 113 | + real_scandir = os.scandir |
| 114 | + with mock.patch( |
| 115 | + "mcp_server_git.server.os.scandir", |
| 116 | + lambda path: JunctionLikeScan(real_scandir(path)), |
| 117 | + ): |
| 118 | + yield |
| 119 | + |
| 120 | + |
| 121 | +@contextmanager |
| 122 | +def nothing_patched() -> Iterator[None]: |
| 123 | + yield |
| 124 | + |
| 125 | + |
| 126 | +# Each case: how to make the link, and what to patch while the server runs. |
| 127 | +REAL = pytest.param(junction, nothing_patched, marks=windows_only, id="junction") |
| 128 | +LIKE = pytest.param(symlink, links_scan_as_junctions, id="junction-like") |
| 129 | +either = pytest.mark.parametrize(("link", "patched"), [REAL, LIKE]) |
| 130 | + |
| 131 | + |
| 132 | +@either |
| 133 | +@pytest.mark.parametrize("entry", ["objects", "refs"]) |
| 134 | +async def test_junction_leading_outside_is_refused( |
| 135 | + tmp_path: Path, |
| 136 | + repo: git.Repo, |
| 137 | + link: Link, |
| 138 | + patched: Callable[[], Any], |
| 139 | + entry: str, |
| 140 | +): |
| 141 | + # `.git/objects` (or `refs`) of a nested repository is a junction to |
| 142 | + # another repository's, outside the allowed one. |
| 143 | + root = root_of(repo) |
| 144 | + other = make_repo(tmp_path / "other") |
| 145 | + nested = make_repo(root / "nested") |
| 146 | + nested_git = Path(nested.git_dir) |
| 147 | + nested.close() |
| 148 | + target = Path(other.git_dir) / entry |
| 149 | + rmtree(nested_git / entry) |
| 150 | + link(nested_git / entry, target) |
| 151 | + try: |
| 152 | + with patched(): |
| 153 | + result = await status(root, root / "nested") |
| 154 | + assert uses_outside(result, target.resolve(), root), result |
| 155 | + finally: |
| 156 | + other.close() |
| 157 | + |
| 158 | + |
| 159 | +@either |
| 160 | +async def test_junction_staying_inside_is_followed_and_checked( |
| 161 | + tmp_path: Path, repo: git.Repo, link: Link, patched: Callable[[], Any] |
| 162 | +): |
| 163 | + # A junction to a directory in the allowed repository is allowed, and git |
| 164 | + # follows it, so what it leads to is checked: here a second junction, in |
| 165 | + # that directory, to outside. |
| 166 | + root = root_of(repo) |
| 167 | + other = make_repo(tmp_path / "other") |
| 168 | + store = root / "store" |
| 169 | + store.mkdir() |
| 170 | + link(Path(repo.git_dir) / "extra", store) |
| 171 | + escape = Path(other.git_dir) / "objects" |
| 172 | + link(store / "elsewhere", escape) |
| 173 | + # A cycle of allowed junctions ends rather than being walked forever. |
| 174 | + link(store / "loop", store) |
| 175 | + try: |
| 176 | + with patched(): |
| 177 | + result = await status(root, root) |
| 178 | + assert uses_outside(result, escape.resolve(), root), result |
| 179 | + finally: |
| 180 | + other.close() |
| 181 | + |
| 182 | + |
| 183 | +@either |
| 184 | +async def test_junctions_that_stay_inside_are_accepted( |
| 185 | + tmp_path: Path, repo: git.Repo, link: Link, patched: Callable[[], Any] |
| 186 | +): |
| 187 | + # Into the working tree, within the git directory, and around in a cycle: |
| 188 | + # none leads anywhere new. Nor does a `hooks` junction to a shared |
| 189 | + # directory outside, since no hook runs. |
| 190 | + root = root_of(repo) |
| 191 | + git_dir = Path(repo.git_dir) |
| 192 | + docs = root / "docs" |
| 193 | + docs.mkdir() |
| 194 | + link(git_dir / "extra", docs) |
| 195 | + link(git_dir / "refs-again", git_dir / "refs") |
| 196 | + link(git_dir / "loop", git_dir) |
| 197 | + shared_hooks = tmp_path / "shared-hooks" |
| 198 | + shared_hooks.mkdir() |
| 199 | + hooks = git_dir / "hooks" |
| 200 | + if hooks.exists(): |
| 201 | + rmtree(hooks) |
| 202 | + link(hooks, shared_hooks) |
| 203 | + with patched(): |
| 204 | + result = await status(root, root) |
| 205 | + assert result["isError"] is False, result |
| 206 | + |
| 207 | + |
| 208 | +@windows_only |
| 209 | +async def test_dangling_junction_inside_is_not_walked(repo: git.Repo): |
| 210 | + # A junction is still a directory to `is_dir()` once its target is gone; |
| 211 | + # walking it would fail the call with the scan's own error. |
| 212 | + root = root_of(repo) |
| 213 | + gone = root / "gone" |
| 214 | + gone.mkdir() |
| 215 | + junction(Path(repo.git_dir) / "extra", gone) |
| 216 | + gone.rmdir() |
| 217 | + result = await status(root, root) |
| 218 | + assert result["isError"] is False, result |
| 219 | + |
| 220 | + |
| 221 | +@windows_only |
| 222 | +async def test_dangling_junction_outside_is_refused(tmp_path: Path, repo: git.Repo): |
| 223 | + root = root_of(repo) |
| 224 | + gone = tmp_path / "gone" |
| 225 | + gone.mkdir() |
| 226 | + junction(Path(repo.git_dir) / "extra", gone.resolve()) |
| 227 | + gone.rmdir() |
| 228 | + result = await status(root, root) |
| 229 | + # Not `uses_outside`: how a target that is gone is spelled is up to the |
| 230 | + # host, so only the refusal is pinned. |
| 231 | + assert result["isError"] is True, result |
| 232 | + assert ( |
| 233 | + f"which is outside the allowed repository '{root}'" |
| 234 | + in result["content"][0]["text"] |
| 235 | + ), result |
0 commit comments