The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(config): a refused .env write fails instead of reporting success and half-applying
John Paul Soliva2981ca24da43
diff --git a/hermes_cli/callbacks.py b/hermes_cli/callbacks.pyindex c3a9c974226..9a36c0ea5e4 100644--- a/hermes_cli/callbacks.py+++ b/hermes_cli/callbacks.py@@ -38,7 +38,11 @@ def _secret_result(var_name: str, value: str) -> dict:if not value:cprint(f"\n{_DIM} ⏭ Secret entry skipped{_RST}")return _skipped(var_name, "cancelled", "Secret setup was skipped.")- stored = save_env_value_secure(var_name, value)+ try:+ stored = save_env_value_secure(var_name, value)+ except ValueError as exc: # a locked or denylisted key: the skill setup only logs it, so say why here+ cprint(f"\n ✗ {exc}")+ raisecprint(f"\n{_DIM} ✓ Stored secret in {display_hermes_home()}/.env as {var_name}{_RST}")return {**stored,diff --git a/hermes_cli/config.py b/hermes_cli/config.pyindex ea90e05ec08..da860f6d9bf 100644--- a/hermes_cli/config.py+++ b/hermes_cli/config.py@@ -2661,20 +2661,34 @@ def _publish_env_value(key: str, value: Optional[str]) -> None:target[key] = value-def _env_write_blocked(key: str, action: str) -> bool:- """Shared write-lock check for ``.env`` writers; prints the refusal and returns True when blocked.+def env_write_refusal(key: str, action: str) -> Optional[str]:+ """The ``.env`` write-lock refusal for ``key``, or None when the write is allowed.Two distinct locks: ``is_managed()`` (package-manager install) and the managed *scope*(administrator-pinned env key — the managed .env wins at load anyway)."""if is_managed():- managed_error(f"{action} {key}")- return True-+ return format_managed_message(f"{action} {key}")if managed_scope.is_env_managed(key):- print(+ return (f"Cannot {action} {key}: it is managed by your administrator ({_managed_source('.env')}) "- f"and cannot be changed.", file=sys.stderr)- return True- return False+ "and cannot be changed.")+ return None+++def _env_write_blocked(key: str, action: str) -> bool:+ """Shared write-lock check for ``.env`` writers; prints the refusal and returns True when blocked."""+ refusal = env_write_refusal(key, action)+ if refusal:+ print(refusal, file=sys.stderr)+ return refusal is not None+++def require_env_writable(key: str, action: str) -> None:+ """Raise ``ValueError`` with the refusal when the ``.env`` write lock forbids ``key``.+ ``save_env_value`` / ``remove_env_value`` refuse by returning, which their caller cannot tell+ from success, so a writer that also touches config.yaml or the credential pool must ask first."""+ refusal = env_write_refusal(key, action)+ if refusal:+ raise ValueError(refusal)def _managed_source(filename: str):@@ -3544,7 +3558,10 @@ def set_config_value(key: str, value: str, force: bool = False):# Unified lifecycle: also rotates any config.yaml mirror of the old value so a stale# higher-precedence copy can't win (#62269).- save_provider_env_credential(key.upper(), value)+ try:+ save_provider_env_credential(key.upper(), value)+ except ValueError as exc:+ _exit_invalid(f"✗ {exc}")print(f"✓ Set {key} in {get_env_path()}")returnfrom hermes_cli.config_env_routing import is_env_setting_key, save_env_setting@@ -3711,7 +3728,11 @@ def unset_config_value(key: str):# See #51071.from hermes_cli.credential_lifecycle import remove_provider_env_credential- if not remove_provider_env_credential(key.upper()).get("found"):+ try:+ found = remove_provider_env_credential(key.upper()).get("found")+ except ValueError as exc:+ _exit_invalid(f"✗ {exc}")+ if not found:_exit_invalid(f"Config key not set: {key}")print(f"✓ Unset {key} from {get_env_path()}")return@@ -3719,7 +3740,11 @@ def unset_config_value(key: str):if is_env_setting_key(key):# Also drops a stale top-level config.yaml copy left by older `config set` runs (#111848).- if not remove_env_setting(key):+ try:+ found = remove_env_setting(key)+ except ValueError as exc:+ _exit_invalid(f"✗ {exc}")+ if not found:_exit_invalid(f"Config key not set: {key}")print(f"✓ Unset {key} from {get_env_path()}")returndiff --git a/hermes_cli/config_env_routing.py b/hermes_cli/config_env_routing.pyindex 9b4759571ec..8bbc6180b02 100644--- a/hermes_cli/config_env_routing.py+++ b/hermes_cli/config_env_routing.py@@ -57,16 +57,18 @@ def _drop_config_yaml_copies(key: str) -> bool:def save_env_setting(key: str, value: str) -> None:- from hermes_cli.config import save_env_value+ from hermes_cli.config import require_env_writable, save_env_value+ require_env_writable(key.upper(), "set")save_env_value(key.upper(), value)_drop_config_yaml_copies(key)def remove_env_setting(key: str) -> bool:"""Remove the ``.env`` entry and any stale ``config.yaml`` copy; False when neither existed."""- from hermes_cli.config import remove_env_value+ from hermes_cli.config import remove_env_value, require_env_writable+ require_env_writable(key.upper(), "remove")removed = remove_env_value(key.upper())return _drop_config_yaml_copies(key) or removeddiff --git a/hermes_cli/credential_lifecycle.py b/hermes_cli/credential_lifecycle.pyindex 17233914b73..caf027e8cfa 100644--- a/hermes_cli/credential_lifecycle.py+++ b/hermes_cli/credential_lifecycle.py@@ -176,8 +176,11 @@ def save_provider_env_credential(env_var: str, value: str) -> Dict[str, Any]:kept 401'ing until the user ran ``hermes auth add <provider> --type api-key`` separately. This makes theDesktop save's effect on disk match what ``hermes auth add`` does."""- from hermes_cli.config import load_env, save_env_value+ from hermes_cli.config import load_env, require_env_writable, save_env_value+ # A locked key must fail here: save_env_value's refusal returns like a success, and the mirror+ # scrub below would still move the new value into config.yaml.+ require_env_writable(env_var, "set")old_value = load_env().get(env_var)save_env_value(env_var, value)@@ -199,8 +202,10 @@ def save_provider_env_credential(env_var: str, value: str) -> Dict[str, Any]:def remove_provider_env_credential(env_var: str) -> Dict[str, Any]:"""Remove a credential from EVERY store: ``.env`` (and process env), env-seeded``credential_pool`` entries, model-cache rows, config.yaml mirrors of the same value."""- from hermes_cli.config import load_env, remove_env_value+ from hermes_cli.config import load_env, remove_env_value, require_env_writable+ # Before the pool prune and mirror scrub: a refused remove must not strip the other stores.+ require_env_writable(env_var, "remove")old_value = load_env().get(env_var)removed_from_env = remove_env_value(env_var)refs = purge_env_credential_references(env_var)diff --git a/hermes_cli/web_routers/config_env.py b/hermes_cli/web_routers/config_env.pyindex 887b50e6eb9..4735f76b0ec 100644--- a/hermes_cli/web_routers/config_env.py+++ b/hermes_cli/web_routers/config_env.py@@ -61,9 +61,10 @@ _CATEGORY_ORDER = [@contextlib.contextmanagerdef _env_write_errors(log_msg: str, *, http_passthrough: bool):"""``ValueError`` -> 400 with its message (save/remove_env_value reject- invalid names and denylisted keys — LD_PRELOAD, PATH, PYTHONPATH, …, and- the SPA needs the reason, not an opaque 500); anything else is logged and- becomes 500 "Internal server error"."""+ invalid names and denylisted keys — LD_PRELOAD, PATH, PYTHONPATH, …, the+ credential lifecycle rejects keys a managed install or administrator pins,+ and the SPA needs the reason, not an opaque 500); anything else is logged+ and becomes 500 "Internal server error"."""try:yieldexcept HTTPException:diff --git a/tests/hermes_cli/test_managed_scope_writeguard.py b/tests/hermes_cli/test_managed_scope_writeguard.pyindex dbc084cd07a..51f427e1712 100644--- a/tests/hermes_cli/test_managed_scope_writeguard.py+++ b/tests/hermes_cli/test_managed_scope_writeguard.py@@ -65,6 +65,149 @@ def test_save_env_value_managed_key_rejected(env_homes, capsys):assert "user.example" not in body+# ── refused .env writes must fail, not half-apply ────────────────────────────++# Runtime-constructed fake credentials (never literal key-shaped strings).+ADMIN_KEY = "sk-ds-" + "a" * 24+OLD_KEY = "sk-ds-" + "b" * 24+NEW_KEY = "sk-ds-" + "c" * 24+++def pinned_env(tmp_path, monkeypatch):+ """The administrator pins DEEPSEEK_API_KEY and TELEGRAM_HOME_CHANNEL; the user's own stores+ still hold an older key in .env, a config.yaml mirror of it, its env-seeded pool entry, and a+ stale top-level config.yaml copy of the channel."""+ import json++ import hermes_cli.config as cfg+ from hermes_cli import managed_scope++ home, managed = tmp_path / "home", tmp_path / "managed"+ home.mkdir()+ managed.mkdir()+ monkeypatch.setenv("HERMES_HOME", str(home))+ monkeypatch.setenv("HERMES_MANAGED_DIR", str(managed))+ (managed / ".env").write_text(+ f"DEEPSEEK_API_KEY={ADMIN_KEY}\nTELEGRAM_HOME_CHANNEL=111\n", encoding="utf-8")+ (home / ".env").write_text(+ f"DEEPSEEK_API_KEY={OLD_KEY}\nTELEGRAM_HOME_CHANNEL=222\n", encoding="utf-8")+ (home / "config.yaml").write_text(+ f"model:\n provider: deepseek\n default: deepseek-chat\n api_key: {OLD_KEY}\n"+ "TELEGRAM_HOME_CHANNEL: '333'\n", encoding="utf-8")+ (home / "auth.json").write_text(json.dumps({"credential_pool": {"deepseek": [{+ "id": "e1", "label": "env", "auth_type": "api_key", "priority": 0,+ "source": "env:DEEPSEEK_API_KEY", "access_token": OLD_KEY}]}}), encoding="utf-8")+ cfg._LOAD_CONFIG_CACHE.clear()+ cfg._RAW_CONFIG_CACHE.clear()+ cfg.invalidate_env_cache()+ managed_scope.invalidate_managed_cache()+ return home, _user_stores(home)+++def _user_stores(home):+ return {name: (home / name).read_text(encoding="utf-8") for name in (".env", "config.yaml", "auth.json")}+++def _assert_user_stores_untouched(home, before):+ assert _user_stores(home) == before++[email protected]("command, args", [+ pytest.param("set", ("DEEPSEEK_API_KEY", NEW_KEY), id="set-credential"),+ pytest.param("set", ("TELEGRAM_HOME_CHANNEL", "999"), id="set-env-setting"),+ pytest.param("unset", ("DEEPSEEK_API_KEY",), id="unset-credential"),+ pytest.param("unset", ("TELEGRAM_HOME_CHANNEL",), id="unset-env-setting"),+])+def test_config_set_unset_of_pinned_env_key_exits_nonzero_and_writes_nothing(pinned_env, capsys, command, args):+ from hermes_cli.config import set_config_value, unset_config_value++ home, before = pinned_env+ with pytest.raises(SystemExit) as exc:+ (set_config_value if command == "set" else unset_config_value)(*args)+ assert exc.value.code == 1+ out = capsys.readouterr()+ assert "managed by your administrator" in out.err+ assert "✓" not in out.out+ _assert_user_stores_untouched(home, before)++[email protected]("method", ["PUT", "DELETE"])[email protected]("lock, refusal", [+ pytest.param("scope", "managed by your administrator", id="managed-scope"),+ pytest.param("install", "managed by nixos", id="package-managed"),+])+def test_api_env_write_of_locked_key_is_refused_and_writes_nothing(pinned_env, monkeypatch, method, lock, refusal):+ from fastapi.testclient import TestClient++ from hermes_cli.web_server import _SESSION_TOKEN, app++ if lock == "install":+ monkeypatch.setenv("HERMES_MANAGED", "nixos")+ home, before = pinned_env+ body = {"key": "DEEPSEEK_API_KEY", **({"value": NEW_KEY} if method == "PUT" else {})}+ resp = TestClient(app).request(method, "/api/env", json=body, headers={"X-Hermes-Session-Token": _SESSION_TOKEN})+ assert resp.status_code == 400+ assert refusal in resp.json()["detail"]+ _assert_user_stores_untouched(home, before)+++_ANTHROPIC_ENV_VARS = ("ANTHROPIC_API_KEY", "ANTHROPIC_TOKEN", "CLAUDE_CODE_OAUTH_TOKEN")+++def anthropic_homes(tmp_path, monkeypatch):+ """A user home whose auth.json holds a manually added anthropic key, and an empty managed dir."""+ import json++ import hermes_cli.config as cfg+ from hermes_cli import managed_scope++ home, managed = tmp_path / "home", tmp_path / "managed"+ home.mkdir()+ managed.mkdir()+ monkeypatch.setenv("HERMES_HOME", str(home))+ monkeypatch.setenv("HERMES_MANAGED_DIR", str(managed))+ for name in _ANTHROPIC_ENV_VARS:+ monkeypatch.delenv(name, raising=False)+ (home / "auth.json").write_text(json.dumps({"credential_pool": {"anthropic": [{+ "id": "m1", "label": "manual", "auth_type": "api_key", "priority": 0,+ "source": "manual", "access_token": OLD_KEY}]}}), encoding="utf-8")++ def reload():+ cfg.invalidate_env_cache()+ managed_scope.invalidate_managed_cache()++ reload()+ return home, managed, reload+++def _disconnect(slug):+ from tui_gateway import server++ return server._methods["model.disconnect"](1, {"slug": slug})+++def test_disconnect_on_a_package_managed_install_still_clears_the_auth_store(anthropic_homes, monkeypatch):+ """The .env lock refuses every key on such an install, but a key that holds nothing is nothing to refuse."""+ import json++ home, _managed, _reload = anthropic_homes+ monkeypatch.setenv("HERMES_MANAGED", "nixos")+ resp = _disconnect("anthropic")+ assert resp.get("result", {}).get("disconnected") is True, resp+ assert "anthropic" not in json.loads((home / "auth.json").read_text(encoding="utf-8"))["credential_pool"]+++def test_disconnect_refuses_a_pinned_key_before_removing_any_other(anthropic_homes):+ home, managed, reload = anthropic_homes+ (managed / ".env").write_text(f"ANTHROPIC_TOKEN={ADMIN_KEY}\n", encoding="utf-8")+ (home / ".env").write_text(f"ANTHROPIC_API_KEY={OLD_KEY}\n", encoding="utf-8")+ reload()+ before = {name: (home / name).read_text(encoding="utf-8") for name in (".env", "auth.json")}+ resp = _disconnect("anthropic")+ assert "managed by your administrator" in resp.get("error", {}).get("message", ""), resp+ assert {name: (home / name).read_text(encoding="utf-8") for name in (".env", "auth.json")} == before# ── bulk save strips managed leaves ──────────────────────────────────────────diff --git a/tui_gateway/methods_complete.py b/tui_gateway/methods_complete.pyindex 9ab8ee3393e..863b7505458 100644--- a/tui_gateway/methods_complete.py+++ b/tui_gateway/methods_complete.py@@ -389,14 +389,24 @@ def _(rid, params: dict) -> dict:@_catch(5035)def _(rid, params: dict) -> dict:"""Remove all credentials (env keys AND OAuth/pool state) for provider ``slug``."""+ from hermes_cli import managed_scopefrom hermes_cli.auth import PROVIDER_REGISTRY, clear_provider_auth+ from hermes_cli.config import env_write_refusal, load_envfrom hermes_cli.credential_lifecycle import remove_provider_env_credentialif not (slug := (params.get("slug") or "").strip()):return _err(rid, 4001, "slug is required")pconfig = PROVIDER_REGISTRY.get(slug)# Remove EVERY env var plus its mirrors or the provider resurrects in the picker after restart.env_vars = (pconfig.api_key_env_vars if pconfig else None) or ()- cleared_env = any([remove_provider_env_credential(ev).get("found") for ev in env_vars])+ # Ask the .env lock about every var before removing any: a refusal part-way through left the earlier stores+ # stripped. A locked var that holds nothing is no refusal (a package-managed install keeps keys in auth.json).+ removable = []+ for ev in env_vars:+ if (refusal := env_write_refusal(ev, "remove")) is None:+ removable.append(ev)+ elif managed_scope.is_env_managed(ev) or os.environ.get(ev) or load_env().get(ev):+ return _err(rid, 5035, refusal)+ cleared_env = any([remove_provider_env_credential(ev).get("found") for ev in removable])cleared_auth = clear_provider_auth(slug) # full disconnect: OAuth grants go tooif not cleared_env and not cleared_auth:return _err(rid, 4005, f"no credentials found for {slug}")