Skip to content

The agent that grows with you

fix(vault): a --clone-all copy owns its keychain entry before it is published

Teknium7cb0168ee6fd
diff --git a/agent/vault_store.py b/agent/vault_store.py
index 79054efcee8..25f5d8597a0 100644
--- a/agent/vault_store.py
+++ b/agent/vault_store.py
@@ -337,10 +337,38 @@ class VaultStore:
# reads would prefer over a working keychain entry. Callers hold the vault lock.
atomic_write_bytes(self._key_path, key, mode=0o600, fsync_dir=True)
+ def own_copied_key(self, published_base: Path) -> None:
+ """A ``--clone-all`` copy carries the source's ``vault.keyref``, which names the SOURCE's entry;
+ the source moving its key to a file deletes that entry. Before the clone is published at
+ ``published_base``, give it an entry of its own, so it never depends on another profile.
+ Raises VaultError when the keychain cannot be read or written: the clone must not be published
+ sharing the source's entry."""
+ 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):
+ return # key file layout (a vault.key always wins on read): nothing is shared
+ try:
+ key = kc.load_key(ref)
+ if not self._decrypts(key):
+ return # the source's own entry is already gone: the copy is no worse off than it
+ mine = kc.new_ref(published_base)
+ kc.store_key(mine, key)
+ except kc.KeychainUnavailable as exc:
+ 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
+
def _adopt(self, ref: dict) -> dict:
- """Give a copied/moved vault (profile clone or rename) its own keychain entry. Never deletes the
- entry it came from: another copy may still depend on it. Raises KeychainUnavailable only when the
- shared entry cannot be read; if the new entry cannot be written, the shared one keeps serving."""
+ """Give a moved vault (profile rename, or a clone made before clones got their own entry at
+ creation) its own keychain entry. Never deletes the entry it came from: another copy may still
+ depend on it. Raises KeychainUnavailable only when the shared entry cannot be read; if the new
+ entry cannot be written, the shared one keeps serving."""
from agent import vault_keychain as kc
if kc.owns(ref, self._base):
diff --git a/hermes_cli/profiles.py b/hermes_cli/profiles.py
index 5e67e3faf0c..9006f7a0f6d 100644
--- a/hermes_cli/profiles.py
+++ b/hermes_cli/profiles.py
@@ -1287,6 +1287,11 @@ def _clone_all_into(source_dir: Path, profile_dir: Path, canon: str) -> None:
"profile %s: dropped cloned single-use OAuth grants %s "
"(inherits the root grant instead)", canon, stripped,
)
+ from agent.vault_store import VaultError, VaultStore
+ try: # a keychain-mode vault's copied pointer names the source's entry: the clone gets its own
+ VaultStore(profile_dir / "vault").own_copied_key(get_profile_dir(canon) / "vault")
+ except VaultError as exc:
+ raise ValueError(f"Cannot copy the vault from {source_dir}: {exc}") from exc
def _strip_multiplex_flag(config_path: Path) -> None:
@@ -1439,7 +1444,8 @@ 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.
- staging = _clone_staging_dir(profile_dir)
+ from hermes_cli.profiles_initialization import clone_staging_dir, finish_profile_layout
+ staging = clone_staging_dir(profile_dir)
try:
if clone_all and source_dir:
_clone_all_into(source_dir, staging, canon)
@@ -1450,7 +1456,6 @@ def create_profile(
stripped = strip_channel_settings(staging, include_state=clone_all, source_dir=source_dir)
if stripped:
logger.info("profile %s: cloned without messaging channels %s", canon, stripped)
- from hermes_cli.profiles_initialization import finish_profile_layout
finish_profile_layout(staging, no_skills=no_skills, clone_all=clone_all, description=description, soul=soul)
os.rename(staging, profile_dir)
except BaseException:
@@ -1467,18 +1472,6 @@ def create_profile(
return profile_dir
-def _clone_staging_dir(profile_dir: Path) -> Path:
- """Fresh ``profiles/.<name>.staging-<pid>`` beside the final dir (same filesystem, so the publish
- rename is atomic). A leftover from a crashed create is discarded."""
- staging = profile_dir.parent / f".{profile_dir.name}.staging-{os.getpid()}"
- profile_dir.parent.mkdir(parents=True, exist_ok=True)
- if staging.is_symlink() or staging.is_file():
- staging.unlink()
- elif staging.is_dir():
- shutil.rmtree(staging, ignore_errors=True)
- return staging
-
-
def _notify_multiplexer(canon: str) -> None:
from hermes_cli.gateway_multiplex_served import notify_multiplexer_profiles_changed
notify_multiplexer_profiles_changed(canon)
diff --git a/hermes_cli/profiles_initialization.py b/hermes_cli/profiles_initialization.py
index 8dbe1052649..f9a438cf8aa 100644
--- a/hermes_cli/profiles_initialization.py
+++ b/hermes_cli/profiles_initialization.py
@@ -1,9 +1,23 @@
"""Initial profile files, written on the staging tree before publication."""
import contextlib
+import os
+import shutil
from pathlib import Path
from typing import Optional
+def clone_staging_dir(profile_dir: Path) -> Path:
+ """Fresh ``profiles/.<name>.staging-<pid>`` beside the final dir (same filesystem, so the publish
+ rename is atomic). A leftover from a crashed create is discarded."""
+ staging = profile_dir.parent / f".{profile_dir.name}.staging-{os.getpid()}"
+ profile_dir.parent.mkdir(parents=True, exist_ok=True)
+ if staging.is_symlink() or staging.is_file():
+ staging.unlink()
+ elif staging.is_dir():
+ shutil.rmtree(staging, ignore_errors=True)
+ return staging
+
+
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 c9f895dffe5..dbc921413d0 100644
--- a/tests/agent/test_vault_key_storage.py
+++ b/tests/agent/test_vault_key_storage.py
@@ -14,6 +14,7 @@ from __future__ import annotations
import shutil
import stat
import sys
+from pathlib import Path
import keyring
from cryptography.fernet import Fernet
@@ -197,6 +198,38 @@ def test_cloned_and_renamed_keychain_vaults_never_share_or_overwrite_an_entry(ho
assert VaultStore(renamed / "vault").resolve_secret(item)["password"] == _LOGIN["password"]
+def test_clone_all_owns_its_key_before_the_source_ever_migrates(home, keychain, tmp_path, monkeypatch):
+ """A --clone-all copy gets its own keychain entry when it is created, so the source moving its key
+ to a file (which deletes the source's entry) cannot strand a clone that was never opened."""
+ from hermes_cli.profiles import create_profile
+
+ monkeypatch.setenv("HOME", str(tmp_path))
+ monkeypatch.setattr(Path, "home", lambda: tmp_path)
+ source = home(".hermes", key_storage="keychain")
+ item = _add(VaultStore())
+ clone = create_profile("vault-clone", clone_from="default", clone_all=True, no_alias=True)
+
+ assert VaultStore().migrate_key("file") == "file" # the clone has not opened its vault yet
+ assert VaultStore(source / "vault").resolve_secret(item)["password"] == _LOGIN["password"]
+ assert VaultStore(clone / "vault").resolve_secret(item)["password"] == _LOGIN["password"]
+ assert not (clone / "vault" / "vault.key").exists(), "the clone keeps keychain storage"
+ assert len(keychain.entries) == 1, "only the clone's own entry is left"
+
+
+def test_clone_all_without_a_reachable_keychain_is_refused_not_published_sharing_the_key(
+ home, keychain, tmp_path, monkeypatch):
+ from hermes_cli.profiles import create_profile, get_profile_dir
+
+ monkeypatch.setenv("HOME", str(tmp_path))
+ monkeypatch.setattr(Path, "home", lambda: tmp_path)
+ home(".hermes", key_storage="keychain")
+ _add(VaultStore())
+ keyring.set_keyring(fail.Keyring()) # e.g. an SSH session that cannot reach the login keychain
+ with pytest.raises(ValueError, match="OS keychain"):
+ create_profile("vault-clone", clone_from="default", clone_all=True, no_alias=True)
+ assert not get_profile_dir("vault-clone").exists()
+
+
@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