Skip to content
Merged
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: 1 addition & 1 deletion src/git/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -176,7 +176,7 @@ python -m mcp_server_git

`--repository` (`-r`) accepts any path inside a Git working tree. At startup the server walks up to the enclosing repository root, the way `git rev-parse --show-toplevel` does, so `--repository .` works when a shared config is launched from any subdirectory of the repository. A path inside the repository therefore allows tool calls anywhere in that repository, not only under the subdirectory given. A path that does not exist, or is not inside a Git repository, is logged as a one-line error at startup.

A tool call's `repo_path` must be inside that repository, and so must the directories Git then uses for it: a repository nested inside whose `.git` file, `commondir` or `core.worktree` points outside is refused. A linked worktree can still be the `--repository`, though its Git directory lives under the main repository's `.git`; only the worktree itself may use that directory, so a repository nested in the worktree whose `.git` names it, or the main repository's `.git`, is refused. With `--repository` set, the server also refuses a repository whose Git directory:
A tool call's `repo_path` must be inside that repository, and so must the directories Git then uses for it: a repository nested inside whose `.git` file, `commondir` or `core.worktree` points outside is refused. The `--repository` root itself may use a Git directory outside it only when that directory names the root back. A linked worktree's Git directory lives under the main repository's `.git` (`.git/worktrees/<name>`), and the main repository's record of the worktree names the root back. Only the worktree itself may use that directory, so a repository nested in the worktree whose `.git` names it, or the main repository's `.git`, is refused. A submodule checkout can be the `--repository` too, or any root whose Git directory's own `config` sets `core.worktree` back to it, as a submodule's (`.git/modules/<name>` in the superproject) does. Any other root whose `.git` file or `commondir` names a directory outside it, including one made with `git init --separate-git-dir`, is refused on every call, and the server logs a warning saying so at startup. The root's Git directory and common directory are fixed when the server starts: if the root's `.git` is later replaced, or gains a `commondir`, so that Git would use a different directory outside the root, the call is refused. With `--repository` set, the server also refuses a repository whose Git directory:

- 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.
- 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.
Expand Down
135 changes: 127 additions & 8 deletions src/git/src/mcp_server_git/server.py
Original file line number Diff line number Diff line change
Expand Up @@ -1092,6 +1092,113 @@ def validate_repo_path(repo_path: Path, allowed_repository: Path | None) -> None
)


# The git directory and common directory of each `--repository` root, as
# `record_root_git_dirs` found them when its server was created, or None when
# the root may use no git directory outside itself. Fixing the pair then, rather
# than reopening the root on every call, keeps a `.git` or `commondir` written
# into the root afterwards from naming a different repository as its own.
_ROOT_GIT_DIRS: dict[Path, tuple[Path, Path] | None] = {}


class _RootGit(git.Git):
"""`git.Git` run in its working directory as given, never env-expanded.

`git.Git` expands `$NAME` and `~` in a str working directory whatever
`expand_vars` says, and runs in the current directory when the expansion
does not exist; it takes a `Path` as it is.
"""

def __init__(self, working_dir: str | os.PathLike[str] | None = None) -> None:
super().__init__(None if working_dir is None else Path(working_dir))


class _RootRepo(git.Repo):
"""`git.Repo` whose git commands and object reads run through `_RootGit`.

Set as the wrapper type, so the object database and the environment
`git.Repo` sets up use it too.
"""

GitCommandWrapperType = _RootGit


def record_root_git_dirs(allowed_repository: Path) -> tuple[Path, Path] | None:
"""Record the git directories the `--repository` root may use outside itself.

A root's git directory and common directory are its own when both lie
inside it, or when the git directory outside names the root back, which
only its owner can write:

- a linked worktree: its git directory is `<common dir>/worktrees/<name>`,
and that directory's `gitdir` file, which `git worktree add` writes in
the main repository, names the root's `.git`;
- a git directory that is its own common directory and whose own
`config` sets `core.worktree` to the root, as `git submodule` writes it
for a submodule checkout (`<super>/.git/modules/<name>`).

Any other git directory outside the root (a `.git` file naming another
repository, a `commondir` outside, `git init --separate-git-dir`) is not
the root's own, since nothing outside the root confirms it: None is
recorded, and every call that would use it is refused.
"""
allowed = allowed_repository.resolve()
own: tuple[Path, Path] | None = None
try:
with _RootRepo(allowed, expand_vars=False) as repo:
harden_repo(repo)
git_dir, common_dir = (
Path(p).resolve()
for p in repo.git.rev_parse(
"--path-format=absolute", "--git-dir", "--git-common-dir"
).splitlines()
)
seen_by_gitpython = (
Path(repo.git_dir).resolve(),
Path(repo.common_dir).resolve(),
)
if seen_by_gitpython == (git_dir, common_dir) and (
(git_dir.is_relative_to(allowed) and common_dir.is_relative_to(allowed))
or _is_linked_worktree_of(allowed, git_dir, common_dir)
or _is_submodule_of(repo, allowed, git_dir, common_dir)
):
own = (git_dir, common_dir)
except (git.GitError, OSError, ValueError):
pass
_ROOT_GIT_DIRS[allowed_repository] = own
return own


def _is_linked_worktree_of(allowed: Path, git_dir: Path, common_dir: Path) -> bool:
"""Whether `git_dir` is the main repository's record of worktree `allowed`."""
if git_dir.parent != common_dir / "worktrees":
return False
try:
named = (git_dir / "gitdir").read_text(encoding="utf-8").strip()
except OSError:
return False
# Relative when written with `worktree.useRelativePaths`.
return (git_dir / named).resolve() == allowed / ".git"


def _is_submodule_of(
repo: git.Repo, allowed: Path, git_dir: Path, common_dir: Path
) -> bool:
"""Whether `git_dir` is a submodule's git directory checked out at `allowed`.

Only `git_dir`'s own `config` is read (`--file`, so no other scope and no
include contributes); `core.worktree` there is relative to `git_dir`.
"""
if git_dir != common_dir:
return False
try:
named = repo.git.config(
"--file", str(git_dir / "config"), "--get", "core.worktree"
)
except git.GitCommandError:
return False
return (git_dir / named).resolve() == allowed


def validate_opened_repo(
repo: git.Repo, repo_path: Path, allowed_repository: Path | None
) -> None:
Expand All @@ -1102,8 +1209,9 @@ def validate_opened_repo(
a directory anywhere else, so the working tree, git directory and common
directory git actually uses are checked too. The working tree must lie
inside the allowed repository. The two git directories must lie inside it,
or be the allowed repository's own as a pair, opened from the allowed
repository itself: a linked worktree's git directory lives under the main
or be the allowed repository's own as a pair (`record_root_git_dirs`,
fixed when the server is created), opened from the allowed repository
itself: a linked worktree's git directory lives under the main
repository's `.git`, outside the worktree it serves, and only that
worktree may use it. A repository nested inside a linked worktree whose
`.git` names the main repository's git directory is refused.
Expand Down Expand Up @@ -1146,14 +1254,16 @@ def outside(used: Path) -> ValueError:
p for p in git_dirs + common_dirs if not p.resolve().is_relative_to(allowed)
]
if escaped:
with git.Repo(allowed, expand_vars=False) as allowed_repo:
own_git_dir = Path(allowed_repo.git_dir).resolve()
own_common_dir = Path(allowed_repo.common_dir).resolve()
if allowed_repository in _ROOT_GIT_DIRS:
own = _ROOT_GIT_DIRS[allowed_repository]
else:
own = record_root_git_dirs(allowed_repository)
is_own = (
bool(working_trees)
own is not None
and bool(working_trees)
and all(Path(w).resolve() == allowed for w in working_trees)
and all(p.resolve() == own_git_dir for p in git_dirs)
and all(p.resolve() == own_common_dir for p in common_dirs)
and all(p.resolve() == own[0] for p in git_dirs)
and all(p.resolve() == own[1] for p in common_dirs)
)
if not is_own:
raise outside(escaped[0])
Expand Down Expand Up @@ -1711,6 +1821,15 @@ async def reject_unknown_tools(
subscriptions=False,
)

# The git directories the root may use outside itself are fixed now, not
# read again from the root on each call.
if repository is not None and record_root_git_dirs(repository) is None:
logging.getLogger(__name__).warning(
f"{repository}: its Git directory is outside it and is not a "
"linked worktree's or a submodule's, so tool calls that use it "
"will be refused"
)

def open_repo(repo_path: str) -> git.Repo:
path = Path(repo_path)
validate_repo_path(path, repository)
Expand Down
Loading