The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(env_loader): isolate external-secret snapshots per HERMES_HOME (#74283)
Tranquil-Flow303d8391335e
diff --git a/hermes_cli/env_loader.py b/hermes_cli/env_loader.pyindex 887baeb357d..ac8b0ba72ee 100644--- a/hermes_cli/env_loader.py+++ b/hermes_cli/env_loader.py@@ -410,6 +410,13 @@ def load_hermes_dotenv(project_env_path = Path(project_env) if project_env else Noneload_pass = next(_DOTENV_PASSES) # one pass: later layers below see the earlier layers' output+ # Snapshot the values an external secret source (Bitwarden, 1Password, ...) already resolved for THIS+ # home on an earlier load. load_dotenv(override=True) below would write the raw .env placeholder+ # (``__BITWARDEN_MANAGED__``) or a stale token back over them, and _apply_external_secret_sources() is a+ # once-per-home no-op (``_APPLIED_HOMES``), so the clobber would stick for the life of the process+ # (#74265). Per-home on purpose: a process-global snapshot would leak profile A's secrets into B.+ protected_secret_values = get_secret_source_values(home_path)+if user_env.exists(): # normalize formatting / strip NULs before parsing_sanitize_env_file_if_needed(user_env)if project_env_path and project_env_path.exists():@@ -431,6 +438,12 @@ def load_hermes_dotenv(_load_dotenv_with_fallback(project_env_path, override=not loaded, load_pass=load_pass)loaded.append(project_env_path)+ # Undo the dotenv clobber of external-source secrets before the (no-op on reload) source pass. Managed+ # scope, applied last with override=True, still beats a source value on purpose.+ for name, value in protected_secret_values.items():+ if os.environ.get(name) != value:+ os.environ[name] = value+# External sources are skipped for the updater (dotenv + managed env still load): ``update`` must not# import optional secret-manager libs (Bitwarden → cryptography → _rust.pyd) into the process replacing# that env on Windows, and a fresh retry after a deferred dependency install would otherwise make thediff --git a/tests/agent/test_env_loader_reload_restore.py b/tests/agent/test_env_loader_reload_restore.pynew file mode 100644index 00000000000..5efec89c10d--- /dev/null+++ b/tests/agent/test_env_loader_reload_restore.py@@ -0,0 +1,80 @@+"""load_hermes_dotenv() reloads must not clobber values an external secret source resolved (#74265).++The gateway module import, per-turn reloads and cron fires all call ``load_hermes_dotenv()`` again;+``load_dotenv(override=True)`` writes the raw ``.env`` placeholder back and the once-per-home source+pass no longer re-applies, so without the restore the process authenticates with the placeholder.+"""++from __future__ import annotations++import os+import sys+from pathlib import Path++import pytest+++ROOT = Path(__file__).resolve().parents[2]+if str(ROOT) not in sys.path:+ sys.path.insert(0, str(ROOT))++from hermes_cli import env_loader # noqa: E402++[email protected](autouse=True)+def _fresh_state():+ from agent.secret_sources import registry as reg_module++ reg_module._reset_registry_for_tests()+ env_loader._SECRET_SOURCES.clear()+ env_loader.reset_secret_source_cache()+ yield+ reg_module._reset_registry_for_tests()+ env_loader._SECRET_SOURCES.clear()+ env_loader.reset_secret_source_cache()+++def _register_fake_source(values: dict[str, str], *, override_existing: bool):+ """One bulk source supplying ``values``; ``override_existing`` mirrors the config knob the real+ sources expose (Bitwarden defaults True, the command source False)."""+ from agent.secret_sources import registry as reg_module+ from agent.secret_sources.base import FetchResult, SecretSource++ class _Fake(SecretSource):+ name = "fakebulk"+ label = "Fake"+ shape = "bulk"+ override_existing_default = override_existing++ def fetch(self, cfg, home_path):+ result = FetchResult()+ result.secrets = dict(values)+ return result++ reg_module.register_source(_Fake(), replace=True)+++def _make_home(tmp_path: Path, monkeypatch, env_text: str) -> Path:+ home = tmp_path / ".hermes"+ home.mkdir()+ (home / "config.yaml").write_text("secrets:\n fakebulk:\n enabled: true\n", encoding="utf-8")+ (home / ".env").write_text(env_text, encoding="utf-8")+ monkeypatch.setenv("HERMES_HOME", str(home))+ monkeypatch.delenv("GLM_API_KEY", raising=False)+ return home+++def test_source_secret_survives_second_load_hermes_dotenv(tmp_path, monkeypatch):+ """#74265: a source that overrides .env (Bitwarden's default) resolves the ``__BITWARDEN_MANAGED__``+ placeholder on load 1; load 2 (gateway import / per-turn reload / cron fire) must keep the+ resolved value instead of writing the placeholder back."""+ home = _make_home(tmp_path, monkeypatch, "GLM_API_KEY=__BITWARDEN_MANAGED__\n")+ _register_fake_source({"GLM_API_KEY": "vault-value"}, override_existing=True)++ env_loader.load_hermes_dotenv(hermes_home=home)+ assert os.environ["GLM_API_KEY"] == "vault-value"++ env_loader.load_hermes_dotenv(hermes_home=home)+ assert os.environ["GLM_API_KEY"] == "vault-value", (+ "second load_hermes_dotenv() wrote the .env placeholder back over the source-resolved value"+ )