Skip to content

Commit f1be0d9

Browse files
authored
Merge pull request #5627 from modelcontextprotocol/v2/fix/5599-git-recheck-confinement
fix(git): repeat the --repository check after a tool writes the working tree
2 parents bea7320 + 1f53bc5 commit f1be0d9

3 files changed

Lines changed: 330 additions & 15 deletions

File tree

‎src/git/README.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -180,6 +180,8 @@ A tool call's `repo_path` must be inside that repository, and so must the direct
180180

181181
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.
182182

183+
These checks run when a tool call opens the repository, and again after each Git command in the call that writes the working tree (`git_checkout`, `git_merge` and the `git merge --abort` after a conflict, and the autostash `git_commit` reapplies when it concludes a merge), since such a write can change the repository's configuration (a `.git/config` linked to a tracked file that gains a `core.worktree`). If the repository no longer passes, the call stops with an error before it runs another Git command, and the working tree stays as that command wrote it; a merge that conflicted is then still in progress rather than aborted.
184+
183185
### A repository's own programs
184186

185187
A repository's configuration and hooks travel with it (an unpacked archive, a shared folder, a vendored tree), so the server never runs a program they name, with or without `--repository`. Every Git command it runs overrides, through `GIT_CONFIG_COUNT`, the settings that would start one:

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

Lines changed: 71 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -459,7 +459,9 @@ def _has_staged_changes(repo: git.Repo) -> bool:
459459
return bool(repo.index.diff(repo.head.commit))
460460

461461

462-
def git_commit(repo: git.Repo, message: str) -> str:
462+
def git_commit(
463+
repo: git.Repo, message: str, *, allowed_repository: Path | None = None
464+
) -> str:
463465
# repo.index.commit() writes a tree unconditionally, so without this check
464466
# a caller that forgot to stage gets a hash back for an empty commit and no
465467
# way to tell it apart from a real one.
@@ -480,7 +482,7 @@ def git_commit(repo: git.Repo, message: str) -> str:
480482
commit = repo.index.commit(message, parent_commits=parents, skip_hooks=True)
481483
for name in ("MERGE_HEAD", "MERGE_MSG", "MERGE_MODE", "AUTO_MERGE"):
482484
(git_dir / name).unlink(missing_ok=True)
483-
autostash_note = _apply_merge_autostash(repo)
485+
autostash_note = _apply_merge_autostash(repo, allowed_repository)
484486
else:
485487
# skip_hooks: GitPython runs the repository's hooks itself, ignoring
486488
# the core.hooksPath override (`harden_repo`).
@@ -489,7 +491,9 @@ def git_commit(repo: git.Repo, message: str) -> str:
489491
return f"Changes committed successfully with hash {commit.hexsha}{autostash_note}"
490492

491493

492-
def _apply_merge_autostash(repo: git.Repo) -> str:
494+
def _apply_merge_autostash(
495+
repo: git.Repo, allowed_repository: Path | None = None
496+
) -> str:
493497
"""Reapply a `git merge --autostash` stash, as `git commit` does.
494498
495499
Mirrors git's sequencer: apply the stash, store it in the stash list if
@@ -503,7 +507,9 @@ def _apply_merge_autostash(repo: git.Repo) -> str:
503507
try:
504508
# Through _rewrite_tree although nothing after it runs a driver today
505509
# (`git stash store` runs none): any later git command must be safe.
506-
_rewrite_tree(repo, "stash", "apply", stash_oid)
510+
_rewrite_tree(
511+
repo, "stash", "apply", stash_oid, allowed_repository=allowed_repository
512+
)
507513
note = "\nApplied autostash."
508514
except git.GitCommandError:
509515
repo.git.stash("store", "-m", "autostash", "-q", stash_oid)
@@ -652,8 +658,13 @@ def git_create_branch(
652658
return f"Created branch '{branch_name}' from {base_label}"
653659

654660

655-
def _rewrite_tree(repo: git.Repo, command: str, *args: str) -> str:
656-
"""Run `git <command> <args>`, which writes the working tree, then re-harden.
661+
def _rewrite_tree(
662+
repo: git.Repo,
663+
command: str,
664+
*args: str,
665+
allowed_repository: Path | None = None,
666+
) -> str:
667+
"""Run `git <command> <args>`, which writes the working tree, then re-check.
657668
658669
`harden_repo` reads the repository's configuration when the call opens
659670
the repository, but that configuration can depend on the working tree: an
@@ -671,6 +682,16 @@ def _rewrite_tree(repo: git.Repo, command: str, *args: str) -> str:
671682
If that read fails, the overrides may be incomplete, so the call stops
672683
with a `GitError`, which a caller's `except GitCommandError` cleanup does
673684
not catch, and no further git command runs.
685+
686+
The same holds for where git operates (#5599). `open_repo` checked the
687+
directories git uses against `allowed_repository` (`--repository`) before
688+
the write, and the write can move them: a `.git/config` that is a link to
689+
a tracked file gains a `core.worktree` naming a directory outside, and
690+
the next git command that writes the tree (the `git merge --abort` after
691+
a conflict) writes there instead. So `validate_opened_repo` runs again
692+
too, after the drivers are read, as at open. A repository that no longer
693+
passes stops the call the same way: no git command can be trusted to
694+
stay inside, the cleanup included, so the tree stays as written.
674695
"""
675696
try:
676697
return getattr(repo.git, command)(*args)
@@ -684,9 +705,22 @@ def _rewrite_tree(repo: git.Repo, command: str, *args: str) -> str:
684705
f"tree was left as git {command} wrote it (a merge may still be in "
685706
f"progress), and no further git command was run: {e}"
686707
) from e
708+
if allowed_repository is not None:
709+
try:
710+
validate_opened_repo(repo, Path(repo.working_dir), allowed_repository)
711+
except (ValueError, OSError, git.GitError) as e:
712+
raise git.GitError(
713+
f"Stopped: after git {command} changed the working tree, the "
714+
"repository no longer passes the --repository check. The "
715+
f"working tree was left as git {command} wrote it (a merge may "
716+
"still be in progress), and no further git command was run: "
717+
f"{e}"
718+
) from e
687719

688720

689-
def git_checkout(repo: git.Repo, branch_name: str) -> str:
721+
def git_checkout(
722+
repo: git.Repo, branch_name: str, *, allowed_repository: Path | None = None
723+
) -> str:
690724
# Defense in depth: reject branch names starting with '-' to prevent flag injection,
691725
# even if a malicious ref with that name exists (e.g. via filesystem manipulation)
692726
if branch_name.startswith("-"):
@@ -699,7 +733,9 @@ def git_checkout(repo: git.Repo, branch_name: str) -> str:
699733
# --quiet: without it, git checks each checked-out submodule of the new
700734
# branch for local changes, running git inside it under its own
701735
# configuration; the reply below does not use git's output.
702-
_rewrite_tree(repo, "checkout", "--quiet", branch_name)
736+
_rewrite_tree(
737+
repo, "checkout", "--quiet", branch_name, allowed_repository=allowed_repository
738+
)
703739
# rev_parse accepts any revision, so branch_name may have been a sha, tag or
704740
# remote-tracking ref rather than a branch. Report what actually happened instead of
705741
# claiming a branch switch; a detached HEAD is easy to commit onto by mistake.
@@ -717,7 +753,12 @@ def _git_stderr(error: git.GitCommandError) -> str:
717753
return message or str(error)
718754

719755

720-
def _merge_failure(repo: git.Repo, error: git.GitCommandError, what: str) -> str:
756+
def _merge_failure(
757+
repo: git.Repo,
758+
error: git.GitCommandError,
759+
what: str,
760+
allowed_repository: Path | None = None,
761+
) -> str:
721762
"""Why `git merge` failed, after undoing whatever it left behind.
722763
723764
A merge that stops on conflicts, or fails to write its merge commit,
@@ -737,7 +778,7 @@ def _merge_failure(repo: git.Repo, error: git.GitCommandError, what: str) -> str
737778
).splitlines()
738779
# Through _rewrite_tree although it is the last git command here, so a git
739780
# command added after it reads drivers the restored tree defines.
740-
_rewrite_tree(repo, "merge", "--abort")
781+
_rewrite_tree(repo, "merge", "--abort", allowed_repository=allowed_repository)
741782
if conflicts:
742783
return (
743784
f"{what} stopped on conflicts in: {', '.join(conflicts)}. {unchanged} "
@@ -747,7 +788,11 @@ def _merge_failure(repo: git.Repo, error: git.GitCommandError, what: str) -> str
747788

748789

749790
def git_merge(
750-
repo: git.Repo, source_branch: str, fast_forward_only: bool = True
791+
repo: git.Repo,
792+
source_branch: str,
793+
fast_forward_only: bool = True,
794+
*,
795+
allowed_repository: Path | None = None,
751796
) -> str:
752797
"""Merge `source_branch` into the current branch, or change nothing.
753798
@@ -757,6 +802,9 @@ def git_merge(
757802
The conflicts are reported for the caller to resolve by hand. By default
758803
only a fast-forward is allowed; `fast_forward_only=False` lets git create
759804
a merge commit when the branches have diverged.
805+
806+
`allowed_repository` is the `--repository` the call was opened under,
807+
checked again after each write to the working tree (`_rewrite_tree`).
760808
"""
761809
# Defense in depth: reject sources starting with '-' to prevent flag
762810
# injection, even if a malicious ref with that name exists.
@@ -825,10 +873,11 @@ def git_merge(
825873
"-m",
826874
f"Merge '{source_branch}' into '{target}'",
827875
source.hexsha,
876+
allowed_repository=allowed_repository,
828877
)
829878
except git.GitCommandError as e:
830879
what = f"Merge of '{source_branch}' into '{target}'"
831-
raise ValueError(_merge_failure(repo, e, what)) from e
880+
raise ValueError(_merge_failure(repo, e, what, allowed_repository)) from e
832881
merged = repo.head.commit
833882
if fast_forward:
834883
return f"Fast-forwarded '{target}' to '{source_branch}' ({merged.hexsha[:7]})"
@@ -1597,7 +1646,7 @@ def diff(
15971646
)
15981647
@reports_failures
15991648
def commit(repo_path: str, message: str) -> str:
1600-
return git_commit(open_repo(repo_path), message)
1649+
return git_commit(open_repo(repo_path), message, allowed_repository=repository)
16011650

16021651
@server.tool(
16031652
name=GitTools.ADD.value,
@@ -1707,7 +1756,9 @@ def create_branch(
17071756
)
17081757
@reports_failures
17091758
def checkout(repo_path: str, branch_name: str) -> str:
1710-
return git_checkout(open_repo(repo_path), branch_name)
1759+
return git_checkout(
1760+
open_repo(repo_path), branch_name, allowed_repository=repository
1761+
)
17111762

17121763
@server.tool(
17131764
name=GitTools.MERGE.value,
@@ -1738,7 +1789,12 @@ def merge(
17381789
),
17391790
] = True,
17401791
) -> str:
1741-
return git_merge(open_repo(repo_path), source_branch, fast_forward_only)
1792+
return git_merge(
1793+
open_repo(repo_path),
1794+
source_branch,
1795+
fast_forward_only,
1796+
allowed_repository=repository,
1797+
)
17421798

17431799
@server.tool(
17441800
name=GitTools.SHOW.value,

0 commit comments

Comments
 (0)