From 9349ff58ee00c9fb14d515c8e693f33b2144b238 Mon Sep 17 00:00:00 2001
From: Byron <sebastian.thiel@icloud.com>
Date: Mon, 28 Sep 2026 04:31:10 +0200
Subject: [PATCH] fix(repo): preserve literal separate Git directory paths

<!-- Byron -->

The code-change itself is trivial. Skimmed the tests, better to have them,
but kind of low value given the amount of code they take. Oh well...

<!-- agent -->
`Repo._clone()` expanded `separate_git_dir` before invoking Git, so
metadata could be written under a different directory name from the one
requested. Preserve literal paths to address `GHSA-fx3j-rwgx-fr94`.

Disable expansion in the shared `Git.polish_url()` call. Normalize
path-like arguments with `os.fspath()` first so `pathlib.Path` and other
`os.PathLike` implementations remain supported. Existing path separator
conversion still applies.

Add local regression coverage for both clone APIs, three path argument
types, variable-like names, and recursive submodule initialization. Check
the metadata location, usable submodule commit, and debug output.

Git reference: checkout `d38352cd43ab9745686d697872408bc3249a153f`,
`builtin/clone.c` and `t/t5601-clone.sh`'s separate-git-dir tests.
Native Git 2.54.0 also preserved all three literal variable forms.

Assisted-by: GPT 6.0
Co-authored-by: GPT 6.0 <codex@openai.com>
---
 doc/source/changes.rst |  9 ++++++++-
 git/repo/base.py       |  2 +-
 git/repo/fun.py        |  2 +-
 test/test_clone.py     | 22 ++++++++++++++++++++++
 test/test_submodule.py | 30 ++++++++++++++++++++++++++++++
 5 files changed, 62 insertions(+), 3 deletions(-)

Index: GitPython-3.1.59/git/repo/base.py
===================================================================
--- GitPython-3.1.59.orig/git/repo/base.py
+++ GitPython-3.1.59/git/repo/base.py
@@ -1528,7 +1528,7 @@ class Repo:
         clone_path = Git.polish_url(path) if Git.is_cygwin() and "bare" in kwargs else path
         sep_dir = kwargs.get("separate_git_dir")
         if sep_dir:
-            kwargs["separate_git_dir"] = Git.polish_url(sep_dir)
+            kwargs["separate_git_dir"] = Git.polish_url(os.fspath(sep_dir), expand_vars=False)
         multi = None
         if multi_options:
             multi = shlex.split(" ".join(multi_options))
Index: GitPython-3.1.59/git/repo/fun.py
===================================================================
--- GitPython-3.1.59.orig/git/repo/fun.py
+++ GitPython-3.1.59/git/repo/fun.py
@@ -152,7 +152,7 @@ def find_submodule_git_dir(d: PathLike)
         # Cygwin creates submodules prefixed with `/cygdrive/...`.
         # Cygwin git understands Cygwin paths much better than Windows ones.
         # Also the Cygwin tests are assuming Cygwin paths.
-        path = cygpath(path)
+        path = cygpath(path, expand_vars=False)
     if not osp.isabs(path):
         path = osp.normpath(osp.join(osp.dirname(d), path))
     return path if is_git_dir(path) else None
Index: GitPython-3.1.59/test/test_clone.py
===================================================================
--- GitPython-3.1.59.orig/test/test_clone.py
+++ GitPython-3.1.59/test/test_clone.py
@@ -21,6 +21,28 @@ import git
 import pytest
 
 
+@pytest.mark.parametrize("clone_method", ["clone", "clone_from"])
+@pytest.mark.parametrize("path_type", [str, Path, PathLikeMock])
+@pytest.mark.parametrize("name", ["$GITPYTHON_TEST_SECRET", "${GITPYTHON_TEST_SECRET}", "%GITPYTHON_TEST_SECRET%"])
+def test_clone_preserves_literal_separate_git_dir(tmp_path, monkeypatch, caplog, clone_method, path_type, name):
+    monkeypatch.setenv("GITPYTHON_TEST_SECRET", "sensitive-value")
+    caplog.set_level("DEBUG", logger="git.cmd")
+    separate_git_dir = tmp_path / name
+    options = {"separate_git_dir": path_type(str(separate_git_dir)), "allow_unsafe_options": True}
+
+    with Repo.init(tmp_path / "source") as source:
+        if clone_method == "clone":
+            cloned = source.clone(tmp_path / "clone", **options)
+        else:
+            cloned = Repo.clone_from(source.git_dir, tmp_path / "clone", **options)
+        with cloned:
+            assert (separate_git_dir / "HEAD").is_file()
+            assert separate_git_dir.samefile(cloned.git_dir)
+
+    assert not (tmp_path / "sensitive-value").exists()
+    assert "sensitive-value" not in caplog.text
+
+
 class TestClone(TestBase):
     @with_rw_directory
     def test_checkout_in_non_empty_dir(self, rw_dir):
Index: GitPython-3.1.59/test/test_submodule.py
===================================================================
--- GitPython-3.1.59.orig/test/test_submodule.py
+++ GitPython-3.1.59/test/test_submodule.py
@@ -51,6 +51,36 @@ def _patch_git_config(name, value):
         yield
 
 
+@pytest.mark.parametrize(
+    "name", ["module", "$GITPYTHON_TEST_SECRET", "prefix-${GITPYTHON_TEST_SECRET}-suffix", "%GITPYTHON_TEST_SECRET%"]
+)
+def test_submodule_update_preserves_literal_name(tmp_path, monkeypatch, caplog, name):
+    monkeypatch.setenv("GITPYTHON_TEST_SECRET", "sensitive-value")
+    caplog.set_level("DEBUG", logger="git.cmd")
+    with git.Repo.init(tmp_path / "source") as source, git.Repo.init(tmp_path / "parent") as parent:
+        source.git.symbolic_ref("HEAD", "refs/heads/master")
+        source.index.commit("Initial commit")
+        with _patch_git_config("protocol.file.allow", "always"):
+            parent.git.submodule("add", "--name", name, source.working_tree_dir, "module")
+        parent.index.commit("Add submodule")
+
+        with git.Repo.clone_from(parent.working_tree_dir, tmp_path / "clone") as clone:
+            clone.submodule_update(init=True, recursive=True)
+
+            modules_dir = Path(clone.git_dir, "modules")
+            assert {path.name for path in modules_dir.iterdir()} == {name}
+            # Exercise relative gitfile conversion on every platform.
+            with mock.patch.object(Git, "is_cygwin", return_value=True):
+                resolved_git_dir = find_submodule_git_dir(Path(clone.working_tree_dir, "module", ".git"))
+            assert resolved_git_dir is not None
+            assert (modules_dir / name).samefile(resolved_git_dir)
+            with clone.submodules[0].module() as module:
+                assert (modules_dir / name).samefile(module.git_dir)
+                assert module.head.commit == source.head.commit
+
+    assert "sensitive-value" not in caplog.text
+
+
 class TestRootProgress(RootUpdateProgress):
     """Just prints messages, for now without checking the correctness of the states"""
 
