Skip to content

Commit 44d24fd

Browse files
committed
Merge branch 'v2/fix/5520-git-windows-junction' into v2/rollup/5604-git-v2.6.0
Signed-off-by: cliffhall <cliff@futurescale.com>
2 parents aad8ae4 + 7660d00 commit 44d24fd

3 files changed

Lines changed: 257 additions & 19 deletions

File tree

‎src/git/README.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -177,6 +177,7 @@ A tool call's `repo_path` must be inside that repository, and so must the direct
177177

178178
- 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.
179179
- 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.
180+
- holds a Windows directory junction that resolves outside both, anywhere in it. A junction is judged like a symbolic link: one that stays inside is followed and what it leads to is checked, and a `hooks` junction is allowed.
180181

181182
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.
182183

‎src/git/src/mcp_server_git/server.py‎

Lines changed: 21 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -1098,10 +1098,17 @@ def _check_git_dir_contents(
10981098
`directory` itself: a link at `objects`, `refs`, `index`, `HEAD` or
10991099
anything else in a git directory is followed by git, for reading and
11001100
for writing (a linked `index` takes git_add's writes elsewhere).
1101-
1102-
A link that is allowed and names a directory is walked too, since git
1103-
follows it into that directory and on into any link inside it; each
1104-
directory is walked once, so a cycle of links ends.
1101+
- A directory that resolves outside them, which is what a Windows
1102+
directory junction is: `is_symlink()` is false for one and `is_dir()`
1103+
true, and git follows it as it follows a link. Every directory is
1104+
judged by where it resolves rather than by detecting a junction
1105+
(`is_junction()` exists only from Python 3.12): an ordinary directory
1106+
resolves to itself, inside the directory being walked, and passes.
1107+
1108+
A link or directory that is allowed is walked where it resolves, since
1109+
git follows it there and on into any link inside it; each directory is
1110+
walked once, so a cycle of links ends, and one whose target is gone
1111+
(a dangling link or junction) is not walked.
11051112
11061113
`hooks` is not walked: no hook runs (`HARDENED_CONFIG`), so a hooks
11071114
directory linked to a shared one elsewhere is harmless.
@@ -1125,21 +1132,16 @@ def _check_git_dir_contents(
11251132
for entry in entries:
11261133
if current == directory and entry.name == "hooks":
11271134
continue
1128-
if entry.is_symlink():
1129-
target = Path(entry.path).resolve()
1130-
if not (
1131-
target.is_relative_to(allowed)
1132-
or target.is_relative_to(directory)
1133-
):
1134-
raise outside(target)
1135-
if target.is_dir() and target not in visited:
1136-
visited.add(target)
1137-
pending.append(target)
1138-
elif entry.is_dir():
1139-
real = Path(entry.path).resolve()
1140-
if real not in visited:
1141-
visited.add(real)
1142-
pending.append(real)
1135+
if not (entry.is_symlink() or entry.is_dir()):
1136+
continue
1137+
target = Path(entry.path).resolve()
1138+
if not (
1139+
target.is_relative_to(allowed) or target.is_relative_to(directory)
1140+
):
1141+
raise outside(target)
1142+
if target.is_dir() and target not in visited:
1143+
visited.add(target)
1144+
pending.append(target)
11431145

11441146

11451147
def git_branch(

‎src/git/tests/test_junction.py‎

Lines changed: 235 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,235 @@
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

Comments
 (0)