Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions src/git/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -180,6 +180,8 @@ A tool call's `repo_path` must be inside that repository, and so must the direct

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.

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.

### A repository's own programs

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:
Expand Down
86 changes: 71 additions & 15 deletions src/git/src/mcp_server_git/server.py
Original file line number Diff line number Diff line change
Expand Up @@ -459,7 +459,9 @@ def _has_staged_changes(repo: git.Repo) -> bool:
return bool(repo.index.diff(repo.head.commit))


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


def _apply_merge_autostash(repo: git.Repo) -> str:
def _apply_merge_autostash(
repo: git.Repo, allowed_repository: Path | None = None
) -> str:
"""Reapply a `git merge --autostash` stash, as `git commit` does.

Mirrors git's sequencer: apply the stash, store it in the stash list if
Expand All @@ -503,7 +507,9 @@ def _apply_merge_autostash(repo: git.Repo) -> str:
try:
# Through _rewrite_tree although nothing after it runs a driver today
# (`git stash store` runs none): any later git command must be safe.
_rewrite_tree(repo, "stash", "apply", stash_oid)
_rewrite_tree(
repo, "stash", "apply", stash_oid, allowed_repository=allowed_repository
)
note = "\nApplied autostash."
except git.GitCommandError:
repo.git.stash("store", "-m", "autostash", "-q", stash_oid)
Expand Down Expand Up @@ -652,8 +658,13 @@ def git_create_branch(
return f"Created branch '{branch_name}' from {base_label}"


def _rewrite_tree(repo: git.Repo, command: str, *args: str) -> str:
"""Run `git <command> <args>`, which writes the working tree, then re-harden.
def _rewrite_tree(
repo: git.Repo,
command: str,
*args: str,
allowed_repository: Path | None = None,
) -> str:
"""Run `git <command> <args>`, which writes the working tree, then re-check.

`harden_repo` reads the repository's configuration when the call opens
the repository, but that configuration can depend on the working tree: an
Expand All @@ -671,6 +682,16 @@ def _rewrite_tree(repo: git.Repo, command: str, *args: str) -> str:
If that read fails, the overrides may be incomplete, so the call stops
with a `GitError`, which a caller's `except GitCommandError` cleanup does
not catch, and no further git command runs.

The same holds for where git operates (#5599). `open_repo` checked the
directories git uses against `allowed_repository` (`--repository`) before
the write, and the write can move them: a `.git/config` that is a link to
a tracked file gains a `core.worktree` naming a directory outside, and
the next git command that writes the tree (the `git merge --abort` after
a conflict) writes there instead. So `validate_opened_repo` runs again
too, after the drivers are read, as at open. A repository that no longer
passes stops the call the same way: no git command can be trusted to
stay inside, the cleanup included, so the tree stays as written.
"""
try:
return getattr(repo.git, command)(*args)
Expand All @@ -684,9 +705,22 @@ def _rewrite_tree(repo: git.Repo, command: str, *args: str) -> str:
f"tree was left as git {command} wrote it (a merge may still be in "
f"progress), and no further git command was run: {e}"
) from e
if allowed_repository is not None:
try:
validate_opened_repo(repo, Path(repo.working_dir), allowed_repository)
except (ValueError, OSError, git.GitError) as e:
raise git.GitError(
f"Stopped: after git {command} changed the working tree, the "
"repository no longer passes the --repository check. The "
f"working tree was left as git {command} wrote it (a merge may "
"still be in progress), and no further git command was run: "
f"{e}"
) from e


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


def _merge_failure(repo: git.Repo, error: git.GitCommandError, what: str) -> str:
def _merge_failure(
repo: git.Repo,
error: git.GitCommandError,
what: str,
allowed_repository: Path | None = None,
) -> str:
"""Why `git merge` failed, after undoing whatever it left behind.

A merge that stops on conflicts, or fails to write its merge commit,
Expand All @@ -737,7 +778,7 @@ def _merge_failure(repo: git.Repo, error: git.GitCommandError, what: str) -> str
).splitlines()
# Through _rewrite_tree although it is the last git command here, so a git
# command added after it reads drivers the restored tree defines.
_rewrite_tree(repo, "merge", "--abort")
_rewrite_tree(repo, "merge", "--abort", allowed_repository=allowed_repository)
if conflicts:
return (
f"{what} stopped on conflicts in: {', '.join(conflicts)}. {unchanged} "
Expand All @@ -747,7 +788,11 @@ def _merge_failure(repo: git.Repo, error: git.GitCommandError, what: str) -> str


def git_merge(
repo: git.Repo, source_branch: str, fast_forward_only: bool = True
repo: git.Repo,
source_branch: str,
fast_forward_only: bool = True,
*,
allowed_repository: Path | None = None,
) -> str:
"""Merge `source_branch` into the current branch, or change nothing.

Expand All @@ -757,6 +802,9 @@ def git_merge(
The conflicts are reported for the caller to resolve by hand. By default
only a fast-forward is allowed; `fast_forward_only=False` lets git create
a merge commit when the branches have diverged.

`allowed_repository` is the `--repository` the call was opened under,
checked again after each write to the working tree (`_rewrite_tree`).
"""
# Defense in depth: reject sources starting with '-' to prevent flag
# injection, even if a malicious ref with that name exists.
Expand Down Expand Up @@ -825,10 +873,11 @@ def git_merge(
"-m",
f"Merge '{source_branch}' into '{target}'",
source.hexsha,
allowed_repository=allowed_repository,
)
except git.GitCommandError as e:
what = f"Merge of '{source_branch}' into '{target}'"
raise ValueError(_merge_failure(repo, e, what)) from e
raise ValueError(_merge_failure(repo, e, what, allowed_repository)) from e
merged = repo.head.commit
if fast_forward:
return f"Fast-forwarded '{target}' to '{source_branch}' ({merged.hexsha[:7]})"
Expand Down Expand Up @@ -1597,7 +1646,7 @@ def diff(
)
@reports_failures
def commit(repo_path: str, message: str) -> str:
return git_commit(open_repo(repo_path), message)
return git_commit(open_repo(repo_path), message, allowed_repository=repository)

@server.tool(
name=GitTools.ADD.value,
Expand Down Expand Up @@ -1684,7 +1733,9 @@ def create_branch(
)
@reports_failures
def checkout(repo_path: str, branch_name: str) -> str:
return git_checkout(open_repo(repo_path), branch_name)
return git_checkout(
open_repo(repo_path), branch_name, allowed_repository=repository
)

@server.tool(
name=GitTools.MERGE.value,
Expand Down Expand Up @@ -1715,7 +1766,12 @@ def merge(
),
] = True,
) -> str:
return git_merge(open_repo(repo_path), source_branch, fast_forward_only)
return git_merge(
open_repo(repo_path),
source_branch,
fast_forward_only,
allowed_repository=repository,
)

@server.tool(
name=GitTools.SHOW.value,
Expand Down
Loading
Loading