The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(security): match credential env names case-insensitively
beardthelionb534f4b8c8cd
diff --git a/tests/tools/test_docker_environment.py b/tests/tools/test_docker_environment.pyindex ce78514946c..b72f286ea7b 100644--- a/tests/tools/test_docker_environment.py+++ b/tests/tools/test_docker_environment.py@@ -929,6 +929,32 @@ def test_egress_enabled_does_not_reuse_pre_egress_container(monkeypatch):assert run_invocations, "egress-enabled containers require a fresh docker run"+def test_forward_env_collision_matches_case_insensitively():+ """docker_forward_env names resolve via os.getenv() on the host, which is+ case-insensitive on Windows — a case variant of an egress-protected name+ must still collide, or it injects the real credential past the token swap."""+ from tools.environments.docker_egress import check_forward_env_collisions++ with pytest.raises(RuntimeError, match="openai_api_key"):+ check_forward_env_collisions(["openai_api_key"], {"OPENAI_API_KEY"}, enforce=True)+ # Negative arm: an unrelated lowercase name is not flagged.+ check_forward_env_collisions(["my_own_key"], {"OPENAI_API_KEY"}, enforce=True)+++def test_extra_args_collision_matches_case_insensitively():+ """``-e NAME`` resolves NAME in the host env (case-insensitive on Windows),+ so a variant spelling must collide with the critical set too."""+ from tools.environments.docker_egress import _extra_args_egress_collisions++ critical = {"OPENAI_API_KEY", "HTTPS_PROXY"}+ assert _extra_args_egress_collisions(+ ["-e", "openai_api_key=sk-real"], critical) == ["openai_api_key"]+ assert _extra_args_egress_collisions(+ ["--env=HtTpS_PrOxY=http://evil"], critical) == ["HtTpS_PrOxY"]+ # Negative arm: unrelated names pass.+ assert _extra_args_egress_collisions(["-e", "MY_OWN_KEY=x"], critical) == []++def test_reuse_probe_format_is_podman_compatible(monkeypatch):"""Podman does not implement the Docker-only ``{{.Label "key"}}`` templatefunction — a reuse probe using it fails wholesale (``podman ps`` exitsdiff --git a/tests/tools/test_env_passthrough.py b/tests/tools/test_env_passthrough.pyindex 8ad562e3128..9a81e6558a8 100644--- a/tests/tools/test_env_passthrough.py+++ b/tests/tools/test_env_passthrough.py@@ -363,6 +363,66 @@ class TestTerminalIntegration:assert blocked_var not in resultassert "PATH" in result+ def test_passthrough_case_variant_of_blocklist_rejected(self):+ """A case-variant registration (``openai_api_key``) must be refused just+ like the canonical name: the remote-exec env builder resolves each+ registered name via ``os.getenv``, which is case-insensitive on Windows,+ so a variant would tunnel the real ``OPENAI_API_KEY`` value into+ SSH/Docker children: the same GHSA-rhgp-j443-p4rf primitive."""+ for var in ("openai_api_key", "OpenAi_Api_Key", "anthropic_api_key",+ "Aws_Bearer_Token_Bedrock"):+ register_env_passthrough([var])+ assert not is_env_passthrough(var), (+ f"{var} should be refused passthrough registration")++ def test_passthrough_case_variant_via_config_rejected(self, tmp_path, monkeypatch):+ """The config-based allowlist (terminal.env_passthrough) must refuse+ case variants of provider credentials on the same filter."""+ config = {"terminal": {"env_passthrough": ["openai_api_key", "MY_OWN_KEY"]}}+ config_path = tmp_path / "config.yaml"+ config_path.write_text(yaml.dump(config), encoding="utf-8")+ monkeypatch.setenv("HERMES_HOME", str(tmp_path))+ _ep_mod._config_passthrough.clear()++ assert not is_env_passthrough("openai_api_key")+ assert is_env_passthrough("MY_OWN_KEY")++ def test_passthrough_case_variant_never_reaches_remote_exec_env(self, monkeypatch):+ """Even if a case-variant name were present in the registered set, the+ remote env builder must not resolve it: on Windows ``os.getenv`` is+ case-insensitive, so ``openai_api_key`` would carry the real+ ``OPENAI_API_KEY`` into SSH/Docker exec envs."""+ from tools.environments import remote_common++ register_env_passthrough(["openai_api_key"])+ exec_env, _unset = remote_common.resolve_passthrough_env(set())+ assert not any(k.lower() == "openai_api_key" for k in exec_env)++ # Defense in depth, load-bearing on POSIX too: force the variant into+ # the registered set and set a real env entry under that spelling, so+ # os.getenv() resolves it and only the folded blocklist drops it.+ monkeypatch.setenv("openai_api_key", "sk-variant-value")+ monkeypatch.setenv("MY_OWN_KEY", "own-value")+ monkeypatch.setattr(+ "tools.env_passthrough.get_all_passthrough",+ lambda: {"openai_api_key", "MY_OWN_KEY"})+ exec_env, _unset = remote_common.resolve_passthrough_env(set())+ assert "openai_api_key" not in exec_env+ assert exec_env.get("MY_OWN_KEY") == "own-value"++ def test_passthrough_case_variant_never_reaches_execute_code_env(self):+ """The GHSA-rhgp-j443-p4rf path end to end: the variant registration+ is refused, so is_env_passthrough cannot carry the name past the+ execute_code scrub."""+ from tools.code_execution_env import _scrub_child_env++ register_env_passthrough(["openai_api_key"])+ child_env = _scrub_child_env(+ {"openai_api_key": "sk-real", "PATH": "/usr/bin"},+ is_passthrough=is_env_passthrough, is_windows=False)+ assert "openai_api_key" not in child_env+ assert child_env["PATH"] == "/usr/bin"+def test_passthrough_cannot_override_internal_dynamic_secret(self):"""A skill must NOT be able to register dynamically-named Hermessecrets (AUXILIARY_*_API_KEY / _BASE_URL, GATEWAY_RELAY_* auth) asdiff --git a/tests/tools/test_hermes_subprocess_env.py b/tests/tools/test_hermes_subprocess_env.pyindex b3381a50cb4..97c1dad12ec 100644--- a/tests/tools/test_hermes_subprocess_env.py+++ b/tests/tools/test_hermes_subprocess_env.py@@ -77,6 +77,16 @@ class TestStripByDefault:result = _build()assert result.get("PYTHONUTF8") == "1"+ def test_case_variant_keys_stripped_by_default(self):+ """Credential names match case-insensitively: on Windows the env block+ is case-insensitive, so a lowercase-stored ``openai_api_key`` IS the+ real credential, and both tiers must strip it."""+ result = _build({"openai_api_key": "sk-lower", "Anthropic_Api_Key": "ant-mixed",+ "gh_token": "ghp-lower", "telegram_bot_token": "bot-lower"})+ for var in ("openai_api_key", "Anthropic_Api_Key", "gh_token",+ "telegram_bot_token"):+ assert var not in result, f"{var} (case variant) leaked"+class TestInheritCredentials:def test_provider_keys_preserved_when_inheriting(self):@@ -96,6 +106,15 @@ class TestInheritCredentials:for var in _PROVIDER_SAMPLE:assert var in result+ def test_case_variant_provider_keys_preserved_when_inheriting(self):+ """inherit_credentials=True keeps provider creds under any casing+ (the fold widens only the default strip), while Tier-1 variants still+ strip: a lowercase-stored ``gh_token`` is GH_TOKEN on Windows."""+ result = _build({"openai_api_key": "sk-lower", "gh_token": "ghp-lower"},+ inherit_credentials=True)+ assert result.get("openai_api_key") == "sk-lower"+ assert "gh_token" not in result+def test_pythonutf8_set_when_inheriting(self):assert _build(inherit_credentials=True).get("PYTHONUTF8") == "1"diff --git a/tests/tools/test_local_env_blocklist.py b/tests/tools/test_local_env_blocklist.pyindex 4fefee77809..fc61e790d02 100644--- a/tests/tools/test_local_env_blocklist.py+++ b/tests/tools/test_local_env_blocklist.py@@ -121,6 +121,46 @@ class TestProviderEnvBlocklist:"AWS_BEARER_TOKEN_BEDROCK leaked into subprocess env (see #32314)")+ def test_case_variant_blocked_vars_are_stripped(self):+ """A blocklisted credential stored under variant casing must not reach+ subprocess env: on Windows the environment block is case-insensitive,+ so a lowercase-stored ``openai_api_key`` IS the real credential."""+ leaked_vars = {+ "openai_api_key": "sk-fake-key",+ "Anthropic_Api_Key": "ant-fake-key",+ "aws_bearer_token_bedrock": "bedrock-bearer-secret",+ }+ result_env = _run_with_env(extra_os_env=leaked_vars)++ for var in leaked_vars:+ assert var not in result_env, (+ f"{var} (case variant of a blocklisted credential) leaked"+ )++ def test_strip_launch_profile_env_folds_case(self, monkeypatch, tmp_path):+ """The routed-profile residue strip must match names the way the+ platform resolves them: on Windows a lowercase-stored+ ``openai_api_key`` IS the launch profile's credential and must not+ ride into a sibling profile's child env."""+ from tools.environments.local import strip_launch_profile_env++ launch = tmp_path / "launch"+ launch.mkdir()+ (launch / ".env").write_text(+ "OPENAI_API_KEY=sk-launch\nTERMINAL_ENV={}\n", encoding="utf-8")+ target = tmp_path / "target"+ target.mkdir()+ monkeypatch.setenv("HERMES_HOME", str(launch))++ env = {"openai_api_key": "sk-launch", "terminal_env": "{}",+ "PATH": "/usr/bin:/bin", "MY_OWN_KEY": "keep"}+ strip_launch_profile_env(env, target)++ assert "openai_api_key" not in env+ assert "terminal_env" not in env+ assert env["PATH"] == "/usr/bin:/bin"+ assert env["MY_OWN_KEY"] == "keep"+def test_vertex_credentials_path_is_stripped(self):"""The Vertex AI service-account JSON path must not leak intosubprocesses, even though it is filesystem path metadata rather@@ -372,6 +412,36 @@ class TestTerminalFirstPartyPlatformEnv:assert var not in run_env, f"{var} leaked into non-Buzz foreground env"assert var not in sanitized, f"{var} leaked into non-Buzz background env"+ def test_case_variant_buzz_var_carveout(self, monkeypatch):+ """The first-party prefix check folds case symmetrically with the+ blocklist: on Windows a lowercase-stored ``buzz_private_key`` IS+ BUZZ_PRIVATE_KEY, so under Buzz context it must still reach terminal+ children, and without context it stays stripped."""+ from gateway.session_context import _SESSION_PLATFORM+ from tools.environments.local import _make_run_env, _sanitize_subprocess_env++ monkeypatch.delenv("BUZZ_MANAGED_AGENT", raising=False)+ monkeypatch.setenv("buzz_private_key", "nsec1faketestkey")+ buzz_vars = {"buzz_private_key": "nsec1faketestkey"}++ token = _SESSION_PLATFORM.set("buzz")+ try:+ run_env = _make_run_env({})+ sanitized = _sanitize_subprocess_env({**buzz_vars, "HOME": "/home/user"})+ finally:+ _SESSION_PLATFORM.reset(token)+ assert run_env.get("buzz_private_key") == "nsec1faketestkey"+ assert sanitized.get("buzz_private_key") == "nsec1faketestkey"++ token = _SESSION_PLATFORM.set("telegram")+ try:+ run_env = _make_run_env({})+ sanitized = _sanitize_subprocess_env({**buzz_vars, "HOME": "/home/user"})+ finally:+ _SESSION_PLATFORM.reset(token)+ assert "buzz_private_key" not in run_env+ assert "buzz_private_key" not in sanitized+def test_session_platform_buzz_enables_carveout(self, monkeypatch):"""A live gateway session whose platform is ``buzz`` gets thecarve-out even without BUZZ_MANAGED_AGENT (native buzz gatewaydiff --git a/tests/tui_gateway/test_served_profile_child_env.py b/tests/tui_gateway/test_served_profile_child_env.pyindex 80e38efe168..26ad0b4527a 100644--- a/tests/tui_gateway/test_served_profile_child_env.py+++ b/tests/tui_gateway/test_served_profile_child_env.py@@ -130,3 +130,21 @@ def test_helper_children_resolve_secrets_through_the_served_profile(mux_homes):seen = _child_view(browser_env)_assert_is_b_env(seen, b, with_secrets=False) # provider tier stays scrubbed for the browserassert seen["FIRECRAWL_API_KEY"] == "b-fc" # the passthrough key is B's, not the launch profile's+++def test_case_variant_launch_residue_stripped_for_served_child(mux_homes, monkeypatch):+ """On Windows the env block is case-insensitive, so launch residue stored+ under variant casing (``firecrawl_api_key`` IS FIRECRAWL_API_KEY,+ ``hermes_model`` IS HERMES_MODEL) must not ride into a routed profile's+ child env — caught by the folded credential scrub and residue strip."""+ from tools.environments.local import served_profile_child_env++ a, b = mux_homes+ monkeypatch.setenv("firecrawl_api_key", "a-fc-variant")+ monkeypatch.setenv("hermes_model", "a-model-variant")++ env = served_profile_child_env(target_home=b)++ assert "firecrawl_api_key" not in env+ assert "hermes_model" not in env+ assert env["HERMES_HOME"] == str(b)diff --git a/tools/env_passthrough.py b/tools/env_passthrough.pyindex e5fd6847fd3..ee8678c9827 100644--- a/tools/env_passthrough.py+++ b/tools/env_passthrough.py@@ -44,13 +44,16 @@ def _is_hermes_provider_credential(name: str) -> bool:registerable. Fails closed when the blocklist cannot be imported."""try:from tools.environments.local_env_policy import (- _HERMES_PROVIDER_ENV_BLOCKLIST, _is_hermes_internal_secret)+ _is_hermes_internal_secret, _is_provider_env_blocklisted)except Exception as e:logger.warning("env passthrough: provider credential blocklist import failed; ""failing closed and refusing passthrough registration for %r: %s", name, e)return True- return _is_hermes_internal_secret(name) or name in _HERMES_PROVIDER_ENV_BLOCKLIST+ # Case-folded membership too: the remote-exec env builder resolves each+ # registered name via os.getenv(), which is case-insensitive on Windows, so+ # ``openai_api_key`` would tunnel the real OPENAI_API_KEY into children.+ return _is_hermes_internal_secret(name) or _is_provider_env_blocklisted(name)def register_env_passthrough(var_names: Iterable[str]) -> None:diff --git a/tools/environments/docker_egress.py b/tools/environments/docker_egress.pyindex 37344ce5981..895a04a9ed5 100644--- a/tools/environments/docker_egress.py+++ b/tools/environments/docker_egress.py@@ -180,6 +180,10 @@ def _env_flag_value(arg: str) -> tuple[str, str | None] | None:def _extra_args_egress_collisions(extra_args: list[str], critical_names: set[str]) -> list[str]:"""Return docker_extra_args entries that can override egress controls."""+ # Folded membership: ``-e NAME`` resolves NAME in the host env, which is+ # case-insensitive on Windows — ``-eopenai_api_key`` would inject the real+ # credential past the token swap.+ critical_folded = {n.upper() for n in critical_names}collisions: list[str] = []i = 0while i < len(extra_args):@@ -198,7 +202,7 @@ def _extra_args_egress_collisions(extra_args: list[str], critical_names: set[strvalue = inline_value if inline_value is not None else (extra_args[i + 1] if i + 1 < len(extra_args) else "")name = value.split("=", 1)[0]- if name in critical_names:+ if name.upper() in critical_folded:collisions.append(name)i += 1 if inline_value is not None else 2continue@@ -217,7 +221,11 @@ def _collision_guard(msg: str, *, enforce: bool, remedy: str, consequence: str)def check_forward_env_collisions(forward_env: list[str], critical: set[str], enforce: bool) -> None:- collisions = sorted(k for k in forward_env if k in critical)+ # Folded membership: forward_env names are resolved via os.getenv() on the+ # host, which is case-insensitive on Windows — ``openai_api_key`` would+ # inject the real credential into the container under a variant name.+ critical_folded = {k.upper() for k in critical}+ collisions = sorted(k for k in forward_env if k.upper() in critical_folded)if collisions:_collision_guard(f"docker_forward_env would inject real egress-protected variables {collisions}",diff --git a/tools/environments/local.py b/tools/environments/local.pyindex f75bcabc75a..1cae359460a 100644--- a/tools/environments/local.py+++ b/tools/environments/local.py@@ -21,8 +21,8 @@ from tools.environments.base import BaseEnvironmentfrom tools.environments.base_output import _pipe_stdinfrom hermes_cli._subprocess_compat import windows_hide_flagsfrom tools.environments.local_env_policy import (- _ALWAYS_STRIP_KEYS, _HERMES_PROVIDER_ENV_BLOCKLIST, _HERMES_PROVIDER_ENV_FORCE_PREFIX,- _is_hermes_internal_secret, _is_terminal_first_party_env,+ _ALWAYS_STRIP_KEYS, _HERMES_PROVIDER_ENV_FORCE_PREFIX,+ _is_hermes_internal_secret, _is_provider_env_blocklisted, _is_terminal_first_party_env,_matches_terminal_first_party_prefix, _plugin_terminal_env_strip_keys, strip_profile_gate_env)from tools.environments.local_gitbash_probe import (_bash_probe_details_cache, _bash_starts, _git_bash_aslr_help,@@ -244,6 +244,7 @@ def _filter_secret_env(from tools.env_passthrough import is_env_passthrough, resolve_passthrough_valueexcept Exception:is_env_passthrough, resolve_passthrough_value = (lambda _: False), (lambda _n, fb: fb)+ plugin_strip_folded = frozenset(k.upper() for k in plugin_strip)for key, value in items.items():if key.startswith(_HERMES_PROVIDER_ENV_FORCE_PREFIX):if not unwrap_force:@@ -252,11 +253,11 @@ def _filter_secret_env(if not _is_hermes_internal_secret(key):out[key] = valuecontinue- if _is_hermes_internal_secret(key) or key in plugin_strip:+ if _is_hermes_internal_secret(key) or key.upper() in plugin_strip_folded:continuefirst_party = _is_terminal_first_party_env(key)passthrough = is_env_passthrough(key)- if key in _HERMES_PROVIDER_ENV_BLOCKLIST and not (passthrough or first_party):+ if _is_provider_env_blocklisted(key) and not (passthrough or first_party):continueif passthrough and not first_party:value = resolve_passthrough_value(key, value)@@ -319,11 +320,13 @@ def hermes_subprocess_env(*, inherit_credentials: bool = False) -> dict[str, strdef _scrub_credentials(env: dict, *, inherit_credentials: bool) -> dict:"""Tier 1 (always) and, unless ``inherit_credentials``, Tier 2 provider/tool credentials, in place."""- strip = _ALWAYS_STRIP_KEYS | _plugin_terminal_env_strip_keys()- if not inherit_credentials:- strip |= _HERMES_PROVIDER_ENV_BLOCKLIST+ # Credential names fold to uppercase for membership: on Windows the env block+ # itself is case-insensitive, so a lowercase-stored ``gh_token`` IS GH_TOKEN.+ strip_folded = frozenset(k.upper() for k in (_ALWAYS_STRIP_KEYS | _plugin_terminal_env_strip_keys()))for key in list(env):- if (key in strip or key.startswith(_HERMES_PROVIDER_ENV_FORCE_PREFIX)+ if (key.upper() in strip_folded+ or (not inherit_credentials and _is_provider_env_blocklisted(key))+ or key.startswith(_HERMES_PROVIDER_ENV_FORCE_PREFIX)or _is_hermes_internal_secret(key)):del env[key]return env@@ -424,9 +427,16 @@ def strip_launch_profile_env(env: dict, target_home: "str | Path | None" = None)return envlaunch_home = get_process_hermes_home()from hermes_cli.config import TERMINAL_CONFIG_ENV_MAP- for key in set(load_env_file(launch_home / ".env")) | set(TERMINAL_CONFIG_ENV_MAP.values()):- if not _is_global_env(key) or key.startswith("TERMINAL_"):- env.pop(key, None)+ # Folded strip: on Windows the env block is case-insensitive, so residue+ # stored under a variant casing is the same variable and must go too. The+ # selection folds the same way so a lowercase ``path`` in .env is still+ # recognized as a global name and left alone.+ residue_names = {+ key.upper() for key in+ set(load_env_file(launch_home / ".env")) | set(TERMINAL_CONFIG_ENV_MAP.values())+ if not _is_global_env(key.upper()) or key.upper().startswith("TERMINAL_")}+ for key in [k for k in env if k.upper() in residue_names]:+ del env[key]# Authorization gates are the one residue a name list cannot see: a unit-file ``Environment=``# or an operator export never appears in the launch ``.env``, the secret scrub ignores# non-credentials, and the target's own ``.env`` rarely defines the key to overwrite it (#113270).diff --git a/tools/environments/local_env_policy.py b/tools/environments/local_env_policy.pyindex f392a8c5386..fdcad79f5b9 100644--- a/tools/environments/local_env_policy.py+++ b/tools/environments/local_env_policy.py@@ -81,6 +81,16 @@ def _build_provider_env_blocklist() -> frozenset:_HERMES_PROVIDER_ENV_BLOCKLIST = _build_provider_env_blocklist()++def _is_provider_env_blocklisted(name: str) -> bool:+ """``name`` is a blocklisted provider/tool credential, matched the way the+ platform's environment resolves names: exact plus case-folded. On Windows+ the environment block is case-insensitive, so ``openai_api_key`` IS+ ``OPENAI_API_KEY``; consistent with ``_is_hermes_internal_secret``, which+ already folds (``key.upper()``)."""+ return (name in _HERMES_PROVIDER_ENV_BLOCKLIST+ or name.upper() in _HERMES_PROVIDER_ENV_BLOCKLIST)+# First-party platform credentials (``BUZZ_*``, driving the platform-mandated ``buzz``# CLI) carved out of the TERMINAL scrub only (``_make_run_env``,# ``_sanitize_subprocess_env``); execute_code, hermes_subprocess_env, docker and@@ -122,8 +132,11 @@ _TERMINAL_FIRST_PARTY_ENV_PREFIXES = ("BUZZ_",)def _matches_terminal_first_party_prefix(name: str) -> bool:"""Pure name check (``BUZZ_*``), regardless of session context — the snapshot- exclusion must stay conservative even when the carve-out is inactive."""- return name.startswith(_TERMINAL_FIRST_PARTY_ENV_PREFIXES)+ exclusion must stay conservative even when the carve-out is inactive.+ Case-folded: on Windows the env block is case-insensitive, so a+ lowercase-stored ``buzz_private_key`` IS the credential; it needs the+ carve-out (and the snapshot exclusion) just like the canonical name."""+ return name.upper().startswith(_TERMINAL_FIRST_PARTY_ENV_PREFIXES)def _buzz_terminal_context_active() -> bool:diff --git a/tools/environments/remote_common.py b/tools/environments/remote_common.pyindex 537cc0c5181..3a81561aebc 100644--- a/tools/environments/remote_common.py+++ b/tools/environments/remote_common.py@@ -8,7 +8,7 @@ import subprocessfrom typing import Callable, Iterablefrom tools.environments.base_session_env import _SHELL_ENV_NAME_RE-from tools.environments.local_env_policy import _HERMES_PROVIDER_ENV_BLOCKLIST, _is_hermes_internal_secret+from tools.environments.local_env_policy import _is_hermes_internal_secret, _is_provider_env_blocklisteddef load_hermes_env_vars() -> dict[str, str]:@@ -44,7 +44,8 @@ def resolve_passthrough_env(explicit_forward: Iterable[str] = (),except Exception:passimplicit_forward = {k for k in passthrough_keys if not _is_hermes_internal_secret(k)}- forward_keys = set(explicit_forward) | (implicit_forward - _HERMES_PROVIDER_ENV_BLOCKLIST)+ forward_keys = set(explicit_forward) | {+ k for k in implicit_forward if not _is_provider_env_blocklisted(k)}hermes_env = hermes_env_loader() if forward_keys else {}exec_env: dict[str, str] = {}unset_names: set[str] = set()