The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(env): load an unreadable profile .env as absent, with a warning
emozilla26f6f63579a9
diff --git a/hermes_cli/config.py b/hermes_cli/config.pyindex 74af83c9f4a..00ac5bb97d9 100644--- a/hermes_cli/config.py+++ b/hermes_cli/config.py@@ -2767,18 +2767,18 @@ def save_env_value_secure(key: str, value: str) -> dict[str, Any]:def reload_env() -> int:- """Re-read ~/.hermes/.env into os.environ; returns count of vars changed.- Removes deleted vars only when known to Hermes (OPTIONAL_ENV_VARS and _EXTRA_ENV_KEYS) so- unrelated environment is never clobbered."""+ """Re-read ~/.hermes/.env into os.environ; returns count of vars changed. Removes deleted vars only when+ known to Hermes (OPTIONAL_ENV_VARS and _EXTRA_ENV_KEYS), and none while the .env exists but is unreadable."""+ from hermes_cli.env_loader import dotenv_unreadableenv_vars = load_env()count = 0for key, value in env_vars.items():if os.environ.get(key) != value:os.environ[key] = valuecount += 1- for key in (set(OPTIONAL_ENV_VARS) | _EXTRA_ENV_KEYS) - set(env_vars):- if key in os.environ:- del os.environ[key]+ known = set() if dotenv_unreadable(get_env_path()) else set(OPTIONAL_ENV_VARS) | _EXTRA_ENV_KEYS+ for key in known - set(env_vars):+ if os.environ.pop(key, None) is not None:count += 1return countdiff --git a/hermes_cli/env_loader.py b/hermes_cli/env_loader.pyindex cf8777bf903..fa153d6f03a 100644--- a/hermes_cli/env_loader.py+++ b/hermes_cli/env_loader.py@@ -29,6 +29,7 @@ _CREDENTIAL_SUFFIXES = ("_API_KEY", "_TOKEN", "_SECRET", "_KEY")_WARNED_KEYS: set[str] = set() # credential names already given the non-ASCII warning_WARNED_UTF32_PATHS: set[str] = set() # .env paths already given the UTF-32 refuse-to-mangle warning_SCOPED_SKIP_LOGGED: set[str] = set() # routed profile homes whose multiplex dotenv skip was logged+_WARNED_UNREADABLE_PATHS: set[str] = set() # unreadable profile .env paths already given the warning# env-var name → source label ("bitwarden", …) for externally injected credentials; setup / `hermes# model` tell users WHERE a key came from when .env lacks it.@@ -618,6 +619,36 @@ def _sanitize_env_file_if_needed(path: Path) -> None:pass # best-effort — don't block gateway startup+def dotenv_unreadable(path: Path) -> bool:+ """True when *path* exists but this process may not read it."""+ try:+ with open(path, "rb"):+ return False+ except PermissionError:+ return True+ except OSError: # missing, or a failure that is not a refusal+ return False+++def _load_user_dotenv(path: Path, *, load_pass: int) -> bool:+ """Load the profile ``.env``; False when it exists but cannot be read and managed scope pins+ ``terminal.backend``. A sandbox launcher withholds the file, passes the keys it allows in as+ environment and pins the backend. Without that pin the ``PermissionError`` propagates: the file may+ be the only place the backend is set, and skipping it would run terminal commands on the host."""+ try:+ _load_dotenv_with_fallback(path, override=True, load_pass=load_pass)+ except PermissionError:+ from hermes_cli import managed_scope++ if managed_scope.pinned_terminal_backend() is None:+ raise+ if str(path) not in _WARNED_UNREADABLE_PATHS:+ _WARNED_UNREADABLE_PATHS.add(str(path))+ logger.warning("Cannot read %s; managed scope pins terminal.backend, so it loads as absent", path)+ return False+ return True++def load_hermes_dotenv(*,hermes_home: str | os.PathLike | None = None,@@ -682,8 +713,7 @@ def load_hermes_dotenv(if project_env_path and project_env_path.exists():_sanitize_env_file_if_needed(project_env_path)- if user_env.exists():- _load_dotenv_with_fallback(user_env, override=True, load_pass=load_pass)+ if user_env.exists() and _load_user_dotenv(user_env, load_pass=load_pass):loaded.append(user_env)_clear_known_keys_missing_from_dotenv(user_env) # mirrors reload_env(): inherited keys must not leak@@ -695,7 +725,7 @@ def load_hermes_dotenv(_load_dotenv_with_fallback(op_env, override=False, load_pass=load_pass)if project_env_path and project_env_path.exists():- _load_dotenv_with_fallback(project_env_path, override=not loaded, load_pass=load_pass)+ _load_dotenv_with_fallback(project_env_path, override=not user_env.exists(), load_pass=load_pass)loaded.append(project_env_path)# The override=True loads above wrote the raw .env line (``__BITWARDEN_MANAGED__`` placeholder, stalediff --git a/hermes_cli/managed_scope.py b/hermes_cli/managed_scope.pyindex 78d03f4b2fe..a00ac0630d4 100644--- a/hermes_cli/managed_scope.py+++ b/hermes_cli/managed_scope.py@@ -178,3 +178,11 @@ def is_key_managed(dotted_key: str) -> bool:def is_env_managed(name: str) -> bool:"""True if the env var name is pinned by the managed .env layer."""return name in load_managed_env()+++def pinned_terminal_backend() -> Optional[str]:+ """The non-empty ``terminal.backend`` the managed config pins, or None. An empty or null value+ names no backend to run, so it pins nothing."""+ terminal = apply_managed_overlay({}).get("terminal")+ backend = terminal.get("backend") if isinstance(terminal, dict) else None+ return (backend.strip() or None) if isinstance(backend, str) else Nonediff --git a/tests/hermes_cli/test_env_loader_unreadable.py b/tests/hermes_cli/test_env_loader_unreadable.pynew file mode 100644index 00000000000..f34f02607d2--- /dev/null+++ b/tests/hermes_cli/test_env_loader_unreadable.py@@ -0,0 +1,134 @@+"""A profile .env that exists but cannot be read, as a sandbox launcher leaves it.++The launcher withholds the profile's .env, passes the keys it allows in as environment and pins+``terminal.backend`` through managed scope. Under that pin the file loads as absent, and neither a+project .env nor ``/reload`` may replace or remove the launcher's keys. Without the pin the read error+still stops the load.+"""++import builtins+import io+import logging+import os+from pathlib import Path++import pytest++from hermes_cli import managed_scope+from hermes_cli.env_loader import load_hermes_dotenv+++def _deny_reads(monkeypatch, path: Path) -> None:+ """Make *path* exist but refuse every read, as Windows does for a file a sandbox denies."""+ denied = os.path.abspath(path)+ real_open = io.open++ def guarded_open(file, *args, **kwargs):+ if isinstance(file, (str, os.PathLike)) and os.path.abspath(file) == denied:+ raise PermissionError(13, "Access is denied", os.fspath(file))+ return real_open(file, *args, **kwargs)++ monkeypatch.setattr(io, "open", guarded_open)+ monkeypatch.setattr(builtins, "open", guarded_open)+++def managed_dir(tmp_path, monkeypatch):+ md = tmp_path / "managed"+ md.mkdir()+ monkeypatch.setenv("HERMES_MANAGED_DIR", str(md))+ managed_scope.invalidate_managed_cache()+ yield md+ managed_scope.invalidate_managed_cache()+++def _write_managed(md: Path, body: str) -> None:+ (md / "config.yaml").write_text(body, encoding="utf-8")+ managed_scope.invalidate_managed_cache()+++def pinned(managed_dir):+ _write_managed(managed_dir, "terminal:\n backend: busybox\n")+ return managed_dir+++def _profile(tmp_path: Path) -> tuple[Path, Path]:+ home = tmp_path / "hermes"+ home.mkdir()+ env_file = home / ".env"+ env_file.write_text("OPENAI_API_KEY=from-file\n", encoding="utf-8")+ return home, env_file+++def test_unreadable_user_env_loads_as_absent_under_a_pinned_backend(tmp_path, monkeypatch, caplog, pinned):+ home, env_file = _profile(tmp_path)+ monkeypatch.setenv("OPENAI_API_KEY", "from-launcher")+ monkeypatch.setenv("HERMES_ACP_AUTH_METHOD", "from-launcher") # a readable .env clears it when unset there+ _deny_reads(monkeypatch, env_file)++ with caplog.at_level(logging.WARNING, logger="hermes_cli.env_loader"):+ for _ in range(3): # gateways reload the .env every turn+ assert load_hermes_dotenv(hermes_home=home) == []++ assert os.environ["OPENAI_API_KEY"] == "from-launcher"+ assert os.environ["HERMES_ACP_AUTH_METHOD"] == "from-launcher"+ warnings = [r for r in caplog.records if str(env_file) in r.getMessage()]+ assert len(warnings) == 1++[email protected]("managed_yaml", [+ None,+ "terminal:\n timeout: 5\n",+ "terminal:\n backend:\n",+ "terminal:\n backend: ''\n",+ "terminal:\n backend: ' '\n",+])+def test_unreadable_user_env_raises_without_a_pinned_backend(tmp_path, monkeypatch, managed_dir, managed_yaml):+ """The file may be the only place the backend is set; skipping it would run commands on the host."""+ if managed_yaml is not None:+ _write_managed(managed_dir, managed_yaml)+ home, env_file = _profile(tmp_path)+ _deny_reads(monkeypatch, env_file)++ with pytest.raises(PermissionError):+ load_hermes_dotenv(hermes_home=home)+++def test_project_env_does_not_replace_launcher_keys(tmp_path, monkeypatch, pinned):+ home, env_file = _profile(tmp_path)+ project_env = tmp_path / "project.env"+ project_env.write_text("OPENAI_API_KEY=from-project\nLAB_PROJECT_ONLY=from-project\n", encoding="utf-8")+ monkeypatch.setenv("OPENAI_API_KEY", "from-launcher")+ monkeypatch.setenv("LAB_PROJECT_ONLY", "unset at teardown")+ monkeypatch.delenv("LAB_PROJECT_ONLY")+ _deny_reads(monkeypatch, env_file)++ assert load_hermes_dotenv(hermes_home=home, project_env=project_env) == [project_env]++ assert os.environ["OPENAI_API_KEY"] == "from-launcher"+ assert os.environ["LAB_PROJECT_ONLY"] == "from-project"+++def test_reload_keeps_known_keys_when_user_env_is_unreadable(monkeypatch):+ from hermes_cli.config import get_env_path, reload_env++ env_file = get_env_path()+ env_file.write_text("OPENAI_API_KEY=from-file\n", encoding="utf-8")+ monkeypatch.setenv("OPENAI_API_KEY", "from-launcher")+ _deny_reads(monkeypatch, env_file)++ assert reload_env() == 0+ assert os.environ["OPENAI_API_KEY"] == "from-launcher"+++def test_reload_still_removes_keys_a_readable_env_dropped(monkeypatch):+ from hermes_cli.config import get_env_path, reload_env++ get_env_path().write_text("ANTHROPIC_API_KEY=from-file\n", encoding="utf-8")+ monkeypatch.setenv("OPENAI_API_KEY", "stale")+ monkeypatch.setenv("ANTHROPIC_API_KEY", "stale")++ assert reload_env() == 2+ assert "OPENAI_API_KEY" not in os.environ+ assert os.environ["ANTHROPIC_API_KEY"] == "from-file"diff --git a/website/docs/user-guide/managed-scope.md b/website/docs/user-guide/managed-scope.mdindex 46f9654477f..6a10e285c0c 100644--- a/website/docs/user-guide/managed-scope.md+++ b/website/docs/user-guide/managed-scope.md@@ -90,6 +90,11 @@ usual "an environment variable overrides config.yaml" rule, and it applies onlyto the specific keys the managed layer specifies.:::+When the managed `config.yaml` pins a non-empty `terminal.backend`, a profile+`.env` that exists but cannot be read (a sandbox launcher withholds it and+passes the keys as environment) loads as absent with a warning; without that+pin the read error still stops Hermes.+## Seeing what's managed```bash