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 @@ -190,6 +190,7 @@ A repository's configuration and hooks travel with it (an unpacked archive, a sh
- `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`).
- Diffs pass `--no-ext-diff` and `--no-textconv`, so `diff.external`, `diff.<driver>.command` and `diff.<driver>.textconv` are ignored.
- 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.
- Git LFS's driver, trusted as yours, reads its own settings from the repository's configuration, so each program that configuration names for it is emptied too: an extension's `lfs.extension.<name>.clean` and `smudge`, and a transfer agent's `lfs.customtransfer.<name>.path` and `args` (and `lfs.standalonetransferagent`). A tool that would run an emptied extension fails with Git LFS's error. Git LFS never downloads an object either (`GIT_LFS_SKIP_SMUDGE=1`), since a download runs the SSH command, credential helper and askpass program set for an endpoint the repository chooses: `git_checkout` and `git_merge` write each Git LFS file as its pointer file, and `git lfs pull` (or `git lfs checkout`, when the objects are already local) replaces the pointers with the content afterwards.
- 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.
- `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`.
- 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).
Expand Down
29 changes: 25 additions & 4 deletions src/git/src/mcp_server_git/server.py
Original file line number Diff line number Diff line change
Expand Up @@ -179,11 +179,29 @@ def _git_text(repo: git.Repo, command: str, *args: str) -> str:
# value shows that git applied the overrides. A driver's name may be empty
# (`[filter ""]`, read back as `filter..clean`, selected by `filter=`), so
# the name is matched with `.*`, not `.+`.
#
# A trusted driver can still read the repository's configuration itself.
# Git LFS's does: it runs `lfs.extension.<name>.clean` and `.smudge` on every
# file it filters, and a transfer agent (`lfs.customtransfer.<name>.path`
# and `.args`, picked by `lfs.standalonetransferagent`) when it downloads an
# object, so those keys are emptied the same way. An emptied extension makes
# Git LFS fail the command rather than run anything. A download also runs
# programs no key in this list names (`core.sshCommand`, `credential.helper`
# and `core.askpass`, for an endpoint the repository picks), so `harden_repo`
# turns downloads off (`_LFS_ENV`) instead.
_LISTED_KEYS = (
r"^(core\.hookspath|filter\..*\.(clean|smudge|process)|merge\..*\.driver"
r"|branch\..+\.mergeoptions)$"
r"|branch\..+\.mergeoptions|lfs\.extension\..*\.(clean|smudge)"
r"|lfs\.customtransfer\..*\.(path|args)|lfs\.standalonetransferagent)$"
)

# GIT_LFS_SKIP_SMUDGE=1 makes Git LFS's smudge filter write each file's
# pointer instead of its content, so a checkout or merge never downloads an
# object, and never starts the programs a download runs. The repository's
# configuration cannot turn it back on: Git LFS reads it from the environment
# only.
_LFS_ENV = {"GIT_LFS_SKIP_SMUDGE": "1"}

# Scopes whose configuration the user wrote rather than the repository.
_TRUSTED_SCOPES = frozenset({"system", "global", "command"})

Expand Down Expand Up @@ -332,8 +350,9 @@ def _submodule_drivers(repo: git.Repo) -> set[str]:
def harden_repo(repo: git.Repo) -> None:
"""Keep every git command run for `repo` from running a program it names.

Sets `HARDENED_CONFIG` on the repository's git, then reads which filter
and merge drivers the repository's own configuration (its `.git/config`,
Sets `HARDENED_CONFIG` and `_LFS_ENV` on the repository's git, then reads
which filter and merge drivers (and Git LFS programs, `_LISTED_KEYS`) the
repository's own configuration (its `.git/config`,
a worktree's `config.worktree`, and files they include) defines, and
overrides each with an empty command. The same read checks that git
applied the overrides: git older than 2.31 ignores GIT_CONFIG_COUNT, and
Expand All @@ -344,7 +363,9 @@ def harden_repo(repo: git.Repo) -> None:
(`_PROMISOR_KEYS`).
"""
entries = list(HARDENED_CONFIG)
repo.git.update_environment(GIT_NO_LAZY_FETCH="1", **_config_env(entries))
repo.git.update_environment(
GIT_NO_LAZY_FETCH="1", **_LFS_ENV, **_config_env(entries)
)
try:
listed = repo.git.config("--show-scope", "-z", "--get-regexp", _LISTED_KEYS)
except git.GitCommandError as e:
Expand Down
267 changes: 267 additions & 0 deletions src/git/tests/test_lfs_config.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,267 @@
"""Git LFS never runs a program the repository's own configuration names.

The Git LFS filter comes from the user's global or system configuration, so
the server trusts it and leaves it working. Git LFS then reads its own keys
from the repository's configuration, and some of them name programs: an
extension's `clean` and `smudge` commands, and a transfer agent's `path` and
`args`. A download also runs the SSH command, credential helpers and askpass
program configured for an endpoint the repository can pick. `harden_repo`
empties the first group the way it empties filter drivers, and turns
downloads off (GIT_LFS_SKIP_SMUDGE), which covers the rest.

Git LFS is not installed in CI, so the protocol-level tests that always run
use a stand-in `git-lfs`: a filter that reads those keys with `git config`
and runs what they name, as Git LFS does, so a test sees exactly the
configuration and environment the real one would. The tests that drive the
real Git LFS skip when it is not on PATH. The payloads are POSIX shell
scripts, so the protocol-level tests skip on Windows.
"""

import shlex
import shutil
import stat
from pathlib import Path
from typing import Any

import git
import pytest
from conftest import connect, wire
from test_empty_driver_name import make_stale
from test_repository_config import Payload, commit_file, posix_only, root_of
from test_submodule_config import embed

from mcp_server_git.server import _submodule_drivers, harden_repo

# The Git LFS keys that name a program, each with a subsection name that
# exercises the match: plain, dotted and empty.
LFS_PROGRAM_KEYS = (
"lfs.extension.poc.clean",
"lfs.extension.poc.smudge",
"lfs.extension.a.b.clean",
"lfs.extension..smudge",
"lfs.customtransfer.poc.path",
"lfs.customtransfer.poc.args",
"lfs.standalonetransferagent",
)

real_lfs = pytest.mark.skipif(
shutil.which("git-lfs") is None, reason="Git LFS is not installed"
)

# What `git lfs install` writes to the user's configuration.
LFS_DRIVER = (
'[filter "lfs"]\n'
"\tclean = git-lfs clean -- %f\n"
"\tsmudge = git-lfs smudge -- %f\n"
"\tprocess = git-lfs filter-process\n"
"\trequired = true\n"
)


@pytest.fixture
def payload(tmp_path: Path) -> Payload:
return Payload(tmp_path / "payload")


def use_global_config(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch, content: str
) -> None:
"""Make `content` the user's whole configuration, for git and the server."""
config = tmp_path / "global-config"
config.write_text(content)
monkeypatch.setenv("GIT_CONFIG_GLOBAL", str(config))
monkeypatch.setenv("GIT_CONFIG_NOSYSTEM", "1")


# --------------------------------------------------------------------------
# harden_repo itself
# --------------------------------------------------------------------------


@pytest.mark.parametrize("key", LFS_PROGRAM_KEYS)
def test_harden_repo_empties_the_repositorys_lfs_programs(repo: git.Repo, key: str):
repo.git.config(key, "program")
harden_repo(repo)
assert repo.git.config("--get", key) == ""


def test_harden_repo_keeps_the_users_own_lfs_programs(
tmp_path: Path, repo: git.Repo, monkeypatch: pytest.MonkeyPatch
):
use_global_config(
tmp_path,
monkeypatch,
'[lfs "extension.mine"]\n\tclean = my-clean\n'
'[lfs "customtransfer.mine"]\n\tpath = my-agent\n'
"[lfs]\n\tstandalonetransferagent = mine\n",
)
harden_repo(repo)
assert repo.git.config("--get", "lfs.extension.mine.clean") == "my-clean"
assert repo.git.config("--get", "lfs.customtransfer.mine.path") == "my-agent"
assert repo.git.config("--get", "lfs.standalonetransferagent") == "mine"


def test_harden_repo_turns_lfs_downloads_off(repo: git.Repo):
harden_repo(repo)
assert repo.git.environment()["GIT_LFS_SKIP_SMUDGE"] == "1"


def test_a_submodules_lfs_programs_are_listed(repo: git.Repo):
# The Git LFS run inside a checked-out submodule reads the submodule's
# configuration, so its keys are emptied like the opened repository's.
inner = embed(repo, "sm")
inner.git.config("lfs.extension.poc.clean", "program")
assert "lfs.extension.poc.clean" in _submodule_drivers(repo)


# --------------------------------------------------------------------------
# Through the server, with a stand-in for Git LFS
# --------------------------------------------------------------------------


def install_stand_in(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
"""A user filter `lfs` that runs what the LFS keys name, as Git LFS does.

Its clean step runs the `poc` extension's `clean`; its smudge step runs
the extension's `smudge` and, unless GIT_LFS_SKIP_SMUDGE is set, the
transfer agent `lfs.standalonetransferagent` picks. It then passes the
file through unchanged.
"""
script = tmp_path / "git-lfs-stand-in.sh"
script.write_text(
"#!/bin/sh\n"
'run() { if [ -n "$1" ]; then sh -c "$1" </dev/null; fi; }\n'
'case "$1" in\n'
' clean) run "$(git config --get lfs.extension.poc.clean)" ;;\n'
" smudge)\n"
' run "$(git config --get lfs.extension.poc.smudge)"\n'
' if [ "$GIT_LFS_SKIP_SMUDGE" != 1 ]; then\n'
" agent=$(git config --get lfs.standalonetransferagent)\n"
' run "$(git config --get "lfs.customtransfer.$agent.path")"\n'
" fi ;;\n"
"esac\n"
"exec cat\n"
)
script.chmod(script.stat().st_mode | stat.S_IEXEC)
command = shlex.quote(str(script))
use_global_config(
tmp_path,
monkeypatch,
f'[filter "lfs"]\n\tclean = {command} clean\n'
f"\tsmudge = {command} smudge\n\trequired = true\n",
)


@posix_only
async def test_lfs_programs_never_run(
tmp_path: Path, repo: git.Repo, payload: Payload, monkeypatch: pytest.MonkeyPatch
):
install_stand_in(tmp_path, monkeypatch)
commit_file(repo, ".gitattributes", "*.bin filter=lfs -text\n")
commit_file(repo, "a.bin", "a\n")
repo.git.checkout("-b", "other")
commit_file(repo, "b.bin", "b\n")
repo.git.checkout("main")
repo.git.config("lfs.extension.poc.clean", payload.command("clean"))
repo.git.config("lfs.extension.poc.smudge", payload.command("smudge"))
repo.git.config("lfs.standalonetransferagent", "poc")
repo.git.config("lfs.customtransfer.poc.path", payload.command("agent"))
make_stale(root_of(repo) / "a.bin")
(root_of(repo) / "new.bin").write_text("new\n")
path = str(root_of(repo))

for repository in (None, root_of(repo)):
async with connect(repository) as session:
for tool, arguments in (
("git_status", {}),
("git_diff_unstaged", {}),
("git_diff", {"target": "HEAD"}),
("git_add", {"files": ["new.bin"]}),
("git_checkout", {"branch_name": "other"}),
("git_checkout", {"branch_name": "main"}),
):
result: dict[str, Any] = wire(
await session.call_tool(tool, {"repo_path": path, **arguments})
)
assert result["isError"] is False, (tool, result)

assert payload.runs() == []


# --------------------------------------------------------------------------
# Through the server, with the real Git LFS
# --------------------------------------------------------------------------


def lfs_repo(
tmp_path: Path, repo: git.Repo, monkeypatch: pytest.MonkeyPatch
) -> git.Repo:
"""`repo` with Git LFS installed for the user and one LFS file committed."""
use_global_config(tmp_path, monkeypatch, LFS_DRIVER)
commit_file(repo, ".gitattributes", "*.bin filter=lfs diff=lfs merge=lfs -text\n")
commit_file(repo, "a.bin", "a\n")
return repo


async def call(name: str, repo: git.Repo, **arguments: str) -> dict[str, Any]:
async with connect(root_of(repo)) as session:
return wire(
await session.call_tool(
name, {"repo_path": str(root_of(repo)), **arguments}
)
)


@real_lfs
@posix_only
async def test_git_lfs_keeps_working(
tmp_path: Path, repo: git.Repo, monkeypatch: pytest.MonkeyPatch
):
lfs_repo(tmp_path, repo, monkeypatch)
make_stale(root_of(repo) / "a.bin")
result = await call("git_status", repo)
assert result["isError"] is False
assert "nothing to commit" in result["content"][0]["text"]


@real_lfs
@posix_only
async def test_git_lfs_extension_never_runs(
tmp_path: Path, repo: git.Repo, payload: Payload, monkeypatch: pytest.MonkeyPatch
):
# Git LFS fails the command when an extension's program is empty.
lfs_repo(tmp_path, repo, monkeypatch)
repo.git.config("lfs.extension.poc.clean", payload.command("clean"))
repo.git.config("lfs.extension.poc.priority", "0")
make_stale(root_of(repo) / "a.bin")

result = await call("git_status", repo)

assert payload.runs() == []
assert result["isError"] is True


@real_lfs
@posix_only
async def test_git_lfs_transfer_agent_never_runs(
tmp_path: Path, repo: git.Repo, payload: Payload, monkeypatch: pytest.MonkeyPatch
):
# The object is not in the local store, so a checkout would download it.
# It writes the pointer file instead.
lfs_repo(tmp_path, repo, monkeypatch)
repo.git.checkout("-b", "other")
commit_file(repo, "b.bin", "b\n")
repo.git.checkout("main")
shutil.rmtree(Path(repo.git_dir) / "lfs" / "objects")
repo.git.config("lfs.url", "http://127.0.0.1:9/")
repo.git.config("lfs.standalonetransferagent", "poc")
# Git LFS runs the path as one program, with the arguments split from `args`.
repo.git.config("lfs.customtransfer.poc.path", str(payload.script))
repo.git.config("lfs.customtransfer.poc.args", "agent")

result = await call("git_checkout", repo, branch_name="other")

assert payload.runs() == []
assert result["isError"] is False, result
pointer = (root_of(repo) / "b.bin").read_text()
assert pointer.startswith("version https://git-lfs.github.com/spec/v1\n")