The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
harden vault error handling for malformed state
beardthelion04dc1907be16
diff --git a/agent/vault_store.py b/agent/vault_store.pyindex 6b1ea010596..dc90d4fa686 100644--- a/agent/vault_store.py+++ b/agent/vault_store.py@@ -281,7 +281,14 @@ class VaultStore:raise VaultError("vault file could not be decrypted (key mismatch or corruption)") from exc- data = json.loads(raw.decode("utf-8"))+ try:+ data = json.loads(raw.decode("utf-8"))+ except (json.JSONDecodeError, UnicodeDecodeError) as exc:+ raise VaultError(+ "vault file is corrupted (invalid JSON)"+ ) from exc+ if not isinstance(data, dict):+ raise VaultError("vault file is corrupted (unexpected shape)")items = data.get("items", [])return items if isinstance(items, list) else []diff --git a/hermes_cli/vault.py b/hermes_cli/vault.pyindex abe70097367..5f3968cc059 100644--- a/hermes_cli/vault.py+++ b/hermes_cli/vault.py@@ -142,7 +142,7 @@ def _cmd_sources(args) -> None:"""Show the detected password managers; `--disable`/`--enable` flip the opt-out (`vault.<name>.enabled`)."""from agent.vault_backends import enabled_backendsfrom agent.vault_backends.base import external_backend_classes, is_installed- from hermes_cli.config import load_config, save_config+ from hermes_cli.config import _ensure_dict, load_config, save_configc = _console()classes = {cls.name: cls for cls in external_backend_classes()}@@ -152,7 +152,9 @@ def _cmd_sources(args) -> None:c.print(f"[red]Unknown password manager {name!r}[/] (expected one of {', '.join(classes)})")returncfg = load_config()- section = cfg.setdefault("vault", {}).setdefault(name, {})+ if not isinstance(cfg, dict):+ cfg = {}+ section = _ensure_dict(_ensure_dict(cfg, "vault"), name)if args.enable:section.pop("enabled", None) # detected managers are on by default; drop the opt-outelse:@@ -211,8 +213,13 @@ def register_cli(subparser) -> None:def vault_command(args) -> None:+ from agent.vault_store import VaultError+handler = getattr(args, "_vault_handler", None)- if handler is None:- _cmd_list(args)- return- handler(args)+ try:+ if handler is None:+ _cmd_list(args)+ return+ handler(args)+ except VaultError as exc:+ _console().print(f"[red]Error:[/] {exc}")diff --git a/tests/agent/test_vault_store.py b/tests/agent/test_vault_store.pynew file mode 100644index 00000000000..e2f64cf1039--- /dev/null+++ b/tests/agent/test_vault_store.py@@ -0,0 +1,70 @@+"""``VaultStore._read_all`` must surface every decryptable-but-malformed vault+file as ``VaultError`` so callers that catch ``VaultError`` (the ``hermes vault``+commands, ``vault.*`` RPC handlers) get the designed error path instead of a raw+traceback. Corruption arrives via partial-write survivors, manual edits of the+envelope, or format drift."""++import pytest++from agent.vault_store import VaultError, VaultStore+++def _corrupt(store: VaultStore, payload: bytes) -> None:+ store._vault_path.write_bytes(store._fernet().encrypt(payload))+++def _store(tmp_path) -> VaultStore:+ store = VaultStore(tmp_path / "vault")+ store.add_item(+ "login",+ "Example login",+ {"identifier_type": "email", "identifier": "[email protected]", "password": "pw"},+ origin="https://example.com",+ )+ return store+++def test_malformed_json_vault_file_raises_vault_error(tmp_path):+ store = _store(tmp_path)+ _corrupt(store, b"{not json")+ with pytest.raises(VaultError, match="corrupted"):+ store.list_items()+++def test_non_dict_json_vault_file_raises_vault_error(tmp_path):+ store = _store(tmp_path)+ _corrupt(store, b"[1, 2]")+ with pytest.raises(VaultError, match="corrupted"):+ store.list_items()+++def test_non_utf8_vault_file_raises_vault_error(tmp_path):+ store = _store(tmp_path)+ _corrupt(store, b"\xff\xfe\x00binary")+ with pytest.raises(VaultError, match="corrupted"):+ store.list_items()+++ "op",+ ["list_items", "get_meta", "remove_item", "resolve_secret", "add_item"],+)+def test_corrupt_vault_raises_vault_error_on_every_reader(tmp_path, op):+ """Every ``_read_all`` consumer must see the same VaultError contract so+ callers that catch VaultError all get the designed error path."""+ store = _store(tmp_path)+ _corrupt(store, b"{not json")+ call = {+ "list_items": lambda: store.list_items(),+ "get_meta": lambda: store.get_meta("vault_x"),+ "remove_item": lambda: store.remove_item("vault_x"),+ "resolve_secret": lambda: store.resolve_secret("vault_x"),+ "add_item": lambda: store.add_item(+ "login",+ "x",+ {"identifier_type": "email", "identifier": "u", "password": "p"},+ origin="https://x.example",+ ),+ }[op]+ with pytest.raises(VaultError):+ call()diff --git a/tests/hermes_cli/test_vault_sources_shape.py b/tests/hermes_cli/test_vault_sources_shape.pynew file mode 100644index 00000000000..1492e9ab068--- /dev/null+++ b/tests/hermes_cli/test_vault_sources_shape.py@@ -0,0 +1,62 @@+"""`hermes vault sources --disable` must not crash on a hand-edited non-dict+``vault:`` section in config.yaml (the same YAML-shape hazard class+``_voice_cfg_dict`` guards for voice.*, #19835): the malformed section is+coerced to a dict before the opt-out is written."""++from types import SimpleNamespace++import yaml++from agent.vault_store import VaultStore+from hermes_cli.vault import _cmd_rm, _cmd_sources, vault_command+++def _corrupt_vault(home):+ store = VaultStore(home / "vault")+ store.add_item(+ "login",+ "site",+ {"identifier_type": "email", "identifier": "u", "password": "p"},+ origin="https://x.example",+ )+ store._vault_path.write_bytes(store._fernet().encrypt(b"{not json"))+++def test_sources_disable_tolerates_scalar_vault_section(tmp_path, monkeypatch):+ home = tmp_path / ".hermes"+ home.mkdir()+ monkeypatch.setenv("HERMES_HOME", str(home))+ (home / "config.yaml").write_text("vault: true\n")++ _cmd_sources(SimpleNamespace(enable=None, disable="bitwarden"))++ saved = yaml.safe_load((home / "config.yaml").read_text())+ assert saved["vault"]["bitwarden"]["enabled"] is False+++def test_vault_command_surfaces_corrupt_store_as_clean_error(tmp_path, monkeypatch, capsys):+ """A decryptable-but-malformed vault file surfaces through the VaultError+ contract as a clean error line on every subcommand, not a traceback."""+ home = tmp_path / ".hermes"+ home.mkdir()+ monkeypatch.setenv("HERMES_HOME", str(home))+ _corrupt_vault(home)++ vault_command(SimpleNamespace()) # bare `hermes vault` -> _cmd_list++ out = capsys.readouterr().out+ assert "Error" in out+ assert "corrupted" in out+++def test_vault_rm_surfaces_corrupt_store_as_clean_error(tmp_path, monkeypatch, capsys):+ home = tmp_path / ".hermes"+ home.mkdir()+ monkeypatch.setenv("HERMES_HOME", str(home))+ _corrupt_vault(home)++ vault_command(SimpleNamespace(_vault_handler=_cmd_rm, handle="vault_x"))++ out = capsys.readouterr().out+ assert "Error" in out+ assert "corrupted" in outdiff --git a/tests/tui_gateway/test_vault_methods.py b/tests/tui_gateway/test_vault_methods.pyindex 24746f0986c..7ac0aba9586 100644--- a/tests/tui_gateway/test_vault_methods.py+++ b/tests/tui_gateway/test_vault_methods.py@@ -138,9 +138,71 @@ def test_undetected_manager_stays_off(home, monkeypatch):monkeypatch.setattr("agent.vault_backends.base.is_installed", lambda name: False)rows = _sources_rows(home)assert rows["bitwarden"]["installed"] is False+++def test_source_set_tolerates_scalar_vault_section(home, monkeypatch):+ """A hand-edited ``vault: true`` in config.yaml must not crash the Desktop+ Credential Vault source toggle: the malformed section is coerced to a dict+ before the opt-out is written (same YAML-shape hazard class _voice_cfg_dict+ documents for voice.*, #19835)."""+ monkeypatch.setattr(+ "agent.vault_backends.base.is_installed", lambda name: name == "bitwarden"+ )+ (home / "config.yaml").write_text("vault: true\n")+ _result(+ srv._methods["vault.source.set"](82, {"name": "bitwarden", "enabled": False})+ )+ rows = _sources_rows(home)+ assert rows["bitwarden"]["enabled"] is False+++def test_source_set_tolerates_scalar_named_section(home, monkeypatch):+ """``vault: {bitwarden: true}`` must not crash either: the named section is+ coerced before ``enabled`` is written."""+ monkeypatch.setattr(+ "agent.vault_backends.base.is_installed", lambda name: name == "bitwarden"+ )+ (home / "config.yaml").write_text("vault:\n bitwarden: true\n")+ _result(+ srv._methods["vault.source.set"](83, {"name": "bitwarden", "enabled": False})+ )+ rows = _sources_rows(home)assert rows["bitwarden"]["enabled"] is False+def test_source_set_enable_tolerates_scalar_vault_section(home, monkeypatch):+ """The enable arm (``section.pop``) must also survive a scalar ``vault:``+ section: coercion happens before either write shape."""+ monkeypatch.setattr(+ "agent.vault_backends.base.is_installed", lambda name: name == "bitwarden"+ )+ (home / "config.yaml").write_text("vault: true\n")+ _result(+ srv._methods["vault.source.set"](84, {"name": "bitwarden", "enabled": True})+ )+ rows = _sources_rows(home)+ assert rows["bitwarden"]["enabled"] is True+++def test_vault_list_reports_corrupt_store_cleanly(home):+ """A decryptable-but-malformed vault file degrades to the 5095 envelope+ carrying the VaultError text, never a traceback."""+ from agent.vault_store import VaultStore++ store = VaultStore(home / "vault")+ store.add_item(+ "login",+ "site",+ {"identifier_type": "email", "identifier": "u", "password": "p"},+ origin="https://x.example",+ )+ store._vault_path.write_bytes(store._fernet().encrypt(b"{not json"))++ err = _error(srv._methods["vault.list"](95, {}))+ assert err["code"] == 5095+ assert "corrupted" in err["message"]++def test_remove_is_idempotent(home):item_id = _result(srv._methods["vault.add"](1, dict(_LOGIN_PARAMS)))["id"]assert _result(srv._methods["vault.remove"](2, {"id": item_id}))["removed"] is Truediff --git a/tui_gateway/methods_vault.py b/tui_gateway/methods_vault.pyindex 17c09976f71..c3e3a9eb7d3 100644--- a/tui_gateway/methods_vault.py+++ b/tui_gateway/methods_vault.py@@ -81,14 +81,16 @@ def _(rid, params: dict) -> dict:"""Enable/disable an external manager: writes ``vault.<name>.enabled`` and locks it when disabling."""from agent.vault_backends.base import external_backend_classesfrom agent.vault_backends.unlock import lock- from hermes_cli.config import load_config, save_config+ from hermes_cli.config import _ensure_dict, load_config, save_configname = str(params.get("name") or "")if name not in {cls.name for cls in external_backend_classes()}:return _err(rid, 5095, f"unknown vault source: {name}")enabled = bool(params.get("enabled"))cfg = load_config()- section = cfg.setdefault("vault", {}).setdefault(name, {})+ if not isinstance(cfg, dict):+ cfg = {}+ section = _ensure_dict(_ensure_dict(cfg, "vault"), name)if enabled:section.pop("enabled", None) # detected managers are on by default; this removes the opt-outelse: