From f2550b65bf60ca087190981e2c7b6865e201f40c Mon Sep 17 00:00:00 2001
From: Byron <sebastian.thiel@icloud.com>
Date: Tue, 4 Aug 2026 03:18:54 +0000
Subject: [PATCH] Guard pathspec file inputs in high-level commands

<!-- agent -->
GHSA-hh9p-6wh2-4mfc reports that high-level rm and checkout wrappers
forwarded pathspec file options without GitPython's unsafe-option policy.
A regression showed that both commands surfaced multi-line pathspec data in
Git errors, while reset consumed the same caller-selected file without a
validation error. The audit also found that reset's positional commit could
carry the option before its argument separator.

Define one shared unsafe pathspec-file option list and apply it to
IndexFile.remove, Head.checkout, and HEAD.reset before invoking Git. Check
reset's positional commit as well as keyword options, retain the standard
allow_unsafe_options escape hatch for trusted callers, and cover abbreviated
long-option spellings.

An audit against Git cf5497b14c5a24f10c13f7e0ee85cb95af13ea6a
(v2.55.0.windows.3-16-gcf5497b14c) found pathspec-file support in add,
checkout/restore, commit, reset, rm, and stash. GitPython has no arbitrary
high-level option forwarding to the other commands, and git mv does not
support this option.

Validated with focused rejection and opt-in tests, 214 affected-module
regressions, Ruff, basedpyright, and git diff --check.

Assisted-by: GPT 5.6
Co-authored-by: GPT 5.6 <codex@openai.com>
---
 git/cmd.py         |  6 ++++++
 git/index/base.py  | 10 ++++++++++
 git/refs/head.py   | 27 ++++++++++++++++++++++++++-
 test/test_git.py   | 12 ++++++++++++
 test/test_index.py | 26 ++++++++++++++++++++++++++
 test/test_refs.py  | 45 +++++++++++++++++++++++++++++++++++++++++++++
 6 files changed, 125 insertions(+), 1 deletion(-)

Index: GitPython-3.1.34.1693646983.2a2ae77/git/cmd.py
===================================================================
--- GitPython-3.1.34.1693646983.2a2ae77.orig/git/cmd.py
+++ GitPython-3.1.34.1693646983.2a2ae77/git/cmd.py
@@ -272,6 +272,12 @@ class Git(LazyMixin):
         "--upload-pack",
     ]
 
+    unsafe_git_pathspec_from_file_options = [
+        # Reads pathspecs from a caller-controlled file. Some commands include an
+        # unmatched pathspec in their error output, which can disclose the file.
+        "--pathspec-from-file",
+    ]
+
     def __getstate__(self) -> Dict[str, Any]:
         return slots_to_dict(self, exclude=self._excluded_)
 
Index: GitPython-3.1.34.1693646983.2a2ae77/git/index/base.py
===================================================================
--- GitPython-3.1.34.1693646983.2a2ae77.orig/git/index/base.py
+++ GitPython-3.1.34.1693646983.2a2ae77/git/index/base.py
@@ -936,6 +936,7 @@ class IndexFile(LazyMixin, git_diff.Diff
         self,
         items: Sequence[Union[PathLike, Blob, BaseIndexEntry, "Submodule"]],
         working_tree: bool = False,
+        allow_unsafe_options: bool = False,
         **kwargs: Any,
     ) -> List[str]:
         """Remove the given items from the index and optionally from
@@ -964,6 +965,10 @@ class IndexFile(LazyMixin, git_diff.Diff
             removing the respective file. This may fail if there are uncommitted changes
             in it.
 
+        :param allow_unsafe_options:
+            Allow unsafe options such as ``--pathspec-from-file`` to be passed to
+            :manpage:`git-rm(1)`.
+
         :param kwargs:
             Additional keyword arguments to be passed to git-rm, such
             as 'r' to allow recursive removal of
@@ -973,6 +978,11 @@ class IndexFile(LazyMixin, git_diff.Diff
             been removed effectively.
             This is interesting to know in case you have provided a directory or
             globs. Paths are relative to the repository."""
+        if not allow_unsafe_options:
+            Git.check_unsafe_options(
+                options=Git._option_candidates([], kwargs),
+                unsafe_options=Git.unsafe_git_pathspec_from_file_options,
+            )
         args = []
         if not working_tree:
             args.append("--cached")
Index: GitPython-3.1.34.1693646983.2a2ae77/git/refs/head.py
===================================================================
--- GitPython-3.1.34.1693646983.2a2ae77.orig/git/refs/head.py
+++ GitPython-3.1.34.1693646983.2a2ae77/git/refs/head.py
@@ -9,6 +9,7 @@ from .reference import Reference
 
 from typing import Any, Sequence, Union, TYPE_CHECKING
 
+from git.cmd import Git
 from git.types import PathLike, Commit_ish
 
 if TYPE_CHECKING:
@@ -54,6 +55,7 @@ class HEAD(SymbolicReference):
         index: bool = True,
         working_tree: bool = False,
         paths: Union[PathLike, Sequence[PathLike], None] = None,
+        allow_unsafe_options: bool = False,
         **kwargs: Any,
     ) -> "HEAD":
         """Reset our HEAD to the given commit optionally synchronizing
@@ -77,10 +79,19 @@ class HEAD(SymbolicReference):
             Single path or list of paths relative to the git root directory
             that are to be reset. This allows to partially reset individual files.
 
+        :param allow_unsafe_options:
+            Allow unsafe options such as ``--pathspec-from-file`` to be passed to
+            :manpage:`git-reset(1)`.
+
         :param kwargs:
             Additional arguments passed to git-reset.
 
         :return: self"""
+        if not allow_unsafe_options:
+            Git.check_unsafe_options(
+                options=Git._option_candidates([commit], kwargs),
+                unsafe_options=Git.unsafe_git_pathspec_from_file_options,
+            )
         mode: Union[str, None]
         mode = "--soft"
         if index:
@@ -217,7 +228,12 @@ class Head(Reference):
         self.path = "%s/%s" % (self._common_path_default, new_path)
         return self
 
-    def checkout(self, force: bool = False, **kwargs: Any) -> Union["HEAD", "Head"]:
+    def checkout(
+        self,
+        force: bool = False,
+        allow_unsafe_options: bool = False,
+        **kwargs: Any,
+    ) -> Union["HEAD", "Head"]:
         """Checkout this head by setting the HEAD to this reference, by updating the index
         to reflect the tree we point to and by updating the working tree to reflect
         the latest index.
@@ -228,6 +244,10 @@ class Head(Reference):
             If True, changes to the index and the working tree will be discarded.
             If False, GitCommandError will be raised in that situation.
 
+        :param allow_unsafe_options:
+            Allow unsafe options such as ``--pathspec-from-file`` to be passed to
+            :manpage:`git-checkout(1)`.
+
         :param kwargs:
             Additional keyword arguments to be passed to git checkout, i.e.
             b='new_branch' to create a new branch at the given spot.
@@ -242,6 +262,11 @@ class Head(Reference):
             By default it is only allowed to checkout heads - everything else
             will leave the HEAD detached which is allowed and possible, but remains
             a special state that some tools might not be able to handle."""
+        if not allow_unsafe_options:
+            Git.check_unsafe_options(
+                options=Git._option_candidates([], kwargs),
+                unsafe_options=Git.unsafe_git_pathspec_from_file_options,
+            )
         kwargs["f"] = force
         if kwargs["f"] is False:
             kwargs.pop("f")
Index: GitPython-3.1.34.1693646983.2a2ae77/test/test_git.py
===================================================================
--- GitPython-3.1.34.1693646983.2a2ae77.orig/test/test_git.py
+++ GitPython-3.1.34.1693646983.2a2ae77/test/test_git.py
@@ -145,6 +145,18 @@ class TestGit(TestBase):
 
         self.assertEqual(options, ["--max-count"])
 
+    def test_option_candidates_include_falsey_non_boolean_values(self):
+        kwargs = {"pathspec_from_file": 0}
+        candidates = Git._option_candidates(kwargs=kwargs)
+
+        self.assertEqual(candidates, ["--pathspec-from-file"])
+        self.assertEqual(self.git.transform_kwargs(**kwargs), ["--pathspec-from-file=0"])
+        with self.assertRaises(UnsafeOptionError):
+            Git.check_unsafe_options(
+                options=candidates,
+                unsafe_options=Git.unsafe_git_pathspec_from_file_options,
+            )
+
     def test_option_candidates_include_split_single_char_option_values(self):
         cases = [
             ({"n": "--upload-pack=helper"}, ["-n", "--upload-pack=helper"], ["--upload-pack"]),
Index: GitPython-3.1.34.1693646983.2a2ae77/test/test_index.py
===================================================================
--- GitPython-3.1.34.1693646983.2a2ae77.orig/test/test_index.py
+++ GitPython-3.1.34.1693646983.2a2ae77/test/test_index.py
@@ -67,6 +67,32 @@ class TestIndex(TestBase):
             rw_repo.index.checkout(prefix=f"{target}/", allow_unsafe_options=True)
             self.assertTrue(osp.isfile(osp.join(target, "CHANGES")))
 
+    @with_rw_repo("HEAD")
+    def test_remove_rejects_pathspec_from_file(self, rw_repo):
+        with tempfile.TemporaryDirectory() as tdir:
+            pathspecs = Path(tdir) / "pathspecs"
+            pathspecs.write_bytes(b"unmatched-path-one\nunmatched-path-two")
+            for option_name in ("pathspec_from_file", "pathspec_from"):
+                with self.assertRaises(UnsafeOptionError):
+                    rw_repo.index.remove(
+                        [],
+                        pathspec_file_nul=True,
+                        **{option_name: str(pathspecs)},
+                    )
+
+    @with_rw_repo("HEAD")
+    def test_remove_allows_explicit_pathspec_from_file(self, rw_repo):
+        with tempfile.TemporaryDirectory() as tdir:
+            pathspecs = Path(tdir) / "pathspecs"
+            pathspecs.write_bytes(b"CHANGES\0")
+            removed = rw_repo.index.remove(
+                [],
+                pathspec_from_file=str(pathspecs),
+                pathspec_file_nul=True,
+                allow_unsafe_options=True,
+            )
+            assert "CHANGES" in removed
+
     def __init__(self, *args):
         super(TestIndex, self).__init__(*args)
         self._reset_progress()
Index: GitPython-3.1.34.1693646983.2a2ae77/test/test_refs.py
===================================================================
--- GitPython-3.1.34.1693646983.2a2ae77.orig/test/test_refs.py
+++ GitPython-3.1.34.1693646983.2a2ae77/test/test_refs.py
@@ -244,6 +244,51 @@ class TestRefs(TestBase):
         assert isinstance(res, SymbolicReference)
         assert res.name == "HEAD"
 
+    @with_rw_repo("HEAD")
+    def test_head_checkout_rejects_pathspec_from_file(self, rw_repo):
+        with tempfile.TemporaryDirectory() as tdir:
+            pathspecs = Path(tdir) / "pathspecs"
+            pathspecs.write_bytes(b"unmatched-path-one\nunmatched-path-two")
+            for option_name in ("pathspec_from_file", "pathspec_from"):
+                with self.assertRaises(UnsafeOptionError):
+                    rw_repo.active_branch.checkout(
+                        pathspec_file_nul=True,
+                        **{option_name: str(pathspecs)},
+                    )
+
+    @with_rw_repo("HEAD")
+    def test_head_reset_rejects_pathspec_from_file(self, rw_repo):
+        with tempfile.TemporaryDirectory() as tdir:
+            pathspecs = Path(tdir) / "pathspecs"
+            pathspecs.write_bytes(b"unmatched-path-one\nunmatched-path-two")
+            for option_name in ("pathspec_from_file", "pathspec_from"):
+                with self.assertRaises(UnsafeOptionError):
+                    rw_repo.head.reset(
+                        pathspec_file_nul=True,
+                        **{option_name: str(pathspecs)},
+                    )
+            for option_name in ("--pathspec-from-file", "--pathspec-from"):
+                with self.assertRaises(UnsafeOptionError):
+                    rw_repo.head.reset(
+                        f"{option_name}={pathspecs}",
+                        pathspec_file_nul=True,
+                    )
+
+    @with_rw_repo("HEAD")
+    def test_head_commands_allow_explicit_pathspec_from_file(self, rw_repo):
+        with tempfile.TemporaryDirectory() as tdir:
+            pathspecs = Path(tdir) / "pathspecs"
+            pathspecs.write_bytes(b"CHANGES\0")
+            options = {
+                "pathspec_from_file": str(pathspecs),
+                "pathspec_file_nul": True,
+                "allow_unsafe_options": True,
+            }
+            head = rw_repo.head
+            branch = rw_repo.active_branch
+            assert head.reset(**options) is head
+            assert branch.checkout(**options) == branch
+
     @with_rw_repo("0.1.6")
     def test_head_reset(self, rw_repo):
         cur_head = rw_repo.head
