The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(git): preserve safe.directory ordering and reset markers when carrying it
privacydied02200f0b6520
diff --git a/hermes_cli/_subprocess_compat.py b/hermes_cli/_subprocess_compat.pyindex 6c8dea3a9ee..d8c52e06efe 100644--- a/hermes_cli/_subprocess_compat.py+++ b/hermes_cli/_subprocess_compat.py@@ -233,12 +233,20 @@ _GIT_CONFIG_OVERRIDES = {def _user_safe_directories(base_env: "Mapping[str, str]") -> list[str]:- """The user's configured ``safe.directory`` values, read from their real global/system config.+ """The user's configured ``safe.directory`` values, in git's own effective order.- Read with ``git config --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.+ 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 leavesthe caller exactly as it behaved before.++ ``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+ repositories they actually trust. Order and empty resets are therefore policy, not formatting:+ scopes are read lowest-precedence first (system, then global) and every value is preserved+ verbatim -- no de-duplication (it is a sequence, not a set) and no dropping of the reset+ 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."""env = dict(base_env)# --get-all itself must not be derailed by ambient injection or an interactive prompt.@@ -248,11 +256,10 @@ def _user_safe_directories(base_env: "Mapping[str, str]") -> list[str]:env.pop("GIT_CONFIG_COUNT", None)env["GIT_TERMINAL_PROMPT"] = "0"values: list[str] = []- seen: set[str] = set()- for scope in ("--global", "--system"):+ for scope in ("--system", "--global"):try:proc = subprocess.run(- ["git", "config", scope, "--get-all", "safe.directory"],+ ["git", "config", scope, "-z", "--get-all", "safe.directory"],capture_output=True, text=True, encoding="utf-8", errors="replace",timeout=5, stdin=subprocess.DEVNULL, env=env, check=False,)@@ -260,11 +267,12 @@ def _user_safe_directories(base_env: "Mapping[str, str]") -> list[str]:continueif proc.returncode != 0:continue- for line in proc.stdout.splitlines():- entry = line.strip()- if entry and entry not in seen:- seen.add(entry)- values.append(entry)+ # -z terminates every value with NUL, so the trailing split field is always empty and is+ # not a config entry; interior empty fields are real reset markers and must survive.+ records = proc.stdout.split("\0")+ if records and records[-1] == "":+ records.pop()+ values.extend(records)return values@@ -318,9 +326,11 @@ def noninteractive_git_env(base: "Mapping[str, str] | None" = None) -> dict[str,# st_uid != geteuid() -- NFS/CIFS mounts without idmapping, shared checkouts, containers with# a remapped uid -- even though the user's own `git config --global --add safe.directory` is# correctly set and their interactive git works fine. Carried over the GIT_CONFIG_KEY_n- # channel, which survives GIT_CONFIG_GLOBAL=/dev/null. Read-only: it never widens the set- # beyond what the user already trusts, and the hardening overrides above still win because a- # later key of the same name takes precedence in git's config order.+ # channel, which survives GIT_CONFIG_GLOBAL=/dev/null. Read-only and non-widening: the values+ # are replayed in git's own effective order, empty reset markers included (see+ # _user_safe_directories), so a global reset still revokes a system-wide wildcard exactly as it+ # does for the user's interactive git. Appended last, but the hardening overrides above are+ # distinct keys, so they are unaffected by ordering within safe.directory.overrides.extend(("safe.directory", value) for value in safe_directories)env["GIT_CONFIG_COUNT"] = str(len(overrides))for idx, (key, value) in enumerate(overrides):diff --git a/tests/hermes_cli/test_noninteractive_git.py b/tests/hermes_cli/test_noninteractive_git.pyindex 5054c984972..95cf11cad13 100644--- a/tests/hermes_cli/test_noninteractive_git.py+++ b/tests/hermes_cli/test_noninteractive_git.py@@ -177,6 +177,95 @@ class TestNoninteractiveGitEnv:assert "/attacker/controlled" not in safeassert "/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.++ ``safe.directory`` is an ordered multi-valued setting where an empty value resets every+ earlier entry, which is how a user revokes a system-wide ``safe.directory=*`` and then+ names only the repositories they trust. Reading global-before-system, dropping the empty+ marker, or de-duplicating turns ``* -> reset -> /trusted/only`` into ``/trusted/only, *``+ and silently restores the wildcard the user revoked. Contract: the injected sequence equals+ what git itself reports for the same config (system scope first, then global, verbatim).+ """+ system_config = tmp_path / "system-gitconfig"+ system_config.write_text("[safe]\n\tdirectory = *\n", encoding="utf-8")+ global_config = tmp_path / "gitconfig"+ global_config.write_text(+ "[safe]\n\tdirectory = \n\tdirectory = /trusted/only\n", encoding="utf-8"+ )+ monkeypatch.setenv("GIT_CONFIG_SYSTEM", str(system_config))+ monkeypatch.setenv("GIT_CONFIG_GLOBAL", str(global_config))++ env = noninteractive_git_env()+ injected = [+ env[f"GIT_CONFIG_VALUE_{idx}"]+ for idx in range(int(env["GIT_CONFIG_COUNT"]))+ if env[f"GIT_CONFIG_KEY_{idx}"] == "safe.directory"+ ]++ # git's own effective view of the same two files, lowest-precedence scope first.+ expected = subprocess.run(+ ["git", "config", "-z", "--get-all", "safe.directory"],+ capture_output=True, text=True, check=True,+ env={**os.environ, "GIT_CONFIG_SYSTEM": str(system_config),+ "GIT_CONFIG_GLOBAL": str(global_config)},+ ).stdout.split("\0")[:-1]++ assert expected == ["*", "", "/trusted/only"], "git's documented reset shape changed"+ assert injected == expected++ def test_safe_directory_reset_still_revokes_wildcard_for_real_git(self, tmp_path):+ """End-to-end: a revoked wildcard stays revoked, and the named repo stays usable.++ Proves the injected sequence produces the same *trust decision* real git makes, not merely+ the same list. Both repos are made cross-owner via ``safe.directory=*`` being the only+ thing that could authorise them, so the negative control fails exactly as the user's+ interactive git does.+ """+ if not shutil.which("git"):+ pytest.skip("git not installed")++ def _repo(name: str) -> Path:+ path = tmp_path / name+ path.mkdir()+ subprocess.run(["git", "init", "-q"], cwd=path, check=True)+ subprocess.run(+ ["git", "-c", "user.email=t@t", "-c", "user.name=t",+ "commit", "-q", "--allow-empty", "-m", "x"],+ cwd=path, check=True,+ )+ return path++ trusted = _repo("trusted")+ unrelated = _repo("unrelated")++ system_config = tmp_path / "system-gitconfig"+ system_config.write_text("[safe]\n\tdirectory = *\n", encoding="utf-8")+ global_config = tmp_path / "gitconfig"+ global_config.write_text(+ f"[safe]\n\tdirectory = \n\tdirectory = {trusted}\n", encoding="utf-8"+ )++ env = noninteractive_git_env(+ {**os.environ, "GIT_CONFIG_SYSTEM": str(system_config),+ "GIT_CONFIG_GLOBAL": str(global_config)}+ )+ # Force the ownership check that safe.directory governs; without it git trusts the repo+ # because the test process owns the checkout it just created.+ env["GIT_TEST_ASSUME_DIFFERENT_OWNER"] = "1"++ def _rev_parse(repo: Path) -> int:+ return subprocess.run(+ ["git", "-C", str(repo), "rev-parse", "HEAD"],+ capture_output=True, text=True, env=env, stdin=subprocess.DEVNULL,+ ).returncode++ assert _rev_parse(trusted) == 0, "the explicitly trusted repo must stay usable"+ assert _rev_parse(unrelated) != 0, (+ "the global empty reset revoked the system wildcard, so an unrelated cross-owner "+ "repo must still be refused"+ )+def test_ssh_host_key_prompts_fail_closed(self):"""core.sshCommand is pinned to BatchMode ssh (#104591).