Skip to content

The agent that grows with you

refactor(git): trim safe.directory tests to two invariants, memoise the config read

Teknium66adfaee6b61
diff --git a/hermes_cli/_subprocess_compat.py b/hermes_cli/_subprocess_compat.py
index d8c52e06efe..9ae2ce29ada 100644
--- a/hermes_cli/_subprocess_compat.py
+++ b/hermes_cli/_subprocess_compat.py
@@ -232,13 +232,41 @@ _GIT_CONFIG_OVERRIDES = {
}
+def _safe_directory_cache_key(env: "Mapping[str, str]") -> tuple:
+ """Everything that decides which files ``git config --system/--global`` reads, plus the
+ global candidates' mtimes so an edit to ``~/.gitconfig`` is picked up without a restart."""
+ home = env.get("HOME", "")
+ xdg = env.get("XDG_CONFIG_HOME") or os.path.join(home, ".config")
+ candidates = (
+ env.get("GIT_CONFIG_SYSTEM") or "/etc/gitconfig",
+ env.get("GIT_CONFIG_GLOBAL") or os.path.join(home, ".gitconfig"),
+ os.path.join(xdg, "git", "config"),
+ )
+ stamps = []
+ for path in candidates:
+ try:
+ stamps.append(os.stat(path).st_mtime_ns)
+ except OSError:
+ stamps.append(None)
+ return (
+ env.get("GIT_CONFIG_GLOBAL"), env.get("GIT_CONFIG_SYSTEM"), env.get("GIT_CONFIG_NOSYSTEM"),
+ home, env.get("XDG_CONFIG_HOME"), env.get("PATH"), *stamps,
+ )
+
+
+_safe_directory_cache: dict[tuple, list[str]] = {}
+
+
def _user_safe_directories(base_env: "Mapping[str, str]") -> list[str]:
"""The user's configured ``safe.directory`` values, in git's own effective order.
Read with ``git config -z --get-all`` under *base_env* (the caller's untouched environment) so
an explicit ``GIT_CONFIG_GLOBAL``/``GIT_CONFIG_SYSTEM`` still points at the file the user means.
Best-effort: any failure (git missing, malformed config, timeout) yields no entries and leaves
- the caller exactly as it behaved before.
+ the caller exactly as it behaved before. Memoised per process on the inputs that select the
+ config files (and the global file's mtime): ``noninteractive_git_env()`` runs on every internal
+ git call, including the startup banner probe, and two ``git config`` children per call is
+ ~10 ms against ~0.2 ms for the rest of the function.
``safe.directory`` is an *ordered* multi-valued setting and an empty value resets every entry
seen so far, so a user can revoke a system-wide ``safe.directory=*`` and then name only the
@@ -248,6 +276,10 @@ def _user_safe_directories(base_env: "Mapping[str, str]") -> list[str]:
marker, either of which would resurrect a revoked wildcard and widen trust. ``-z`` keeps a
value containing whitespace or a newline as the single entry git reads it as.
"""
+ cache_key = _safe_directory_cache_key(base_env)
+ cached = _safe_directory_cache.get(cache_key)
+ if cached is not None:
+ return list(cached)
env = dict(base_env)
# --get-all itself must not be derailed by ambient injection or an interactive prompt.
for key in list(env):
@@ -273,6 +305,7 @@ def _user_safe_directories(base_env: "Mapping[str, str]") -> list[str]:
if records and records[-1] == "":
records.pop()
values.extend(records)
+ _safe_directory_cache[cache_key] = list(values)
return values
diff --git a/tests/hermes_cli/test_noninteractive_git.py b/tests/hermes_cli/test_noninteractive_git.py
index 95cf11cad13..0d36f099bd8 100644
--- a/tests/hermes_cli/test_noninteractive_git.py
+++ b/tests/hermes_cli/test_noninteractive_git.py
@@ -97,86 +97,6 @@ class TestNoninteractiveGitEnv:
assert values["sequence.editor"] == "true"
assert values["diff.external"] == ""
- def test_carries_user_safe_directory_past_config_isolation(self, tmp_path, monkeypatch):
- """safe.directory survives GIT_CONFIG_GLOBAL=/dev/null (#dubious-ownership on NFS).
-
- git honours safe.directory only from global/system config, and both are blanked here. If
- it is not re-injected, every internal git call fails "detected dubious ownership" on a
- repo whose st_uid != geteuid() -- an NFS/CIFS mount without idmapping, a shared checkout,
- a container with a remapped uid -- even though the user configured it correctly.
- """
- gitconfig = tmp_path / "gitconfig"
- gitconfig.write_text(
- "[safe]\n\tdirectory = /mnt/nfs/repo\n\tdirectory = /srv/shared/other\n",
- encoding="utf-8",
- )
- empty_system = tmp_path / "system-gitconfig"
- empty_system.write_text("", encoding="utf-8")
- monkeypatch.setenv("GIT_CONFIG_GLOBAL", str(gitconfig))
- monkeypatch.setenv("GIT_CONFIG_SYSTEM", str(empty_system))
-
- env = noninteractive_git_env()
- pairs = [
- (env[f"GIT_CONFIG_KEY_{idx}"], env[f"GIT_CONFIG_VALUE_{idx}"])
- for idx in range(int(env["GIT_CONFIG_COUNT"]))
- ]
- safe = [value for key, value in pairs if key == "safe.directory"]
-
- assert "/mnt/nfs/repo" in safe
- assert "/srv/shared/other" in safe
- # Isolation is still in force: the values ride the KEY_n channel, not the config file.
- assert env["GIT_CONFIG_GLOBAL"] == os.devnull
- assert env["GIT_CONFIG_SYSTEM"] == os.devnull
- # And the hardening overrides are untouched by the appended entries.
- assert ("core.pager", "cat") in pairs
- assert ("credential.helper", "") in pairs
-
- def test_safe_directory_absent_when_user_configured_none(self, tmp_path, monkeypatch):
- """No user entries -> no injected entries; the env is exactly as it was before."""
- gitconfig = tmp_path / "gitconfig"
- gitconfig.write_text("[user]\n\tname = nobody\n", encoding="utf-8")
- empty_system = tmp_path / "system-gitconfig"
- empty_system.write_text("", encoding="utf-8")
- monkeypatch.setenv("GIT_CONFIG_GLOBAL", str(gitconfig))
- # Pin the system scope too: a real /etc/gitconfig on the test host may carry its own
- # safe.directory entries, which would otherwise leak in and mask the assertion.
- monkeypatch.setenv("GIT_CONFIG_SYSTEM", str(empty_system))
-
- env = noninteractive_git_env()
- keys = [env[f"GIT_CONFIG_KEY_{idx}"] for idx in range(int(env["GIT_CONFIG_COUNT"]))]
-
- assert "safe.directory" not in keys
-
- def test_ambient_safe_directory_injection_is_not_trusted(self, tmp_path, monkeypatch):
- """A caller-supplied GIT_CONFIG_KEY_n=safe.directory is dropped, not laundered through.
-
- Only what the user's own config file says is carried; ambient injection stays stripped so
- this cannot become a path-trust escalation vector.
- """
- gitconfig = tmp_path / "gitconfig"
- gitconfig.write_text("[safe]\n\tdirectory = /mnt/nfs/repo\n", encoding="utf-8")
- empty_system = tmp_path / "system-gitconfig"
- empty_system.write_text("", encoding="utf-8")
- monkeypatch.setenv("GIT_CONFIG_GLOBAL", str(gitconfig))
- monkeypatch.setenv("GIT_CONFIG_SYSTEM", str(empty_system))
-
- env = noninteractive_git_env(
- {
- **os.environ,
- "GIT_CONFIG_COUNT": "1",
- "GIT_CONFIG_KEY_0": "safe.directory",
- "GIT_CONFIG_VALUE_0": "/attacker/controlled",
- }
- )
- safe = [
- env[f"GIT_CONFIG_VALUE_{idx}"]
- for idx in range(int(env["GIT_CONFIG_COUNT"]))
- if env[f"GIT_CONFIG_KEY_{idx}"] == "safe.directory"
- ]
-
- assert "/attacker/controlled" not in safe
- assert "/mnt/nfs/repo" in safe
-
def test_safe_directory_preserves_git_ordering_and_reset_markers(self, tmp_path, monkeypatch):
"""The user's effective trust policy is replayed verbatim, resets included.
@@ -196,7 +116,19 @@ class TestNoninteractiveGitEnv:
monkeypatch.setenv("GIT_CONFIG_SYSTEM", str(system_config))
monkeypatch.setenv("GIT_CONFIG_GLOBAL", str(global_config))
- env = noninteractive_git_env()
+ # Ambient GIT_CONFIG_KEY_n=safe.directory must not be laundered through alongside the
+ # user's own entries -- only the config files are a trust source.
+ env = noninteractive_git_env(
+ {
+ **os.environ,
+ "GIT_CONFIG_COUNT": "1",
+ "GIT_CONFIG_KEY_0": "safe.directory",
+ "GIT_CONFIG_VALUE_0": "/attacker/controlled",
+ }
+ )
+ # Isolation itself is unchanged: the values ride the KEY_n channel, not the config file.
+ assert env["GIT_CONFIG_GLOBAL"] == os.devnull
+ assert env["GIT_CONFIG_SYSTEM"] == os.devnull
injected = [
env[f"GIT_CONFIG_VALUE_{idx}"]
for idx in range(int(env["GIT_CONFIG_COUNT"]))