Skip to content

Commit f777ce6

Browse files
committed
Merge branch 'v2/fix/GHSA-87qg-cmw8-jc5m' into v2/fix/GHSA-pm7p-vphh-2cg7
# Conflicts: # src/git/README.md
2 parents 9acea80 + 719a6a2 commit f777ce6

5 files changed

Lines changed: 818 additions & 6 deletions

File tree

‎src/git/README.md‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -185,7 +185,10 @@ A repository's configuration and hooks travel with it (an unpacked archive, a sh
185185
- `core.fsmonitor` is `false`, and `core.hooksPath` points at the null device, so no hook runs; `git_commit` also skips the hooks GitPython would run itself (`pre-commit`, `commit-msg`, `post-commit`).
186186
- Diffs pass `--no-ext-diff` and `--no-textconv`, so `diff.external`, `diff.<driver>.command` and `diff.<driver>.textconv` are ignored.
187187
- Each filter driver (`filter.<name>.clean`, `smudge`, `process`) and merge driver (`merge.<name>.driver`) that the repository's own configuration defines is emptied, including one with an empty name (`[filter ""]`, selected by `filter=`): files are staged and checked out unfiltered, and a file a merge driver would have merged is a conflict, which `git_merge` aborts. Drivers from your global or system configuration, such as Git LFS's, keep working.
188+
- The repository's configuration can depend on its working tree (an `[include]` or `[includeIf]` path into it, or a `.git/config` linked to a tracked file), so a tool that writes the working tree (`git_checkout`, `git_merge`, and the `git merge --abort` after a conflict) reads the drivers again before it runs any other Git command, and a driver that the files it wrote define is emptied as well.
188189
- `commit.gpgSign` and `merge.verifySignatures` are `false`, and `git_merge` passes `--no-gpg-sign` and `--no-verify-signatures`. Each `branch.<name>.mergeOptions` the repository's own configuration sets is emptied, since Git reads it as command-line options. `submodule.recurse` and `merge.autoStash` are `false`, and `core.pager` is `cat`.
190+
- Git never fetches a missing object from a promisor remote by itself (`GIT_NO_LAZY_FETCH=1`), since that fetch runs the transport program the repository's configuration names (`remote.<name>.uploadpack`, `core.sshCommand`). In a partial clone, or any repository that declares a promisor remote, a tool that needs an object that is not on disk reports it missing. A Git too old to honor the variable (before 2.45.1, other than the maintenance releases 2.39.4, 2.40.2, 2.41.1, 2.42.2, 2.43.4 and 2.44.1 made with it) refuses a repository that declares a promisor remote (`remote.<name>.promisor`, `remote.<name>.partialCloneFilter` or `extensions.partialClone`, with or without a remote name).
191+
- `maintenance.auto` is `false` and `gc.auto` is `0`, so no tool starts Git's automatic maintenance (which `git merge` runs when it finishes), whose garbage collection would run the commands a repository's `gc.recentObjectsHook` names. Repositories the server works in are not garbage-collected automatically; your own Git commands still do it.
189192
- `git_status`, `git_diff_unstaged` and `git_diff` pass `--ignore-submodules=dirty`, because looking for changes inside a submodule runs Git under the submodule's own configuration. A submodule whose checked-out commit moved is still reported; changes inside one are not, so run the tool on the submodule's path to see them.
190193

191194
This needs Git 2.31 or later; with an older Git every tool call fails with an error saying so, rather than run unprotected.

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

Lines changed: 105 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -130,6 +130,15 @@ def _git_text(repo: git.Repo, command: str, *args: str) -> str:
130130
# - `submodule.recurse` would carry checkout and merge into submodules, whose
131131
# own configuration this override cannot neutralize (see `_LISTED_KEYS`).
132132
# - `merge.autoStash` keeps git_merge from stashing behind the tool's back.
133+
# - `maintenance.auto` keeps a merge (or any other command that ends in
134+
# `git maintenance run --auto`) from starting git's automatic maintenance,
135+
# whose cruft repacks (git 2.42+) run each command the repository's
136+
# `gc.recentObjectsHook` names. Stopping the launch covers every task,
137+
# including a geometric repack the repository enables, which its own
138+
# `maintenance.<task>.auto` gates; `gc.auto` is a backstop for the gc task
139+
# only, so it does not replace `maintenance.auto`.
140+
# That hook cannot be emptied like a driver: it is multi-valued, and an
141+
# empty override adds a value rather than replacing the repository's.
133142
#
134143
# External diff programs and textconv filters are turned off per command
135144
# (`_DIFF_FLAGS`), and filter and merge drivers per repository (`_LISTED_KEYS`).
@@ -142,6 +151,8 @@ def _git_text(repo: git.Repo, command: str, *args: str) -> str:
142151
("submodule.recurse", "false"),
143152
("status.submoduleSummary", "false"),
144153
("merge.autoStash", "false"),
154+
("maintenance.auto", "false"),
155+
("gc.auto", "0"),
145156
)
146157

147158
# A filter driver (`filter.<name>.clean`/`smudge`/`process`, applied by
@@ -178,6 +189,50 @@ def _git_text(repo: git.Repo, command: str, *args: str) -> str:
178189
# `submodule.<name>.ignore`, which the repository could set to `none`.
179190
_NO_SUBMODULE_STATUS = "--ignore-submodules=dirty"
180191

192+
# A repository that declares a promisor remote has git fetch any object it is
193+
# missing from that remote, by itself, on a read-only command (git show, git
194+
# status with HEAD's tree gone). The fetch runs a transport program the
195+
# repository's configuration names (`remote.<name>.uploadpack`,
196+
# `core.sshCommand`, an `ext::` URL), and no override can pin it by name,
197+
# since the remote's name is the repository's choice; `protocol.allow=never`
198+
# is no help either, as a repository-level `protocol.<name>.allow` outranks
199+
# it. GIT_NO_LAZY_FETCH=1 turns the fetch off, so a missing object is an
200+
# error. Git honors it from 2.45.1 and the maintenance releases made with it
201+
# (2.39.4, 2.40.2, ..., 2.44.1), mapped here as minor -> first patch; an
202+
# older git ignores it, so `harden_repo` refuses a repository with a promisor
203+
# remote there. Any of these keys declares one; git also reads a
204+
# `remote.promisor` with no remote name, as a promisor remote named "".
205+
_NO_LAZY_FETCH_SINCE = {39: 4, 40: 2, 41: 1, 42: 2, 43: 4, 44: 1, 45: 1}
206+
_PROMISOR_KEYS = (
207+
r"^(extensions\.partialclone|remote\.(.+\.)?(promisor|partialclonefilter))$"
208+
)
209+
210+
211+
def _honors_no_lazy_fetch(version: tuple[int, ...]) -> bool:
212+
"""Whether git at `version` honors GIT_NO_LAZY_FETCH."""
213+
major, minor, patch = (tuple(version) + (0, 0, 0))[:3]
214+
if (major, minor) > (2, 45):
215+
return True
216+
since = _NO_LAZY_FETCH_SINCE.get(minor) if major == 2 else None
217+
return since is not None and patch >= since
218+
219+
220+
def _refuse_promisor_remote(repo: git.Repo) -> None:
221+
"""Refuse a repository with a promisor remote, for a git that would fetch."""
222+
try:
223+
repo.git.config("--get-regexp", _PROMISOR_KEYS)
224+
except git.GitCommandError as e:
225+
# Exit 1 is "nothing matched": no promisor remote, nothing to fetch.
226+
if e.status == 1:
227+
return
228+
raise
229+
raise git.GitError(
230+
"Git 2.45.1 or later (or 2.39.4, 2.40.2, 2.41.1, 2.42.2, 2.43.4, "
231+
"2.44.1) is required for a repository with a promisor remote (a "
232+
"partial clone): an older git fetches missing objects from it, and "
233+
"the fetch runs a program the repository's configuration names"
234+
)
235+
181236

182237
def _config_env(entries: list[tuple[str, str]]) -> dict[str, str]:
183238
"""GIT_CONFIG_COUNT variables for `entries`, after any the user set."""
@@ -197,10 +252,12 @@ def harden_repo(repo: git.Repo) -> None:
197252
a worktree's `config.worktree`, and files they include) defines, and
198253
overrides each with an empty command. The same read checks that git
199254
applied the overrides: git older than 2.31 ignores GIT_CONFIG_COUNT, and
200-
is refused rather than run unprotected.
255+
is refused rather than run unprotected. Lazy fetching is turned off
256+
(GIT_NO_LAZY_FETCH), and a repository with a promisor remote is refused
257+
on a git too old to honor that (`_PROMISOR_KEYS`).
201258
"""
202259
entries = list(HARDENED_CONFIG)
203-
repo.git.update_environment(**_config_env(entries))
260+
repo.git.update_environment(GIT_NO_LAZY_FETCH="1", **_config_env(entries))
204261
try:
205262
listed = repo.git.config("--show-scope", "-z", "--get-regexp", _LISTED_KEYS)
206263
except git.GitCommandError as e:
@@ -228,6 +285,8 @@ def harden_repo(repo: git.Repo) -> None:
228285
if drivers:
229286
entries += [(key, "") for key in sorted(drivers)]
230287
repo.git.update_environment(**_config_env(entries))
288+
if not _honors_no_lazy_fetch(repo.git.version_info):
289+
_refuse_promisor_remote(repo)
231290

232291

233292
def git_status(repo: git.Repo) -> str:
@@ -354,7 +413,9 @@ def _apply_merge_autostash(repo: git.Repo) -> str:
354413
return ""
355414
stash_oid = autostash.read_text().strip()
356415
try:
357-
repo.git.stash("apply", stash_oid)
416+
# Through _rewrite_tree although nothing after it runs a driver today
417+
# (`git stash store` runs none): any later git command must be safe.
418+
_rewrite_tree(repo, "stash", "apply", stash_oid)
358419
note = "\nApplied autostash."
359420
except git.GitCommandError:
360421
repo.git.stash("store", "-m", "autostash", "-q", stash_oid)
@@ -503,6 +564,40 @@ def git_create_branch(
503564
return f"Created branch '{branch_name}' from {base_label}"
504565

505566

567+
def _rewrite_tree(repo: git.Repo, command: str, *args: str) -> str:
568+
"""Run `git <command> <args>`, which writes the working tree, then re-harden.
569+
570+
`harden_repo` reads the repository's configuration when the call opens
571+
the repository, but that configuration can depend on the working tree: an
572+
`[include]` or `[includeIf]` path into it (git skips one whose file is
573+
missing), a `.git/config` that is a link into it, or an `includeIf
574+
"onbranch:..."` that a branch switch satisfies. A command that writes the
575+
tree can so create or change configuration. Git reads configuration once
576+
per process, at start, so the command itself runs under what was read,
577+
but every git command after it in the same call reads afresh, and would
578+
find filter or merge drivers that were never overridden. Every command
579+
that writes the tree therefore goes through here, and the drivers are
580+
read again before any other git command runs, whether or not it failed:
581+
a failed merge has written files too, and its cleanup runs git next.
582+
583+
If that read fails, the overrides may be incomplete, so the call stops
584+
with a `GitError`, which a caller's `except GitCommandError` cleanup does
585+
not catch, and no further git command runs.
586+
"""
587+
try:
588+
return getattr(repo.git, command)(*args)
589+
finally:
590+
try:
591+
harden_repo(repo)
592+
except git.GitCommandError as e:
593+
raise git.GitError(
594+
"Stopped: the repository's configuration could not be read "
595+
f"again after git {command} changed the working tree. The working "
596+
f"tree was left as git {command} wrote it (a merge may still be in "
597+
f"progress), and no further git command was run: {e}"
598+
) from e
599+
600+
506601
def git_checkout(repo: git.Repo, branch_name: str) -> str:
507602
# Defense in depth: reject branch names starting with '-' to prevent flag injection,
508603
# even if a malicious ref with that name exists (e.g. via filesystem manipulation)
@@ -513,7 +608,7 @@ def git_checkout(repo: git.Repo, branch_name: str) -> str:
513608
repo.rev_parse(
514609
branch_name
515610
) # Validates branch_name is a real git ref, throws BadName if not
516-
repo.git.checkout(branch_name)
611+
_rewrite_tree(repo, "checkout", branch_name)
517612
# rev_parse accepts any revision, so branch_name may have been a sha, tag or
518613
# remote-tracking ref rather than a branch. Report what actually happened instead of
519614
# claiming a branch switch; a detached HEAD is easy to commit onto by mistake.
@@ -549,7 +644,9 @@ def _merge_failure(repo: git.Repo, error: git.GitCommandError, what: str) -> str
549644
conflicts = _git_text(
550645
repo, "diff", _NO_SUBMODULE_STATUS, "--name-only", "--diff-filter=U"
551646
).splitlines()
552-
repo.git.merge("--abort")
647+
# Through _rewrite_tree although it is the last git command here, so a git
648+
# command added after it reads drivers the restored tree defines.
649+
_rewrite_tree(repo, "merge", "--abort")
553650
if conflicts:
554651
return (
555652
f"{what} stopped on conflicts in: {', '.join(conflicts)}. {unchanged} "
@@ -624,7 +721,9 @@ def git_merge(
624721
# names what the caller asked for.
625722
mode = "--ff-only" if fast_forward_only else "--ff"
626723
try:
627-
repo.git.merge(
724+
_rewrite_tree(
725+
repo,
726+
"merge",
628727
mode,
629728
"--commit",
630729
"--no-squash",
Lines changed: 145 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,145 @@
1+
"""No tool starts git's automatic maintenance in a repository it opens.
2+
3+
`git merge` ends in `git maintenance run --auto`, which runs `git gc` when
4+
the repository's own configuration says it is due (`gc.auto`,
5+
`gc.autoPackLimit`). That gc's cruft repack runs every command the
6+
repository's `gc.recentObjectsHook` names, so a repository could run a
7+
program as the server's user through git_merge. `HARDENED_CONFIG` pins
8+
`maintenance.auto` and `gc.auto` off; these tests plant a repository that
9+
forces a gc on the next merge, with a hook that records its own run in a
10+
canary file, and assert the canary is never written.
11+
12+
The hook is a POSIX shell script, so the tests that run it skip on Windows;
13+
the check of the pinned values runs everywhere.
14+
"""
15+
16+
import os
17+
import shlex
18+
import stat
19+
import subprocess
20+
import sys
21+
from pathlib import Path
22+
23+
import git
24+
import pytest
25+
from conftest import connect, wire
26+
27+
from mcp_server_git.server import harden_repo
28+
29+
posix_only = pytest.mark.skipif(
30+
sys.platform == "win32", reason="the hook is a POSIX shell script"
31+
)
32+
# gc.recentObjectsHook arrived in git 2.42; an older git never runs it.
33+
needs_hook = pytest.mark.skipif(
34+
git.Git().version_info < (2, 42), reason="gc.recentObjectsHook needs git 2.42"
35+
)
36+
37+
38+
def root_of(repo: git.Repo) -> Path:
39+
assert repo.working_dir is not None
40+
return Path(repo.working_dir)
41+
42+
43+
def commit_file(repo: git.Repo, name: str, content: str) -> None:
44+
(root_of(repo) / name).write_text(content, newline="\n")
45+
repo.git.add(name)
46+
repo.git.commit("-m", f"write {name}")
47+
48+
49+
def plant_due_gc(repo: git.Repo, canary: Path, *, diverge: bool) -> None:
50+
"""Make the next merge of `feature` run a gc that asks the hook.
51+
52+
Two packs make gc due under `gc.auto=1` and `gc.autoPackLimit=1`, and
53+
their sizes (6 or 3 objects against 4) are within a factor of two, so a
54+
git whose maintenance repacks geometrically finds them due too. An old
55+
unreachable loose object makes the cruft repack consult
56+
`gc.recentObjectsHook`. `diverge` adds a commit on `main`, so the merge
57+
is not a fast-forward.
58+
"""
59+
# Each commit comes before the pack it lands in: a commit runs automatic
60+
# maintenance too, which could consolidate packs already made.
61+
repo.git.branch("feature")
62+
if diverge:
63+
commit_file(repo, "main.txt", "main\n")
64+
repo.git.repack("-a", "-d")
65+
repo.git.checkout("feature")
66+
(root_of(repo) / "feature-1.txt").write_text("one\n", newline="\n")
67+
(root_of(repo) / "feature-2.txt").write_text("two\n", newline="\n")
68+
repo.git.add("feature-1.txt", "feature-2.txt")
69+
repo.git.commit("-m", "feature")
70+
repo.git.checkout("main")
71+
repo.git.repack("-d")
72+
73+
hook = canary.parent / "hook.sh"
74+
hook.write_text(f"#!/bin/sh\necho ran >> {shlex.quote(str(canary))}\n")
75+
hook.chmod(hook.stat().st_mode | stat.S_IEXEC)
76+
with repo.config_writer() as config:
77+
config.set_value("gc", "auto", "1")
78+
config.set_value("gc", "autoPackLimit", "1")
79+
config.set_value("gc", "autoDetach", "false")
80+
config.set_value("gc", "recentObjectsHook", shlex.quote(str(hook)))
81+
82+
sha = (
83+
subprocess.run(
84+
["git", "hash-object", "-w", "--stdin"],
85+
cwd=root_of(repo),
86+
input=b"stale\n",
87+
capture_output=True,
88+
check=True,
89+
)
90+
.stdout.decode()
91+
.strip()
92+
)
93+
loose = Path(repo.git_dir) / "objects" / sha[:2] / sha[2:]
94+
os.utime(loose, (0, 0))
95+
96+
97+
@posix_only
98+
@pytest.mark.parametrize("fast_forward_only", [True, False])
99+
@pytest.mark.parametrize("pinned", [False, True], ids=["roots", "repository"])
100+
async def test_merge_never_runs_the_recent_objects_hook(
101+
tmp_path: Path, repo: git.Repo, fast_forward_only: bool, pinned: bool
102+
):
103+
canary = tmp_path / "canary"
104+
plant_due_gc(repo, canary, diverge=not fast_forward_only)
105+
106+
async with connect(root_of(repo) if pinned else None) as session:
107+
result = wire(
108+
await session.call_tool(
109+
"git_merge",
110+
{
111+
"repo_path": str(root_of(repo)),
112+
"source_branch": "feature",
113+
"fast_forward_only": fast_forward_only,
114+
},
115+
)
116+
)
117+
118+
assert result["isError"] is False, result
119+
assert (root_of(repo) / "feature-1.txt").exists()
120+
assert not canary.exists()
121+
122+
123+
@posix_only
124+
@needs_hook
125+
@pytest.mark.parametrize("diverge", [False, True], ids=["fast-forward", "merge"])
126+
def test_the_planted_repository_runs_the_hook_without_the_overrides(
127+
tmp_path: Path, repo: git.Repo, diverge: bool
128+
):
129+
# The control: the same merge under plain git does run the hook, so the
130+
# test above fails if the overrides go missing.
131+
canary = tmp_path / "canary"
132+
plant_due_gc(repo, canary, diverge=diverge)
133+
repo.git.merge("--ff", "--no-edit", "feature")
134+
assert canary.read_text() == "ran\n"
135+
136+
137+
def test_harden_repo_turns_automatic_maintenance_off(repo: git.Repo):
138+
with repo.config_writer() as config:
139+
config.set_value("gc", "auto", "1")
140+
config.set_value("maintenance", "auto", "true")
141+
harden_repo(repo)
142+
assert repo.git.config("--show-scope", "--get", "gc.auto") == "command\t0"
143+
assert (
144+
repo.git.config("--show-scope", "--get", "maintenance.auto") == "command\tfalse"
145+
)

0 commit comments

Comments
 (0)