From 54538428f79b0c91ba52cda5229856a6edf7ac06 Mon Sep 17 00:00:00 2001
From: "GPT 5.5" <codex@openai.com>
Date: Tue, 5 May 2026 21:34:42 +0800
Subject: [PATCH] Validate config key section names before writing

GitConfigParser already rejected CR, LF, and NUL in config values before
writing, but section and option names could still reach configparser. Because
GitPython writes section headers itself, a newline-bearing section name could
split the output into additional headers.

Reject CR, LF, and NUL in section and option names on write paths that create
or set config keys: add_section(), set(), set_value(), add_value(), and
rename_section() destinations. This matches Git config key validation behavior;
Git source commit 94f057755b7941b321fd11fec1b2e3ca5313a4e0 reports invalid keys
containing newlines from config.c, and local git 2.50.1 rejects newline-bearing
config keys.

Add a regression test covering unsafe section and option names while preserving
safe writes.

Co-authored-by: Sebastian Thiel <sebastian.thiel@icloud.com>
---
 git/config.py       | 17 ++++++++++++++++-
 test/test_config.py | 31 +++++++++++++++++++++++++++++++
 2 files changed, 47 insertions(+), 1 deletion(-)

Index: GitPython-3.1.34.1693646983.2a2ae77/git/config.py
===================================================================
--- GitPython-3.1.34.1693646983.2a2ae77.orig/git/config.py
+++ GitPython-3.1.34.1693646983.2a2ae77/git/config.py
@@ -75,6 +75,9 @@ log.addHandler(logging.NullHandler())
 # invariants
 # represents the configuration level of a configuration file
 
+UNSAFE_CONFIG_CHARS_RE = re.compile(r"[\r\n\x00]")
+"""Characters that cannot be safely written in config names or values."""
+
 
 CONFIG_LEVELS: ConfigLevels_Tup = ("system", "user", "global", "repository")
 
@@ -741,6 +744,7 @@ class GitConfigParser(cp.RawConfigParser
 
     def add_section(self, section: str) -> None:
         """Assures added options will stay in order"""
+        self._assure_config_name_safe(section, "section")
         return super(GitConfigParser, self).add_section(section)
 
     @property
@@ -839,10 +843,14 @@ class GitConfigParser(cp.RawConfigParser
 
     def _value_to_string_safe(self, value: Union[str, bytes, int, float, bool]) -> str:
         value_str = self._value_to_string(value)
-        if re.search(r"[\r\n\x00]", value_str):
+        if UNSAFE_CONFIG_CHARS_RE.search(value_str):
             raise ValueError("Git config values must not contain CR, LF, or NUL")
         return value_str
 
+    def _assure_config_name_safe(self, name: "cp._SectionName", label: str) -> None:
+        if isinstance(name, str) and UNSAFE_CONFIG_CHARS_RE.search(name):
+            raise ValueError("Git config %s names must not contain CR, LF, or NUL" % label)
+
     @needs_values
     @set_dirty_and_flush_changes
     def set(
@@ -851,6 +859,8 @@ class GitConfigParser(cp.RawConfigParser
         option: str,
         value: Union[str, bytes, int, float, bool, None] = None,
     ) -> None:
+        self._assure_config_name_safe(section, "section")
+        self._assure_config_name_safe(option, "option")
         if value is not None:
             value = self._value_to_string_safe(value)
         return super().set(section, option, value)
@@ -868,6 +878,8 @@ class GitConfigParser(cp.RawConfigParser
         :param value: Value to set the option to. It must be a string or convertible
             to a string
         :return: this instance"""
+        self._assure_config_name_safe(section, "section")
+        self._assure_config_name_safe(option, "option")
         value_str = self._value_to_string_safe(value)
         if not self.has_section(section):
             self.add_section(section)
@@ -888,6 +900,8 @@ class GitConfigParser(cp.RawConfigParser
         :param value: Value to add to option. It must be a string or convertible
             to a string
         :return: this instance"""
+        self._assure_config_name_safe(section, "section")
+        self._assure_config_name_safe(option, "option")
         value_str = self._value_to_string_safe(value)
         if not self.has_section(section):
             self.add_section(section)
@@ -902,6 +916,7 @@ class GitConfigParser(cp.RawConfigParser
         """
         if not self.has_section(section):
             raise ValueError("Source section '%s' doesn't exist" % section)
+        self._assure_config_name_safe(new_name, "section")
         if self.has_section(new_name):
             raise ValueError("Destination section '%s' already exists" % new_name)
 
Index: GitPython-3.1.34.1693646983.2a2ae77/test/test_config.py
===================================================================
--- GitPython-3.1.34.1693646983.2a2ae77.orig/test/test_config.py
+++ GitPython-3.1.34.1693646983.2a2ae77/test/test_config.py
@@ -157,6 +157,37 @@ class TestBase(TestCase):
             self.assertFalse(git_config.has_section("core"))
 
     @with_rw_directory
+    def test_set_value_rejects_unsafe_section_and_option_names(self, rw_dir):
+        config_path = osp.join(rw_dir, "config")
+        bad_keys = ("user]\n[core", "user]\r[core", "user]\x00[core")
+
+        with GitConfigParser(config_path, read_only=False) as git_config:
+            git_config.add_section("user")
+            for bad_key in bad_keys:
+                with pytest.raises(ValueError, match="CR, LF, or NUL"):
+                    git_config.add_section(bad_key)
+                with pytest.raises(ValueError, match="CR, LF, or NUL"):
+                    git_config.set(bad_key, "hooksPath", "/tmp/hooks")
+                with pytest.raises(ValueError, match="CR, LF, or NUL"):
+                    git_config.set("user", bad_key, "/tmp/hooks")
+                with pytest.raises(ValueError, match="CR, LF, or NUL"):
+                    git_config.set_value(bad_key, "hooksPath", "/tmp/hooks")
+                with pytest.raises(ValueError, match="CR, LF, or NUL"):
+                    git_config.set_value("user", bad_key, "/tmp/hooks")
+                with pytest.raises(ValueError, match="CR, LF, or NUL"):
+                    git_config.add_value(bad_key, "hooksPath", "/tmp/hooks")
+                with pytest.raises(ValueError, match="CR, LF, or NUL"):
+                    git_config.add_value("user", bad_key, "/tmp/hooks")
+                with pytest.raises(ValueError, match="CR, LF, or NUL"):
+                    git_config.rename_section("user", bad_key)
+
+            git_config.set_value("user", "name", "safe")
+
+        with GitConfigParser(config_path, read_only=True) as git_config:
+            self.assertEqual(git_config.get_value("user", "name"), "safe")
+            self.assertFalse(git_config.has_section("core"))
+
+    @with_rw_directory
     def test_set_and_add_value_reject_unsafe_value_characters(self, rw_dir):
         config_path = osp.join(rw_dir, "config")
         bad_values = ("foo\rbar", "foo\nbar", "foo\x00bar", b"foo\nbar")
