The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(auth): never fork single-use OAuth grants across profiles (#100339)
Teknium3038493ee629
diff --git a/agent/anthropic_credentials.py b/agent/anthropic_credentials.pyindex a40cdcb298e..660a6722110 100644--- a/agent/anthropic_credentials.py+++ b/agent/anthropic_credentials.py@@ -917,6 +917,22 @@ def _get_hermes_oauth_file() -> Path:return get_hermes_home() / ".anthropic_oauth.json"+def _root_hermes_oauth_file() -> Optional[Path]:+ """Global-root ``.anthropic_oauth.json`` when running inside a named profile.++ ``None`` in classic mode (profile == root). Used to commit a rotation of a+ grant the profile borrowed through the credential-pool root fallback.+ """+ try:+ from hermes_constants import get_default_hermes_root+ root = get_default_hermes_root()+ if root.resolve(strict=False) == get_hermes_home().resolve(strict=False):+ return None+ return root / ".anthropic_oauth.json"+ except Exception:+ return None++def _generate_pkce() -> tuple:"""Generate PKCE code_verifier and code_challenge (S256)."""import base64@@ -1077,9 +1093,16 @@ def _write_hermes_oauth_credentials(access_token: str,refresh_token: Optional[str],expires_at_ms: Optional[int],+ *,+ target: Optional[Path] = None,) -> None:"""Write refreshed hermes_pkce tokens back to ~/.hermes/.anthropic_oauth.json.+ ``target`` overrides the destination: a named profile that rotated a grant+ it BORROWED from the global root (credential-pool root fallback) must+ commit the new pair to the ROOT singleton, not create a forked copy under+ its own HERMES_HOME (#100339).+Without this, a successful pool-level refresh of a ``hermes_pkce``-sourcedentry is invisible to this singleton file. The next ``load_pool()`` callruns ``_seed_from_singletons()``, which reads the stale file and@@ -1090,7 +1113,7 @@ def _write_hermes_oauth_credentials(file, for the same reason ``_write_claude_code_credentials`` does: this isthe commit step of the refresh transaction."""- oauth_file = _get_hermes_oauth_file()+ oauth_file = target if target is not None else _get_hermes_oauth_file()try:oauth_data = {"accessToken": access_token,diff --git a/agent/credential_pool.py b/agent/credential_pool.pyindex c28cabd2baf..55db7165fa7 100644--- a/agent/credential_pool.py+++ b/agent/credential_pool.py@@ -12,7 +12,7 @@ import refrom dataclasses import dataclass, fields, replacefrom datetime import datetime, timezonefrom pathlib import Path-from typing import Any, Dict, List, Optional, Set, Tuple+from typing import Any, Dict, Iterable, List, Optional, Set, Tuplefrom hermes_constants import OPENROUTER_BASE_URLfrom hermes_cli.config import load_env@@ -26,6 +26,7 @@ import hermes_cli.auth as auth_modfrom hermes_cli.auth import (CODEX_ACCESS_TOKEN_REFRESH_SKEW_SECONDS,PROVIDER_REGISTRY,+ SINGLE_USE_REFRESH_POOL_PROVIDERS,_auth_store_lock,_codex_access_token_is_expiring,_decode_jwt_claims,@@ -807,11 +808,134 @@ def _write_through_provider_state_to_global_root()+def _singleton_target_for_entry(pool: "CredentialPool", entry: "PooledCredential") -> Optional[Path]:+ """Root ``.anthropic_oauth.json`` when *entry* is a borrowed hermes_pkce row, else None."""+ if entry.source != "hermes_pkce" or entry.id not in getattr(pool, "_borrowed_root_ids", ()):+ return None+ try:+ from agent.anthropic_credentials import _root_hermes_oauth_file+ return _root_hermes_oauth_file()+ except Exception:+ return None+++def _profile_owns_pool_provider(provider: str) -> bool:+ """True when the ACTIVE auth.json has its own rows for *provider*.++ Named profiles with no local rows read the provider through the+ ``read_credential_pool`` global-root fallback ("borrowing").+ """+ try:+ pool = _load_auth_store().get("credential_pool")+ except Exception:+ return True # unreadable store: assume ownership, keep legacy path+ entries = pool.get(provider) if isinstance(pool, dict) else None+ return isinstance(entries, list) and bool(entries)+++def _borrowed_single_use_pool_root() -> Optional[Path]:+ """Return the global-root auth.json when persisting a BORROWED single-use pool.++ ``None`` means "persist to the active store as usual": classic mode+ (profile == root), or the profile owns its own rows for this provider.+ Pytest seat belt mirrors ``_write_through_provider_state_to_global_root``.+ """+ try:+ global_path = _global_auth_file_path()+ except Exception:+ return None+ if global_path is None:+ return None+ if os.environ.get("PYTEST_CURRENT_TEST"):+ real_home_env = os.environ.get("HOME", "")+ if real_home_env:+ real_root = Path(real_home_env) / ".hermes" / "auth.json"+ try:+ if global_path.resolve(strict=False) == real_root.resolve(strict=False):+ return None+ except Exception:+ return None+ return global_path+++def persist_pool_entries(+ provider: str,+ payloads: List[Dict[str, Any]],+ *,+ removed_ids: Optional[Iterable[str]] = None,+) -> None:+ """Persist a provider's pool rows to the store that OWNS them.++ A named profile that sees a single-use-refresh provider (Anthropic,+ Codex, xAI OAuth) only through the global-root fallback must not+ materialize a local ``credential_pool.<provider>`` copy on its first+ persist: that copy forks the single-use refresh token, the first profile+ to rotate commits the new pair only to its own file, and root plus every+ sibling die with ``invalid_grant`` on their next refresh (#100339). Such+ rows are written back to the root store (under the root lock) so the+ rotation is visible to every profile; everything else goes to the active+ store exactly as before.+ """+ if provider in SINGLE_USE_REFRESH_POOL_PROVIDERS and not _profile_owns_pool_provider(provider):+ global_path = _borrowed_single_use_pool_root()+ if global_path is not None:+ removed = {rid for rid in (removed_ids or ()) if rid}+ try:+ with _auth_store_lock(target_path=global_path):+ store = _load_auth_store(global_path)+ pool = store.get("credential_pool")+ if not isinstance(pool, dict):+ pool = {}+ store["credential_pool"] = pool+ existing = pool.get(provider)+ existing_list = existing if isinstance(existing, list) else []+ incoming_by_id = {+ p.get("id"): p for p in payloads+ if isinstance(p, dict) and p.get("id")+ }+ # UPDATE-ONLY: a borrower may refresh the root's rows+ # (rotation, cooldown state) but never add or delete+ # them — the root owns their lifecycle. In particular a+ # profile's singleton-prune (it has no+ # .anthropic_oauth.json of its own) must not delete the+ # root grant, and ``removed_ids`` is ignored here.+ merged: List[Dict[str, Any]] = []+ changed = False+ for disk_entry in existing_list:+ did = disk_entry.get("id") if isinstance(disk_entry, dict) else None+ incoming = incoming_by_id.get(did) if did else None+ if incoming is None:+ merged.append(disk_entry)+ continue+ updated = auth_mod._merge_disk_cooldown_state(incoming, disk_entry, provider)+ if updated != disk_entry:+ changed = True+ merged.append(updated)+ if changed:+ pool[provider] = merged+ _save_auth_store(store, target_path=global_path)+ return+ except Exception as exc:+ # Fail closed on the FORK, not on the save: never fall back to+ # writing a local copy (that IS the bug). The in-memory pool+ # still holds the rotated pair for this process.+ logger.warning(+ "%s pool: write-through of borrowed root grant failed (%s); "+ "not materializing a profile-local copy",+ provider, exc,+ )+ return+ write_credential_pool(provider, payloads, removed_ids=removed_ids)++class CredentialPool:def __init__(self, provider: str, entries: List[PooledCredential]):self.provider = providerself._entries = sorted(entries, key=lambda entry: entry.priority)self._current_id: Optional[str] = None+ # Ids of rows read via the global-root fallback (single-use OAuth+ # providers only); set by load_pool(), consumed by add_entry().+ self._borrowed_root_ids: Set[str] = set()self._strategy = get_pool_strategy(provider)# RLock: the mutation primitives below (_replace_entry/_persist)# self-acquire this lock so the DEFERRED single-use-token refresh@@ -938,7 +1062,7 @@ class CredentialPool:# Self-locking (RLock): snapshotting self._entries must not race a# concurrent rotation when called from the deferred refresh path.with self._lock:- write_credential_pool(+ persist_pool_entries(self.provider,[entry.to_dict() for entry in self._entries],removed_ids=removed_ids,@@ -1786,10 +1910,14 @@ class CredentialPool:elif entry.source == "hermes_pkce":try:from agent.anthropic_credentials import _write_hermes_oauth_credentials+ # A borrowed row was seeded from the ROOT's singleton+ # (this profile has none); commit the rotation there,+ # never into a new profile-local copy (#100339)._write_hermes_oauth_credentials(refreshed["access_token"],refreshed["refresh_token"],refreshed["expires_at_ms"],+ target=_singleton_target_for_entry(self, entry),)except Exception as wexc:# Same transaction rule as claude_code above.@@ -2806,7 +2934,7 @@ class CredentialPool:replace(entry, priority=new_priority)for new_priority, entry in enumerate(self._entries)]- write_credential_pool(+ persist_pool_entries(self.provider,[entry.to_dict() for entry in self._entries],removed_ids=[removed.id],@@ -2845,7 +2973,22 @@ class CredentialPool:with self._lock:entry = replace(entry, priority=_next_priority(self._entries))self._entries.append(entry)- self._persist()+ borrowed_ids = getattr(self, "_borrowed_root_ids", None)+ if borrowed_ids:+ # ``hermes -p <profile> auth add <single-use provider>``: the+ # profile is claiming its OWN credential. Persist only the+ # profile-owned rows locally — copying the borrowed root+ # grant alongside them would fork its single-use refresh+ # token (#100339). Once the profile owns rows, the root+ # fallback for this provider is shadowed (existing contract).+ write_credential_pool(+ self.provider,+ [e.to_dict() for e in self._entries if e.id not in borrowed_ids],+ )+ self._entries = [e for e in self._entries if e.id not in borrowed_ids]+ self._borrowed_root_ids = set()+ else:+ self._persist()return entry@@ -3678,18 +3821,41 @@ def load_pool(provider: str) -> CredentialPool:# process missing a provider env var must not delete the persisted# pool entry for every other process (#9331). File-backed singletons# still prune when their backing file is gone.- changed |= _prune_stale_seeded_entries(- entries,- singleton_sources | env_sources,- prune_env_sources=False,+ borrowing_root_grant = (+ provider in SINGLE_USE_REFRESH_POOL_PROVIDERS+ and bool(disk_ids)+ and not _profile_owns_pool_provider(provider))+ if borrowing_root_grant:+ # Rows read through the global-root fallback are seeded from the+ # ROOT's singleton files, which this profile cannot see; pruning+ # them as "backing file gone" would hide (and, via write-through,+ # delete) the shared grant. The root's own load_pool() prunes.+ borrowed = [e for e in entries if e.id in disk_ids]+ others = [e for e in entries if e.id not in disk_ids]+ changed |= _prune_stale_seeded_entries(+ others, singleton_sources | env_sources, prune_env_sources=False,+ )+ entries[:] = borrowed + others+ else:+ changed |= _prune_stale_seeded_entries(+ entries,+ singleton_sources | env_sources,+ prune_env_sources=False,+ )changed |= _normalize_pool_priorities(provider, entries)if changed:new_ids = {entry.id for entry in entries}- write_credential_pool(+ persist_pool_entries(provider,[entry.to_dict() for entry in sorted(entries, key=lambda item: item.priority)],removed_ids=disk_ids - new_ids,)- return CredentialPool(provider, entries)+ pool = CredentialPool(provider, entries)+ # Remember which rows are the root's grant (borrowed via fallback) so a+ # later ``add_entry`` in this profile can leave them out of the profile's+ # own store (#100339).+ if provider in SINGLE_USE_REFRESH_POOL_PROVIDERS and not _profile_owns_pool_provider(provider):+ pool._borrowed_root_ids = set(disk_ids)+ return pooldiff --git a/hermes_cli/auth.py b/hermes_cli/auth.pyindex 6f823fa63be..cb888473965 100644--- a/hermes_cli/auth.py+++ b/hermes_cli/auth.py@@ -1687,6 +1687,120 @@ def is_runtime_provider_routable(provider_id: str) -> bool:return True+# Pool providers whose OAuth refresh tokens are SINGLE-USE: redeeming the+# refresh token rotates the pair and revokes the old one. A grant forked into+# two auth.json files is therefore not two credentials but one credential with+# two owners — the first owner to refresh strands the other with+# ``invalid_grant`` / ``refresh_token_reused`` (#100339; same class as the+# ``providers.<id>`` write-through hazard in #48415 / #43589). Profiles must+# never receive a copy of these grants: ONE grant lives at the global root and+# named profiles read it through the ``read_credential_pool`` root fallback.+SINGLE_USE_REFRESH_POOL_PROVIDERS = frozenset({+ "anthropic",+ "openai-codex",+ "xai-oauth",+})++# Singleton credential files that hold the same single-use grants outside+# ``auth.json``. Copying one into a profile re-seeds a forked pool row on the+# profile's next ``load_pool()``.+SINGLE_USE_OAUTH_SINGLETON_FILES = (".anthropic_oauth.json",)+++def _is_oauth_pool_payload(entry: Any) -> bool:+ if not isinstance(entry, dict):+ return False+ auth_type = str(entry.get("auth_type") or "").strip().lower()+ if auth_type == "oauth":+ return True+ # Legacy rows predating ``auth_type``: an Anthropic OAuth access token or+ # any row carrying a refresh token is an OAuth grant.+ if str(entry.get("refresh_token") or "").strip():+ return True+ return str(entry.get("access_token") or "").startswith("sk-ant-oat")+++def strip_cloned_single_use_oauth_grants(profile_dir: Path) -> Dict[str, Any]:+ """Remove forked single-use OAuth grants from a freshly cloned profile.++ Called after any code path that copies credential files from one profile+ into another (``hermes profile create --clone-all``, the dashboard/TUI+ ``mirror_credentials`` flow). API-key pool rows are kept — a static key is+ safe to duplicate. OAuth rows for the providers in+ ``SINGLE_USE_REFRESH_POOL_PROVIDERS``, the matching ``providers.<id>``+ device-code blocks, and the ``.anthropic_oauth.json`` singleton are+ dropped so the clone reads the grant from the global root instead of+ holding its own doomed copy (#100339).++ Returns a summary ``{"pool": [...provider ids], "providers": [...],+ "files": [...]}`` of what was stripped (empty lists when nothing was).+ Never raises: a clone must not fail because credential hygiene could not+ run — the caller logs the summary.+ """+ stripped: Dict[str, Any] = {"pool": [], "providers": [], "files": []}+ profile_dir = Path(profile_dir)+ for name in SINGLE_USE_OAUTH_SINGLETON_FILES:+ try:+ target = profile_dir / name+ if target.is_file() or target.is_symlink():+ target.unlink()+ stripped["files"].append(name)+ except OSError:+ logger.debug("Could not remove cloned %s from %s", name, profile_dir, exc_info=True)++ auth_path = profile_dir / "auth.json"+ if not auth_path.is_file():+ return stripped+ try:+ store = json.loads(auth_path.read_text(encoding="utf-8-sig"))+ except (OSError, json.JSONDecodeError):+ return stripped+ if not isinstance(store, dict):+ return stripped++ changed = False+ pool = store.get("credential_pool")+ if isinstance(pool, dict):+ for provider_id in list(pool):+ if provider_id not in SINGLE_USE_REFRESH_POOL_PROVIDERS:+ continue+ entries = pool.get(provider_id)+ if not isinstance(entries, list):+ continue+ kept = [e for e in entries if not _is_oauth_pool_payload(e)]+ if len(kept) != len(entries):+ changed = True+ stripped["pool"].append(provider_id)+ if kept:+ pool[provider_id] = kept+ else:+ # No local rows at all → read_credential_pool falls back+ # to the root slice for this provider.+ del pool[provider_id]+ providers = store.get("providers")+ if isinstance(providers, dict):+ # Device-code grants for these providers live under providers.<id>;+ # _load_provider_state has the same root fallback, so dropping the+ # copy keeps the profile working while removing the fork.+ for provider_id in ("openai-codex", "xai-oauth"):+ block = providers.get(provider_id)+ if isinstance(block, dict) and block:+ del providers[provider_id]+ stripped["providers"].append(provider_id)+ changed = True+ if not changed:+ return stripped+ try:+ _save_auth_store(store, target_path=auth_path)+ except Exception:+ logger.debug(+ "Failed to strip cloned single-use OAuth grants from %s",+ auth_path,+ exc_info=True,+ )+ return stripped++def read_credential_pool(provider_id: Optional[str] = None) -> Dict[str, Any]:"""Return the persisted credential pool, or one provider slice.diff --git a/hermes_cli/profiles.py b/hermes_cli/profiles.pyindex 389cc7933b1..9948b07f200 100644--- a/hermes_cli/profiles.py+++ b/hermes_cli/profiles.py@@ -1261,6 +1261,18 @@ def create_profile(# Strip runtime filesfor stale in _CLONE_ALL_STRIP:(profile_dir / stale).unlink(missing_ok=True)+ # A clone-all copies auth.json and .anthropic_oauth.json verbatim.+ # Single-use OAuth grants (Anthropic / Codex / xAI) forked that way+ # are one credential with two owners: the first profile to refresh+ # revokes the pair for every sibling (#100339). Drop the copies; the+ # clone reads the root grant through the credential-pool fallback.+ from hermes_cli.auth import strip_cloned_single_use_oauth_grants+ stripped = strip_cloned_single_use_oauth_grants(profile_dir)+ if any(stripped.values()):+ logger.info(+ "profile %s: dropped cloned single-use OAuth grants %s "+ "(inherits the root grant instead)", canon, stripped,+ )else:# Bootstrap directory structureprofile_dir.mkdir(parents=True, exist_ok=True)diff --git a/tests/agent/test_credential_pool_profile_oauth_fork.py b/tests/agent/test_credential_pool_profile_oauth_fork.pynew file mode 100644index 00000000000..a0f5ecd1f28--- /dev/null+++ b/tests/agent/test_credential_pool_profile_oauth_fork.py@@ -0,0 +1,257 @@+"""Regression tests for #100339: cloned / borrowed single-use Anthropic OAuth+grants must never fork across profiles.++Real imports, real temp HERMES_HOME root + named profile, real auth.json I/O.+The Anthropic token endpoint is replaced at the ``urllib.request.urlopen``+boundary with genuine single-use semantics (a refresh token redeems once;+a second POST returns ``invalid_grant``).+"""+from __future__ import annotations++import io+import json+import os+import time+import urllib.error+import urllib.request++import pytest+++def fleet(tmp_path, monkeypatch):+ """Root HERMES_HOME with an expired-but-refreshable Anthropic pool row."""+ root = tmp_path / "hermes-root"+ root.mkdir()+ (tmp_path / "fakehome").mkdir()+ # Keep host ~/.claude and host auth.json out of the picture.+ monkeypatch.setenv("HOME", str(tmp_path / "fakehome"))+ monkeypatch.setenv("CLAUDE_CONFIG_DIR", str(tmp_path / "fakehome"))+ for var in ("ANTHROPIC_TOKEN", "ANTHROPIC_API_KEY", "CLAUDE_CODE_OAUTH_TOKEN"):+ monkeypatch.delenv(var, raising=False)+ monkeypatch.setenv("HERMES_HOME", str(root))+ # The pytest seat-belt in the root write-through compares the global path+ # against $HOME/.hermes/auth.json; our root is elsewhere, so writes go.+ import hermes_constants+ hermes_constants._default_hermes_root_memo = None # type: ignore[attr-defined]++ expired = int((time.time() - 3600) * 1000)+ store = {+ "version": 1,+ "providers": {},+ "credential_pool": {+ "anthropic": [{+ "id": "abc123", "label": "team-grant", "auth_type": "oauth",+ "priority": 0, "source": "manual:hermes_pkce",+ "access_token": "sk-ant-oat01-AT0", "refresh_token": "sk-ant-ort-RT0",+ "expires_at_ms": expired, "base_url": "https://api.anthropic.com",+ }],+ "openai": [{+ "id": "key001", "label": "static", "auth_type": "api_key",+ "priority": 0, "source": "manual", "access_token": "sk-static-key",+ }],+ },+ }+ (root / "auth.json").write_text(json.dumps(store))++ server = {"valid": {"sk-ant-ort-RT0"}, "spent": set(), "n": 0, "log": []}++ class _Resp(io.BytesIO):+ def __enter__(self):+ return self++ def __exit__(self, *a):+ return False++ def fake_urlopen(req, timeout=None):+ assert "oauth/token" in req.full_url+ body = req.data.decode()+ if req.get_header("Content-type", "").startswith("application/json"):+ rt = json.loads(body)["refresh_token"]+ else:+ from urllib.parse import parse_qsl+ rt = dict(parse_qsl(body))["refresh_token"]+ if rt in server["spent"] or rt not in server["valid"]:+ server["log"].append(("REUSE", rt))+ raise urllib.error.HTTPError(+ req.full_url, 400, "Bad Request", {},+ io.BytesIO(b'{"error":"invalid_grant","error_description":"refresh_token_reused"}'),+ )+ server["n"] += 1+ server["spent"].add(rt)+ server["valid"].discard(rt)+ new_rt = f"sk-ant-ort-RT{server['n']}"+ server["valid"].add(new_rt)+ server["log"].append(("ROTATE", rt, new_rt))+ return _Resp(json.dumps({+ "access_token": f"sk-ant-oat01-AT{server['n']}",+ "refresh_token": new_rt, "expires_in": 28800, "token_type": "Bearer",+ }).encode())++ monkeypatch.setattr(urllib.request, "urlopen", fake_urlopen)++ def use(home):+ """Switch the process to *home* (root or a profile dir)."""+ monkeypatch.setenv("HERMES_HOME", str(home))+ hermes_constants._default_hermes_root_memo = None # type: ignore[attr-defined]+ import hermes_cli.auth as auth_mod+ auth_mod._global_auth_store_cache = None++ def pool_rows(home):+ p = home / "auth.json"+ if not p.exists():+ return None+ return (json.loads(p.read_text()).get("credential_pool") or {}).get("anthropic")++ return {"root": root, "server": server, "use": use, "rows": pool_rows}+++def _profile(fleet, name, **kw):+ from hermes_cli.profiles import create_profile+ fleet["use"](fleet["root"])+ return create_profile(name, **kw)+++# ── A. cloning never copies single-use OAuth grants ──────────────────────++def test_clone_all_strips_oauth_grant_but_keeps_api_keys(fleet):+ (fleet["root"] / ".anthropic_oauth.json").write_text(+ json.dumps({"accessToken": "sk-ant-oat01-AT0", "refreshToken": "sk-ant-ort-RT0", "expiresAt": 1})+ )+ pdir = _profile(fleet, "forge", clone_all=True)+ store = json.loads((pdir / "auth.json").read_text())+ assert "anthropic" not in store["credential_pool"], "OAuth grant was forked into the clone"+ assert store["credential_pool"]["openai"][0]["access_token"] == "sk-static-key"+ assert not (pdir / ".anthropic_oauth.json").exists()+++def test_strip_helper_drops_device_code_blocks_and_reports(tmp_path):+ from hermes_cli.auth import strip_cloned_single_use_oauth_grants+ pdir = tmp_path / "p"+ pdir.mkdir()+ (pdir / "auth.json").write_text(json.dumps({+ "version": 1,+ "providers": {"openai-codex": {"access_token": "a", "refresh_token": "r"}, "nous": {"agent_key": "k"}},+ "credential_pool": {+ "xai-oauth": [{"id": "x", "auth_type": "oauth", "access_token": "t", "refresh_token": "r"}],+ "anthropic": [+ {"id": "legacy", "access_token": "sk-ant-oat01-legacy"}, # no auth_type field+ {"id": "key", "auth_type": "api_key", "access_token": "sk-ant-api03-x"},+ ],+ },+ }))+ summary = strip_cloned_single_use_oauth_grants(pdir)+ store = json.loads((pdir / "auth.json").read_text())+ assert sorted(summary["pool"]) == ["anthropic", "xai-oauth"]+ assert summary["providers"] == ["openai-codex"]+ assert "xai-oauth" not in store["credential_pool"]+ assert [e["id"] for e in store["credential_pool"]["anthropic"]] == ["key"]+ assert "openai-codex" not in store["providers"] and "nous" in store["providers"]+++def test_strip_helper_is_a_noop_without_credentials(tmp_path):+ from hermes_cli.auth import strip_cloned_single_use_oauth_grants+ assert strip_cloned_single_use_oauth_grants(tmp_path) == {"pool": [], "providers": [], "files": []}+++# ── B. borrowed rotation commits to root, never a profile copy ───────────++def test_first_profile_rotation_does_not_strand_root_or_siblings(fleet):+ from agent.credential_pool import load_pool++ forge = _profile(fleet, "forge")+ atlas = _profile(fleet, "atlas")++ fleet["use"](forge)+ sel = load_pool("anthropic").select()+ assert sel is not None and sel.access_token == "sk-ant-oat01-AT1"+ # The rotated pair landed in ROOT; forge did not grow a local copy.+ assert fleet["rows"](forge) is None+ assert fleet["rows"](fleet["root"])[0]["refresh_token"] == "sk-ant-ort-RT1"++ for home in (atlas, fleet["root"], forge):+ fleet["use"](home)+ sel = load_pool("anthropic").select()+ assert sel is not None and sel.access_token == "sk-ant-oat01-AT1", home+ assert [e[0] for e in fleet["server"]["log"]] == ["ROTATE"], fleet["server"]["log"]+ assert fleet["rows"](atlas) is None and fleet["rows"](forge) is None+++def test_agent_init_resolver_sees_sibling_rotation(fleet):+ from agent.anthropic_credentials import resolve_anthropic_token+ from agent.credential_pool import load_pool++ forge = _profile(fleet, "forge")+ atlas = _profile(fleet, "atlas")+ fleet["use"](forge)+ load_pool("anthropic").select()+ fleet["use"](atlas)+ assert resolve_anthropic_token() == "sk-ant-oat01-AT1"+++def test_borrowing_profile_load_pool_does_not_materialize_local_copy(fleet):+ from agent.credential_pool import load_pool++ fresh = _profile(fleet, "fresh")+ fleet["use"](fresh)+ pool = load_pool("anthropic")+ assert [e.id for e in pool.entries()] == ["abc123"]+ assert pool._borrowed_root_ids == {"abc123"}+ assert fleet["rows"](fresh) is None+++def test_borrower_prune_never_deletes_root_singleton_grant(fleet, tmp_path):+ """Root's hermes_pkce row is seeded from ROOT's .anthropic_oauth.json; a+ profile without that file must not prune (and write-through-delete) it."""+ from agent.credential_pool import load_pool++ root = fleet["root"]+ (root / ".anthropic_oauth.json").write_text(json.dumps({+ "accessToken": "sk-ant-oat01-AT0", "refreshToken": "sk-ant-ort-RT0",+ "expiresAt": int((time.time() - 3600) * 1000),+ }))+ store = json.loads((root / "auth.json").read_text())+ store["active_provider"] = "anthropic"+ del store["credential_pool"]["anthropic"]+ (root / "auth.json").write_text(json.dumps(store))+ fleet["use"](root)+ root_rows = [e for e in load_pool("anthropic").entries()]+ assert [e.source for e in root_rows] == ["hermes_pkce"]++ kid = _profile(fleet, "kid")+ fleet["use"](kid)+ pool = load_pool("anthropic")+ assert [e.source for e in pool.entries()] == ["hermes_pkce"], "borrowed root grant was pruned"+ assert fleet["rows"](root) and fleet["rows"](root)[0]["source"] == "hermes_pkce"+ assert fleet["rows"](kid) is None++ # Rotating from the profile commits BOTH the pool row and the singleton at ROOT.+ sel = pool.select()+ assert sel is not None and sel.access_token == "sk-ant-oat01-AT1"+ assert json.loads((root / ".anthropic_oauth.json").read_text())["refreshToken"] == "sk-ant-ort-RT1"+ assert not (kid / ".anthropic_oauth.json").exists()+ assert fleet["rows"](root)[0]["refresh_token"] == "sk-ant-ort-RT1"+++def test_profile_auth_add_owns_only_its_own_rows(fleet):+ from agent.credential_pool import AUTH_TYPE_OAUTH, PooledCredential, load_pool++ kid = _profile(fleet, "kid")+ fleet["use"](kid)+ pool = load_pool("anthropic")+ pool.add_entry(PooledCredential(+ provider="anthropic", id="own001", label="mine", auth_type=AUTH_TYPE_OAUTH,+ priority=0, source="manual:hermes_pkce", access_token="sk-ant-oat01-MINE",+ refresh_token="rt-mine",+ ))+ assert [e["id"] for e in fleet["rows"](kid)] == ["own001"], "borrowed root row was copied into the profile"+ assert [e["id"] for e in fleet["rows"](fleet["root"])] == ["abc123"]+++def test_classic_mode_persist_is_unchanged(fleet):+ from agent.credential_pool import load_pool++ fleet["use"](fleet["root"])+ sel = load_pool("anthropic").select()+ assert sel is not None and sel.access_token == "sk-ant-oat01-AT1"+ assert fleet["rows"](fleet["root"])[0]["refresh_token"] == "sk-ant-ort-RT1"diff --git a/tui_gateway/methods_profiles.py b/tui_gateway/methods_profiles.pyindex db894586bf4..3cc757d3b57 100644--- a/tui_gateway/methods_profiles.py+++ b/tui_gateway/methods_profiles.py@@ -467,6 +467,15 @@ def _(rid, params: dict) -> dict:os.chmod(str(dst_auth), 0o600)except OSError:pass+ # Mirroring must not fork single-use OAuth grants (Anthropic /+ # Codex / xAI): the first profile to refresh strands every+ # sibling (#100339). API keys stay; OAuth rows are dropped+ # and read from the root grant via the pool fallback.+ try:+ from hermes_cli.auth import strip_cloned_single_use_oauth_grants+ strip_cloned_single_use_oauth_grants(path)+ except Exception:+ passmirrored["auth"] = Trueexcept Exception:passdiff --git a/website/docs/user-guide/profiles.md b/website/docs/user-guide/profiles.mdindex ae4ad7055f3..ca3349defd7 100644--- a/website/docs/user-guide/profiles.md+++ b/website/docs/user-guide/profiles.md@@ -64,6 +64,10 @@ hermes profile create backup --clone-allCopies **everything** — config, API keys, personality, all memories, skills, cron jobs, plugins. A complete working snapshot. Per-profile history is excluded (session history, `state.db`, `backups/`, `state-snapshots/`, `checkpoints/`) — these belong to the source profile and can reach tens of GB. For a full backup including history, use `hermes profile export` or `hermes backup` instead.+:::note OAuth logins are shared, not copied+Anthropic (Claude Pro/Max), OpenAI Codex, and xAI OAuth logins use **single-use refresh tokens** — a copy of one is not a second credential, it is the same credential with two owners, and the first profile to refresh it revokes it for every other copy. `--clone-all` (and the dashboard's credential mirroring) therefore drops those OAuth rows from the clone. The new profile keeps reading the login from the root `~/.hermes/auth.json`, and a token refresh performed inside any profile is written back to root, so all profiles stay signed in. Static API keys are copied as usual. To give a profile its own separate OAuth login, run `hermes -p <name> auth add <provider>` inside it.+:::+### Clone from a specific profile```bash