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
1 change: 1 addition & 0 deletions src/git/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -180,6 +180,7 @@ With `--repository` set, the server's `instructions` (in the `initialize` result

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:

- holds a file with more than one hard link, anywhere in it or in what a link in it leads to (other than a linked `hooks` directory), outside its object stores (`objects`, and a submodule's under `modules`). Git appends to a reflog in place, and rewrites files such as `MERGE_MSG` and `COMMIT_EDITMSG` in place, so such a file hard-linked to a file elsewhere would take that write there. A local clone hard-links the object store it clones, which is allowed, so a link that leads into or onto an object store holding such files is refused instead.
- 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`, `logs`, `index`, `HEAD`, `hooks` or anywhere else in it) that resolves outside the repository's Git directories: that Git directory, or, for a linked worktree, the main repository's `.git` it shares. A link into the working tree is refused too, since Git writes through a link and a checkout can change what a working-tree path holds first. A link that stays inside is followed, and what it leads to is checked the same way. `hooks` is no exception, although no hook runs: a `hooks` directory or hook script linked elsewhere, such as to a shared hooks directory or to a script in the working tree, is refused (Git's `core.hooksPath` setting shares hooks without a link).
- holds a Windows directory junction that resolves outside those Git directories, anywhere in it. A junction is judged like a symbolic link: one that stays inside is followed and what it leads to is checked.
Expand Down
98 changes: 98 additions & 0 deletions src/git/src/mcp_server_git/server.py
Original file line number Diff line number Diff line change
Expand Up @@ -1357,6 +1357,8 @@ def outside(kind: str) -> ValueError:
for directory in admitted:
_check_git_dir_contents(repo_path, directory, admitted)

_check_shared_files(repo_path, {p.resolve() for p in git_dirs + common_dirs})

if bare != "true":
_check_index_entries(repo, repo_path)

Expand Down Expand Up @@ -1403,6 +1405,102 @@ def _check_index_entries(repo: git.Repo, repo_path: Path) -> None:
)


def _check_shared_files(repo_path: Path, admitted: Collection[Path]) -> None:
"""Refuse a file in a git directory that shares its contents with another.
Git writes some files in a git directory in place: it appends to a reflog
(`logs/HEAD`, `logs/refs/...`), and truncates and rewrites `MERGE_MSG`,
`MERGE_HEAD`, `MERGE_MODE`, `COMMIT_EDITMSG` and `FETCH_HEAD`. A file
hard-linked to one elsewhere takes that write there. (The rest it writes
to a lock file renamed over the old one, which leaves another link
alone.) So a regular file with more than one hard link is refused in
each git directory in `admitted` (the repository's git directory and
common directory, resolved), and in whatever a link or junction in it
leads to, as git follows those.
Object stores (`_in_object_store`) are exempt: a local clone hard-links
every file of the store it clones, and git only ever adds a file to a
store, by rename. The exemption holds only where git never writes in
place, so a link that leads into a store holding shared files, or onto a
directory holding such a store, is refused too, as is a link to a shared
file.
A real `hooks` directory is part of the git directory, so its files are
checked like any other (without following a link in it); a `hooks` that
is a link or junction is not followed.
"""

def refused(entry: str, why: str) -> ValueError:
return ValueError(
f"Repository path '{repo_path}' has '{entry}' in its git directory, "
f"{why}: not allowed with --repository"
)

# Directory links, and the store directories holding shared files,
# judged against each other once the walk has seen them all.
linked: list[tuple[str, Path]] = []
shared: set[Path] = set()
# Each directory to scan, and whether links in it are followed.
pending = [(d, True) for d in admitted]
visited = set(admitted)
while pending:
current, follow = pending.pop()
in_store = _in_object_store(current, admitted)
try:
with os.scandir(current) as scan:
entries = list(scan)
except OSError as err:
raise refused(str(current), f"which cannot be read ({err.strerror})")
for entry in entries:
if entry.is_symlink() or entry.is_dir():
target = Path(entry.path).resolve()
if not follow and (entry.is_symlink() or target != Path(entry.path)):
continue
if current in admitted and entry.name == "hooks":
if target != Path(entry.path):
continue
follow_inside = False
else:
follow_inside = follow
if target.is_dir():
if target != Path(entry.path):
linked.append((entry.path, target))
if target not in visited:
visited.add(target)
pending.append((target, follow_inside))
elif target.is_file() and target.stat().st_nlink > 1:
raise refused(entry.path, "which leads to a shared file")
elif os.lstat(entry.path).st_nlink > 1:
if not in_store:
raise refused(entry.path, "a file with more than one hard link")
shared.add(current)
for entry_path, target in linked:
if any(s.is_relative_to(target) or target.is_relative_to(s) for s in shared):
raise refused(entry_path, "which leads to a shared object store")


def _in_object_store(path: Path, admitted: Collection[Path]) -> bool:
"""Whether directory `path` lies in an object store of a git directory.
The store is `objects` at the top of an admitted git directory, or at the
top of a submodule's under its `modules` (`git submodule add` of a local
path hard-links that one too); nothing under a `logs` directory, where git
appends, counts. Judged within the innermost admitted directory holding
`path`: a git directory placed inside another's store (a linked
worktree's at `<common>/objects/<name>`) is not a store itself, so the
files git writes in place at its top are checked.
"""
holders = [d for d in admitted if path.is_relative_to(d)]
if not holders:
return False
parts = path.relative_to(max(holders, key=lambda d: len(d.parts))).parts
return (
bool(parts)
and "logs" not in parts
and (parts[0] == "objects" or (parts[0] == "modules" and "objects" in parts))
)


# Files in a git directory that name more object stores for git to read: an
# alternate's objects are read as the repository's own, from wherever it is.
_ALTERNATES = ("alternates", "http-alternates")
Expand Down
Loading