The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(git): carry user safe.directory past non-interactive config isolation
privacydied01a3206e905f
diff --git a/hermes_cli/_subprocess_compat.py b/hermes_cli/_subprocess_compat.pyindex d55e4dec1b2..6c8dea3a9ee 100644--- a/hermes_cli/_subprocess_compat.py+++ b/hermes_cli/_subprocess_compat.py@@ -232,6 +232,42 @@ _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.++ 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.+ Best-effort: any failure (git missing, malformed config, timeout) yields no entries and leaves+ the caller exactly as it behaved before.+ """+ env = dict(base_env)+ # --get-all itself must not be derailed by ambient injection or an interactive prompt.+ for key in list(env):+ if key == "GIT_CONFIG_PARAMETERS" or key.startswith(_GIT_CONFIG_INJECT_PREFIXES):+ env.pop(key, None)+ env.pop("GIT_CONFIG_COUNT", None)+ env["GIT_TERMINAL_PROMPT"] = "0"+ values: list[str] = []+ seen: set[str] = set()+ for scope in ("--global", "--system"):+ try:+ proc = subprocess.run(+ ["git", "config", scope, "--get-all", "safe.directory"],+ capture_output=True, text=True, encoding="utf-8", errors="replace",+ timeout=5, stdin=subprocess.DEVNULL, env=env, check=False,+ )+ except (OSError, subprocess.SubprocessError):+ continue+ if 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)+ return values++def noninteractive_git_env(base: "Mapping[str, str] | None" = None) -> dict[str, str]:"""Environment for *internal* git invocations that must never prompt.@@ -258,6 +294,9 @@ def noninteractive_git_env(base: "Mapping[str, str] | None" = None) -> dict[str,for input nobody can type."""env = dict(base if base is not None else os.environ)+ # Captured before the isolation below rewrites GIT_CONFIG_GLOBAL/SYSTEM to /dev/null --+ # reading after that point would resolve the user's config to an empty file.+ safe_directories = _user_safe_directories(base if base is not None else os.environ)env["GIT_TERMINAL_PROMPT"] = "0"env["GCM_INTERACTIVE"] = "Never"# Drop caller-supplied config injection; the GIT_CONFIG_COUNT block is rebuilt below so@@ -272,8 +311,19 @@ def noninteractive_git_env(base: "Mapping[str, str] | None" = None) -> dict[str,env["GIT_PAGER"] = "cat"env["PAGER"] = "cat"env["GIT_EDITOR"] = "true"- env["GIT_CONFIG_COUNT"] = str(len(_GIT_CONFIG_OVERRIDES))- for idx, (key, value) in enumerate(_GIT_CONFIG_OVERRIDES.items()):+ overrides = list(_GIT_CONFIG_OVERRIDES.items())+ # safe.directory is honoured ONLY from global/system config (git rejects it from repo-level+ # config so a hostile repo cannot self-authorise), and both are blanked just above. Without+ # re-injection every internal git call fails "detected dubious ownership" on any repo whose+ # 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.+ overrides.extend(("safe.directory", value) for value in safe_directories)+ env["GIT_CONFIG_COUNT"] = str(len(overrides))+ for idx, (key, value) in enumerate(overrides):env[f"GIT_CONFIG_KEY_{idx}"] = keyenv[f"GIT_CONFIG_VALUE_{idx}"] = valuereturn envdiff --git a/tests/hermes_cli/test_noninteractive_git.py b/tests/hermes_cli/test_noninteractive_git.pyindex a3e0588965f..5054c984972 100644--- a/tests/hermes_cli/test_noninteractive_git.py+++ b/tests/hermes_cli/test_noninteractive_git.py@@ -97,6 +97,86 @@ 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_ssh_host_key_prompts_fail_closed(self):"""core.sshCommand is pinned to BatchMode ssh (#104591).