Skip to content

Commit eeca1dd

Browse files
authored
Merge pull request #5675 from modelcontextprotocol/v2/fix/GHSA-f33v-89w7-f9vc
fix(git): GHSA-f33v-89w7-f9vc - repo_path expands environment variables and error messages disclose their values
2 parents 772e50e + 0475c7c commit eeca1dd

3 files changed

Lines changed: 143 additions & 3 deletions

File tree

‎src/git/README.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,8 @@ Please note that mcp-server-git is currently in early development. The functiona
1414

1515
### Tools
1616

17+
Every tool's `repo_path` is taken literally: neither a leading `~` nor `$NAME` or `${NAME}` is expanded, and a relative path is relative to the server's working directory.
18+
1719
1. `git_status`
1820
- Shows the working tree status
1921
- Input:

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

Lines changed: 32 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1146,7 +1146,7 @@ def outside(used: Path) -> ValueError:
11461146
p for p in git_dirs + common_dirs if not p.resolve().is_relative_to(allowed)
11471147
]
11481148
if escaped:
1149-
with git.Repo(allowed) as allowed_repo:
1149+
with git.Repo(allowed, expand_vars=False) as allowed_repo:
11501150
own_git_dir = Path(allowed_repo.git_dir).resolve()
11511151
own_common_dir = Path(allowed_repo.common_dir).resolve()
11521152
is_own = (
@@ -1658,6 +1658,30 @@ def reported_as_invalid_params() -> Iterator[None]:
16581658
raise MCPError(code=INVALID_PARAMS, message=str(e)) from e
16591659

16601660

1661+
class _LiteralGit(git.Git):
1662+
"""A `git.Git` whose working directory is taken literally.
1663+
1664+
`git.Git` runs `os.path.expandvars` on a `str` working directory, and
1665+
`git.Repo` hands it one, whatever `expand_vars` the repository was opened
1666+
with. A `Path` is only resolved, so a `$NAME` in it stays as written.
1667+
"""
1668+
1669+
def __init__(self, working_dir: str | os.PathLike[str] | None = None) -> None:
1670+
super().__init__(None if working_dir is None else Path(working_dir))
1671+
1672+
1673+
class _LiteralRepo(git.Repo):
1674+
"""A `git.Repo` whose git commands run in the directory it was opened at.
1675+
1676+
Opened with `expand_vars=False` and an absolute path, a repository path is
1677+
taken literally: neither a `$NAME` nor a leading `~` in it becomes the
1678+
value of the server's environment, in the directory opened, in where its
1679+
commands run, or in an error.
1680+
"""
1681+
1682+
GitCommandWrapperType = _LiteralGit
1683+
1684+
16611685
def create_server(repository: Path | None) -> MCPServer:
16621686
"""The git server, confined to `repository` when one is given."""
16631687

@@ -1690,7 +1714,10 @@ async def reject_unknown_tools(
16901714
def open_repo(repo_path: str) -> git.Repo:
16911715
path = Path(repo_path)
16921716
validate_repo_path(path, repository)
1693-
repo = git.Repo(path)
1717+
# Opened at exactly the path checked above. GitPython expands a leading
1718+
# `~` in a relative path whatever `expand_vars` says, so it is made
1719+
# absolute first, which leaves nothing for it to expand.
1720+
repo = _LiteralRepo(path.absolute(), expand_vars=False)
16941721
try:
16951722
# First, so that no git command run for the repository, the
16961723
# confinement checks' included, runs a program it names.
@@ -2011,7 +2038,9 @@ async def serve(repository: Path | None, transport: str = "stdio") -> None:
20112038
# Walk up to the enclosing working tree, like `git rev-parse
20122039
# --show-toplevel`, so `--repository .` works from a subdirectory.
20132040
root = Path(
2014-
git.Repo(repository, search_parent_directories=True).working_dir
2041+
git.Repo(
2042+
repository, search_parent_directories=True, expand_vars=False
2043+
).working_dir
20152044
)
20162045
except git.NoSuchPathError:
20172046
logger.error(f"{repository} does not exist")

‎src/git/tests/test_expand_vars.py‎

Lines changed: 109 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,109 @@
1+
"""A tool's `repo_path` is taken literally: no `$NAME` or `~` in it is expanded.
2+
3+
GitPython's `Repo()` expands environment variables in the path it is given
4+
unless it is passed `expand_vars=False`, and expands a leading `~` (from
5+
`HOME`) in any relative path. A `$NAME`, `${NAME}` or `~` in `repo_path` must
6+
name a file whose name holds those characters, so the result of a tool call
7+
(its errors included) never holds the value of `HOME` or of a variable the
8+
path names. A `$NAME` in `--repository` is taken literally too. These tests
9+
set a variable, name it in a path, and assert on what a client receives over
10+
the wire.
11+
"""
12+
13+
from pathlib import Path
14+
15+
import git
16+
import pytest
17+
from conftest import connect, make_repo, wire
18+
19+
VALUE = "value-of-the-variable"
20+
NAME = "MCP_GIT_TEST_VARIABLE"
21+
22+
23+
@pytest.fixture(autouse=True)
24+
def variable(monkeypatch: pytest.MonkeyPatch) -> None:
25+
monkeypatch.setenv(NAME, VALUE)
26+
27+
28+
async def status(repository: Path | None, repo_path: str) -> dict[str, object]:
29+
async with connect(repository) as session:
30+
return wire(await session.call_tool("git_status", {"repo_path": repo_path}))
31+
32+
33+
def text_of(result: dict[str, object]) -> str:
34+
content = result["content"]
35+
assert isinstance(content, list)
36+
return "".join(block["text"] for block in content)
37+
38+
39+
@pytest.mark.parametrize("reference", [f"${NAME}", f"${{{NAME}}}"])
40+
async def test_relative_repo_path_is_not_expanded(
41+
tmp_path: Path, monkeypatch: pytest.MonkeyPatch, reference: str
42+
):
43+
monkeypatch.chdir(tmp_path)
44+
result = await status(None, reference)
45+
assert result["isError"] is True
46+
assert VALUE not in text_of(result)
47+
assert reference in text_of(result)
48+
49+
50+
@pytest.mark.parametrize("reference", [f"${NAME}", f"${{{NAME}}}"])
51+
async def test_repo_path_under_repository_is_not_expanded(
52+
tmp_path: Path, monkeypatch: pytest.MonkeyPatch, reference: str
53+
):
54+
root = tmp_path / "repo"
55+
make_repo(root).close()
56+
# With the working directory inside the allowed repository, a relative
57+
# path passes the --repository check before the repository is opened.
58+
monkeypatch.chdir(root)
59+
for repo_path in (reference, str(root / reference)):
60+
result = await status(root, repo_path)
61+
assert result["isError"] is True
62+
assert VALUE not in text_of(result)
63+
64+
65+
@pytest.mark.parametrize("reference", ["~", "~/repo"])
66+
async def test_tilde_in_repo_path_is_not_expanded(
67+
tmp_path: Path, monkeypatch: pytest.MonkeyPatch, reference: str
68+
):
69+
home = tmp_path / VALUE
70+
make_repo(home / "repo").close()
71+
monkeypatch.setenv("HOME", str(home))
72+
monkeypatch.setenv("USERPROFILE", str(home))
73+
monkeypatch.chdir(tmp_path)
74+
result = await status(None, reference)
75+
assert result["isError"] is True
76+
assert VALUE not in text_of(result)
77+
assert str(tmp_path / reference) in text_of(result)
78+
79+
80+
async def test_repository_named_with_a_dollar_sign_opens(tmp_path: Path):
81+
# Made under a plain name and renamed, since `make_repo` would expand it.
82+
root = tmp_path / f"${NAME}"
83+
make_repo(tmp_path / "plain").close()
84+
(tmp_path / "plain").rename(root)
85+
for repository in (None, root):
86+
result = await status(repository, str(root))
87+
assert result["isError"] is False, result
88+
assert "On branch main" in text_of(result)
89+
# Reading a commit goes through the object database's own git.
90+
async with connect(repository) as session:
91+
log = wire(await session.call_tool("git_log", {"repo_path": str(root)}))
92+
assert log["isError"] is False, log
93+
assert "initial commit" in text_of(log)
94+
95+
96+
async def test_repository_with_separate_git_dir_named_with_a_dollar_sign(
97+
tmp_path: Path,
98+
):
99+
# A git dir outside the working tree makes the --repository check compare
100+
# it with the allowed root's own. Its `core.worktree` names the root back,
101+
# as a submodule's git dir does, so the root is one the check accepts.
102+
root = tmp_path / f"${NAME}"
103+
root.mkdir()
104+
git_dir = tmp_path / "gitdir"
105+
git.Git(root).init(f"--separate-git-dir={git_dir}")
106+
git.Git(root).config("core.worktree", str(root))
107+
result = await status(root, str(root))
108+
assert result["isError"] is False, result
109+
assert "No commits yet" in text_of(result)

0 commit comments

Comments
 (0)