Skip to content

The agent that grows with you

fix(vault): a keychain entry no pointer names is deleted, never left behind

Tekniumd1a65f5e30f3
diff --git a/agent/vault_keychain.py b/agent/vault_keychain.py
index 01193a4339e..0cd5aab6cb2 100644
--- a/agent/vault_keychain.py
+++ b/agent/vault_keychain.py
@@ -97,6 +97,21 @@ def write_ref(path: Path, ref: dict) -> None:
atomic_write_bytes(path, json.dumps(ref, indent=2).encode("utf-8"), mode=0o600, fsync_dir=True)
+def save_new_ref(path: Path, ref: dict) -> None:
+ """Save the pointer to an entry just created. If saving fails, delete the entry unless the pointer
+ did land (a replace can succeed before a later step errors): every account is random, so an entry
+ no pointer names is a key Hermes would never find or remove again."""
+ try:
+ write_ref(path, ref)
+ except OSError:
+ from agent.vault_store import VaultError
+ with suppress(VaultError):
+ if (read_ref(path) or {}).get("account") == ref["account"]:
+ raise
+ delete_key(ref)
+ raise
+
+
def load_key(ref: dict) -> Optional[bytes]:
"""The stored key, or None when the entry is gone. Raises KeychainUnavailable."""
backend = os_keyring()
diff --git a/agent/vault_store.py b/agent/vault_store.py
index 25f5d8597a0..b4cd4c03494 100644
--- a/agent/vault_store.py
+++ b/agent/vault_store.py
@@ -326,7 +326,7 @@ class VaultStore:
# working: the key goes to the 0600 file exactly as it always has.
logger.warning("vault.key_storage is keychain, but %s; using %s instead", exc, self._key_path)
else:
- kc.write_ref(self._keyref_path, ref)
+ kc.save_new_ref(self._keyref_path, ref)
return key
kc.remove_file(self._keyref_path)
self._write_key_file(key)
@@ -346,7 +346,7 @@ class VaultStore:
from agent import vault_keychain as kc
ref = kc.read_ref(self._keyref_path)
- if ref is None or self._key_path.exists() or kc.owns(ref, published_base):
+ if ref is None or self._key_path.exists():
return # key file layout (a vault.key always wins on read): nothing is shared
try:
key = kc.load_key(ref)
@@ -358,11 +358,17 @@ class VaultStore:
raise VaultError(
f"its key is in the OS keychain, which this session cannot use ({exc}). Clone from a session "
"that can reach the keychain, or run `hermes vault key migrate --to file` on the source first.") from exc
- try:
- kc.write_ref(self._keyref_path, mine)
- except OSError:
- kc.delete_key(mine)
- raise
+ kc.save_new_ref(self._keyref_path, mine)
+
+ def discard_copied_key(self, source_base: Path) -> None:
+ """Undo :meth:`own_copied_key` for a clone that was never published: delete the entry this copy
+ was given, never one the source's pointer names. Never raises (it runs while unwinding)."""
+ from agent import vault_keychain as kc
+
+ with suppress(VaultError):
+ mine, theirs = kc.read_ref(self._keyref_path), kc.read_ref(Path(source_base) / "vault.keyref")
+ if mine is not None and mine["account"] != (theirs or {}).get("account"):
+ kc.delete_key(mine)
def _adopt(self, ref: dict) -> dict:
"""Give a moved vault (profile rename, or a clone made before clones got their own entry at
@@ -462,7 +468,11 @@ class VaultStore:
kc.delete_key(ref)
raise VaultError(f"could not move the vault key to the OS keychain ({exc}); "
f"it stays in {self._key_path}") from exc
- kc.write_ref(self._keyref_path, ref)
+ if ref is not existing:
+ try:
+ kc.save_new_ref(self._keyref_path, ref)
+ except OSError as exc:
+ raise VaultError(f"could not save {self._keyref_path.name} ({exc}); the key stays in {self._key_path}") from exc
kc.remove_file(self._key_path)
return "keychain"
diff --git a/hermes_cli/profiles.py b/hermes_cli/profiles.py
index 9006f7a0f6d..f3cdc359f0a 100644
--- a/hermes_cli/profiles.py
+++ b/hermes_cli/profiles.py
@@ -1444,7 +1444,7 @@ def create_profile(
# on every create and every 30 s, and ``_iter_named_profile_dirs`` only lists valid ids (no leading
# dot), so it can never adopt the half-copied tree and start adapters on credentials the strip
# below has not removed yet.
- from hermes_cli.profiles_initialization import clone_staging_dir, finish_profile_layout
+ from hermes_cli.profiles_initialization import clone_staging_dir, discard_unpublished_vault_key, finish_profile_layout
staging = clone_staging_dir(profile_dir)
try:
if clone_all and source_dir:
@@ -1459,6 +1459,7 @@ def create_profile(
finish_profile_layout(staging, no_skills=no_skills, clone_all=clone_all, description=description, soul=soul)
os.rename(staging, profile_dir)
except BaseException:
+ discard_unpublished_vault_key(staging, source_dir if clone_all else None)
shutil.rmtree(staging, ignore_errors=True)
raise
diff --git a/hermes_cli/profiles_initialization.py b/hermes_cli/profiles_initialization.py
index f9a438cf8aa..624c6aa84ba 100644
--- a/hermes_cli/profiles_initialization.py
+++ b/hermes_cli/profiles_initialization.py
@@ -18,6 +18,13 @@ def clone_staging_dir(profile_dir: Path) -> Path:
return staging
+def discard_unpublished_vault_key(staging: Path, source_dir: Optional[Path]) -> None:
+ """A create that fails after a --clone-all copy got its own keychain entry must not leave it behind."""
+ if source_dir is not None and (staging / "vault").is_dir():
+ from agent.vault_store import VaultStore
+ VaultStore(staging / "vault").discard_copied_key(source_dir / "vault")
+
+
def finish_profile_layout(profile_dir: Path, *, no_skills: bool, clone_all: bool,
description: Optional[str], soul: Optional[str] = None) -> None:
"""Seed files a fresh profile owns from day one; runs on the staging tree before publish."""
diff --git a/tests/agent/test_vault_key_storage.py b/tests/agent/test_vault_key_storage.py
index dbc921413d0..8abab17da6c 100644
--- a/tests/agent/test_vault_key_storage.py
+++ b/tests/agent/test_vault_key_storage.py
@@ -230,6 +230,43 @@ def test_clone_all_without_a_reachable_keychain_is_refused_not_published_sharing
assert not get_profile_dir("vault-clone").exists()
+def test_a_clone_that_fails_to_publish_leaves_no_keychain_entry_behind(home, keychain, tmp_path, monkeypatch):
+ from hermes_cli import profiles_initialization
+ from hermes_cli.profiles import create_profile, get_profile_dir
+
+ monkeypatch.setenv("HOME", str(tmp_path))
+ monkeypatch.setattr(Path, "home", lambda: tmp_path)
+ source = home(".hermes", key_storage="keychain")
+ item = _add(VaultStore())
+
+ def fail_layout(*args, **kwargs):
+ raise RuntimeError("dummy failure after the clone got its own entry")
+
+ monkeypatch.setattr(profiles_initialization, "finish_profile_layout", fail_layout)
+ with pytest.raises(RuntimeError):
+ create_profile("vault-clone", clone_from="default", clone_all=True, no_alias=True)
+ assert not get_profile_dir("vault-clone").exists()
+ assert len(keychain.entries) == 1, "the unpublished clone's entry is removed; the source's is kept"
+ assert VaultStore(source / "vault").resolve_secret(item)["password"] == _LOGIN["password"]
+
+
+def test_migration_whose_pointer_cannot_be_saved_leaves_no_untracked_entry(home, keychain, monkeypatch):
+ from agent import vault_keychain
+
+ h = home()
+ item = _add(VaultStore())
+
+ def failing_write_ref(path, ref):
+ raise OSError(28, "No space left on device")
+
+ monkeypatch.setattr(vault_keychain, "write_ref", failing_write_ref)
+ with pytest.raises(VaultError, match="vault.keyref"):
+ VaultStore().migrate_key("keychain")
+ assert keychain.entries == {}, "a retry would mint another random account, so nothing may be left"
+ assert (h / "vault" / "vault.key").exists()
+ assert VaultStore().resolve_secret(item)["password"] == _LOGIN["password"]
+
+
@pytest.mark.parametrize("pointer_landed", [False, True])
def test_copied_vault_keeps_opening_when_saving_its_own_pointer_fails(home, keychain, monkeypatch, pointer_landed):
from agent import vault_keychain