Skip to content

The agent that grows with you

fix(vault): finish keychain cleanup and copied-vault adoption on partial failures

Teknium4c11da1139a0
diff --git a/agent/vault_keychain.py b/agent/vault_keychain.py
index a893f3ce757..01193a4339e 100644
--- a/agent/vault_keychain.py
+++ b/agent/vault_keychain.py
@@ -15,6 +15,7 @@ from __future__ import annotations
import json
import os
import uuid
+from contextlib import suppress
from pathlib import Path
from typing import Optional
@@ -120,11 +121,15 @@ def store_key(ref: dict, key: bytes) -> None:
def delete_key(ref: dict) -> bool:
+ """True once the entry is gone, including when an earlier, interrupted cleanup already removed it."""
+ service, account = str(ref.get("service") or SERVICE), str(ref["account"])
try:
- os_keyring().delete_password(str(ref.get("service") or SERVICE), str(ref["account"]))
- except Exception: # health: allow BLE001 -- best effort; an orphaned entry is harmless
+ backend = os_keyring()
+ with suppress(Exception): # a missing entry raises PasswordDeleteError; the read below decides
+ backend.delete_password(service, account)
+ return backend.get_password(service, account) is None
+ except Exception: # health: allow BLE001 -- unreachable keychain: the caller keeps the pointer to retry
return False
- return True
def remove_file(path: Path) -> None:
diff --git a/agent/vault_store.py b/agent/vault_store.py
index f8b8a6f6661..8a53bcfae3c 100644
--- a/agent/vault_store.py
+++ b/agent/vault_store.py
@@ -351,10 +351,11 @@ class VaultStore:
mine = kc.new_ref(self._base)
try:
kc.store_key(mine, key)
- except kc.KeychainUnavailable:
+ kc.write_ref(self._keyref_path, mine)
+ except (kc.KeychainUnavailable, OSError):
+ kc.delete_key(mine) # no orphan per retry; the shared entry keeps serving reads
logger.warning("could not give the copied vault in %s its own keychain entry", self._base, exc_info=True)
return ref
- kc.write_ref(self._keyref_path, mine)
return mine
def _decrypts(self, key: Optional[bytes]) -> bool:
diff --git a/tests/agent/test_vault_key_storage.py b/tests/agent/test_vault_key_storage.py
index ae2b35cd43f..1751b972060 100644
--- a/tests/agent/test_vault_key_storage.py
+++ b/tests/agent/test_vault_key_storage.py
@@ -195,3 +195,31 @@ def test_cloned_and_renamed_keychain_vaults_never_share_or_overwrite_an_entry(ho
(work / "vault").rename(renamed / "vault")
_add(VaultStore(work / "vault")) # a new vault where the renamed one used to live
assert VaultStore(renamed / "vault").resolve_secret(item)["password"] == _LOGIN["password"]
+
+
+def test_copied_vault_still_opens_when_its_own_pointer_cannot_be_written(home, keychain, monkeypatch):
+ from agent import vault_keychain
+
+ work = home("work", key_storage="keychain")
+ item = _add(VaultStore())
+ clone = home("clone", key_storage="keychain")
+ shutil.copytree(work / "vault", clone / "vault")
+
+ def disk_full(*_a, **_k):
+ raise OSError(28, "No space left on device")
+
+ monkeypatch.setattr(vault_keychain, "write_ref", disk_full)
+ assert VaultStore().resolve_secret(item)["password"] == _LOGIN["password"]
+ assert len(keychain.entries) == 1, "the half-made entry is removed, not left behind on every retry"
+
+
+def test_cleanup_of_an_already_deleted_keychain_entry_completes(home, keychain):
+ h = home(key_storage="keychain")
+ item = _add(VaultStore())
+ keyref = (h / "vault" / "vault.keyref").read_bytes()
+ assert VaultStore().migrate_key("file") == "file"
+ (h / "vault" / "vault.keyref").write_bytes(keyref) # stopped after deleting the entry, before the pointer
+ assert VaultStore().migrate_key("file") == "file"
+ assert "keychain_entry_left" not in VaultStore().key_location()
+ assert not (h / "vault" / "vault.keyref").exists()
+ assert VaultStore().resolve_secret(item)["password"] == _LOGIN["password"]