From 35758b7b79039557eace3e43eccb299b6e166eb5 Mon Sep 17 00:00:00 2001 From: cliffhall Date: Fri, 27 Nov 2026 00:26:38 -0500 Subject: [PATCH 1/3] fix(git): GHSA-qf89-h82f-h5r5 Co-Authored-By: Claude Opus 5.5 Signed-off-by: cliffhall --- src/git/README.md | 2 +- src/git/src/mcp_server_git/server.py | 55 +++++++++++++++++++- src/git/tests/test_merge.py | 76 ++++++++++++++++++++++++++++ 3 files changed, 131 insertions(+), 2 deletions(-) diff --git a/src/git/README.md b/src/git/README.md index ccff61aa5e..1e354e88a1 100644 --- a/src/git/README.md +++ b/src/git/README.md @@ -91,7 +91,7 @@ Please note that mcp-server-git is currently in early development. The functiona - `source_branch` (string): Branch, tag or commit to merge into the current branch (check out the branch to merge into first with `git_checkout`) - `fast_forward_only` (boolean, optional): Only fast-forward, failing if the branches have diverged (default `true`). `false` lets Git create a merge commit when they have - Returns: `Fast-forwarded`, `Merged ... with merge commit `, or `Already up to date` - - Refuses a detached HEAD, a working tree with uncommitted changes, a merge already in progress, and a merge that would overwrite an ignored local file. A merge that stops on conflicts is aborted (`git merge --abort`) and the error names the conflicting files, so the repository is left as it was + - Refuses a detached HEAD, a working tree with uncommitted changes, a merge already in progress, and a merge that would overwrite an ignored local file, whether it fast-forwards or makes a merge commit. A merge that stops on conflicts is aborted (`git merge --abort`) and the error names the conflicting files, so the repository is left as it was 12. `git_show` - Shows the contents of a commit, or of a file or directory at a revision - Inputs: diff --git a/src/git/src/mcp_server_git/server.py b/src/git/src/mcp_server_git/server.py index 9aea4cfb3c..3117b9e62b 100644 --- a/src/git/src/mcp_server_git/server.py +++ b/src/git/src/mcp_server_git/server.py @@ -787,6 +787,49 @@ def _merge_failure( return f"{what} failed. {unchanged} Git reported:\n{_git_stderr(error)}" +def _ignored_files_overwritten(repo: git.Repo, head: str, source: str) -> list[str]: + """The ignored files in the working tree a merge of `source` would replace. + + Git does not honor `--no-overwrite-ignore` when it makes a merge commit (a + fast-forward does), so `git_merge` checks before it runs. The tree is + clean, so every untracked path is one HEAD does not track, and the merge + can only write such a path if the source tracks it. For each such path, + what is in the way is whatever exists there (a file, a link, or a + directory and everything in it) or the nearest existing ancestor that is + not a directory. The ignored files among those are returned; an untracked + file that is not ignored is left for git to refuse, as it does. + + This is conservative: a path the merge would end up deleting again (the + source tracks it, HEAD deleted it) is counted too. + """ + root = Path(repo.working_dir) + added = repo.git.diff_tree( + "-r", "-z", "--no-renames", "--name-only", "--diff-filter=A", head, source + ) + in_the_way: set[str] = set() + for path in filter(None, added.split("\0")): + parts = path.split("/") + for depth in range(1, len(parts) + 1): + prefix = "/".join(parts[:depth]) + target = root / prefix + if not os.path.lexists(target): + break + if depth == len(parts) or target.is_symlink() or not target.is_dir(): + in_the_way.add(prefix) + break + if not in_the_way: + return [] + listed = repo.git.ls_files( + "-z", + "--others", + "--ignored", + "--exclude-standard", + "--", + *(f":(top,literal){path}" for path in sorted(in_the_way)), + ) + return sorted(filter(None, listed.split("\0"))) + + def git_merge( repo: git.Repo, source_branch: str, @@ -852,6 +895,8 @@ def git_merge( # for it (see `_LISTED_KEYS`). --no-overwrite-ignore refuses to # replace an ignored local file (a `.env`, say) that the source tracks: # `is_dirty()` cannot see one, and git would overwrite it unrecoverably. + # Git honors it only on a fast-forward, so a merge commit is checked + # first (`_ignored_files_overwritten`). # # Git is given the commit validated above, not the name: a name can stand # for more than one commit (`git merge FETCH_HEAD` merges every head @@ -859,6 +904,15 @@ def git_merge( # With a sha, git's default message would name the sha, so the message # names what the caller asked for. mode = "--ff-only" if fast_forward_only else "--ff" + what = f"Merge of '{source_branch}' into '{target}'" + if not fast_forward: + ignored = _ignored_files_overwritten(repo, head.hexsha, source.hexsha) + if ignored: + raise ValueError( + f"{what} refused: it would overwrite ignored local files: " + f"{', '.join(ignored)}. Nothing was changed. Move or remove " + "them first." + ) try: _rewrite_tree( repo, @@ -876,7 +930,6 @@ def git_merge( allowed_repository=allowed_repository, ) except git.GitCommandError as e: - what = f"Merge of '{source_branch}' into '{target}'" raise ValueError(_merge_failure(repo, e, what, allowed_repository)) from e merged = repo.head.commit if fast_forward: diff --git a/src/git/tests/test_merge.py b/src/git/tests/test_merge.py index 4853b4e1bc..e9432ef995 100644 --- a/src/git/tests/test_merge.py +++ b/src/git/tests/test_merge.py @@ -265,6 +265,82 @@ async def test_ignored_file_the_source_tracks_is_not_overwritten(repo: git.Repo) assert (root_of(repo) / ".env").read_text() == "SECRET=local\n" +def ignored_local(repo: git.Repo, ignore: str, tracked: dict[str, str]) -> str: + """Ignore `ignore` on main, track `tracked` on a diverged `feature`. + + Leaves `main` checked out with one commit of its own, so merging + `feature` makes a merge commit. Returns main's head sha. + """ + commit_file(repo, ".gitignore", ignore) + repo.git.checkout("-b", "feature") + for name, content in tracked.items(): + path = root_of(repo) / name + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(content, newline="\n") + repo.git.add("-f", name) + repo.index.commit("track ignored paths") + repo.git.checkout("main") + return commit_file(repo, "main.txt", "main\n").hexsha + + +async def test_merge_commit_refuses_to_overwrite_an_ignored_file(repo: git.Repo): + # Git does not honor --no-overwrite-ignore when it makes a merge commit, + # so the tool checks the incoming paths itself before git runs. + head = ignored_local(repo, ".env\n", {".env": "tracked\n"}) + (root_of(repo) / ".env").write_text("SECRET=local\n") + + result = await merge(repo, "feature", fast_forward_only=False) + + assert result == tool_error( + "git_merge", + "Merge of 'feature' into 'main' refused: it would overwrite ignored " + "local files: .env. Nothing was changed. Move or remove them first.", + ) + assert repo.head.commit.hexsha == head + assert not (Path(repo.git_dir) / "MERGE_HEAD").exists() + assert (root_of(repo) / ".env").read_text() == "SECRET=local\n" + + +async def test_merge_commit_refuses_ignored_files_in_a_directory_it_replaces( + repo: git.Repo, +): + # The source tracks a file where an ignored directory is, and a file + # under an ignored file: both would destroy the ignored content. + head = ignored_local( + repo, "cache\nlocal.cfg\n", {"cache": "file\n", "local.cfg/x": "x\n"} + ) + (root_of(repo) / "cache").mkdir() + (root_of(repo) / "cache" / "data").write_text("keep\n") + (root_of(repo) / "local.cfg").write_text("keep\n") + + result = await merge(repo, "feature", fast_forward_only=False) + + assert result == tool_error( + "git_merge", + "Merge of 'feature' into 'main' refused: it would overwrite ignored " + "local files: cache/data, local.cfg. Nothing was changed. Move or " + "remove them first.", + ) + assert repo.head.commit.hexsha == head + assert (root_of(repo) / "cache" / "data").read_text() == "keep\n" + assert (root_of(repo) / "local.cfg").read_text() == "keep\n" + + +async def test_merge_commit_into_an_ignored_directory_is_allowed(repo: git.Repo): + # A new file inside an ignored directory replaces nothing that is there. + ignored_local(repo, "build/\n", {"build/tracked.txt": "tracked\n"}) + (root_of(repo) / "build").mkdir() + (root_of(repo) / "build" / "local.txt").write_text("keep\n") + + result = await merge(repo, "feature", fast_forward_only=False) + + assert result == text_result( + f"Merged 'feature' into 'main' with merge commit {repo.head.commit.hexsha[:7]}" + ) + assert (root_of(repo) / "build" / "local.txt").read_text() == "keep\n" + assert (root_of(repo) / "build" / "tracked.txt").read_text() == "tracked\n" + + @pytest.mark.parametrize("options", ["--no-commit", "--squash"]) async def test_configured_merge_options_still_complete_the_merge( repo: git.Repo, options: str From 6773576767a653b7174227ee03dff6757d3aa392 Mon Sep 17 00:00:00 2001 From: cliffhall Date: Fri, 27 Nov 2026 00:50:44 -0500 Subject: [PATCH 2/3] fix(git): GHSA-qf89-h82f-h5r5 Co-Authored-By: Claude Opus 5.5 Signed-off-by: cliffhall --- src/git/src/mcp_server_git/server.py | 81 +++++++++++++++--- src/git/tests/test_merge.py | 120 +++++++++++++++++++++++++++ 2 files changed, 188 insertions(+), 13 deletions(-) diff --git a/src/git/src/mcp_server_git/server.py b/src/git/src/mcp_server_git/server.py index 3117b9e62b..3b7a999941 100644 --- a/src/git/src/mcp_server_git/server.py +++ b/src/git/src/mcp_server_git/server.py @@ -663,9 +663,12 @@ def _rewrite_tree( command: str, *args: str, allowed_repository: Path | None = None, + config: str | None = None, ) -> str: """Run `git `, which writes the working tree, then re-check. + `config`, a `name=value`, is passed as `git -c` for this command only. + `harden_repo` reads the repository's configuration when the call opens the repository, but that configuration can depend on the working tree: an `[include]` or `[includeIf]` path into it (git skips one whose file is @@ -694,7 +697,8 @@ def _rewrite_tree( stay inside, the cleanup included, so the tree stays as written. """ try: - return getattr(repo.git, command)(*args) + runner = repo.git(c=config) if config is not None else repo.git + return getattr(runner, command)(*args) finally: try: harden_repo(repo) @@ -787,27 +791,76 @@ def _merge_failure( return f"{what} failed. {unchanged} Git reported:\n{_git_stderr(error)}" +def _on_disk_spelling(root: Path, path: str) -> str: + """`path`, an existing entry under `root`, as the directory listings spell it. + + On a case-insensitive or normalization-insensitive filesystem (macOS, + Windows) the path a source tracks can name an entry whose name is spelled + differently (`.ENV` for `.env`, or decomposed for precomposed Unicode). + Git matches a pathspec to its own spelling, so each component is replaced + with the listed name of the same file (by device and inode). + """ + parent = root + spelled: list[str] = [] + for name in path.split("/"): + names = os.listdir(parent) + if name not in names: + wanted = os.lstat(parent / name) + name = next( + entry + for entry in names + if os.path.samestat(os.lstat(parent / entry), wanted) + ) + spelled.append(name) + parent = parent / name + return "/".join(spelled) + + def _ignored_files_overwritten(repo: git.Repo, head: str, source: str) -> list[str]: """The ignored files in the working tree a merge of `source` would replace. Git does not honor `--no-overwrite-ignore` when it makes a merge commit (a fast-forward does), so `git_merge` checks before it runs. The tree is clean, so every untracked path is one HEAD does not track, and the merge - can only write such a path if the source tracks it. For each such path, - what is in the way is whatever exists there (a file, a link, or a - directory and everything in it) or the nearest existing ancestor that is + writes only such a path when it is one of: + + - a path the source tracks and HEAD does not. This includes one HEAD + deleted since the merge base: if the source changed it, the + modify/delete conflict writes the source's version, so it must be + counted, not filtered out against the merge base. (The merge runs with + `merge.directoryRenames=false`, so git does not move a path the source + adds into a directory HEAD renamed, a path in neither tree.) + - the side name of a file/directory conflict: HEAD's file `` moved + to `~HEAD`, or the source's to `~`. + + For each, what is in the way is whatever exists there (a file, a link, or + a directory and everything in it) or the nearest existing ancestor that is not a directory. The ignored files among those are returned; an untracked file that is not ignored is left for git to refuse, as it does. - - This is conservative: a path the merge would end up deleting again (the - source tracks it, HEAD deleted it) is counted too. """ root = Path(repo.working_dir) - added = repo.git.diff_tree( - "-r", "-z", "--no-renames", "--name-only", "--diff-filter=A", head, source - ) + changes = repo.git.diff_tree( + "-r", "-z", "--no-renames", "--name-status", "--diff-filter=AD", head, source + ).split("\0") + added: set[str] = set() + deleted: set[str] = set() + for status, path in zip(changes[0::2], changes[1::2]): + (added if status == "A" else deleted).add(path) + deleted_dirs = { + "/".join(parts[:depth]) + for parts in (path.split("/") for path in deleted) + for depth in range(1, len(parts)) + } + written = set(added) + for path in added: + parts = path.split("/") + for depth in range(1, len(parts)): + if (prefix := "/".join(parts[:depth])) in deleted: + written.add(f"{prefix}~HEAD") + if path in deleted_dirs: + written.add(f"{path}~{source}") in_the_way: set[str] = set() - for path in filter(None, added.split("\0")): + for path in written: parts = path.split("/") for depth in range(1, len(parts) + 1): prefix = "/".join(parts[:depth]) @@ -815,7 +868,7 @@ def _ignored_files_overwritten(repo: git.Repo, head: str, source: str) -> list[s if not os.path.lexists(target): break if depth == len(parts) or target.is_symlink() or not target.is_dir(): - in_the_way.add(prefix) + in_the_way.add(_on_disk_spelling(root, prefix)) break if not in_the_way: return [] @@ -896,7 +949,8 @@ def git_merge( # replace an ignored local file (a `.env`, say) that the source tracks: # `is_dirty()` cannot see one, and git would overwrite it unrecoverably. # Git honors it only on a fast-forward, so a merge commit is checked - # first (`_ignored_files_overwritten`). + # first (`_ignored_files_overwritten`), and runs with directory-rename + # detection off, so it writes no path that check cannot predict. # # Git is given the commit validated above, not the name: a name can stand # for more than one commit (`git merge FETCH_HEAD` merges every head @@ -928,6 +982,7 @@ def git_merge( f"Merge '{source_branch}' into '{target}'", source.hexsha, allowed_repository=allowed_repository, + config="merge.directoryRenames=false", ) except git.GitCommandError as e: raise ValueError(_merge_failure(repo, e, what, allowed_repository)) from e diff --git a/src/git/tests/test_merge.py b/src/git/tests/test_merge.py index e9432ef995..0111bc055c 100644 --- a/src/git/tests/test_merge.py +++ b/src/git/tests/test_merge.py @@ -8,6 +8,8 @@ and the repository afterwards. """ +import os +import unicodedata from pathlib import Path from typing import Any @@ -341,6 +343,124 @@ async def test_merge_commit_into_an_ignored_directory_is_allowed(repo: git.Repo) assert (root_of(repo) / "build" / "tracked.txt").read_text() == "tracked\n" +def refused(*paths: str) -> dict[str, Any]: + return tool_error( + "git_merge", + "Merge of 'feature' into 'main' refused: it would overwrite ignored " + f"local files: {', '.join(paths)}. Nothing was changed. Move or remove " + "them first.", + ) + + +@pytest.mark.parametrize("renames", [None, "true"]) +async def test_merge_commit_does_not_follow_a_directory_rename_onto_an_ignored_file( + repo: git.Repo, renames: str | None +): + # HEAD renamed d/ to e/ since the fork, and the source adds d/new. With + # directory-rename detection git would write e/new, a path in neither + # tree; the tool turns it off, so the file lands at d/new. + commit_file(repo, ".gitignore", "new\n") + (root_of(repo) / "d").mkdir() + commit_file(repo, "d/kept.txt", "kept\n") + repo.git.checkout("-b", "feature") + commit_file(repo, "d/new", "feature\n") + repo.git.checkout("main") + repo.git.mv("d", "e") + repo.index.commit("rename d to e") + if renames is not None: + with repo.config_writer() as config: + config.set_value("merge", "directoryRenames", renames) + (root_of(repo) / "e" / "new").write_text("LOCAL\n") + + result = await merge(repo, "feature", fast_forward_only=False) + + assert result == text_result( + f"Merged 'feature' into 'main' with merge commit {repo.head.commit.hexsha[:7]}" + ) + assert (root_of(repo) / "e" / "new").read_text() == "LOCAL\n" + assert (root_of(repo) / "d" / "new").read_text() == "feature\n" + + +async def test_merge_commit_refuses_an_ignored_file_at_a_file_directory_side_name( + repo: git.Repo, +): + # HEAD tracks a file p where the source tracks a directory p/: git moves + # HEAD's file to p~HEAD, which would replace an ignored file of that name. + commit_file(repo, ".gitignore", "*~*\n") + repo.git.checkout("-b", "feature") + (root_of(repo) / "p").mkdir() + commit_file(repo, "p/x", "feature\n") + repo.git.checkout("main") + head = commit_file(repo, "p", "main\n").hexsha + (root_of(repo) / "p~HEAD").write_text("LOCAL\n") + + assert await merge(repo, "feature", fast_forward_only=False) == refused("p~HEAD") + assert repo.head.commit.hexsha == head + assert (root_of(repo) / "p~HEAD").read_text() == "LOCAL\n" + + +async def test_merge_commit_refuses_an_ignored_file_at_the_source_side_name( + repo: git.Repo, +): + # The other way round: the source's file q moves to q~. + commit_file(repo, ".gitignore", "*~*\n") + repo.git.checkout("-b", "feature") + sha = commit_file(repo, "q", "feature\n").hexsha + repo.git.checkout("main") + (root_of(repo) / "q").mkdir() + head = commit_file(repo, "q/y", "main\n").hexsha + (root_of(repo) / f"q~{sha}").write_text("LOCAL\n") + + assert await merge(repo, "feature", fast_forward_only=False) == refused(f"q~{sha}") + assert repo.head.commit.hexsha == head + assert (root_of(repo) / f"q~{sha}").read_text() == "LOCAL\n" + + +def spelling_insensitive(directory: Path, stored: str, other: str) -> bool: + """Whether the filesystem under `directory` finds `stored` as `other`.""" + probe = directory / stored + probe.write_text("") + try: + return (directory / other).exists() and other not in os.listdir(directory) + finally: + probe.unlink() + + +NFC = unicodedata.normalize("NFC", "caf\u00e9.env") +NFD = unicodedata.normalize("NFD", NFC) + + +@pytest.mark.parametrize( + ("local", "tracked"), [(".env", ".ENV"), (NFC, NFD)], ids=["case", "unicode"] +) +async def test_merge_commit_refuses_an_ignored_file_spelled_differently( + repo: git.Repo, local: str, tracked: str +): + # On a case- or normalization-insensitive filesystem the source's spelling + # names the same file; the check matches it by identity, not by name. + if not spelling_insensitive(root_of(repo), local, tracked): + pytest.skip("the filesystem tells these spellings apart") + commit_file(repo, ".gitignore", "*.env\n.env\n") + repo.git.checkout("-b", "feature") + (root_of(repo) / tracked).write_text("feature\n") + repo.git.add("-f", "--", tracked) + repo.index.commit("track") + (root_of(repo) / tracked).unlink() + repo.git.checkout("main") + head = commit_file(repo, "main.txt", "main\n").hexsha + (root_of(repo) / local).write_text("LOCAL\n") + + result = await merge(repo, "feature", fast_forward_only=False) + + assert result["isError"] is True + assert ( + "refused: it would overwrite ignored local files" + in (result["content"][0]["text"]) + ) + assert repo.head.commit.hexsha == head + assert (root_of(repo) / local).read_text() == "LOCAL\n" + + @pytest.mark.parametrize("options", ["--no-commit", "--squash"]) async def test_configured_merge_options_still_complete_the_merge( repo: git.Repo, options: str From 13816b7c9cad846bd07c6fdf1f436a374fa9ac6d Mon Sep 17 00:00:00 2001 From: cliffhall Date: Fri, 27 Nov 2026 01:17:24 -0500 Subject: [PATCH 3/3] fix(git): GHSA-qf89-h82f-h5r5 Co-Authored-By: Claude Opus 5.5 Signed-off-by: cliffhall --- src/git/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/src/git/README.md b/src/git/README.md index 1e354e88a1..d8271d46fd 100644 --- a/src/git/README.md +++ b/src/git/README.md @@ -92,6 +92,7 @@ Please note that mcp-server-git is currently in early development. The functiona - `fast_forward_only` (boolean, optional): Only fast-forward, failing if the branches have diverged (default `true`). `false` lets Git create a merge commit when they have - Returns: `Fast-forwarded`, `Merged ... with merge commit `, or `Already up to date` - Refuses a detached HEAD, a working tree with uncommitted changes, a merge already in progress, and a merge that would overwrite an ignored local file, whether it fast-forwards or makes a merge commit. A merge that stops on conflicts is aborted (`git merge --abort`) and the error names the conflicting files, so the repository is left as it was + - Directory renames are not followed: a file the source adds in a directory the current branch renamed is merged at the path the source gave it 12. `git_show` - Shows the contents of a commit, or of a file or directory at a revision - Inputs: