from pathlib import Path from unittest import mock import git import pytest from git.exc import BadName from mcp.server import Server from mcp_server_git.server import ( git_add, git_branch, git_checkout, git_commit, git_create_branch, git_diff, git_diff_staged, git_diff_unstaged, git_log, git_reset, git_show, git_status, serve, validate_repo_path, ) def test_git_checkout_existing_branch(test_repository): test_repository.git.branch("test-branch") result = git_checkout(test_repository, "test-branch") assert "Switched to branch 'test-branch'" in result assert test_repository.active_branch.name == "test-branch" def test_git_checkout_nonexistent_branch(test_repository): with pytest.raises(BadName): git_checkout(test_repository, "nonexistent-branch") def test_git_checkout_sha_reports_detached_head(test_repository): """rev_parse accepts a sha, so the reply must not claim a branch switch.""" sha = test_repository.head.commit.hexsha result = git_checkout(test_repository, sha) assert test_repository.head.is_detached assert "detached" in result assert "Switched to branch" not in result @pytest.mark.parametrize("revision", ["HEAD~1", "refs/heads/feature", "origin/main"]) def test_git_checkout_non_branch_revisions_report_detached_head( test_repository, tmp_path, revision ): """The revisions an agent is most likely to send: a relative ref, a full ref name, and a remote-tracking ref. None of them is a branch, so none may be reported as a branch switch.""" test_repository.git.branch("feature") test_repository.index.commit("second commit") git.Repo.init(tmp_path / "remote.git", bare=True) test_repository.create_remote("origin", str(tmp_path / "remote.git")) test_repository.git.push("origin", "HEAD:refs/heads/main") result = git_checkout(test_repository, revision) assert test_repository.head.is_detached assert result.startswith("HEAD is now detached at ") def test_git_checkout_tag_reports_detached_head(test_repository): test_repository.create_tag("v1") result = git_checkout(test_repository, "v1") assert test_repository.head.is_detached assert "detached" in result assert "Switched to branch" not in result def test_git_checkout_branch_name_still_reports_branch(test_repository): test_repository.git.branch("attached-checkout") result = git_checkout(test_repository, "attached-checkout") assert not test_repository.head.is_detached assert result == "Switched to branch 'attached-checkout'" def test_git_branch_local(test_repository): test_repository.git.branch("new-branch-local") result = git_branch(test_repository, "local") assert "new-branch-local" in result def test_git_branch_remote(test_repository): result = git_branch(test_repository, "remote") assert "" == result.strip() # Should be empty if no remote branches def test_git_branch_all(test_repository): test_repository.git.branch("new-branch-all") result = git_branch(test_repository, "all") assert "new-branch-all" in result def test_git_branch_contains(test_repository): # Get the default branch name (could be "main" or "master") default_branch = test_repository.active_branch.name # Create a new branch and commit to it test_repository.git.checkout("-b", "feature-branch") Path(test_repository.working_dir / Path("feature.txt")).write_text( "feature content" ) test_repository.index.add(["feature.txt"]) commit = test_repository.index.commit("feature commit") test_repository.git.checkout(default_branch) result = git_branch(test_repository, "local", contains=commit.hexsha) assert "feature-branch" in result assert default_branch not in result def test_git_branch_not_contains(test_repository): # Get the default branch name (could be "main" or "master") default_branch = test_repository.active_branch.name # Create a new branch and commit to it test_repository.git.checkout("-b", "another-feature-branch") Path(test_repository.working_dir / Path("another_feature.txt")).write_text( "another feature content" ) test_repository.index.add(["another_feature.txt"]) commit = test_repository.index.commit("another feature commit") test_repository.git.checkout(default_branch) result = git_branch(test_repository, "local", not_contains=commit.hexsha) assert "another-feature-branch" not in result assert default_branch in result def test_git_add_all_files(test_repository): file_path = Path(test_repository.working_dir) / "all_file.txt" file_path.write_text("adding all") result = git_add(test_repository, ["."]) staged_files = [item.a_path for item in test_repository.index.diff("HEAD")] assert "all_file.txt" in staged_files assert result == "Files staged successfully" def test_git_add_specific_files(test_repository): file1 = Path(test_repository.working_dir) / "file1.txt" file2 = Path(test_repository.working_dir) / "file2.txt" file1.write_text("file 1 content") file2.write_text("file 2 content") result = git_add(test_repository, ["file1.txt"]) staged_files = [item.a_path for item in test_repository.index.diff("HEAD")] assert "file1.txt" in staged_files assert "file2.txt" not in staged_files assert result == "Files staged successfully" def test_git_add_rejects_an_empty_file_list(test_repository): # #4763: `git add --` with no pathspec is a no-op that exits 0. with pytest.raises(ValueError, match="No files provided to stage"): git_add(test_repository, []) def test_git_add_clean_tree_reports_nothing_staged(test_repository): result = git_add(test_repository, ["."]) assert result.startswith("No changes were staged") assert not test_repository.index.diff(test_repository.head.commit) def test_git_add_already_staged_file_reports_nothing_staged(test_repository): # A change staged earlier must not make a no-op call read as a success. Path(test_repository.working_dir, "staged.txt").write_text("staged") test_repository.index.add(["staged.txt"]) assert git_add(test_repository, ["staged.txt"]).startswith("No changes were staged") assert git_add(test_repository, ["."]).startswith("No changes were staged") def test_git_add_reports_a_staged_deletion(test_repository): Path(test_repository.working_dir, "test.txt").unlink() assert git_add(test_repository, ["test.txt"]) == "Files staged successfully" assert "test.txt" not in [path for path, _stage in test_repository.index.entries] def test_git_add_rejects_path_traversal(test_repository): # Security invariant (CVE-2026-27735): a relative path escaping the # repository must never be staged. Accept rejection from either the # defense-in-depth validation (ValueError) or the underlying git CLI # (GitCommandError) so the test asserts the property, not the layer. outside = Path(test_repository.working_dir).parent / "outside.txt" outside.write_text("secret") with pytest.raises((ValueError, git.GitCommandError)): git_add(test_repository, ["../outside.txt"]) staged = [path for path, _stage in test_repository.index.entries] assert "../outside.txt" not in staged assert "outside.txt" not in staged def test_git_add_rejects_absolute_path_outside(test_repository): # An absolute path outside the repository must never be staged. outside = Path(test_repository.working_dir).parent / "abs_outside.txt" outside.write_text("secret") with pytest.raises((ValueError, git.GitCommandError)): git_add(test_repository, [str(outside)]) staged = [path for path, _stage in test_repository.index.entries] assert "abs_outside.txt" not in staged def test_git_status(test_repository): result = git_status(test_repository) assert result is not None assert "On branch" in result or "branch" in result.lower() def test_git_diff_unstaged(test_repository): file_path = Path(test_repository.working_dir) / "test.txt" file_path.write_text("modified content") result = git_diff_unstaged(test_repository) assert "test.txt" in result assert "modified content" in result def test_git_diff_unstaged_empty(test_repository): result = git_diff_unstaged(test_repository) assert result == "" def test_git_diff_staged(test_repository): file_path = Path(test_repository.working_dir) / "staged_file.txt" file_path.write_text("staged content") test_repository.index.add(["staged_file.txt"]) result = git_diff_staged(test_repository) assert "staged_file.txt" in result assert "staged content" in result def test_git_diff_staged_empty(test_repository): result = git_diff_staged(test_repository) assert result == "" def test_git_diff(test_repository): # Get the default branch name (could be "main" or "master") default_branch = test_repository.active_branch.name test_repository.git.checkout("-b", "feature-diff") file_path = Path(test_repository.working_dir) / "test.txt" file_path.write_text("feature changes") test_repository.index.add(["test.txt"]) test_repository.index.commit("feature commit") result = git_diff(test_repository, default_branch) assert "test.txt" in result assert "feature changes" in result def test_git_diff_range_with_omitted_endpoint_means_head(test_repository): """`a..` and `..b` default the missing endpoint to HEAD, as git does.""" default_branch = test_repository.active_branch.name test_repository.git.checkout("-b", "feature-range") file_path = Path(test_repository.working_dir) / "test.txt" file_path.write_text("range changes") test_repository.index.add(["test.txt"]) test_repository.index.commit("range commit") assert git_diff(test_repository, f"{default_branch}..") == git_diff( test_repository, f"{default_branch}..HEAD" ) assert "range changes" in git_diff(test_repository, f"{default_branch}..") assert git_diff(test_repository, "..HEAD") == "" def test_git_diff_single_revision_containing_dots_is_not_split(test_repository): """A revision that resolves whole is used whole, even with '..' inside it.""" test_repository.index.commit("fix..bug") # ':/fix..bug' names the commit whose message matches, not a range. assert git_diff(test_repository, ":/fix..bug") == "" @pytest.mark.parametrize("target", ["HEAD..feature..x", "...."]) def test_git_diff_rejects_malformed_ranges(test_repository, target): """Only the first '..' or '...' splits; anything left must still resolve.""" test_repository.git.branch("feature") with pytest.raises(BadName): git_diff(test_repository, target) # A non-ASCII name, and the octal escape git prints for its first character # under its default core.quotepath=true (#5129). NON_ASCII_FILENAME = "日本語.txt" NON_ASCII_OCTAL = "\\346\\227\\245" def pin_quotepath_true(repo: git.Repo) -> None: """Pin git's default repo-locally, so a global config cannot hide the bug.""" with repo.config_writer() as config: config.set_value("core", "quotepath", "true") def commit_non_ascii_file(repo: git.Repo) -> None: """Commit NON_ASCII_FILENAME, then leave an unstaged change to it.""" pin_quotepath_true(repo) file_path = Path(repo.working_dir) / NON_ASCII_FILENAME file_path.write_text("original\n") repo.index.add([NON_ASCII_FILENAME]) repo.index.commit("add non-ASCII file") file_path.write_text("changed\n") def test_git_status_prints_non_ascii_path_unquoted(test_repository): pin_quotepath_true(test_repository) (Path(test_repository.working_dir) / NON_ASCII_FILENAME).write_text("new\n") result = git_status(test_repository) assert f"\t{NON_ASCII_FILENAME}\n" in result assert NON_ASCII_OCTAL not in result def test_git_status_non_ascii_path_round_trips_through_git_add(test_repository): pin_quotepath_true(test_repository) (Path(test_repository.working_dir) / NON_ASCII_FILENAME).write_text("new\n") untracked = [ line.strip() for line in git_status(test_repository).splitlines() if line.startswith("\t") ] git_add(test_repository, untracked) staged = [path for path, _stage in test_repository.index.entries] assert NON_ASCII_FILENAME in staged @pytest.mark.parametrize("tool", ["unstaged", "staged", "target"]) def test_git_diff_tools_print_non_ascii_path_unquoted(test_repository, tool): commit_non_ascii_file(test_repository) if tool == "unstaged": result = git_diff_unstaged(test_repository) elif tool == "staged": test_repository.index.add([NON_ASCII_FILENAME]) result = git_diff_staged(test_repository) else: result = git_diff(test_repository, "HEAD") assert f"diff --git a/{NON_ASCII_FILENAME} b/{NON_ASCII_FILENAME}" in result assert NON_ASCII_OCTAL not in result def test_quotepath_override_is_not_written_to_repo_config(test_repository): commit_non_ascii_file(test_repository) config_path = Path(test_repository.git_dir) / "config" before = config_path.read_bytes() git_status(test_repository) git_diff_unstaged(test_repository) assert config_path.read_bytes() == before # The override was for that one command: a plain call still escapes. assert NON_ASCII_OCTAL in test_repository.git.status() @pytest.mark.parametrize("tool", ["unstaged", "staged", "target"]) def test_git_diff_tools_replace_undecodable_bytes(test_repository, tool): """A Latin-1 file's diff comes back with U+FFFD, not lone surrogates (#5193).""" file_path = Path(test_repository.working_dir) / "latin1.txt" file_path.write_bytes(b"caf\xe9\n") test_repository.index.add(["latin1.txt"]) test_repository.index.commit("add Latin-1 file") file_path.write_bytes(b"caf\xe9 na\xefve\n") if tool == "unstaged": result = git_diff_unstaged(test_repository) elif tool == "staged": test_repository.index.add(["latin1.txt"]) result = git_diff_staged(test_repository) else: result = git_diff(test_repository, "HEAD") assert "+caf� na�ve" in result result.encode("utf-8") # raises UnicodeEncodeError on a lone surrogate def test_git_commit(test_repository): file_path = Path(test_repository.working_dir) / "commit_test.txt" file_path.write_text("content to commit") test_repository.index.add(["commit_test.txt"]) result = git_commit(test_repository, "test commit message") assert "Changes committed successfully with hash" in result latest_commit = test_repository.head.commit assert latest_commit.message.strip() == "test commit message" def test_git_commit_refuses_when_nothing_is_staged(test_repository): # #4762: repo.index.commit() writes a tree unconditionally, so each of # these used to come back as a hash for an empty commit. head_before = test_repository.head.commit.hexsha working_file = Path(test_repository.working_dir) / "test.txt" # A clean tree. with pytest.raises(ValueError, match="No changes staged for commit"): git_commit(test_repository, "nothing to record") # An untracked file, which git_add was never called for. Path(test_repository.working_dir, "untracked.txt").write_text("never added") with pytest.raises(ValueError, match="No changes staged for commit"): git_commit(test_repository, "nothing to record") # A tracked file edited but not staged. working_file.write_text("edited but never staged") with pytest.raises(ValueError, match="No changes staged for commit"): git_commit(test_repository, "nothing to record") assert test_repository.head.commit.hexsha == head_before assert working_file.read_text() == "edited but never staged" def test_git_commit_records_a_staged_deletion(test_repository): # A deletion leaves no file behind, so it must not read as an empty index. test_repository.git.rm("test.txt") result = git_commit(test_repository, "remove test.txt") assert "Changes committed successfully with hash" in result assert "test.txt" not in test_repository.head.commit.tree def test_git_commit_allows_the_first_commit_on_an_unborn_branch(tmp_path: Path): repo = git.Repo.init(tmp_path / "unborn") Path(repo.working_dir, "first.txt").write_text("first") repo.index.add(["first.txt"]) result = git_commit(repo, "initial commit") assert "Changes committed successfully with hash" in result assert repo.head.commit.message.strip() == "initial commit" repo.close() def test_git_commit_refuses_an_empty_unborn_branch(tmp_path: Path): repo = git.Repo.init(tmp_path / "unborn") with pytest.raises(ValueError, match="No changes staged for commit"): git_commit(repo, "initial commit") assert not repo.head.is_valid() repo.close() def test_git_commit_allows_an_empty_merge_commit(repo): # git permits an empty commit while a merge is in progress, so a merge # whose result matches HEAD must still be committable. --no-commit sets # MERGE_HEAD deterministically, without provoking a conflict. starting_branch = repo.active_branch.name repo.git.checkout("-b", "side") Path(repo.working_dir, "side.txt").write_text("side only") repo.git.add("side.txt") side_sha = repo.index.commit("side change").hexsha repo.git.checkout(starting_branch) head_before = repo.head.commit.hexsha repo.git.merge("side", "--no-commit", "--no-ff") assert (Path(repo.git_dir) / "MERGE_HEAD").exists() # Roll the index back to HEAD's own content: the pending merge commit # records no change at all, which git allows. repo.git.rm("side.txt", "--cached") Path(repo.working_dir, "side.txt").unlink() assert not repo.index.diff(repo.head.commit) result = git_commit(repo, "merge side") assert "Changes committed successfully with hash" in result assert [p.hexsha for p in repo.head.commit.parents] == [head_before, side_sha] assert not (Path(repo.git_dir) / "MERGE_HEAD").exists() def test_git_commit_concludes_a_merge_with_both_parents(repo): # #5012: a merge commit records HEAD and MERGE_HEAD as parents and clears # the merge state, as `git commit` does. starting_branch = repo.active_branch.name repo.git.checkout("-b", "side") Path(repo.working_dir, "side.txt").write_text("side only") repo.git.add("side.txt") side_sha = repo.index.commit("side change").hexsha repo.git.checkout(starting_branch) head_before = repo.head.commit.hexsha repo.git.merge("side", "--no-commit", "--no-ff") result = git_commit(repo, "merge side") commit = repo.head.commit assert commit.hexsha in result assert [p.hexsha for p in commit.parents] == [head_before, side_sha] assert "side.txt" in commit.tree git_dir = Path(repo.git_dir) for name in ("MERGE_HEAD", "MERGE_MSG", "MERGE_MODE"): assert not (git_dir / name).exists() assert repo.active_branch.name == starting_branch def _start_autostash_merge(repo: git.Repo, dirty: str) -> str: """Begin `git merge --no-commit --autostash side` over a dirty test.txt. Returns the autostash's oid, read from MERGE_AUTOSTASH. """ starting_branch = repo.active_branch.name repo.git.checkout("-b", "side") Path(repo.working_dir, "side.txt").write_text("side only") repo.git.add("side.txt") repo.index.commit("side change") repo.git.checkout(starting_branch) Path(repo.working_dir, "test.txt").write_text(dirty, newline="\n") repo.git.merge("side", "--no-commit", "--no-ff", "--autostash") autostash = Path(repo.git_dir) / "MERGE_AUTOSTASH" assert autostash.exists() # The merge stashed the edit away, so the tree is back at HEAD. assert Path(repo.working_dir, "test.txt").read_text() != dirty return autostash.read_text().strip() def test_git_commit_reapplies_a_merge_autostash(repo): # #5050: concluding a `--autostash` merge restores the pre-merge edits and # removes MERGE_AUTOSTASH, as `git commit` does. dirty = "line 1\nline 2\nline 3\nline 4\nline 5\ndirty\n" _start_autostash_merge(repo, dirty) result = git_commit(repo, "merge side") assert "Applied autostash." in result assert len(repo.head.commit.parents) == 2 assert Path(repo.working_dir, "test.txt").read_text() == dirty assert not (Path(repo.git_dir) / "MERGE_AUTOSTASH").exists() assert repo.git.stash("list") == "" def test_git_commit_stores_a_conflicting_merge_autostash(repo): # #5050: when reapplying the autostash conflicts, `git commit` keeps it in # the stash list instead, so the edits are never lost. stash_oid = _start_autostash_merge(repo, "dirty\n") # Stage a different edit to the same line into the merge commit, so the # stash no longer applies cleanly on top of it. Path(repo.working_dir, "test.txt").write_text("merged\n", newline="\n") repo.git.add("test.txt") result = git_commit(repo, "merge side") assert "Applying autostash resulted in conflicts" in result assert len(repo.head.commit.parents) == 2 assert not (Path(repo.git_dir) / "MERGE_AUTOSTASH").exists() assert repo.git.rev_parse("stash@{0}") == stash_oid def test_git_reset(test_repository): file_path = Path(test_repository.working_dir) / "reset_test.txt" file_path.write_text("content to reset") test_repository.index.add(["reset_test.txt"]) staged_before = [item.a_path for item in test_repository.index.diff("HEAD")] assert "reset_test.txt" in staged_before result = git_reset(test_repository) assert result == "All staged changes reset" staged_after = [item.a_path for item in test_repository.index.diff("HEAD")] assert "reset_test.txt" not in staged_after def test_git_log(test_repository): for i in range(3): file_path = Path(test_repository.working_dir) / f"log_test_{i}.txt" file_path.write_text(f"content {i}") test_repository.index.add([f"log_test_{i}.txt"]) test_repository.index.commit(f"commit {i}") result = git_log(test_repository, max_count=2) assert isinstance(result, list) assert len(result) == 2 assert "Commit:" in result[0] assert "Author:" in result[0] assert "Date:" in result[0] assert "Message:" in result[0] def test_git_log_default(test_repository): result = git_log(test_repository) assert isinstance(result, list) assert len(result) >= 1 assert "initial commit" in result[0] def test_git_create_branch(test_repository): result = git_create_branch(test_repository, "new-feature-branch") assert "Created branch 'new-feature-branch'" in result branches = [ref.name for ref in test_repository.references] assert "new-feature-branch" in branches def test_git_create_branch_from_base(test_repository): test_repository.git.checkout("-b", "base-branch") file_path = Path(test_repository.working_dir) / "base.txt" file_path.write_text("base content") test_repository.index.add(["base.txt"]) test_repository.index.commit("base commit") result = git_create_branch(test_repository, "derived-branch", "base-branch") assert "Created branch 'derived-branch' from 'base-branch'" in result def test_git_create_branch_on_detached_head_uses_current_commit(test_repository): # #5192: with no base_branch, a detached HEAD branches from its commit. head = test_repository.head.commit test_repository.git.checkout("--detach") result = git_create_branch(test_repository, "keep") assert result == f"Created branch 'keep' from commit {head.hexsha[:7]}" assert test_repository.heads["keep"].commit == head # Creating the branch does not attach HEAD to it. assert test_repository.head.is_detached def test_git_create_branch_from_commit_sha(test_repository): # #5192: a base that is not a reference is resolved as a commit-ish. first = test_repository.head.commit file_path = Path(test_repository.working_dir) / "later.txt" file_path.write_text("later") test_repository.index.add(["later.txt"]) test_repository.index.commit("later commit") result = git_create_branch(test_repository, "from-sha", first.hexsha) assert result == f"Created branch 'from-sha' from commit {first.hexsha[:7]}" assert test_repository.heads["from-sha"].commit == first def test_git_create_branch_from_relative_revision(test_repository): first = test_repository.head.commit test_repository.index.commit("second commit") git_create_branch(test_repository, "from-parent", "HEAD~1") assert test_repository.heads["from-parent"].commit == first @pytest.mark.parametrize("base", ["nope", "HEAD^{tree}"]) def test_git_create_branch_unknown_base(test_repository, base): # An unknown name (BadName) and an object that is not a commit (ValueError) # both get the same clear message, not GitPython's raw lookup error. with pytest.raises(ValueError, match="Unknown base branch or commit"): git_create_branch(test_repository, "x", base) assert not any(head.name == "x" for head in test_repository.heads) def test_git_create_branch_from_sha_keeps_existing_branch_check(test_repository): sha = test_repository.head.commit.hexsha test_repository.git.branch("taken") with pytest.raises(ValueError, match="refs/heads/taken already exists"): git_create_branch(test_repository, "taken", sha) def test_git_show(test_repository): file_path = Path(test_repository.working_dir) / "show_test.txt" file_path.write_text("show content") test_repository.index.add(["show_test.txt"]) test_repository.index.commit("show test commit") commit_sha = test_repository.head.commit.hexsha result = git_show(test_repository, commit_sha) assert result.startswith("commit ") assert "Author:" in result assert "show test commit" in result assert "show_test.txt" in result def test_git_show_initial_commit(test_repository): initial_commit = list(test_repository.iter_commits())[-1] result = git_show(test_repository, initial_commit.hexsha) assert result.startswith("commit ") assert "initial commit" in result assert "test.txt" in result def test_git_show_blob_object_spec(test_repository): file_path = Path(test_repository.working_dir) / "logic" / "infos.py" file_path.parent.mkdir() file_path.write_bytes(b"print('infos')\n") test_repository.index.add(["logic/infos.py"]) test_repository.index.commit("add infos") result = git_show(test_repository, "HEAD:logic/infos.py") assert result == "print('infos')\n" def test_git_show_tree_object_spec(test_repository): file_path = Path(test_repository.working_dir) / "logic" / "infos.py" file_path.parent.mkdir() file_path.write_text("print('infos')\n") test_repository.index.add(["logic/infos.py"]) test_repository.index.commit("add infos") result = git_show(test_repository, "HEAD:") assert result == "logic/\ntest.txt" # Tests for validate_repo_path (repository scoping security fix) def test_validate_repo_path_no_restriction(): """When no repository restriction is configured, any path should be allowed.""" validate_repo_path(Path("/any/path"), None) # Should not raise def test_validate_repo_path_exact_match(tmp_path: Path): """When repo_path exactly matches allowed_repository, validation should pass.""" allowed = tmp_path / "repo" allowed.mkdir() validate_repo_path(allowed, allowed) # Should not raise def test_validate_repo_path_subdirectory(tmp_path: Path): """When repo_path is a subdirectory of allowed_repository, validation should pass.""" allowed = tmp_path / "repo" allowed.mkdir() subdir = allowed / "subdir" subdir.mkdir() validate_repo_path(subdir, allowed) # Should not raise def test_validate_repo_path_outside_allowed(tmp_path: Path): """When repo_path is outside allowed_repository, validation should raise ValueError.""" allowed = tmp_path / "allowed_repo" allowed.mkdir() outside = tmp_path / "other_repo" outside.mkdir() with pytest.raises(ValueError) as exc_info: validate_repo_path(outside, allowed) assert "outside the allowed repository" in str(exc_info.value) def test_validate_repo_path_traversal_attempt(tmp_path: Path): """Path traversal attempts (../) should be caught and rejected.""" allowed = tmp_path / "allowed_repo" allowed.mkdir() # Attempt to escape via ../ traversal_path = allowed / ".." / "other_repo" with pytest.raises(ValueError) as exc_info: validate_repo_path(traversal_path, allowed) assert "outside the allowed repository" in str(exc_info.value) def test_validate_repo_path_symlink_escape(tmp_path: Path): """Symlinks pointing outside allowed_repository should be rejected.""" allowed = tmp_path / "allowed_repo" allowed.mkdir() outside = tmp_path / "outside" outside.mkdir() # Create a symlink inside allowed that points outside symlink = allowed / "escape_link" symlink.symlink_to(outside) with pytest.raises(ValueError) as exc_info: validate_repo_path(symlink, allowed) assert "outside the allowed repository" in str(exc_info.value) # Tests for argument injection protection def test_git_diff_rejects_flag_injection(test_repository): """git_diff should reject flags that could be used for argument injection.""" with pytest.raises(BadName): git_diff(test_repository, "--output=/tmp/evil") with pytest.raises(BadName): git_diff(test_repository, "--help") with pytest.raises(BadName): git_diff(test_repository, "-p") def test_git_checkout_rejects_flag_injection(test_repository): """git_checkout should reject flags that could be used for argument injection.""" with pytest.raises(BadName): git_checkout(test_repository, "--help") with pytest.raises(BadName): git_checkout(test_repository, "--orphan=evil") with pytest.raises(BadName): git_checkout(test_repository, "-f") def test_git_diff_allows_valid_refs(test_repository): """git_diff should work normally with valid git refs.""" # Get the default branch name default_branch = test_repository.active_branch.name # Create a branch with a commit for diffing test_repository.git.checkout("-b", "valid-diff-branch") file_path = Path(test_repository.working_dir) / "test.txt" file_path.write_text("valid diff content") test_repository.index.add(["test.txt"]) test_repository.index.commit("valid diff commit") # Test with branch name result = git_diff(test_repository, default_branch) assert "test.txt" in result # Test with HEAD~1 result = git_diff(test_repository, "HEAD~1") assert "test.txt" in result # Test with commit hash commit_sha = test_repository.head.commit.hexsha result = git_diff(test_repository, commit_sha) assert result is not None def test_git_checkout_allows_valid_branches(test_repository): """git_checkout should work normally with valid branch names.""" # Get the default branch name default_branch = test_repository.active_branch.name # Create a branch to checkout test_repository.git.branch("valid-checkout-branch") result = git_checkout(test_repository, "valid-checkout-branch") assert "Switched to branch 'valid-checkout-branch'" in result assert test_repository.active_branch.name == "valid-checkout-branch" # Checkout back to default branch result = git_checkout(test_repository, default_branch) assert "Switched to branch" in result assert test_repository.active_branch.name == default_branch def test_git_diff_rejects_malicious_refs(test_repository): """git_diff should reject refs starting with '-' even if they exist. This tests defense in depth against an attacker who creates malicious refs via filesystem manipulation (e.g. using mcp-filesystem to write to .git/refs/heads/--output=...). """ import os # Manually create a malicious ref by writing directly to .git/refs sha = test_repository.head.commit.hexsha refs_dir = Path(test_repository.git_dir) / "refs" / "heads" malicious_ref_path = refs_dir / "--output=evil.txt" malicious_ref_path.write_text(sha) # Even though the ref exists, it should be rejected with pytest.raises(BadName): git_diff(test_repository, "--output=evil.txt") # Verify no file was created (the attack was blocked) assert not os.path.exists("evil.txt") # Cleanup malicious_ref_path.unlink() def test_git_checkout_rejects_malicious_refs(test_repository): """git_checkout should reject refs starting with '-' even if they exist.""" # Manually create a malicious ref sha = test_repository.head.commit.hexsha refs_dir = Path(test_repository.git_dir) / "refs" / "heads" malicious_ref_path = refs_dir / "--orphan=evil" malicious_ref_path.write_text(sha) # Even though the ref exists, it should be rejected with pytest.raises(BadName): git_checkout(test_repository, "--orphan=evil") # Cleanup malicious_ref_path.unlink() # Tests for argument injection protection in git_show, git_create_branch, # git_log, and git_branch — matching the existing guards on git_diff and # git_checkout. def test_git_show_rejects_flag_injection(test_repository): """git_show should reject revisions starting with '-'.""" with pytest.raises(BadName): git_show(test_repository, "--output=/tmp/evil") with pytest.raises(BadName): git_show(test_repository, "-p") def test_git_show_rejects_malicious_refs(test_repository): """git_show should reject refs starting with '-' even if they exist.""" sha = test_repository.head.commit.hexsha refs_dir = Path(test_repository.git_dir) / "refs" / "heads" malicious_ref_path = refs_dir / "--format=evil" malicious_ref_path.write_text(sha) with pytest.raises(BadName): git_show(test_repository, "--format=evil") malicious_ref_path.unlink() def test_git_create_branch_rejects_flag_injection(test_repository): """git_create_branch should reject branch names starting with '-'.""" with pytest.raises(BadName): git_create_branch(test_repository, "--track=evil") with pytest.raises(BadName): git_create_branch(test_repository, "-f") def test_git_create_branch_rejects_base_branch_flag_injection(test_repository): """git_create_branch should reject base branch names starting with '-'.""" with pytest.raises(BadName): git_create_branch(test_repository, "new-branch", "--track=evil") def test_git_log_rejects_timestamp_flag_injection(test_repository): """git_log should reject timestamps starting with '-'.""" with pytest.raises(ValueError): git_log(test_repository, start_timestamp="--exec=evil") with pytest.raises(ValueError): git_log(test_repository, end_timestamp="--exec=evil") def test_git_log_rejects_non_positive_max_count(test_repository): """git_log should reject a max_count below 1 (#5214): git reads a negative -n as "no limit" and 0 as nothing.""" with pytest.raises(ValueError, match="Invalid max_count: 0 - must be at least 1"): git_log(test_repository, max_count=0) with pytest.raises(ValueError, match="Invalid max_count: -1 - must be at least 1"): git_log(test_repository, max_count=-1) def test_git_branch_rejects_contains_flag_injection(test_repository): """git_branch should reject contains/not_contains values starting with '-'.""" with pytest.raises(BadName): git_branch(test_repository, "local", contains="--exec=evil") with pytest.raises(BadName): git_branch(test_repository, "local", not_contains="--exec=evil") def test_git_log_formatting_no_repr(test_repository): """Test that git_log does not use !r formatting (no Python object repr or quotes).""" file_path = Path(test_repository.working_dir) / "multiline.txt" file_path.write_text("multiline test") test_repository.index.add(["multiline.txt"]) test_repository.index.commit( "Subject line\n\nDetailed body line 1\nDetailed body line 2" ) result = git_log(test_repository, max_count=1) entry = result[0] # Verify no python repr quotes around commit hash or message assert "Commit: '" not in entry assert 'Commit: "' not in entry assert "