fix(auth): named profiles no longer inherit the root profile's auth.json (#111724)
A named profile with no credentials of its own silently resolved the root
profile's provider state and credential pool, and a token refresh inside
that profile (xAI, Codex, Anthropic PKCE, Nous) wrote the rotated chain back
into the root store. An isolated service profile therefore acted, and
rotated tokens, as the owner with no way to switch it off.
Maintainer ruling: profiles without credentials are asked to set a provider,
never handed another profile's auth. Profiles are independent islands.
What changes
- `hermes_cli/auth.py`: `_load_provider_state*`, `read_credential_pool` and
`_provider_state_transaction` read the active store only; the global-root
resolver, its mtime memo and `_persist_provider_state_to_store` are gone.
- xAI / Codex / Nous-guest / pool refresh paths persist to the active store;
the root write-through, the borrowed-row bookkeeping
(`_borrowed_root_ids`, `persist_pool_entries`, `_update_root_pool_rows`)
and the forked-grant heal are removed. `_write_hermes_oauth_credentials`
loses its root `target`.
- `resolve_provider` / `agent_init` name the profile in the
no-provider error and print `hermes -p <name> model` guidance.
- `hermes update` prints a one-time notice listing every named profile that
has no provider of its own (`hermes_cli/profile_credential_audit.py`) so a
bot never goes quiet unannounced.
- Desktop create dialog: the "Share keys & accounts" checkbox described the
removed inheritance; it now mirrors API keys (`mirror_credentials`) and
says OAuth logins need a sign-in. `share_auth` is accepted from older
clients and ignored; `ProfileMirrored.auth` is a bool again.
- Docs: profiles.md, multi-profile-gateways.md isolation table,
hermes_cli/AGENTS.md.
The fallback was added in 33bf5f62 so kanban/cron workers under a named
profile did not die with "No LLM provider configured" when the credential
lived only at root; that convenience is exactly the isolation hole the
ruling closes, and `--clone` / dashboard mirroring still copy API keys.
Tests: fallback/write-through/heal pins deleted; 4 invariants proven red on
base (profile never reads root; profile refresh never writes root; Nous
connector gate reads only the profile store; Anthropic pool never borrows or
rotates the root grant, root control still refreshes).
This commit is contained in:
1 parent
3b5456ec64
commit
93889b770d
34 files changed
+480
-2632
No files matched your search
+4
-2
@@ -874,9 +874,11 @@ def _routed_client_kwargs(agent, fallback_model, _provider_timeout) -> Dict[str,
|
||||
f"was found. Set the {_env_hint} environment "
|
||||
f"variable, or switch to a different provider with `hermes model`."
|
||||
)
|
||||
from hermes_constants import profile_cli_selector
|
||||
_sel = profile_cli_selector()
|
||||
raise RuntimeError(
|
||||
"No LLM provider configured. Run `hermes model` to "
|
||||
"select a provider, or run `hermes setup` for first-time "
|
||||
f"No LLM provider configured. Run `hermes {_sel}model` to "
|
||||
f"select a provider, or run `hermes {_sel}setup` for first-time "
|
||||
"configuration."
|
||||
)
|
||||
|
||||
|
||||
@@ -479,17 +479,6 @@ 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`` inside a named profile (None in classic mode); used to commit a
|
||||
rotation of a grant the profile borrowed via the pool's root fallback."""
|
||||
try:
|
||||
from hermes_constants import get_default_hermes_root
|
||||
root = get_default_hermes_root()
|
||||
return None if root.resolve(strict=False) == get_hermes_home().resolve(strict=False) else root / ".anthropic_oauth.json"
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
|
||||
def _generate_pkce() -> tuple:
|
||||
"""Generate PKCE code_verifier and code_challenge (S256)."""
|
||||
verifier = base64.urlsafe_b64encode(secrets.token_bytes(32)).rstrip(b"=").decode()
|
||||
@@ -559,14 +548,13 @@ def read_hermes_oauth_credentials() -> Optional[Dict[str, Any]]:
|
||||
|
||||
|
||||
def _write_hermes_oauth_credentials(
|
||||
access_token: str, refresh_token: Optional[str], expires_at_ms: Optional[int], *, target: Optional[Path] = None
|
||||
access_token: str, refresh_token: Optional[str], expires_at_ms: Optional[int],
|
||||
) -> None:
|
||||
"""Commit refreshed hermes_pkce tokens to ~/.hermes/.anthropic_oauth.json (``CredentialPersistError`` on failure).
|
||||
``target`` lets a named profile commit a grant it BORROWED from the global root back to the ROOT singleton
|
||||
instead of forking a copy under its own HERMES_HOME; without this write-through the next ``load_pool()``
|
||||
re-seeds the stale (consumed) pair from the file over the rotated pool entry."""
|
||||
"""Commit refreshed hermes_pkce tokens to ``<HERMES_HOME>/.anthropic_oauth.json`` (``CredentialPersistError``
|
||||
on failure); without it the next ``load_pool()`` re-seeds the stale (consumed) pair from the file over the
|
||||
rotated pool entry."""
|
||||
_commit_private_json(
|
||||
target if target is not None else _get_hermes_oauth_file(),
|
||||
_get_hermes_oauth_file(),
|
||||
{"accessToken": access_token, "refreshToken": refresh_token, "expiresAt": expires_at_ms},
|
||||
"Hermes OAuth credentials",
|
||||
)
|
||||
+14
-242
@@ -33,13 +33,10 @@ from hermes_cli.auth import (
|
||||
_auth_store_lock,
|
||||
_codex_access_token_is_expiring,
|
||||
_decode_jwt_claims,
|
||||
_global_auth_file_path,
|
||||
_load_auth_store,
|
||||
_load_provider_state,
|
||||
_load_provider_state_with_source,
|
||||
_resolve_kimi_base_url,
|
||||
_resolve_zai_base_url,
|
||||
_same_path,
|
||||
_save_auth_store,
|
||||
_save_provider_state,
|
||||
_store_provider_state,
|
||||
@@ -672,180 +669,6 @@ def resolve_runtime_pool_key(provider: Optional[str], base_url: Optional[str]) -
|
||||
DEFAULT_MAX_CONCURRENT_PER_CREDENTIAL = 1
|
||||
|
||||
|
||||
# --- Multi-profile root write-through ---
|
||||
|
||||
|
||||
def _guarded_global_root(global_path: Optional[Path]) -> Optional[Path]:
|
||||
"""Apply the pytest seat belt to a resolved global-root auth.json path.
|
||||
|
||||
``None`` means classic mode (profile == root) or "refuse": under pytest,
|
||||
never write the real user's ``~/.hermes/auth.json`` even when HERMES_HOME
|
||||
points at a profile path (mirrors the read-side guard in
|
||||
``_load_global_auth_store``). Uses the unmodified HOME env, not
|
||||
``Path.home()`` which fixtures may monkeypatch.
|
||||
"""
|
||||
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 _write_through_provider_state_to_global_root(
|
||||
provider_id: str, state: Dict[str, Any]
|
||||
) -> None:
|
||||
"""Persist a rotated OAuth ``state`` into the global-root auth.json.
|
||||
|
||||
Best-effort write-through for the multi-profile rotation hazard: nous,
|
||||
openai-codex, and xai-oauth rotate the refresh_token on refresh, so when
|
||||
a profile pool refresh rotates a grant it resolved from the root fallback,
|
||||
the rotated chain must land back in root. Otherwise root keeps a revoked
|
||||
refresh token and every other profile dies with ``refresh_token_reused``
|
||||
/ ``invalid_grant`` once its access token expires.
|
||||
|
||||
Only updates ``providers.<provider_id>`` in the root store; never touches
|
||||
the profile store (the caller already saved that). Swallows all errors —
|
||||
a failed write-through degrades to root-stale and must never break the
|
||||
profile's own successful save. Mirrors
|
||||
``hermes_cli.auth._write_through_xai_oauth_to_global_root``.
|
||||
|
||||
See #48415.
|
||||
"""
|
||||
try:
|
||||
global_path = _guarded_global_root(auth_mod._global_auth_file_path())
|
||||
except Exception:
|
||||
return
|
||||
if global_path is None:
|
||||
return
|
||||
try:
|
||||
auth_mod._persist_provider_state_to_store(provider_id, state, global_path, set_active=False)
|
||||
except Exception as exc: # pragma: no cover - best effort
|
||||
logger.debug("%s pool refresh: write-through to global root failed: %s", provider_id, exc)
|
||||
|
||||
|
||||
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]:
|
||||
"""Global-root auth.json when persisting a BORROWED single-use pool, else None.
|
||||
|
||||
``None`` means "persist to the active store as usual": classic mode
|
||||
(profile == root), or the profile owns its own rows for this provider.
|
||||
"""
|
||||
try:
|
||||
return _guarded_global_root(_global_auth_file_path())
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
|
||||
def _update_root_pool_rows(
|
||||
provider: str, payloads: List[Dict[str, Any]], global_path: Path,
|
||||
*, status_cleared_ids: Optional[Iterable[str]] = None,
|
||||
) -> None:
|
||||
"""UPDATE-ONLY merge of *payloads* into the root store's rows for *provider*.
|
||||
|
||||
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, so ``removed_ids`` is ignored by callers.
|
||||
"""
|
||||
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")}
|
||||
cleared = {cid for cid in (status_cleared_ids or ()) if cid}
|
||||
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
|
||||
# A deliberately cleared entry has no disk cooldown worth keeping.
|
||||
updated = auth_mod._merge_disk_cooldown_state(
|
||||
incoming, None if did in cleared else 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)
|
||||
|
||||
|
||||
def persist_pool_entries(
|
||||
provider: str,
|
||||
payloads: List[Dict[str, Any]],
|
||||
*,
|
||||
removed_ids: Optional[Iterable[str]] = None,
|
||||
status_cleared_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: 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`` (#100339). Such rows are written back to the root store
|
||||
(under the root lock); everything else goes to the active store.
|
||||
"""
|
||||
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:
|
||||
try:
|
||||
_update_root_pool_rows(
|
||||
provider, payloads, global_path,
|
||||
status_cleared_ids=status_cleared_ids,
|
||||
)
|
||||
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, status_cleared_ids=status_cleared_ids,
|
||||
)
|
||||
|
||||
|
||||
# --- Per-provider singleton refresh plumbing -------------------------------
|
||||
@@ -895,9 +718,6 @@ class CredentialPool(CredentialPoolAdminMixin):
|
||||
self.provider = provider
|
||||
self._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: _replace_entry/_persist self-acquire it so the DEFERRED
|
||||
# single-use-token refresh path (network I/O outside the lock by
|
||||
@@ -1019,7 +839,7 @@ class CredentialPool(CredentialPoolAdminMixin):
|
||||
) -> None:
|
||||
# Self-locking: snapshotting self._entries must not race a rotation.
|
||||
with self._lock:
|
||||
persist_pool_entries(
|
||||
write_credential_pool(
|
||||
self.provider,
|
||||
[entry.to_dict() for entry in self._entries],
|
||||
removed_ids=removed_ids,
|
||||
@@ -1293,14 +1113,6 @@ class CredentialPool(CredentialPoolAdminMixin):
|
||||
``set_active=False`` everywhere: a sync-back is a token-rotation side
|
||||
effect, not the user choosing a provider; ``_save_provider_state``
|
||||
would flip ``active_provider`` to whichever provider refreshed last.
|
||||
|
||||
#74339: decide the root write-through on WHERE the state resolved
|
||||
from (``_load_provider_state_with_source``), not on whether the
|
||||
profile has a ``providers.<id>`` key — ``_store_provider_state``
|
||||
creates that key unconditionally, which self-sealed the check after
|
||||
the first refresh. When the grant came from the global root, write
|
||||
back to root ONLY and skip the profile store so it never accrues a
|
||||
shadowing key that blocks both the fallback and the write-through.
|
||||
"""
|
||||
# Only singleton-seeded entries sync back; ``manual:*`` entries are
|
||||
# independent credentials and must not write to the singleton.
|
||||
@@ -1309,20 +1121,13 @@ class CredentialPool(CredentialPoolAdminMixin):
|
||||
try:
|
||||
with _auth_store_lock():
|
||||
auth_store = _load_auth_store()
|
||||
state, source_path = _load_provider_state_with_source(auth_store, self.provider)
|
||||
state = _load_provider_state(auth_store, self.provider)
|
||||
if not isinstance(state, dict):
|
||||
return
|
||||
global_root = _global_auth_file_path()
|
||||
is_from_root = bool(
|
||||
source_path is not None and global_root is not None and _same_path(source_path, global_root)
|
||||
)
|
||||
if not self._apply_entry_to_singleton_state(entry, state):
|
||||
return
|
||||
if is_from_root:
|
||||
_write_through_provider_state_to_global_root(self.provider, state)
|
||||
else:
|
||||
_store_provider_state(auth_store, self.provider, state, set_active=False)
|
||||
_save_auth_store(auth_store)
|
||||
_store_provider_state(auth_store, self.provider, state, set_active=False)
|
||||
_save_auth_store(auth_store)
|
||||
except Exception as exc:
|
||||
logger.debug("Failed to sync %s pool entry back to auth store: %s", self.provider, exc)
|
||||
|
||||
@@ -1470,11 +1275,10 @@ class CredentialPool(CredentialPoolAdminMixin):
|
||||
"""Write a rotated Anthropic pair to its authoritative singleton, or fail closed.
|
||||
|
||||
claude_code -> ~/.claude/.credentials.json (so the fallback resolver
|
||||
and other profiles see it). hermes_pkce -> ~/.hermes/.anthropic_oauth.json
|
||||
(``_seed_from_singletons`` re-seeds it every load; a borrowed row commits
|
||||
to the ROOT's file, never a new profile-local copy, #100339). Not
|
||||
``endswith``: manual:hermes_pkce is pool-owned and a singleton for it
|
||||
would be a second authority for the same refresh-token family.
|
||||
and other profiles see it). hermes_pkce -> <HERMES_HOME>/.anthropic_oauth.json
|
||||
(``_seed_from_singletons`` re-seeds it every load). Not ``endswith``:
|
||||
manual:hermes_pkce is pool-owned and a singleton for it would be a second
|
||||
authority for the same refresh-token family.
|
||||
"""
|
||||
if entry.source == "claude_code":
|
||||
store = "~/.claude/.credentials.json"
|
||||
@@ -1488,7 +1292,7 @@ class CredentialPool(CredentialPoolAdminMixin):
|
||||
if entry.source == "claude_code":
|
||||
ac._write_claude_code_credentials(*args)
|
||||
else:
|
||||
ac._write_hermes_oauth_credentials(*args, target=_singleton_target_for_entry(self, entry))
|
||||
ac._write_hermes_oauth_credentials(*args)
|
||||
except Exception as wexc:
|
||||
# Authoritative commit failed: do not mark, persist or return the
|
||||
# rotation as successful, and bypass the re-POST recovery path —
|
||||
@@ -2714,10 +2518,6 @@ def _seed_custom_pool(pool_key: str, entries: List[PooledCredential]) -> Tuple[b
|
||||
|
||||
def load_pool(provider: str) -> CredentialPool:
|
||||
provider = (provider or "").strip().lower()
|
||||
if provider in SINGLE_USE_REFRESH_POOL_PROVIDERS:
|
||||
# One-time heal for installs that forked this grant across profiles
|
||||
# before the clone-strip / root write-through existed (#100339).
|
||||
auth_mod.heal_forked_single_use_oauth_grants(provider)
|
||||
raw_entries = read_credential_pool(provider)
|
||||
disk_ids = {e.get("id") for e in raw_entries if isinstance(e, dict) and e.get("id")}
|
||||
changed = any(
|
||||
@@ -2732,13 +2532,7 @@ def load_pool(provider: str) -> CredentialPool:
|
||||
) != payload.get("auth_type", AUTH_TYPE_API_KEY)
|
||||
for payload in raw_entries
|
||||
)
|
||||
if raw_needs_auth_normalization:
|
||||
# A profile may be reading this provider from the global-root fallback.
|
||||
# Keep that fallback read-only: only the owning store may rewrite these
|
||||
# rows; loading the default/root profile heals global rows.
|
||||
active_pool = _load_auth_store().get("credential_pool")
|
||||
active_entries = active_pool.get(provider) if isinstance(active_pool, dict) else None
|
||||
changed |= bool(active_entries)
|
||||
changed |= raw_needs_auth_normalization
|
||||
|
||||
if provider.startswith(CUSTOM_POOL_PREFIX):
|
||||
custom_changed, custom_sources = _seed_custom_pool(provider, entries)
|
||||
@@ -2750,38 +2544,16 @@ def load_pool(provider: str) -> CredentialPool:
|
||||
changed |= singleton_changed or env_changed
|
||||
# ``load_pool()`` is a non-destructive read for env-seeded entries
|
||||
# (#9331); file-backed singletons still prune when their file is gone.
|
||||
borrowing_root_grant = (
|
||||
provider in SINGLE_USE_REFRESH_POOL_PROVIDERS
|
||||
and bool(disk_ids)
|
||||
and not _profile_owns_pool_provider(provider)
|
||||
changed |= _prune_stale_seeded_entries(
|
||||
entries, singleton_sources | env_sources, prune_env_sources=False,
|
||||
)
|
||||
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 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}
|
||||
persist_pool_entries(
|
||||
write_credential_pool(
|
||||
provider,
|
||||
[entry.to_dict() for entry in sorted(entries, key=lambda item: item.priority)],
|
||||
removed_ids=disk_ids - new_ids,
|
||||
)
|
||||
pool = CredentialPool(provider, entries)
|
||||
# Remember the root's borrowed rows so a later ``add_entry`` in this
|
||||
# profile leaves 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 pool
|
||||
return CredentialPool(provider, entries)
|
||||
@@ -51,18 +51,12 @@ class CredentialPoolAdminMixin:
|
||||
return len(stale)
|
||||
|
||||
def remove_index(self, index: int) -> Optional[PooledCredential]:
|
||||
from agent.credential_pool import persist_pool_entries
|
||||
|
||||
with self._lock:
|
||||
if index < 1 or index > len(self._entries):
|
||||
return None
|
||||
removed = self._entries.pop(index - 1)
|
||||
self._entries = [replace(e, priority=p) for p, e in enumerate(self._entries)]
|
||||
persist_pool_entries(
|
||||
self.provider,
|
||||
[entry.to_dict() for entry in self._entries],
|
||||
removed_ids=[removed.id],
|
||||
)
|
||||
self._persist(removed_ids=[removed.id])
|
||||
if self._current_id == removed.id:
|
||||
self._current_id = None
|
||||
return removed
|
||||
@@ -111,21 +105,10 @@ class CredentialPoolAdminMixin:
|
||||
return None, None, f'No credential matching "{raw}".'
|
||||
|
||||
def add_entry(self, entry: PooledCredential) -> PooledCredential:
|
||||
from agent.credential_pool import _next_priority, write_credential_pool
|
||||
from agent.credential_pool import _next_priority
|
||||
|
||||
with self._lock:
|
||||
entry = replace(entry, priority=_next_priority(self._entries))
|
||||
self._entries.append(entry)
|
||||
borrowed_ids = getattr(self, "_borrowed_root_ids", None)
|
||||
if borrowed_ids:
|
||||
# ``hermes -p <profile> auth add <single-use provider>``: the
|
||||
# profile claims its OWN credential. Persist only profile-owned
|
||||
# rows — copying the borrowed root grant alongside would fork
|
||||
# its single-use refresh token (#100339). Once the profile owns
|
||||
# rows, the root fallback for this provider is shadowed.
|
||||
self._entries = [e for e in self._entries if e.id not in borrowed_ids]
|
||||
write_credential_pool(self.provider, [e.to_dict() for e in self._entries])
|
||||
self._borrowed_root_ids = set()
|
||||
else:
|
||||
self._persist()
|
||||
self._persist()
|
||||
return entry
|
||||
@@ -271,7 +271,6 @@ export async function ensureSetupProfile(request: GatewayRequest): Promise<void>
|
||||
description: 'Where Hermes met you — walks your first run, then checks in as you find your feet.',
|
||||
name: SETUP_PROFILE,
|
||||
clone_from: 'default',
|
||||
share_auth: true,
|
||||
no_alias: true,
|
||||
soul: composeSetupSoul()
|
||||
})
|
||||
|
||||
@@ -140,7 +140,7 @@ export function CreateAgentDialog({ open, onClose, roster }: CreateAgentDialogPr
|
||||
const [provider, setProvider] = useState('')
|
||||
const [soul, setSoul] = useState('')
|
||||
const [noSkills, setNoSkills] = useState(false)
|
||||
const [shareAuth, setShareAuth] = useState(true)
|
||||
const [mirrorCredentials, setMirrorCredentials] = useState(true)
|
||||
const [advTab, setAdvTab] = useState('general')
|
||||
// Where the profile is created: '' = the active gateway (unchanged default),
|
||||
// else a registry connection id — the profiles.create lands on THAT
|
||||
@@ -273,7 +273,7 @@ export function CreateAgentDialog({ open, onClose, roster }: CreateAgentDialogPr
|
||||
setProvider('')
|
||||
setSoul('')
|
||||
setNoSkills(false)
|
||||
setShareAuth(true)
|
||||
setMirrorCredentials(true)
|
||||
setAdvTab('general')
|
||||
setCreatedForCaps(null)
|
||||
setCaps(null)
|
||||
@@ -388,10 +388,10 @@ export function CreateAgentDialog({ open, onClose, roster }: CreateAgentDialogPr
|
||||
// the remote box doesn't have.
|
||||
clone_from: cloneFrom === '__none__' ? null : remoteTarget ? 'default' : cloneFrom,
|
||||
no_skills: noSkills,
|
||||
// Shared (not copied) auth keeps ONE OAuth/token pool with the main
|
||||
// profile, so refreshes can't invalidate each other. Older gateways
|
||||
// ignore the param and copy — still functional, just forked.
|
||||
share_auth: shareAuth,
|
||||
// Copies the main profile's API keys (.env + auth.json) into the new profile. OAuth
|
||||
// logins are never copied (single-use refresh tokens fork) and never inherited: a
|
||||
// profile only reads its own auth.json, so sign the bot in itself for those.
|
||||
mirror_credentials: mirrorCredentials,
|
||||
soul: composeSoul({
|
||||
name: slug,
|
||||
title,
|
||||
@@ -786,12 +786,16 @@ export function CreateAgentDialog({ open, onClose, roster }: CreateAgentDialogPr
|
||||
/>
|
||||
)}
|
||||
<label className="flex items-center gap-2 text-xs text-(--ui-text-secondary)">
|
||||
<Checkbox checked={shareAuth} onCheckedChange={value => setShareAuth(Boolean(value))} />
|
||||
Share keys & accounts with the main profile
|
||||
<Checkbox
|
||||
checked={mirrorCredentials}
|
||||
onCheckedChange={value => setMirrorCredentials(Boolean(value))}
|
||||
/>
|
||||
Copy API keys from the main profile
|
||||
</label>
|
||||
<div className="pl-6 pt-0.5 text-[0.7rem] leading-5 text-(--ui-text-tertiary)">
|
||||
Subscriptions, OAuth logins, and API keys stay shared (not copied), so token refreshes never
|
||||
invalidate each other. Uncheck for an isolated snapshot copy.
|
||||
Each profile owns its credentials. API keys are copied; OAuth logins (Claude, Codex, xAI, Nous)
|
||||
are not — sign the bot in with <code>hermes -p <name> model</code>. Uncheck to start with
|
||||
no credentials.
|
||||
</div>
|
||||
<label className="flex items-center gap-2 text-xs text-(--ui-text-secondary)">
|
||||
<Checkbox checked={noSkills} onCheckedChange={value => setNoSkills(Boolean(value))} />
|
||||
|
||||
@@ -1505,10 +1505,10 @@ export interface ProfilesCreateResult {
|
||||
model_set?: boolean
|
||||
mirrored: ProfileMirrored
|
||||
}
|
||||
/** What was copied from the launch profile; ``auth`` is ``"shared"`` under ``share_auth``. */
|
||||
/** What was copied from the launch profile. */
|
||||
export interface ProfileMirrored {
|
||||
env?: boolean
|
||||
auth?: boolean | 'shared'
|
||||
auth?: boolean
|
||||
model_inherited?: boolean
|
||||
voice?: boolean
|
||||
}
|
||||
|
||||
@@ -18977,7 +18977,7 @@
|
||||
},
|
||||
"ProfileMirrored": {
|
||||
"additionalProperties": false,
|
||||
"description": "What was copied from the launch profile; ``auth`` is ``\"shared\"`` under ``share_auth``.",
|
||||
"description": "What was copied from the launch profile.",
|
||||
"properties": {
|
||||
"env": {
|
||||
"default": false,
|
||||
@@ -18985,17 +18985,9 @@
|
||||
"type": "boolean"
|
||||
},
|
||||
"auth": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "boolean"
|
||||
},
|
||||
{
|
||||
"const": "shared",
|
||||
"type": "string"
|
||||
}
|
||||
],
|
||||
"default": false,
|
||||
"title": "Auth"
|
||||
"title": "Auth",
|
||||
"type": "boolean"
|
||||
},
|
||||
"model_inherited": {
|
||||
"default": false,
|
||||
|
||||
@@ -153,7 +153,9 @@ profile. The multiplex gateway and the Desktop/dashboard `serve` backend instead
|
||||
profile per activity via a contextvar override while `os.environ["HERMES_HOME"]` keeps the launch
|
||||
profile — a module constant or import-time read there freezes to the launch profile (rules in
|
||||
root). Profiles are independent
|
||||
islands by design — no live config inheritance; `--clone` copies at creation, minus messaging
|
||||
islands by design — no live config inheritance and no credential inheritance (a named profile reads
|
||||
only its own `auth.json`/`.env`; the root store is never a fallback and never a write-through target,
|
||||
#111724 — a profile without a provider gets the setup prompt); `--clone` copies at creation, minus messaging
|
||||
channels (`profile_channels.py`: ownership-based inventory evaluated in the SOURCE's plugin scope —
|
||||
adapter-declared keys + canonical/alias prefixes + `GATEWAY_ALLOW*`/`GATEWAY_RELAY_*`; prefixes shared
|
||||
with tools (`HASS_`/`TWILIO_`/`EMAIL_`) are stripped only when the source runs that adapter; never a hand
|
||||
|
||||
+4
-11
@@ -819,12 +819,10 @@ def guest_notice_pending() -> bool:
|
||||
|
||||
|
||||
def mark_guest_notice_shown() -> bool:
|
||||
"""Persist ``guest_notice_shown`` on the guest's ``providers.nous`` state (whichever store holds it).
|
||||
"""Persist ``guest_notice_shown`` on the guest's ``providers.nous`` state (the active store).
|
||||
|
||||
Returns True when a flag was written; False when there is no guest to mark."""
|
||||
from hermes_cli.auth import (
|
||||
_auth_file_path, _load_auth_store, _provider_state_transaction, _same_path, _save_auth_store,
|
||||
_store_section)
|
||||
from hermes_cli.auth import _provider_state_transaction, _save_auth_store, _store_section
|
||||
with _provider_state_transaction("nous") as (auth_store, state, source_path):
|
||||
if not is_guest_state(state) or source_path is None:
|
||||
return False
|
||||
@@ -832,13 +830,8 @@ def mark_guest_notice_shown() -> bool:
|
||||
return True
|
||||
state = dict(state)
|
||||
state[GUEST_NOTICE_FLAG] = True
|
||||
if _same_path(source_path, _auth_file_path()):
|
||||
_store_section(auth_store, "providers")["nous"] = state
|
||||
_save_auth_store(auth_store)
|
||||
else:
|
||||
source_store = _load_auth_store(source_path)
|
||||
_store_section(source_store, "providers")["nous"] = state
|
||||
_save_auth_store(source_store, target_path=source_path)
|
||||
_store_section(auth_store, "providers")["nous"] = state
|
||||
_save_auth_store(auth_store)
|
||||
return True
|
||||
|
||||
|
||||
|
||||
+33
-139
@@ -45,9 +45,7 @@ from hermes_cli.auth_device_flow import ( # noqa: F401 re-exported
|
||||
_print_login_success, _print_loopback_ssh_hint, _prompt_yes_no, _request_device_code,
|
||||
_resolve_verify, _ssh_user_at_host)
|
||||
from hermes_cli.auth_oauth_grants import ( # noqa: F401 re-exported
|
||||
SINGLE_USE_REFRESH_POOL_PROVIDERS, _oauth_heal_clean_marks, _oauth_heal_notices,
|
||||
consume_oauth_heal_notices, heal_forked_single_use_oauth_grants,
|
||||
strip_cloned_single_use_oauth_grants)
|
||||
SINGLE_USE_REFRESH_POOL_PROVIDERS, strip_cloned_single_use_oauth_grants)
|
||||
from hermes_cli.auth_nous import ( # noqa: F401 re-exported
|
||||
NOUS_SESSION_TERMINAL, NOUS_SESSION_UNKNOWN, NOUS_SESSION_VALID, _ALLOWED_NOUS_INFERENCE_HOSTS,
|
||||
_agent_key_is_usable, _apply_nous_refreshed_tokens, _assert_nous_inference_jwt_usable,
|
||||
@@ -70,7 +68,7 @@ from hermes_cli.auth_minimax import ( # noqa: F401 re-exported
|
||||
resolve_minimax_oauth_runtime_credentials)
|
||||
from hermes_cli.auth_xai import ( # noqa: F401 re-exported
|
||||
_login_xai_oauth, _read_xai_oauth_tokens, _refresh_xai_oauth_tokens, _save_xai_oauth_tokens,
|
||||
_write_through_xai_oauth_to_global_root, _xai_access_token_is_expiring,
|
||||
_xai_access_token_is_expiring,
|
||||
_xai_oauth_device_code_login, _xai_oauth_discovery, _xai_oauth_poll_device_token,
|
||||
_xai_oauth_request_device_code, _xai_proactive_refresh_skew_seconds,
|
||||
_xai_validate_inference_base_url, refresh_xai_oauth_pure, resolve_xai_oauth_runtime_credentials)
|
||||
@@ -480,52 +478,6 @@ def _auth_file_path() -> Path:
|
||||
return path
|
||||
|
||||
|
||||
def _global_auth_file_path() -> Optional[Path]:
|
||||
"""Global-root auth.json in profile mode; None when profile and global root are the same dir.
|
||||
|
||||
Read-only fallback path, so no pytest seat belt here (it lives on ``_auth_file_path()``)."""
|
||||
try:
|
||||
from hermes_constants import get_default_hermes_root
|
||||
global_root = get_default_hermes_root()
|
||||
except Exception:
|
||||
return None
|
||||
return None if _same_path(get_hermes_home(), global_root) else global_root / "auth.json"
|
||||
|
||||
|
||||
def _load_global_auth_store() -> Dict[str, Any]:
|
||||
"""Load the global-root auth store (read-only fallback, mtime-memoised); ``{}`` when absent or
|
||||
unreadable — a malformed global store must never break profile reads."""
|
||||
global _global_auth_store_cache
|
||||
global_path = _global_auth_file_path()
|
||||
if global_path is None or not global_path.exists():
|
||||
_global_auth_store_cache = None
|
||||
return {}
|
||||
try:
|
||||
cache_key: Optional[Tuple[str, Tuple[int, int, int, int]]] = (
|
||||
str(global_path.resolve(strict=False)), file_signature(global_path.stat()))
|
||||
except Exception:
|
||||
cache_key = None
|
||||
cached = _global_auth_store_cache
|
||||
if cache_key is not None and cached is not None and cached[:2] == cache_key:
|
||||
return cached[2]
|
||||
if os.environ.get("PYTEST_CURRENT_TEST") and os.environ.get("HOME"):
|
||||
real_root = Path(os.environ["HOME"]) / ".hermes" / "auth.json"
|
||||
try:
|
||||
if global_path.resolve(strict=False) == real_root.resolve(strict=False):
|
||||
_global_auth_store_cache = None
|
||||
return {}
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
store = _load_auth_store(global_path)
|
||||
except Exception:
|
||||
_global_auth_store_cache = None
|
||||
return {}
|
||||
if cache_key is not None:
|
||||
_global_auth_store_cache = (*cache_key, store)
|
||||
return store
|
||||
|
||||
|
||||
_auth_target_lock_holders: Dict[str, threading.local] = {}
|
||||
_auth_target_lock_holders_guard = threading.Lock()
|
||||
|
||||
@@ -537,22 +489,6 @@ def _same_path(left: Path, right: Path) -> bool:
|
||||
return left == right
|
||||
|
||||
|
||||
def _is_same_auth_store(left: Path, right: Path) -> bool:
|
||||
"""True when two auth paths name ONE store rather than two copies.
|
||||
``_same_path`` resolves symlinks and ``..``; ``samefile`` adds hardlinks and bind-mounts
|
||||
(same inode under two resolved names). Used by the forked-grant heal: a shared store has
|
||||
no "other side" to consolidate.
|
||||
|
||||
See #101356.
|
||||
"""
|
||||
if _same_path(left, right):
|
||||
return True
|
||||
try:
|
||||
return left.samefile(right)
|
||||
except OSError:
|
||||
return False
|
||||
|
||||
|
||||
def _resolved_key(path: Path) -> str:
|
||||
"""Canonical string for *path* (resolved when possible) used as a cache / lock-holder key."""
|
||||
try:
|
||||
@@ -582,8 +518,8 @@ def _file_lock(
|
||||
"""Cross-process advisory flock helper, reentrant per-thread via ``holder.depth``.
|
||||
|
||||
Falls back to a depth-only guard when neither ``fcntl`` nor ``msvcrt`` is available. Callers
|
||||
supply their own ``threading.local`` so independent locks (profile store vs global root vs the
|
||||
shared Nous store) track reentrancy separately."""
|
||||
supply their own ``threading.local`` so independent locks (one profile's store vs another's vs
|
||||
the shared Nous store) track reentrancy separately."""
|
||||
if getattr(holder, "depth", 0) > 0:
|
||||
holder.depth += 1
|
||||
try:
|
||||
@@ -633,8 +569,8 @@ def _auth_store_lock(
|
||||
timeout_seconds: float = AUTH_LOCK_TIMEOUT_SECONDS, *, target_path: Optional[Path] = None):
|
||||
"""Cross-process advisory lock for one auth.json read/write transaction.
|
||||
|
||||
``target_path`` is required for profile-to-global write-throughs: each path has its own
|
||||
reentrancy tracker and kernel lock. Lock ordering invariant: ``_auth_store_lock`` FIRST (outer),
|
||||
``target_path`` names a store other than the active profile's (a clone being stripped): each
|
||||
path has its own reentrancy tracker and kernel lock. Lock ordering invariant: ``_auth_store_lock`` FIRST (outer),
|
||||
``_nous_shared_store_lock`` SECOND (inner), else deadlock against a concurrent shared import."""
|
||||
auth_path = target_path if target_path is not None else _auth_file_path()
|
||||
with _file_lock(
|
||||
@@ -706,16 +642,11 @@ def _save_private_json(target: Path, data: Any, *, fsync_dir: bool = False, **du
|
||||
|
||||
def _save_auth_store(auth_store: Dict[str, Any], target_path: Optional[Path] = None) -> Path:
|
||||
"""Atomically persist *auth_store* (0o600, parent tightened to 0o700) to the active store, or to
|
||||
an explicit *target_path* (e.g. the global-root write-through for rotating xAI OAuth grants)."""
|
||||
an explicit *target_path* (a profile store being edited from outside that profile)."""
|
||||
auth_file = target_path if target_path is not None else _auth_file_path()
|
||||
auth_store["version"] = AUTH_STORE_VERSION
|
||||
auth_store["updated_at"] = datetime.now(timezone.utc).isoformat()
|
||||
_save_private_json(auth_file, auth_store, fsync_dir=True)
|
||||
if target_path is not None:
|
||||
# A write-through to the global root must not be masked by the mtime memo: on coarse-mtime
|
||||
# filesystems a read-after-write in the same tick would keep serving the pre-write store.
|
||||
global _global_auth_store_cache
|
||||
_global_auth_store_cache = None
|
||||
return auth_file
|
||||
|
||||
|
||||
@@ -737,39 +668,28 @@ def _provider_state_in(store: Dict[str, Any], provider_id: str) -> Optional[Dict
|
||||
def _load_provider_state_with_source(
|
||||
auth_store: Dict[str, Any], provider_id: str,
|
||||
) -> tuple[Optional[Dict[str, Any]], Optional[Path]]:
|
||||
"""Provider state plus the auth.json path it came from (profile first, then the global root).
|
||||
"""Provider state plus the auth.json path it came from (``(None, None)`` when absent).
|
||||
|
||||
Refresh paths that rotate single-use OAuth refresh tokens must write the updated chain back to
|
||||
the same store they read."""
|
||||
Every profile owns its credentials: a named profile never reads the root ``auth.json``
|
||||
(#111724), so the source is always the active store. Refresh paths that rotate single-use
|
||||
OAuth refresh tokens write the rotated chain back to that same path."""
|
||||
state = _provider_state_in(auth_store, provider_id)
|
||||
if state is not None:
|
||||
return state, _auth_file_path()
|
||||
global_state = _provider_state_in(_load_global_auth_store(), provider_id)
|
||||
return (global_state, _global_auth_file_path()) if global_state is not None else (None, None)
|
||||
return (state, _auth_file_path()) if state is not None else (None, None)
|
||||
|
||||
|
||||
def _load_provider_state(auth_store: Dict[str, Any], provider_id: str) -> Optional[Dict[str, Any]]:
|
||||
"""Provider state; in profile mode falls back to the global-root ``auth.json`` per provider (same
|
||||
shadowing as ``read_credential_pool``), so profile workers see globally-authed providers."""
|
||||
return _load_provider_state_with_source(auth_store, provider_id)[0]
|
||||
|
||||
|
||||
@contextmanager
|
||||
def _provider_state_transaction(
|
||||
provider_id: str, timeout_seconds: float = AUTH_LOCK_TIMEOUT_SECONDS):
|
||||
"""Lock the active auth store and any global fallback source, in that order.
|
||||
"""Lock the active auth store and yield ``(store, provider state, source path)``.
|
||||
|
||||
Re-reading the source after its lock is acquired prevents stale refreshes and whole-file lost
|
||||
updates without inverting the documented auth -> shared lock order. ``timeout_seconds`` applies
|
||||
to BOTH locks: a transaction that spans a network call must let waiters outlive that call."""
|
||||
``timeout_seconds`` must let waiters outlive a network call made inside the transaction."""
|
||||
with _auth_store_lock(timeout_seconds):
|
||||
auth_store = _load_auth_store()
|
||||
state, source_path = _load_provider_state_with_source(auth_store, provider_id)
|
||||
if source_path is None or _same_path(source_path, _auth_file_path()):
|
||||
yield auth_store, state, source_path
|
||||
return
|
||||
with _auth_store_lock(timeout_seconds, target_path=source_path):
|
||||
yield auth_store, _provider_state_in(_load_auth_store(source_path), provider_id), source_path
|
||||
yield (auth_store, *_load_provider_state_with_source(auth_store, provider_id))
|
||||
|
||||
|
||||
def _store_provider_state(
|
||||
@@ -793,16 +713,6 @@ def _save_active_provider_state(provider_id: str, state: Dict[str, Any]) -> Path
|
||||
return _save_auth_store(auth_store)
|
||||
|
||||
|
||||
def _persist_provider_state_to_store(
|
||||
provider_id: str, state: Dict[str, Any], target_path: Path, *, set_active: bool = False,
|
||||
) -> Path:
|
||||
"""Merge one provider into a specific auth store under that store's lock."""
|
||||
with _auth_store_lock(target_path=target_path):
|
||||
auth_store = _load_auth_store(target_path)
|
||||
_store_provider_state(auth_store, provider_id, dict(state), set_active=set_active)
|
||||
return _save_auth_store(auth_store, target_path=target_path)
|
||||
|
||||
|
||||
def _save_provider_state_to_source(
|
||||
auth_store: Dict[str, Any], provider_id: str, state: Dict[str, Any], source_path: Optional[Path],
|
||||
) -> None:
|
||||
@@ -811,11 +721,8 @@ def _save_provider_state_to_source(
|
||||
A token refresh rewrites credentials, not the user's choice of provider: ``active_provider`` is
|
||||
left as it is (a Nous free-tier identity refreshed for a connector call must not become the
|
||||
inference provider of an install that has its own key)."""
|
||||
if source_path is None or _same_path(source_path, _auth_file_path()):
|
||||
_store_provider_state(auth_store, provider_id, state, set_active=False)
|
||||
_save_auth_store(auth_store)
|
||||
else:
|
||||
_persist_provider_state_to_store(provider_id, state, source_path, set_active=False)
|
||||
_store_provider_state(auth_store, provider_id, state, set_active=False)
|
||||
_save_auth_store(auth_store, target_path=source_path)
|
||||
|
||||
|
||||
def mark_provider_active_if_unset(provider_id: str) -> None:
|
||||
@@ -857,30 +764,16 @@ def is_runtime_provider_routable(provider_id: str) -> bool:
|
||||
|
||||
|
||||
def read_credential_pool(provider_id: Optional[str] = None) -> Dict[str, Any]:
|
||||
"""Return the persisted credential pool, or one provider slice.
|
||||
"""Return the persisted credential pool of the ACTIVE store, or one provider slice.
|
||||
|
||||
In profile mode the global-root ``auth.json`` is a read-only fallback applied per provider ONLY
|
||||
when the profile has zero entries for it (``hermes auth add`` in the profile shadows global)."""
|
||||
A named profile reads only its own ``auth.json``: credentials authenticated at the root are
|
||||
not inherited (#111724) — ``hermes -p <name> auth add <provider>`` gives the profile its own."""
|
||||
pool = _load_auth_store().get("credential_pool")
|
||||
pool = pool if isinstance(pool, dict) else {}
|
||||
global_pool = _load_global_auth_store().get("credential_pool")
|
||||
global_pool = global_pool if isinstance(global_pool, dict) else {}
|
||||
|
||||
if provider_id is None:
|
||||
merged = dict(pool)
|
||||
for gp_key, gp_entries in global_pool.items():
|
||||
existing = merged.get(gp_key)
|
||||
if not (isinstance(gp_entries, list) and gp_entries):
|
||||
continue
|
||||
if not (isinstance(existing, list) and existing): # profile wins when it has ANY entries
|
||||
merged[gp_key] = list(gp_entries)
|
||||
return merged
|
||||
|
||||
provider_entries = pool.get(provider_id)
|
||||
if isinstance(provider_entries, list) and provider_entries:
|
||||
return list(provider_entries)
|
||||
global_entries = global_pool.get(provider_id)
|
||||
return list(global_entries) if isinstance(global_entries, list) else []
|
||||
return dict(pool)
|
||||
entries = pool.get(provider_id)
|
||||
return list(entries) if isinstance(entries, list) else []
|
||||
|
||||
|
||||
_POOL_STATUS_FIELDS = (
|
||||
@@ -1021,7 +914,7 @@ def unsuppress_credential_source(provider_id: str, source: str) -> bool:
|
||||
|
||||
|
||||
def get_provider_auth_state(provider_id: str) -> Optional[Dict[str, Any]]:
|
||||
"""Persisted auth state for a provider (profile first, global-root fallback), or None."""
|
||||
"""Persisted auth state for a provider in the active store, or None."""
|
||||
return _load_provider_state(_load_auth_store(), provider_id)
|
||||
|
||||
|
||||
@@ -1506,11 +1399,16 @@ def resolve_provider(
|
||||
return "bedrock"
|
||||
except ImportError:
|
||||
pass # boto3 not installed
|
||||
from hermes_constants import display_hermes_home
|
||||
from hermes_constants import display_hermes_home, profile_cli_selector, profile_name_for_home
|
||||
# A named profile owns its credentials: the root's auth.json is never inherited (#111724), so
|
||||
# the guidance names the profile the user must sign in to.
|
||||
sel = profile_cli_selector()
|
||||
profile_name = profile_name_for_home(get_hermes_home()) if sel else None
|
||||
where = f"Profile '{profile_name}' is" if profile_name else "Hermes is"
|
||||
raise AuthError(
|
||||
"Hermes is not connected to any AI provider yet. Run `hermes model` to pick one (the free "
|
||||
"Nous tier needs no API key), type `/login` in chat, or add a key with "
|
||||
f"`hermes auth add <provider>`. (Advanced: put an API key such as OPENROUTER_API_KEY in "
|
||||
f"{where} not connected to any AI provider yet. Run `hermes {sel}model` to pick one (the free "
|
||||
f"Nous tier needs no API key), type `/login` in chat, or add a key with "
|
||||
f"`hermes {sel}auth add <provider>`. (Advanced: put an API key such as OPENROUTER_API_KEY in "
|
||||
f"{display_hermes_home()}/.env.)",
|
||||
code="no_provider_configured")
|
||||
|
||||
@@ -1705,10 +1603,6 @@ def resolve_nous_access_token(
|
||||
_NOUS_AUTH_STATUS_CACHE_TTL = 15.0 # seconds
|
||||
_nous_auth_status_cache: Optional[Tuple[float, str, Optional[float], Dict[str, Any]]] = None
|
||||
|
||||
# mtime-keyed memo for _load_global_auth_store(): (path, mtime_ns, store); same invalidation rule.
|
||||
_global_auth_store_cache: Optional[Tuple[str, int, Dict[str, Any]]] = None
|
||||
|
||||
|
||||
def _auth_file_cache_key() -> Tuple[str, Optional[float]]:
|
||||
auth_file = _auth_file_path()
|
||||
try:
|
||||
|
||||
+21
-44
@@ -142,27 +142,17 @@ def _sync_codex_pool_entries(
|
||||
_clear_pool_entry_status(entry)
|
||||
|
||||
|
||||
def _save_codex_tokens(
|
||||
tokens: Dict[str, str], last_refresh: str = None, label: str = None, *, write_through: bool = False,
|
||||
) -> None:
|
||||
"""Save Codex OAuth tokens to the auth store the grant was resolved FROM.
|
||||
def _save_codex_tokens(tokens: Dict[str, str], last_refresh: str = None, label: str = None) -> None:
|
||||
"""Save Codex OAuth tokens (singleton AND ``credential_pool`` aliases) to the active auth store.
|
||||
|
||||
Codex refresh tokens are single-use with rotation-family reuse detection. A profile without its
|
||||
own ``providers.openai-codex`` block reads root's grant via the fallback, so a refresh under that
|
||||
profile must rotate ROOT's chain — singleton AND ``credential_pool`` entries — or root keeps the
|
||||
consumed refresh token, the next process replays it and OpenAI revokes the whole family
|
||||
(#87503). Root-only write-back: a profile copy would shadow root and disable the write-through
|
||||
on the next refresh (#74339). Mirrors the xAI source-aware save.
|
||||
|
||||
Only a token REFRESH passes ``write_through=True``: a fresh login or import under a profile
|
||||
is the profile's own grant and must not overwrite the root account it was borrowing.
|
||||
Codex refresh tokens are single-use with rotation-family reuse detection, so the pool rows that
|
||||
alias the singleton must rotate with it or the next process replays the consumed token and
|
||||
OpenAI revokes the whole family (#87503).
|
||||
"""
|
||||
from hermes_cli.auth import (
|
||||
_auth_file_path, _load_auth_store, _provider_state_transaction, _same_path,
|
||||
_save_auth_store, _store_provider_state, _utc_now_z)
|
||||
from hermes_cli.auth import _provider_state_transaction, _save_auth_store, _store_provider_state, _utc_now_z
|
||||
if last_refresh is None:
|
||||
last_refresh = _utc_now_z()
|
||||
with _provider_state_transaction("openai-codex") as (auth_store, state, source_path):
|
||||
with _provider_state_transaction("openai-codex") as (auth_store, state, _source_path):
|
||||
state = dict(state) if state else {}
|
||||
# Capture the previous singleton tokens BEFORE overwriting: the pool sync uses them to
|
||||
# tell legacy singleton-aliases (refresh) from independent ``auth add`` accounts (keep).
|
||||
@@ -171,15 +161,10 @@ def _save_codex_tokens(
|
||||
state.update(tokens=tokens, last_refresh=last_refresh, auth_mode="chatgpt")
|
||||
if label and str(label).strip():
|
||||
state["label"] = str(label).strip()
|
||||
target_store, target_path, set_active = auth_store, None, True
|
||||
if write_through and source_path is not None and not _same_path(source_path, _auth_file_path()):
|
||||
# Root-borrowed grant: the transaction already holds root's lock, so write the rotated
|
||||
# chain into ROOT's store (never set_active — a refresh is not a provider choice).
|
||||
target_store, target_path, set_active = _load_auth_store(source_path), source_path, False
|
||||
_store_provider_state(target_store, "openai-codex", state, set_active=set_active)
|
||||
_store_provider_state(auth_store, "openai-codex", state, set_active=True)
|
||||
_sync_codex_pool_entries(
|
||||
target_store, tokens, last_refresh, previous_singleton_tokens=previous_singleton_tokens)
|
||||
_save_auth_store(target_store, target_path=target_path)
|
||||
auth_store, tokens, last_refresh, previous_singleton_tokens=previous_singleton_tokens)
|
||||
_save_auth_store(auth_store)
|
||||
|
||||
|
||||
def _recover_codex_tokens_from_cli(reason: str) -> Optional[Dict[str, str]]:
|
||||
@@ -377,10 +362,10 @@ def _refresh_codex_auth_tokens(tokens: Dict[str, str], timeout_seconds: float) -
|
||||
"""Refresh Codex access token using the refresh token.
|
||||
|
||||
The whole re-read -> endpoint POST -> write-back runs inside the SOURCE store's transaction:
|
||||
two profiles borrowing the same root grant otherwise both submit the same single-use refresh
|
||||
token (each holds only its own profile lock) and OpenAI revokes the family. A waiter that
|
||||
finds root already rotated by its peer adopts the stored pair instead of replaying the
|
||||
consumed token. Both locks wait out a full endpoint timeout so the waiter adopts, not times out.
|
||||
two processes of one profile otherwise both submit the same single-use refresh token and OpenAI
|
||||
revokes the family. A waiter that finds the store already rotated by its peer adopts the stored
|
||||
pair instead of replaying the consumed token. The lock waits out a full endpoint timeout so the
|
||||
waiter adopts, not times out.
|
||||
"""
|
||||
from hermes_cli.auth import _provider_state_transaction, _save_codex_tokens, refresh_codex_oauth_pure
|
||||
lock_timeout = max(float(AUTH_LOCK_TIMEOUT_SECONDS), float(timeout_seconds) + 5.0)
|
||||
@@ -412,8 +397,8 @@ def _refresh_codex_auth_tokens(tokens: Dict[str, str], timeout_seconds: float) -
|
||||
updated_tokens = {
|
||||
**tokens, "access_token": refreshed["access_token"],
|
||||
"refresh_token": refreshed["refresh_token"]}
|
||||
# Nested transaction: the per-path lock is reentrant, and it re-reads under the held locks.
|
||||
_save_codex_tokens(updated_tokens, write_through=True)
|
||||
# Nested transaction: the per-path lock is reentrant, and it re-reads under the held lock.
|
||||
_save_codex_tokens(updated_tokens)
|
||||
return updated_tokens
|
||||
|
||||
|
||||
@@ -618,15 +603,11 @@ def clear_codex_pool_quota_cooldowns(access_token: Optional[str] = None) -> int:
|
||||
rate-limited entry does (a redeemed banked reset restores the whole account; a still-exhausted
|
||||
entry just re-freezes with fresh metadata on its next 429).
|
||||
"""
|
||||
from agent.credential_pool import _borrowed_single_use_pool_root, _profile_owns_pool_provider
|
||||
from hermes_cli.auth import _auth_store_lock, _load_auth_store, _save_auth_store
|
||||
cleared = 0
|
||||
try:
|
||||
# Same owner rule as ``persist_pool_entries``: a profile with no Codex rows of its own
|
||||
# borrows the global-root pool, so the cooldown must clear where the rows actually live.
|
||||
target = None if _profile_owns_pool_provider("openai-codex") else _borrowed_single_use_pool_root()
|
||||
with _auth_store_lock(target_path=target):
|
||||
auth_store = _load_auth_store(target)
|
||||
with _auth_store_lock():
|
||||
auth_store = _load_auth_store()
|
||||
for entry in _codex_pool_dicts(_pool_entries(auth_store, "openai-codex")):
|
||||
if access_token and str(entry.get("access_token") or "") != access_token:
|
||||
continue
|
||||
@@ -634,7 +615,7 @@ def clear_codex_pool_quota_cooldowns(access_token: Optional[str] = None) -> int:
|
||||
_clear_pool_entry_status(entry)
|
||||
cleared += 1
|
||||
if cleared:
|
||||
_save_auth_store(auth_store, target_path=target)
|
||||
_save_auth_store(auth_store)
|
||||
except Exception:
|
||||
logger.debug("Failed to clear Codex pool quota cooldowns", exc_info=True)
|
||||
return cleared
|
||||
@@ -647,10 +628,7 @@ def _codex_pool_dicts(entries: Optional[List[Any]]) -> Iterator[Dict[str, Any]]:
|
||||
|
||||
|
||||
def _codex_pool_rate_limit_status() -> Optional[Dict[str, Any]]:
|
||||
"""Return metadata for a pool-only Codex credential in quota cooldown.
|
||||
|
||||
Reads through ``read_credential_pool`` so a named profile with no Codex rows of its own sees
|
||||
the global-root pool (the per-provider fallback every other pool read uses)."""
|
||||
"""Return metadata for a pool-only Codex credential in quota cooldown."""
|
||||
from hermes_cli.auth import _nonempty_str, read_credential_pool
|
||||
from agent.credential_pool import _parse_absolute_timestamp
|
||||
try:
|
||||
@@ -681,8 +659,7 @@ def _pool_entries(auth_store: Dict[str, Any], provider_id: str) -> Optional[List
|
||||
def _pool_codex_access_token() -> str:
|
||||
"""First non-empty pool access_token not in an exhaustion cooldown window, else "".
|
||||
|
||||
Fallback for ``resolve_codex_runtime_credentials`` when the singleton has no creds; reads
|
||||
through ``read_credential_pool`` so a profile inherits the global-root pool (#34143).
|
||||
Fallback for ``resolve_codex_runtime_credentials`` when the singleton has no creds.
|
||||
"""
|
||||
from hermes_cli.auth import _nonempty_str, read_credential_pool
|
||||
try:
|
||||
|
||||
@@ -491,13 +491,6 @@ def auth_list_command(args) -> None:
|
||||
)
|
||||
print(row.rstrip())
|
||||
print()
|
||||
_print_oauth_heal_notices()
|
||||
|
||||
|
||||
def _print_oauth_heal_notices() -> None:
|
||||
"""Tell the user when load_pool() just consolidated a forked OAuth grant."""
|
||||
for note in auth_mod.consume_oauth_heal_notices():
|
||||
print(f"note: {note}")
|
||||
|
||||
|
||||
def auth_remove_command(args) -> None:
|
||||
@@ -604,10 +597,7 @@ def auth_status_command(args) -> None:
|
||||
provider = _normalize_provider(getattr(args, "provider", "") or "")
|
||||
if not provider:
|
||||
raise SystemExit("Provider is required. Example: `hermes auth status spotify`.")
|
||||
if provider in auth_mod.SINGLE_USE_REFRESH_POOL_PROVIDERS:
|
||||
load_pool(provider) # runs the forked-grant heal first so the report reflects the consolidated grant
|
||||
status = auth_mod.get_auth_status(provider)
|
||||
_print_oauth_heal_notices()
|
||||
if status.get("free_tier"):
|
||||
# Free tier: not an account login, so no account fields; point at the upgrade path.
|
||||
label, hint = _free_tier_lines()
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
"""Single-use OAuth grant hygiene: strip cloned grants from profiles, heal forked grants.
|
||||
"""Single-use OAuth grant hygiene: strip cloned grants from profiles.
|
||||
|
||||
Split out of ``hermes_cli/auth.py`` and re-exported there; origin helpers are imported lazily
|
||||
inside each function so ``hermes_cli.auth.<name>`` patches still intercept (and no import cycle).
|
||||
@@ -8,11 +8,8 @@ from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
from typing import Any, Dict, List, Optional, Tuple
|
||||
from hermes_cli.auth_constants import _decode_jwt_claims
|
||||
from utils import file_signature
|
||||
from typing import Any, Dict
|
||||
|
||||
# Log-record parity with the origin module (caplog tests pin "hermes_cli.auth").
|
||||
logger = logging.getLogger("hermes_cli.auth")
|
||||
@@ -21,8 +18,7 @@ logger = logging.getLogger("hermes_cli.auth")
|
||||
# revokes the old one, so a grant forked into two auth.json files is ONE credential with two
|
||||
# owners — the first to refresh strands the other with ``invalid_grant`` /
|
||||
# ``refresh_token_reused``.
|
||||
# Profiles must never receive a copy: ONE grant lives at the global root and named profiles read
|
||||
# it through the ``read_credential_pool`` root fallback.
|
||||
# Profiles must never receive a copy; each profile signs in on its own (``hermes -p <name> auth add``).
|
||||
SINGLE_USE_REFRESH_POOL_PROVIDERS = frozenset({"anthropic", "openai-codex", "xai-oauth"})
|
||||
|
||||
# Singleton credential files holding the same single-use grants outside ``auth.json``. Copying one
|
||||
@@ -44,16 +40,12 @@ def _is_oauth_pool_payload(entry: Any) -> bool:
|
||||
or str(entry.get("access_token") or "").startswith("sk-ant-oat"))
|
||||
|
||||
|
||||
def _is_pkce_row(row: Dict[str, Any]) -> bool:
|
||||
return str(row.get("source") or "").endswith("hermes_pkce")
|
||||
|
||||
|
||||
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 path that copies credential files between profiles (``hermes profile create
|
||||
--clone-all``, the dashboard/TUI ``mirror_credentials`` flow). API-key pool rows are kept — a
|
||||
static key is safe to duplicate. Returns ``{"pool": [...provider ids], "providers": [...],
|
||||
static key is safe to duplicate; the clone signs into the OAuth provider itself. Returns ``{"pool": [...provider ids], "providers": [...],
|
||||
"files": [...]}`` of what was stripped. Never raises: a clone must not fail because hygiene
|
||||
could not run — the caller logs the summary.
|
||||
"""
|
||||
@@ -71,10 +63,9 @@ def strip_cloned_single_use_oauth_grants(profile_dir: Path) -> Dict[str, Any]:
|
||||
auth_path = profile_dir / "auth.json"
|
||||
if not auth_path.is_file():
|
||||
return stripped
|
||||
# A profile auth.json that IS the shared root store (symlink / hardlink) is not a clone;
|
||||
# stripping it would delete every profile's single-use grants. _is_same_auth_store swallows
|
||||
# a samefile() OSError as "two stores", which here would fail OPEN — so resolve identity
|
||||
# positively: same path, or samefile() says so; any error refuses.
|
||||
# A profile auth.json that IS the root store (symlink / hardlink) is not a clone; stripping it
|
||||
# would delete the root's single-use grants. Resolve identity positively: same path, or
|
||||
# samefile() says so; any error refuses (fail closed).
|
||||
try:
|
||||
from hermes_constants import get_default_hermes_root
|
||||
root_auth_path = get_default_hermes_root() / "auth.json"
|
||||
@@ -105,12 +96,9 @@ def strip_cloned_single_use_oauth_grants(profile_dir: Path) -> Dict[str, Any]:
|
||||
if kept:
|
||||
pool[provider_id] = kept
|
||||
else:
|
||||
# No local rows → read_credential_pool falls back to the root slice.
|
||||
del pool[provider_id]
|
||||
providers = store.get("providers")
|
||||
if isinstance(providers, dict):
|
||||
# _load_provider_state has the same root fallback, so dropping the copy keeps the
|
||||
# profile working while removing the fork.
|
||||
for provider_id in _DEVICE_CODE_BLOCK_PROVIDERS:
|
||||
block = providers.get(provider_id)
|
||||
if isinstance(block, dict) and block:
|
||||
@@ -125,515 +113,3 @@ def strip_cloned_single_use_oauth_grants(profile_dir: Path) -> Dict[str, Any]:
|
||||
logger.debug(
|
||||
"Failed to strip cloned single-use OAuth grants from %s", auth_path, exc_info=True)
|
||||
return stripped
|
||||
|
||||
|
||||
_OAUTH_TOKEN_FIELDS = (
|
||||
"access_token", "refresh_token", "expires_at", "expires_at_ms", "last_refresh")
|
||||
|
||||
_oauth_heal_notices: List[str] = []
|
||||
|
||||
# provider -> fingerprint (see ``_heal_forked_single_use_oauth_grants``) of the last store
|
||||
# verified fork-free; lets load_pool() skip the locked scan.
|
||||
_oauth_heal_clean_marks: Dict[str, Tuple[Any, ...]] = {}
|
||||
|
||||
# Filename for the ON-DISK twin of ``_oauth_heal_clean_marks``. The in-memory mark only silences
|
||||
# the heal for the life of ONE process, so every fresh `hermes` invocation and every new worker
|
||||
# re-pays the heal's two nested EXCLUSIVE auth-store locks just to discover there is nothing to
|
||||
# consolidate. Behind a sibling holding those locks that costs a full AUTH_LOCK_TIMEOUT_SECONDS
|
||||
# per provider (measured: 30s for two providers on an otherwise-idle machine) before the process
|
||||
# can do anything at all.
|
||||
_OAUTH_HEAL_CLEAN_MARK_FILENAME = "oauth_heal_clean.json"
|
||||
|
||||
|
||||
def _json_shape(fingerprint: tuple) -> list:
|
||||
"""The fingerprint as it reads back from JSON (tuples become lists), so the on-disk compare
|
||||
is exact."""
|
||||
return json.loads(json.dumps(fingerprint))
|
||||
|
||||
|
||||
def _oauth_heal_clean_mark_path() -> Optional[Path]:
|
||||
"""Where the persisted clean marks live, or None when unavailable."""
|
||||
try:
|
||||
from hermes_cli.auth import _auth_file_path
|
||||
|
||||
return _auth_file_path().parent / "cache" / _OAUTH_HEAL_CLEAN_MARK_FILENAME
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
|
||||
def _persisted_oauth_heal_fingerprint(provider_id: str) -> Optional[list]:
|
||||
"""The stored clean-mark fingerprint for ``provider_id``, or None.
|
||||
|
||||
Pure cache read: any problem at all (absent, unreadable, corrupt, wrong shape) means "no
|
||||
mark", which falls through to the locked heal — the pre-existing behaviour. It must never
|
||||
raise into a credential path.
|
||||
"""
|
||||
path = _oauth_heal_clean_mark_path()
|
||||
if path is None:
|
||||
return None
|
||||
try:
|
||||
data = json.loads(path.read_text(encoding="utf-8"))
|
||||
except Exception:
|
||||
return None
|
||||
if not isinstance(data, dict):
|
||||
return None
|
||||
stored = data.get(provider_id)
|
||||
return stored if isinstance(stored, list) else None
|
||||
|
||||
|
||||
def _persist_oauth_heal_clean_mark(provider_id: str, fingerprint: tuple) -> None:
|
||||
"""Record ``provider_id`` as clean for this exact fingerprint.
|
||||
|
||||
Best-effort by design: a failed write only means the next process re-runs the heal, which is
|
||||
what it did before this cache existed.
|
||||
"""
|
||||
path = _oauth_heal_clean_mark_path()
|
||||
if path is None:
|
||||
return
|
||||
try:
|
||||
from utils import atomic_json_write
|
||||
|
||||
try:
|
||||
existing = json.loads(path.read_text(encoding="utf-8"))
|
||||
except Exception:
|
||||
existing = {}
|
||||
if not isinstance(existing, dict):
|
||||
existing = {}
|
||||
marks = {
|
||||
key: value for key, value in existing.items()
|
||||
if isinstance(key, str) and isinstance(value, list)
|
||||
}
|
||||
new_mark = _json_shape(fingerprint)
|
||||
if marks.get(provider_id) == new_mark:
|
||||
return # already recorded; skip the rewrite
|
||||
marks[provider_id] = new_mark
|
||||
from hermes_constants import mkdir_under_hermes_home
|
||||
mkdir_under_hermes_home(path.parent)
|
||||
# 0o600 like the MCP schema cache: this names credential-store paths.
|
||||
atomic_json_write(path, marks, mode=0o600)
|
||||
except Exception:
|
||||
logger.debug(
|
||||
"%s: could not persist the forked-OAuth clean mark", provider_id, exc_info=True)
|
||||
|
||||
|
||||
def _mark_oauth_heal_clean(provider_id: str, fingerprint: tuple) -> None:
|
||||
"""Stamp the clean mark both in memory and on disk."""
|
||||
_oauth_heal_clean_marks[provider_id] = fingerprint
|
||||
_persist_oauth_heal_clean_mark(provider_id, fingerprint)
|
||||
|
||||
|
||||
def consume_oauth_heal_notices() -> List[str]:
|
||||
"""Return (and clear) human-readable notes about heals run in this process.
|
||||
|
||||
``hermes auth list`` / ``hermes auth status`` print them so the user sees the consolidation.
|
||||
"""
|
||||
from hermes_cli.auth import _oauth_heal_notices
|
||||
notes = list(_oauth_heal_notices)
|
||||
_oauth_heal_notices.clear()
|
||||
return notes
|
||||
|
||||
|
||||
def _oauth_identity(entry: Dict[str, Any]) -> Optional[str]:
|
||||
"""Stable account identity for an OAuth row when the token carries one.
|
||||
|
||||
Codex / xAI access tokens are JWTs with ``sub`` / ``email`` / ``chatgpt_account_id`` claims;
|
||||
Anthropic ``sk-ant-oat`` tokens carry none (None → lineage rests on id / token material).
|
||||
"""
|
||||
from hermes_cli.auth import _nonempty_str
|
||||
if not isinstance(entry, dict):
|
||||
return None
|
||||
for token in (entry.get("access_token"), entry.get("id_token")):
|
||||
claims = _decode_jwt_claims(token)
|
||||
if not claims:
|
||||
continue
|
||||
nested = claims.get("https://api.openai.com/auth")
|
||||
account = nested.get("chatgpt_account_id") if isinstance(nested, dict) else None
|
||||
for value in (account, claims.get("sub"), claims.get("email")):
|
||||
if _nonempty_str(value):
|
||||
return value.strip()
|
||||
return None
|
||||
|
||||
|
||||
def _oauth_freshness(entry: Dict[str, Any]) -> float:
|
||||
"""Best-effort 'how recently was this pair issued' score (epoch seconds).
|
||||
|
||||
A rotation always issues a later-expiring access token, so ``expires_at`` ordering identifies
|
||||
the live copy; ``last_refresh`` and the JWT ``exp`` claim are fallbacks.
|
||||
"""
|
||||
from agent.credential_pool import _parse_absolute_timestamp
|
||||
stamps = [entry.get(k) for k in ("expires_at_ms", "expires_at", "last_refresh")]
|
||||
best = max((ts for ts in map(_parse_absolute_timestamp, stamps) if ts), default=0.0)
|
||||
if best == 0.0:
|
||||
exp = _decode_jwt_claims(entry.get("access_token")).get("exp")
|
||||
best = _parse_absolute_timestamp(exp) or 0.0
|
||||
return best
|
||||
|
||||
|
||||
def _find_root_counterpart(
|
||||
profile_row: Dict[str, Any], root_rows: List[Dict[str, Any]]) -> Optional[int]:
|
||||
"""Index of the root OAuth row that shares a grant lineage with *profile_row*.
|
||||
|
||||
Only a copied row ID or shared token material establishes lineage. The same
|
||||
account/client can issue multiple independent grants; identity is not proof.
|
||||
"""
|
||||
from hermes_cli.auth import _nonempty_str
|
||||
candidates = [i for i, r in enumerate(root_rows) if _is_oauth_pool_payload(r)]
|
||||
if not candidates:
|
||||
return None
|
||||
pid = profile_row.get("id")
|
||||
for i in candidates:
|
||||
if pid and root_rows[i].get("id") == pid:
|
||||
return i
|
||||
for key in ("refresh_token", "access_token"):
|
||||
p_val = profile_row.get(key)
|
||||
if not _nonempty_str(p_val):
|
||||
continue
|
||||
for i in candidates:
|
||||
if root_rows[i].get(key) == p_val:
|
||||
return i
|
||||
return None
|
||||
|
||||
|
||||
def _adopt_oauth_material(target: Dict[str, Any], winner: Dict[str, Any]) -> Dict[str, Any]:
|
||||
"""Return *target* carrying *winner*'s token pair, status markers cleared."""
|
||||
from hermes_cli.auth import _POOL_STATUS_FIELDS
|
||||
merged = dict(target)
|
||||
for key in _OAUTH_TOKEN_FIELDS:
|
||||
if winner.get(key) is not None:
|
||||
merged[key] = winner[key]
|
||||
else:
|
||||
merged.pop(key, None)
|
||||
merged.update(dict.fromkeys(_POOL_STATUS_FIELDS))
|
||||
return merged
|
||||
|
||||
|
||||
def _singleton_as_row(path: Path) -> Optional[Dict[str, Any]]:
|
||||
"""Read a ``.anthropic_oauth.json`` as a pool-row-shaped dict, or None."""
|
||||
try:
|
||||
data = json.loads(path.read_text(encoding="utf-8"))
|
||||
except (OSError, ValueError):
|
||||
return None
|
||||
if not isinstance(data, dict) or not str(data.get("accessToken") or "").strip():
|
||||
return None
|
||||
return {
|
||||
"access_token": data.get("accessToken"),
|
||||
"refresh_token": data.get("refreshToken"),
|
||||
"expires_at_ms": data.get("expiresAt")}
|
||||
|
||||
|
||||
def heal_forked_single_use_oauth_grants(provider_id: str) -> Optional[Dict[str, Any]]:
|
||||
"""One-time heal for installs that ALREADY forked a single-use grant into a profile.
|
||||
|
||||
Forked copies are one credential with several owners: whichever profile rotated last holds the
|
||||
only live refresh token and every other copy (root included) is spent. Runs at profile
|
||||
``load_pool()`` time for ``SINGLE_USE_REFRESH_POOL_PROVIDERS``: finds profile rows sharing
|
||||
LINEAGE with a root row (same pool id or shared token material), keeps the
|
||||
freshest rotation, writes it into ROOT when root's is older, and strips the profile's copy so
|
||||
the profile borrows root from then on. Idempotent; never touches API-key rows; never deletes a
|
||||
row with no root counterpart (an independent ``hermes -p <p> auth add`` grant, or the only
|
||||
surviving copy); reads only the two auth.json files the root fallback already reads. Returns
|
||||
``{"adopted", "stripped_ids", "files", "providers_block"}`` when something healed, else None.
|
||||
Never raises.
|
||||
"""
|
||||
if provider_id not in SINGLE_USE_REFRESH_POOL_PROVIDERS:
|
||||
return None
|
||||
try:
|
||||
return _heal_forked_single_use_oauth_grants(provider_id)
|
||||
except Exception:
|
||||
logger.debug("%s: forked-OAuth heal skipped", provider_id, exc_info=True)
|
||||
return None
|
||||
|
||||
|
||||
def _heal_forked_provider_block(
|
||||
profile_store: Dict[str, Any], root_store: Dict[str, Any], provider_id: str,
|
||||
lineage_proven: bool = False) -> Optional[bool]:
|
||||
"""Consolidate a forked ``providers.<id>`` device-code block into root.
|
||||
|
||||
*lineage_proven* carries the pool-row verdict: a profile row that matched root by copied id
|
||||
or shared tokens proves the fork even after both sides rotated past token equality. Root's
|
||||
``load_pool()`` re-seeds its ``device_code`` row FROM this block, so leaving root's block on
|
||||
the spent pair would undo the pool-row heal on the next root load.
|
||||
|
||||
Returns None when nothing matched, False when the profile copy was dropped (root already
|
||||
newest), True when the profile copy was fresher and was adopted into root.
|
||||
"""
|
||||
p_providers, r_providers = profile_store.get("providers"), root_store.get("providers")
|
||||
if not (isinstance(p_providers, dict) and isinstance(r_providers, dict)):
|
||||
return None
|
||||
p_block, r_block = p_providers.get(provider_id), r_providers.get(provider_id)
|
||||
if not (isinstance(p_block, dict) and p_block and isinstance(r_block, dict) and r_block):
|
||||
return None
|
||||
|
||||
def _flat(block: Dict[str, Any]) -> Dict[str, Any]:
|
||||
tokens = block.get("tokens") if isinstance(block.get("tokens"), dict) else {}
|
||||
return {**tokens, "last_refresh": block.get("last_refresh")}
|
||||
|
||||
p_flat, r_flat = _flat(p_block), _flat(r_block)
|
||||
# Provider blocks have no stable pool-row ID. Without a shared token pair
|
||||
# component (or lineage proven by the pool rows), a common account is
|
||||
# insufficient evidence of a copied grant.
|
||||
if not lineage_proven and not any(
|
||||
p_flat.get(key) and p_flat.get(key) == r_flat.get(key)
|
||||
for key in ("access_token", "refresh_token")
|
||||
):
|
||||
return None
|
||||
adopted = _oauth_freshness(p_flat) > _oauth_freshness(r_flat)
|
||||
if adopted:
|
||||
r_providers[provider_id] = dict(p_block)
|
||||
del p_providers[provider_id]
|
||||
return adopted
|
||||
|
||||
|
||||
def _stat_sig(p: Optional[Path]) -> Optional[Tuple[int, int, int, int]]:
|
||||
"""File signature from ONE stat, or None when absent — a torn pair from two stats could
|
||||
leave a persisted clean mark matching a store rewritten between them."""
|
||||
try:
|
||||
st = p.stat() if p is not None else None
|
||||
except OSError:
|
||||
return None
|
||||
return file_signature(st) if st is not None else None
|
||||
|
||||
|
||||
def _pool_rows(store: Dict[str, Any], provider_id: str) -> Tuple[Any, List[Any]]:
|
||||
"""``(store["credential_pool"], its provider_id rows-or-[])`` — pool may be None/non-dict."""
|
||||
pool = store.get("credential_pool")
|
||||
rows = pool.get(provider_id) if isinstance(pool, dict) else None
|
||||
return pool, rows if isinstance(rows, list) else []
|
||||
|
||||
|
||||
def _adopt_if_fresher(
|
||||
target: Dict[str, Any], candidate: Dict[str, Any]) -> Optional[Dict[str, Any]]:
|
||||
"""*target* carrying *candidate*'s pair when the candidate rotated later, else None."""
|
||||
fresher = _oauth_freshness(candidate) > _oauth_freshness(target)
|
||||
return _adopt_oauth_material(target, candidate) if fresher else None
|
||||
|
||||
|
||||
class _HealPass:
|
||||
"""One heal pass over a profile store vs the root store for *provider_id*."""
|
||||
|
||||
def __init__(self, profile_store, root_store, provider_id, root_singleton: Optional[Path]):
|
||||
self.profile_store, self.root_store = profile_store, root_store
|
||||
self.provider_id = provider_id
|
||||
self.summary: Dict[str, Any] = {
|
||||
"adopted": False, "stripped_ids": [], "files": [], "providers_block": False}
|
||||
self.profile_changed = self.root_changed = False
|
||||
self.lineage_proven = False # a profile pool row matched root by copied id / shared tokens
|
||||
self.p_pool, self.p_rows = _pool_rows(profile_store, provider_id)
|
||||
self.r_pool, self.r_rows = _pool_rows(root_store, provider_id)
|
||||
self.r_oauth = [r for r in self.r_rows if _is_oauth_pool_payload(r)]
|
||||
self.root_singleton = root_singleton
|
||||
self.root_singleton_row = (
|
||||
_singleton_as_row(root_singleton)
|
||||
if root_singleton is not None and root_singleton.exists() else None)
|
||||
|
||||
def _adopt_root_row(self, idx: int, row: Dict[str, Any]) -> None:
|
||||
merged = _adopt_if_fresher(self.r_rows[idx], row)
|
||||
if merged is not None:
|
||||
self.r_rows[idx] = merged
|
||||
self.root_changed = self.summary["adopted"] = True
|
||||
|
||||
def _adopt_root_singleton(self, row: Dict[str, Any]) -> None:
|
||||
merged = _adopt_if_fresher(self.root_singleton_row, row)
|
||||
if merged is not None:
|
||||
self.root_singleton_row = merged
|
||||
self.summary["adopted"] = True
|
||||
|
||||
def heal_pool_rows(self) -> None:
|
||||
kept_rows: List[Any] = []
|
||||
for row in self.p_rows:
|
||||
if not _is_oauth_pool_payload(row):
|
||||
kept_rows.append(row) # API keys are safe to duplicate
|
||||
continue
|
||||
match_idx = _find_root_counterpart(row, self.r_rows)
|
||||
if match_idx is not None:
|
||||
self.lineage_proven = True
|
||||
self._adopt_root_row(match_idx, row)
|
||||
# No root pool counterpart. Root's grant may live only in its .anthropic_oauth.json
|
||||
# (the ``hermes auth`` PKCE shape); a profile hermes_pkce-family row is its copy.
|
||||
elif _is_pkce_row(row) and self.root_singleton_row is not None and not self.r_oauth:
|
||||
self._adopt_root_singleton(row)
|
||||
else:
|
||||
# Root holds no copy of this lineage (independent account, or root never had the
|
||||
# grant): the profile's row may be the only surviving copy — leave it alone.
|
||||
kept_rows.append(row)
|
||||
continue
|
||||
self.summary["stripped_ids"].append(row.get("id"))
|
||||
self.profile_changed = True
|
||||
if self.profile_changed and isinstance(self.p_pool, dict):
|
||||
if kept_rows:
|
||||
self.p_pool[self.provider_id] = kept_rows
|
||||
else:
|
||||
self.p_pool.pop(self.provider_id, None)
|
||||
|
||||
def heal_provider_block(self) -> None:
|
||||
if self.provider_id not in _DEVICE_CODE_BLOCK_PROVIDERS:
|
||||
return
|
||||
block_result = _heal_forked_provider_block(
|
||||
self.profile_store, self.root_store, self.provider_id, self.lineage_proven)
|
||||
if block_result is not None:
|
||||
self.profile_changed = self.summary["providers_block"] = True
|
||||
if block_result:
|
||||
self.root_changed = self.summary["adopted"] = True
|
||||
|
||||
def heal_profile_singleton(self, profile_singleton: Optional[Path]) -> None:
|
||||
if profile_singleton is None or not profile_singleton.exists():
|
||||
return
|
||||
from hermes_cli.auth import _is_same_auth_store
|
||||
if self.root_singleton is not None and _is_same_auth_store(profile_singleton, self.root_singleton):
|
||||
return # an aliased singleton pair is one shared grant, not a fork: never self-compare/unlink
|
||||
# See #101356.
|
||||
p_single = _singleton_as_row(profile_singleton)
|
||||
root_has_grant = bool(self.r_oauth) or self.root_singleton_row is not None
|
||||
# Otherwise root has NO grant for this provider (or the file is not a grant): the
|
||||
# profile's singleton may be the only surviving copy — never delete it.
|
||||
if p_single is None or not root_has_grant:
|
||||
return
|
||||
if self.root_singleton_row is not None:
|
||||
self._adopt_root_singleton(p_single)
|
||||
else:
|
||||
# Root only has pool rows: fold the singleton's pair into the freshest-matching
|
||||
# root pkce row, if any.
|
||||
idx = next(
|
||||
(i for i, r in enumerate(self.r_rows)
|
||||
if _is_oauth_pool_payload(r) and _is_pkce_row(r)), None)
|
||||
if idx is not None:
|
||||
self._adopt_root_row(idx, p_single)
|
||||
try:
|
||||
profile_singleton.unlink()
|
||||
self.summary["files"].append(profile_singleton.name)
|
||||
except OSError:
|
||||
logger.debug("could not remove %s", profile_singleton, exc_info=True)
|
||||
|
||||
def sync_root_singleton_with_pkce_row(self) -> None:
|
||||
"""Keep root's singleton and its ``hermes_pkce``-seeded pool row in step.
|
||||
|
||||
Root's next load_pool() re-seeds that row FROM the singleton file, so a stale file would
|
||||
resurrect the spent pair (and a stale row would be overwritten by a fresh file).
|
||||
"""
|
||||
if not (
|
||||
self.summary["adopted"] and self.root_singleton is not None
|
||||
and self.root_singleton_row is not None):
|
||||
return
|
||||
pkce_idx = next(
|
||||
(i for i, r in enumerate(self.r_rows)
|
||||
if _is_oauth_pool_payload(r) and r.get("source") == "hermes_pkce"), None)
|
||||
if pkce_idx is None:
|
||||
return
|
||||
pkce_row = self.r_rows[pkce_idx]
|
||||
row_fresh = _oauth_freshness(pkce_row)
|
||||
single_fresh = _oauth_freshness(self.root_singleton_row)
|
||||
if row_fresh > single_fresh:
|
||||
self.root_singleton_row = _adopt_oauth_material(self.root_singleton_row, pkce_row)
|
||||
elif single_fresh > row_fresh:
|
||||
self.r_rows[pkce_idx] = _adopt_oauth_material(pkce_row, self.root_singleton_row)
|
||||
self.root_changed = True
|
||||
|
||||
@property
|
||||
def dirty(self) -> bool:
|
||||
return bool(self.profile_changed or self.root_changed or self.summary["adopted"])
|
||||
|
||||
def notice(self, profile_name: str) -> str:
|
||||
summary = self.summary
|
||||
log_bits = [bit for bit, present in (
|
||||
(f"pool rows {summary['stripped_ids']}", summary["stripped_ids"]),
|
||||
(f"providers.{self.provider_id} block", summary["providers_block"]),
|
||||
(", ".join(summary["files"]), summary["files"])) if present]
|
||||
verdict = (
|
||||
"profile copy was the live pair; root updated"
|
||||
if summary["adopted"] else "root copy already newest; profile copy dropped")
|
||||
return (
|
||||
f"profile {profile_name}: consolidated forked {self.provider_id} OAuth grant "
|
||||
f"({'; '.join(log_bits) or 'no-op'}) into the root grant — {verdict}; "
|
||||
f"this profile now borrows the root grant (#100339)")
|
||||
|
||||
|
||||
def _heal_forked_single_use_oauth_grants(provider_id: str) -> Optional[Dict[str, Any]]:
|
||||
from hermes_cli.auth import (
|
||||
_auth_file_path, _auth_store_lock, _global_auth_file_path, _load_auth_store,
|
||||
_is_same_auth_store, _oauth_heal_clean_marks, _oauth_heal_notices, _same_path,
|
||||
_save_auth_store)
|
||||
root_path = _global_auth_file_path()
|
||||
if root_path is None:
|
||||
return None # classic mode: nothing to consolidate into
|
||||
if os.environ.get("PYTEST_CURRENT_TEST"):
|
||||
# Same seat belt as the write-through paths: never touch the real user's
|
||||
# ~/.hermes/auth.json from a test that forgot to isolate HOME.
|
||||
real_home_env = os.environ.get("HOME", "")
|
||||
if real_home_env and _same_path(root_path, Path(real_home_env) / ".hermes" / "auth.json"):
|
||||
return None
|
||||
profile_path = _auth_file_path()
|
||||
profile_home = profile_path.parent
|
||||
is_anthropic = provider_id == "anthropic"
|
||||
profile_singleton = profile_home / ".anthropic_oauth.json" if is_anthropic else None
|
||||
root_singleton = root_path.parent / ".anthropic_oauth.json" if is_anthropic else None
|
||||
|
||||
# Hot-path short-circuit: load_pool() runs per model call. Once this profile's store was
|
||||
# verified clean for *provider_id*, skip the locked read-modify-write until one of the files
|
||||
# it reads changes.
|
||||
#
|
||||
# The ROOT store is part of the fingerprint even though only the profile side is read above:
|
||||
# this heal consolidates root -> profile, so a new forked grant appearing in ROOT must
|
||||
# invalidate the mark. The in-memory mark omitted it and got away with it because it died
|
||||
# with the process; a persisted mark would otherwise keep skipping a heal that has become
|
||||
# necessary. Sizes, inodes and ctimes ride along with the mtimes for the same reason:
|
||||
# a metadata-preserving rewrite (``rsync -t``, ``tar -p``, a restore) would otherwise leave
|
||||
# a stale mark looking current indefinitely rather than for one process.
|
||||
fingerprint = (
|
||||
str(profile_path), _stat_sig(profile_path), _stat_sig(profile_singleton),
|
||||
str(root_path), _stat_sig(root_path), _stat_sig(root_singleton),
|
||||
)
|
||||
if _oauth_heal_clean_marks.get(provider_id) == fingerprint:
|
||||
return None
|
||||
# Same check against the on-disk mark, BEFORE taking any lock: a fresh process would
|
||||
# otherwise pay two nested exclusive auth-store locks — a full AUTH_LOCK_TIMEOUT_SECONDS
|
||||
# each behind a sibling holding them — only to find nothing to consolidate.
|
||||
if _persisted_oauth_heal_fingerprint(provider_id) == _json_shape(fingerprint):
|
||||
_oauth_heal_clean_marks[provider_id] = fingerprint
|
||||
return None
|
||||
if fingerprint[1] is None and fingerprint[2] is None:
|
||||
_mark_oauth_heal_clean(provider_id, fingerprint)
|
||||
return None
|
||||
if _is_same_auth_store(profile_path, root_path):
|
||||
# The profile's auth.json IS the root store (symlink/hardlink alias — a deliberate way to
|
||||
# share one grant). Both "sides" would read the same file, every OAuth row would match
|
||||
# itself, and the strip would write through the alias and delete the shared credential.
|
||||
# Nothing to consolidate; the mtime mark keeps this off the per-call hot path.
|
||||
_mark_oauth_heal_clean(provider_id, fingerprint)
|
||||
# See #101356.
|
||||
logger.debug("%s: forked-OAuth heal skipped, %s is the root store", provider_id, profile_path)
|
||||
return None
|
||||
|
||||
# Lock order: active (profile) store first, then the root source store — the same order
|
||||
# ``_provider_state_transaction`` uses.
|
||||
with _auth_store_lock():
|
||||
profile_store = (
|
||||
_load_auth_store(profile_path) if profile_path.exists() else {"providers": {}})
|
||||
with _auth_store_lock(target_path=root_path):
|
||||
root_store = _load_auth_store(root_path) if root_path.exists() else {"providers": {}}
|
||||
run = _HealPass(profile_store, root_store, provider_id, root_singleton)
|
||||
run.heal_pool_rows()
|
||||
run.heal_provider_block()
|
||||
run.heal_profile_singleton(profile_singleton)
|
||||
if not run.dirty:
|
||||
_mark_oauth_heal_clean(provider_id, fingerprint)
|
||||
return None
|
||||
run.sync_root_singleton_with_pkce_row()
|
||||
summary = run.summary
|
||||
if run.root_changed:
|
||||
if isinstance(run.r_pool, dict):
|
||||
run.r_pool[provider_id] = run.r_rows
|
||||
else:
|
||||
root_store["credential_pool"] = {provider_id: run.r_rows}
|
||||
_save_auth_store(root_store, target_path=root_path)
|
||||
singleton_row = run.root_singleton_row
|
||||
if summary["adopted"] and root_singleton is not None and singleton_row is not None:
|
||||
from agent.anthropic_credentials import _write_hermes_oauth_credentials
|
||||
_write_hermes_oauth_credentials(
|
||||
singleton_row.get("access_token") or "", singleton_row.get("refresh_token"),
|
||||
singleton_row.get("expires_at_ms"), target=root_singleton)
|
||||
if run.profile_changed and profile_path.exists():
|
||||
_save_auth_store(profile_store, target_path=profile_path)
|
||||
message = run.notice(profile_home.name)
|
||||
logger.info(message)
|
||||
_oauth_heal_notices.append(message)
|
||||
return summary
|
||||
+4
-45
@@ -71,12 +71,7 @@ def _xai_oauth_state_has_usable_tokens(state: Optional[Dict[str, Any]]) -> bool:
|
||||
|
||||
|
||||
def _read_xai_oauth_tokens(*, _lock: bool = True) -> Dict[str, Any]:
|
||||
from hermes_cli.auth import _load_global_auth_store
|
||||
state = _xai_oauth_state_from_store(_load_auth_store_maybe_locked(_lock))
|
||||
if not _xai_oauth_state_has_usable_tokens(state):
|
||||
global_state = _xai_oauth_state_from_store(_load_global_auth_store())
|
||||
if _xai_oauth_state_has_usable_tokens(global_state):
|
||||
state = global_state
|
||||
if not state:
|
||||
raise _xai_err(
|
||||
"No xAI OAuth credentials stored. Select xAI Grok OAuth (SuperGrok / Premium+) in `hermes model`.",
|
||||
@@ -97,33 +92,6 @@ def _read_xai_oauth_tokens(*, _lock: bool = True) -> Dict[str, Any]:
|
||||
}
|
||||
|
||||
|
||||
def _write_through_xai_oauth_to_global_root(state: Dict[str, Any]) -> None:
|
||||
"""Best-effort persist of a rotated xAI grant into the global-root auth.json.
|
||||
|
||||
xAI rotates refresh_token on every refresh, so a profile that refreshed a root-resolved grant
|
||||
must write the chain back to root. Touches only root ``providers.xai-oauth``; swallows all
|
||||
errors (root-stale is better than breaking the profile's own save).
|
||||
"""
|
||||
from hermes_cli.auth import _global_auth_file_path, _persist_provider_state_to_store
|
||||
global_path = _global_auth_file_path()
|
||||
if global_path is None: # classic mode (profile == root); the profile save already hit root
|
||||
return
|
||||
# Seat belt: under pytest never write the real ~/.hermes/auth.json (mirrors the read-side guard
|
||||
# in _load_global_auth_store). Uses raw HOME, not Path.home(), which fixtures may monkeypatch.
|
||||
real_home_env = os.environ.get("HOME", "") if os.environ.get("PYTEST_CURRENT_TEST") else ""
|
||||
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
|
||||
except Exception:
|
||||
return
|
||||
try:
|
||||
_persist_provider_state_to_store("xai-oauth", state, global_path, set_active=False)
|
||||
except Exception as exc: # pragma: no cover - best effort
|
||||
logger.debug("xAI OAuth: write-through to global root failed: %s", exc)
|
||||
|
||||
|
||||
def _save_xai_oauth_tokens(
|
||||
tokens: Dict[str, Any], *, discovery: Optional[Dict[str, Any]] = None, redirect_uri: str = "",
|
||||
last_refresh: Optional[str] = None, auth_mode: str = "oauth_device_code",
|
||||
@@ -134,28 +102,19 @@ def _save_xai_oauth_tokens(
|
||||
Pass ``set_active=False`` for side-tool bootstrap (TTS/setup, tools config, dashboard, refresh)
|
||||
so inference routing is unchanged.
|
||||
"""
|
||||
from hermes_cli.auth import _auth_store_lock, _global_auth_file_path, _load_auth_store, _load_provider_state_with_source, _same_path, _save_auth_store, _store_provider_state, _utc_now_z, _write_through_xai_oauth_to_global_root
|
||||
from hermes_cli.auth import _auth_store_lock, _load_auth_store, _load_provider_state, _save_auth_store, _store_provider_state, _utc_now_z
|
||||
if last_refresh is None:
|
||||
last_refresh = _utc_now_z()
|
||||
with _auth_store_lock():
|
||||
auth_store = _load_auth_store()
|
||||
# A profile lacking its own xai-oauth block reads root's grant via fallback; refreshing it
|
||||
# must write the rotated chain back to root or root keeps a revoked refresh token. Decide by
|
||||
# where the grant was resolved FROM (key presence lies: _store_provider_state creates it).
|
||||
state, source_path = _load_provider_state_with_source(auth_store, "xai-oauth")
|
||||
state = state if state is not None else {}
|
||||
state = _load_provider_state(auth_store, "xai-oauth") or {}
|
||||
state.update(tokens=tokens, last_refresh=last_refresh, auth_mode=auth_mode)
|
||||
if discovery:
|
||||
state["discovery"] = discovery
|
||||
if redirect_uri:
|
||||
state["redirect_uri"] = redirect_uri
|
||||
global_root = _global_auth_file_path()
|
||||
if source_path is not None and global_root is not None and _same_path(source_path, global_root):
|
||||
# Root-only write-back: a profile copy would shadow root and disable write-through.
|
||||
_write_through_xai_oauth_to_global_root(state)
|
||||
else:
|
||||
_store_provider_state(auth_store, "xai-oauth", state, set_active=set_active)
|
||||
_save_auth_store(auth_store)
|
||||
_store_provider_state(auth_store, "xai-oauth", state, set_active=set_active)
|
||||
_save_auth_store(auth_store)
|
||||
|
||||
|
||||
def _xai_jwt_exp(access_token: Any) -> Optional[float]:
|
||||
|
||||
@@ -0,0 +1,73 @@
|
||||
"""Post-update audit: named profiles that have no credentials of their own.
|
||||
|
||||
Until Sep 2026 a named profile with an empty ``auth.json`` silently read the root profile's
|
||||
``auth.json`` (provider state + credential pool) and even wrote refreshed OAuth tokens back to it.
|
||||
Profiles are independent islands, so that fallback is gone (#111724): such a profile now gets the
|
||||
"not connected to any AI provider" setup prompt instead of the owner's credentials. ``hermes update``
|
||||
names every affected profile up front so nobody discovers the change from a dead bot.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import logging
|
||||
from pathlib import Path
|
||||
from typing import List
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def _auth_store_has_credentials(auth_path: Path) -> bool:
|
||||
try:
|
||||
store = json.loads(auth_path.read_text(encoding="utf-8-sig"))
|
||||
except (OSError, ValueError):
|
||||
return False
|
||||
if not isinstance(store, dict):
|
||||
return False
|
||||
providers = store.get("providers")
|
||||
if isinstance(providers, dict) and any(isinstance(v, dict) and v for v in providers.values()):
|
||||
return True
|
||||
pool = store.get("credential_pool")
|
||||
return isinstance(pool, dict) and any(isinstance(v, list) and v for v in pool.values())
|
||||
|
||||
|
||||
def _profile_has_own_credentials(profile_dir: Path) -> bool:
|
||||
"""auth.json credentials, a provider key in ``.env``, or a model block carrying its own key/base URL."""
|
||||
if _auth_store_has_credentials(profile_dir / "auth.json"):
|
||||
return True
|
||||
from hermes_cli.auth import PROVIDER_REGISTRY
|
||||
from hermes_cli.main import _dotenv_has_provider_key
|
||||
provider_env_vars = {"OPENROUTER_API_KEY", "OPENAI_API_KEY", "ANTHROPIC_API_KEY", "ANTHROPIC_TOKEN", "OPENAI_BASE_URL"}
|
||||
for pconfig in PROVIDER_REGISTRY.values():
|
||||
if pconfig.auth_type == "api_key":
|
||||
provider_env_vars.update(pconfig.api_key_env_vars)
|
||||
if _dotenv_has_provider_key(profile_dir / ".env", provider_env_vars):
|
||||
return True
|
||||
try:
|
||||
import yaml
|
||||
cfg = yaml.safe_load((profile_dir / "config.yaml").read_text(encoding="utf-8")) or {}
|
||||
except Exception:
|
||||
return False
|
||||
model_cfg = cfg.get("model") if isinstance(cfg, dict) else None
|
||||
return isinstance(model_cfg, dict) and any(
|
||||
str(model_cfg.get(k) or "").strip() for k in ("base_url", "api_key"))
|
||||
|
||||
|
||||
def profiles_without_own_credentials() -> List[str]:
|
||||
"""Names of live named profiles that would have inherited the root ``auth.json`` — i.e. the root
|
||||
holds credentials and the profile holds none. Empty when the root has nothing to inherit."""
|
||||
from hermes_constants import get_default_hermes_root
|
||||
from hermes_cli.profiles import _iter_named_profile_dirs
|
||||
if not _auth_store_has_credentials(get_default_hermes_root() / "auth.json"):
|
||||
return []
|
||||
return [p.name for p in _iter_named_profile_dirs() if not _profile_has_own_credentials(p)]
|
||||
|
||||
|
||||
def print_profiles_without_credentials_notice() -> None:
|
||||
names = profiles_without_own_credentials()
|
||||
if not names:
|
||||
return
|
||||
print("\n\033[1;33m⚠ Profiles no longer inherit the root profile's credentials (auth.json).\033[0m")
|
||||
print(" These profiles have no provider of their own and will ask for one on their next turn:")
|
||||
for name in names:
|
||||
print(f" hermes -p {name} model # or: hermes -p {name} auth add <provider>")
|
||||
@@ -854,14 +854,13 @@ def _clone_all_into(source_dir: Path, profile_dir: Path, canon: str) -> None:
|
||||
(profile_dir / stale).unlink(missing_ok=True)
|
||||
# auth.json / .anthropic_oauth.json copied verbatim fork single-use OAuth grants
|
||||
# (Anthropic / Codex / xAI): one credential with two owners, and the first profile to
|
||||
# refresh revokes the pair for every sibling. Drop the copies; the clone reads the root
|
||||
# grant through the credential-pool fallback.
|
||||
# refresh revokes the pair for every sibling. Drop the copies; the clone signs in itself.
|
||||
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,
|
||||
"(run `hermes -p %s auth add <provider>` to sign in)", canon, stripped, canon,
|
||||
)
|
||||
|
||||
|
||||
|
||||
@@ -1026,6 +1026,11 @@ def _print_plugin_compat_notice() -> None:
|
||||
print(f"\n{colour}⚠ {lines[0]}\033[0m\n {lines[1]}")
|
||||
|
||||
|
||||
def _print_profiles_without_credentials_notice() -> None:
|
||||
from hermes_cli.profile_credential_audit import print_profiles_without_credentials_notice
|
||||
print_profiles_without_credentials_notice()
|
||||
|
||||
|
||||
def _print_post_update_notices_and_self_heals() -> None:
|
||||
"""Best-effort notices (FTS optimize, curator) and self-heals (FHS PATH, ACP launcher,
|
||||
Windows bin launchers, cua-driver refresh) that run after the summary."""
|
||||
@@ -1048,6 +1053,9 @@ def _print_post_update_notices_and_self_heals() -> None:
|
||||
('cua-driver refresh failed: %s', _refresh_cua_driver_after_update),
|
||||
('Checkpoint footprint notice failed: %s', _print_checkpoint_footprint_notice),
|
||||
('Plugin compat notice failed: %s', _print_plugin_compat_notice),
|
||||
# Named profiles stopped inheriting the root auth.json (#111724): name every profile that
|
||||
# now has no provider of its own so nobody finds out from a dead bot.
|
||||
('Profile credential notice failed: %s', _print_profiles_without_credentials_notice),
|
||||
# Legacy HERMES_NEMO_RELAY_ATIF_*/ATOF_* vars produce no traces since the Relay cutover;
|
||||
# generate each profile's relay-plugins.toml instead of leaving exports silently dead.
|
||||
('Relay exporter migration failed: %s', _migrate_relay_exporter_env),
|
||||
|
||||
@@ -98,7 +98,6 @@ def _process_claude_code_refresh_worker(
|
||||
|
||||
# Keep this worker hermetic: each profile has its own auth store, while
|
||||
# both workers deliberately point at the same Claude credential source.
|
||||
auth_mod._global_auth_file_path = lambda: None
|
||||
anthropic_mod.claude_code_credentials_path = lambda: shared_path
|
||||
anthropic_mod.read_claude_code_credentials = read_shared_credentials
|
||||
anthropic_mod._write_claude_code_credentials = write_shared_credentials
|
||||
|
||||
@@ -1,27 +1,14 @@
|
||||
"""Regression tests for credential-pool OAuth refresh write-through to root.
|
||||
"""Credential-pool OAuth refresh persistence.
|
||||
|
||||
Companion to ``tests/hermes_cli/test_xai_oauth_writethrough.py``. That file
|
||||
covers the *non-pool* xAI refresh path (``_save_xai_oauth_tokens``). These
|
||||
cover the **credential-pool** refresh path
|
||||
(``CredentialPool._sync_device_code_entry_to_auth_store``): when a profile
|
||||
that has no own ``providers.<id>`` block refreshes — via the pool — a rotating
|
||||
OAuth grant it resolved from the global-root fallback, the rotated chain must
|
||||
be written back to the global root too. Otherwise root keeps a revoked refresh
|
||||
token and every other profile reading root's stale grant dies with
|
||||
``refresh_token_reused`` / ``invalid_grant`` once its access token expires
|
||||
(issue #48415, the Codex/xAI analog of #43589).
|
||||
|
||||
The tests drive the real ``_sync_device_code_entry_to_auth_store`` against
|
||||
real on-disk auth stores (profile + root under ``tmp_path``) rather than
|
||||
mocking the save boundary, so they exercise the actual atomic write path.
|
||||
Single-use refresh tokens (Codex, xAI, Anthropic PKCE) must be POSTed under the cross-process
|
||||
auth lock and the rotated pair committed back to the store/singleton that seeds the pool, or the
|
||||
next ``load_pool()`` re-seeds the consumed pair over the rotated one. Real on-disk stores under
|
||||
``tmp_path``; only the token endpoint is faked.
|
||||
"""
|
||||
|
||||
import json
|
||||
import threading
|
||||
import time
|
||||
|
||||
import pytest
|
||||
|
||||
from agent import credential_pool as CP
|
||||
from agent.credential_pool import (
|
||||
AUTH_TYPE_OAUTH,
|
||||
@@ -38,10 +25,6 @@ def _write_store(path, store):
|
||||
path.write_text(json.dumps(store), encoding="utf-8")
|
||||
|
||||
|
||||
def _read_store(path):
|
||||
return json.loads(path.read_text(encoding="utf-8"))
|
||||
|
||||
|
||||
def _entry(provider: str, *, id: str, access_token: str, refresh_token: str):
|
||||
return PooledCredential(
|
||||
provider=provider,
|
||||
@@ -55,121 +38,6 @@ def _entry(provider: str, *, id: str, access_token: str, refresh_token: str):
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def profile_and_root(tmp_path, monkeypatch):
|
||||
"""Wire a profile auth store + a distinct global-root auth store on disk.
|
||||
|
||||
The pytest seat belt in ``_write_through_provider_state_to_global_root``
|
||||
only refuses the *real* user's ``$HOME/.hermes/auth.json``; a tmp_path
|
||||
root is allowed, so point HOME away from the tmp root to keep the guard
|
||||
from tripping on these fixtures.
|
||||
"""
|
||||
profile_path = tmp_path / "profiles" / "work" / "auth.json"
|
||||
root_path = tmp_path / "root" / "auth.json"
|
||||
|
||||
monkeypatch.setattr(A, "_auth_file_path", lambda: profile_path)
|
||||
monkeypatch.setattr(A, "_global_auth_file_path", lambda: root_path)
|
||||
monkeypatch.setenv("HOME", str(tmp_path / "not-the-root"))
|
||||
return profile_path, root_path
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
def test_global_write_through_preserves_concurrent_root_update(
|
||||
profile_and_root, monkeypatch
|
||||
):
|
||||
"""A stale profile write-through must not erase a concurrent root login."""
|
||||
_profile_path, root_path = profile_and_root
|
||||
_write_store(
|
||||
root_path,
|
||||
{
|
||||
"version": 1,
|
||||
"providers": {
|
||||
"xai-oauth": {
|
||||
"tokens": {"access_token": "old-xai", "refresh_token": "old-r"}
|
||||
}
|
||||
},
|
||||
"credential_pool": {
|
||||
"anthropic": [{"id": "anthropic-existing"}],
|
||||
"openrouter": [{"id": "openrouter-existing"}],
|
||||
},
|
||||
},
|
||||
)
|
||||
|
||||
helper_loaded = threading.Event()
|
||||
helper_has_target_lock = threading.Event()
|
||||
allow_helper_save = threading.Event()
|
||||
writer_started = threading.Event()
|
||||
writer_done = threading.Event()
|
||||
real_auth_load = A._load_auth_store
|
||||
|
||||
def paused_helper_load(path=None):
|
||||
store = real_auth_load(path)
|
||||
if threading.current_thread().name == "profile-write-through":
|
||||
target_holder = A._auth_lock_holder_for(root_path)
|
||||
if getattr(target_holder, "depth", 0) > 0:
|
||||
helper_has_target_lock.set()
|
||||
helper_loaded.set()
|
||||
assert allow_helper_save.wait(timeout=5)
|
||||
return store
|
||||
|
||||
monkeypatch.setattr(A, "_load_auth_store", paused_helper_load)
|
||||
# The pre-fix implementation imported the loader directly; patch both
|
||||
# bindings so reverting the safe helper still exercises the stale ordering.
|
||||
monkeypatch.setattr(CP, "_load_auth_store", paused_helper_load)
|
||||
|
||||
def profile_write_through():
|
||||
CP._write_through_provider_state_to_global_root(
|
||||
"xai-oauth",
|
||||
{"tokens": {"access_token": "new-xai", "refresh_token": "new-r"}},
|
||||
)
|
||||
|
||||
def concurrent_codex_login():
|
||||
writer_started.set()
|
||||
with A._auth_store_lock(target_path=root_path):
|
||||
store = A._load_auth_store(root_path)
|
||||
A._store_provider_state(
|
||||
store,
|
||||
"openai-codex",
|
||||
{"tokens": {"access_token": "codex-a", "refresh_token": "codex-r"}},
|
||||
set_active=False,
|
||||
)
|
||||
pool = store.setdefault("credential_pool", {})
|
||||
pool["openai-codex"] = [{"id": "codex-login"}]
|
||||
A._save_auth_store(store, target_path=root_path)
|
||||
writer_done.set()
|
||||
|
||||
helper = threading.Thread(target=profile_write_through, name="profile-write-through")
|
||||
helper.start()
|
||||
assert helper_loaded.wait(timeout=5)
|
||||
|
||||
writer = threading.Thread(target=concurrent_codex_login, name="concurrent-login")
|
||||
writer.start()
|
||||
assert writer_started.wait(timeout=5)
|
||||
# A fixed helper already owns the target lock, so the writer will merge
|
||||
# after release. A reverted unlocked helper must first let the competing
|
||||
# login finish; only then do we release its stale save. This makes the
|
||||
# losing pre-fix ordering deterministic rather than scheduler-dependent.
|
||||
if not helper_has_target_lock.is_set():
|
||||
assert writer_done.wait(timeout=5)
|
||||
allow_helper_save.set()
|
||||
helper.join(timeout=5)
|
||||
writer.join(timeout=5)
|
||||
assert not helper.is_alive()
|
||||
assert not writer.is_alive()
|
||||
|
||||
root = _read_store(root_path)
|
||||
assert root["providers"]["xai-oauth"]["tokens"]["refresh_token"] == "new-r"
|
||||
assert root["providers"]["openai-codex"]["tokens"]["refresh_token"] == "codex-r"
|
||||
assert root["credential_pool"]["openai-codex"] == [{"id": "codex-login"}]
|
||||
assert root["credential_pool"]["anthropic"] == [{"id": "anthropic-existing"}]
|
||||
assert root["credential_pool"]["openrouter"] == [{"id": "openrouter-existing"}]
|
||||
|
||||
|
||||
def test_codex_pool_refresh_holds_auth_store_lock_across_post(monkeypatch, tmp_path):
|
||||
"""The Codex OAuth pool refresh must POST under the cross-process auth lock.
|
||||
|
||||
@@ -186,8 +54,6 @@ def test_codex_pool_refresh_holds_auth_store_lock_across_post(monkeypatch, tmp_p
|
||||
provider = "openai-codex"
|
||||
profile_path = tmp_path / "auth.json"
|
||||
monkeypatch.setattr(A, "_auth_file_path", lambda: profile_path)
|
||||
monkeypatch.setattr(A, "_global_auth_file_path", lambda: None)
|
||||
monkeypatch.setenv("HOME", str(tmp_path / "not-the-root"))
|
||||
|
||||
lock_held: dict = {"during_post": None}
|
||||
real_lock = A._auth_store_lock
|
||||
@@ -238,90 +104,6 @@ def test_codex_pool_refresh_holds_auth_store_lock_across_post(monkeypatch, tmp_p
|
||||
assert lock_held["during_post"] is True
|
||||
|
||||
|
||||
def test_write_through_fires_on_every_refresh_not_just_first(
|
||||
profile_and_root, monkeypatch
|
||||
):
|
||||
"""Write-through to root must fire on the 2nd, 3rd, … refresh too (#74339).
|
||||
|
||||
The old key-presence check decided write-through on whether the *profile*
|
||||
store had ``providers.<id>`` BEFORE the save — a key that
|
||||
``_store_provider_state()`` unconditionally created. Net effect: first
|
||||
refresh → write-through fires; every later refresh → silently disabled
|
||||
because the profile now "owned" the block, even though it never
|
||||
performed its own OAuth grant.
|
||||
|
||||
The fix skips ``_store_provider_state`` entirely when the grant was
|
||||
resolved from root, so the profile never accrues a shadowing key and
|
||||
``_load_provider_state_with_source`` always resolves from root.
|
||||
"""
|
||||
profile_path, root_path = profile_and_root
|
||||
_write_store(
|
||||
root_path,
|
||||
{
|
||||
"version": 1,
|
||||
"providers": {
|
||||
"openai-codex": {
|
||||
"tokens": {"access_token": "root-ac", "refresh_token": "root-rf"}
|
||||
}
|
||||
},
|
||||
},
|
||||
)
|
||||
|
||||
provider = "openai-codex"
|
||||
# After patching A's module-level attributes, the bare-name imports in
|
||||
# credential_pool.py still hold references to the original functions
|
||||
# (``from X import Y`` creates a local binding that does not update when
|
||||
# ``X.Y`` is reassigned). Patch CP's bindings separately so the
|
||||
# ``_sync_device_code_entry_to_auth_store`` method — whose __globals__
|
||||
# are ``agent.credential_pool.__dict__`` — sees the mocked paths.
|
||||
monkeypatch.setattr(CP, "_global_auth_file_path", lambda: root_path)
|
||||
monkeypatch.setattr(CP, "_same_path", lambda a, b: a == b)
|
||||
# Let _write_through_provider_state_to_global_root run for real so it
|
||||
# persists the rotated token pair to the root auth.json — the test
|
||||
# asserts the on-disk values after each refresh.
|
||||
|
||||
# ---- REFRESH 1 ----
|
||||
_write_store(profile_path, {"version": 1})
|
||||
entry1 = _entry(
|
||||
provider, id="c1", access_token="ac1", refresh_token="rf1"
|
||||
)
|
||||
pool1 = CredentialPool(provider, [entry1])
|
||||
pool1._sync_device_code_entry_to_auth_store(entry1)
|
||||
|
||||
# Verify root was updated with the rotated tokens from refresh 1.
|
||||
root_store = _read_store(root_path)
|
||||
root_tokens = root_store["providers"]["openai-codex"]["tokens"]
|
||||
assert root_tokens["access_token"] == "ac1"
|
||||
assert root_tokens["refresh_token"] == "rf1"
|
||||
|
||||
# After refresh 1 the profile should NOT have a providers.openai-codex
|
||||
# block (the fix skipped _store_provider_state because the grant came
|
||||
# from root). This prevents the self-sealing that broke refresh 2+.
|
||||
profile_store = _read_store(profile_path)
|
||||
assert "openai-codex" not in profile_store.get("providers", {}), (
|
||||
"profile must NOT accrue a shadowing providers.<id> block when the "
|
||||
"grant was resolved from root — that key would disable write-through "
|
||||
"on the next refresh (#74339)"
|
||||
)
|
||||
|
||||
# ---- REFRESH 2 (same scenario, rotated tokens) ----
|
||||
entry2 = _entry(
|
||||
provider, id="c2", access_token="ac2", refresh_token="rf2"
|
||||
)
|
||||
pool2 = CredentialPool(provider, [entry2])
|
||||
pool2._sync_device_code_entry_to_auth_store(entry2)
|
||||
|
||||
# Verify root was updated with the rotated tokens from refresh 2.
|
||||
# The old key-presence check would have silently skipped this write.
|
||||
root_store = _read_store(root_path)
|
||||
root_tokens = root_store["providers"]["openai-codex"]["tokens"]
|
||||
assert root_tokens["access_token"] == "ac2", (
|
||||
"refresh 2: root must carry the rotated token pair. "
|
||||
"The old code self-disabled write-through here (#74339)"
|
||||
)
|
||||
assert root_tokens["refresh_token"] == "rf2"
|
||||
|
||||
|
||||
def test_hermes_pkce_refresh_writes_back_to_singleton(tmp_path, monkeypatch):
|
||||
"""A successful hermes_pkce refresh must update
|
||||
~/.hermes/.anthropic_oauth.json, or ``_seed_from_singletons()`` on the
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
"""Regression tests for #100339: cloned / borrowed single-use Anthropic OAuth
|
||||
grants must never fork across profiles.
|
||||
"""Single-use Anthropic OAuth grants never fork across profiles (#100339) and are never
|
||||
inherited from the root (#111724).
|
||||
|
||||
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``
|
||||
@@ -30,8 +30,6 @@ def fleet(tmp_path, monkeypatch):
|
||||
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]
|
||||
|
||||
@@ -94,14 +92,6 @@ def fleet(tmp_path, monkeypatch):
|
||||
"""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
|
||||
auth_mod._oauth_heal_clean_marks.clear()
|
||||
|
||||
# Process-wide notice buffer: start each test clean.
|
||||
import hermes_cli.auth as _auth_mod
|
||||
_auth_mod._oauth_heal_notices.clear()
|
||||
_auth_mod._oauth_heal_clean_marks.clear()
|
||||
|
||||
def pool_rows(home):
|
||||
p = home / "auth.json"
|
||||
@@ -222,81 +212,27 @@ def test_strip_helper_fails_closed_when_store_identity_check_errors(fleet, monke
|
||||
assert (copied / "auth.json").read_text() == before
|
||||
|
||||
|
||||
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
|
||||
# ── B. a named profile never borrows the root grant ───────────────────────
|
||||
|
||||
|
||||
def test_agent_init_resolver_sees_sibling_rotation(fleet):
|
||||
def test_named_profile_does_not_inherit_or_rotate_the_root_grant(fleet):
|
||||
"""An empty profile sees no Anthropic credential and the root's single-use pair is untouched;
|
||||
the root itself still refreshes and persists its own rotation (control)."""
|
||||
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"
|
||||
assert load_pool("anthropic").select() is None
|
||||
assert resolve_anthropic_token() is None
|
||||
assert fleet["rows"](forge) in (None, [])
|
||||
assert fleet["server"]["log"] == []
|
||||
assert fleet["rows"](fleet["root"])[0]["refresh_token"] == "sk-ant-ort-RT0"
|
||||
|
||||
|
||||
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()
|
||||
fleet["use"](fleet["root"])
|
||||
sel = load_pool("anthropic").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"
|
||||
assert fleet["rows"](fleet["root"])[0]["refresh_token"] == "sk-ant-ort-RT1"
|
||||
|
||||
|
||||
def test_profile_auth_add_owns_only_its_own_rows(fleet):
|
||||
@@ -310,285 +246,10 @@ def test_profile_auth_add_owns_only_its_own_rows(fleet):
|
||||
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"](kid)] == ["own001"]
|
||||
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"
|
||||
|
||||
|
||||
# ── C. one-time heal for installs that ALREADY forked the grant ──────────
|
||||
#
|
||||
# Fleets created on pre-fix code hold profile-local copies of the root grant
|
||||
# (verbatim --clone-all, or the old borrowed-persist). The heal runs inside
|
||||
# the profile's load_pool(): consolidate to ROOT (freshest rotation wins),
|
||||
# strip the profile copy, borrow root from then on.
|
||||
|
||||
def _fork(fleet, name, *, rotated_to=None):
|
||||
"""Create *name* with a pre-fix style verbatim copy of root's auth.json.
|
||||
|
||||
``rotated_to=N`` makes the copy the LIVE pair (RT<N>, spent RT0 server-side)
|
||||
to emulate a profile that already refreshed on the old code.
|
||||
"""
|
||||
pdir = _profile(fleet, name)
|
||||
pdir.mkdir(parents=True, exist_ok=True)
|
||||
store = json.loads((fleet["root"] / "auth.json").read_text())
|
||||
if rotated_to is not None:
|
||||
row = store["credential_pool"]["anthropic"][0]
|
||||
row["access_token"] = f"sk-ant-oat01-AT{rotated_to}"
|
||||
row["refresh_token"] = f"sk-ant-ort-RT{rotated_to}"
|
||||
row["expires_at_ms"] = int((time.time() - 60) * 1000) # newer, still expired
|
||||
srv = fleet["server"]
|
||||
srv["spent"].add("sk-ant-ort-RT0")
|
||||
srv["valid"].discard("sk-ant-ort-RT0")
|
||||
srv["valid"].add(f"sk-ant-ort-RT{rotated_to}")
|
||||
srv["n"] = rotated_to
|
||||
(pdir / "auth.json").write_text(json.dumps(store))
|
||||
return pdir
|
||||
|
||||
|
||||
def test_heal_consolidates_existing_forks_to_the_live_copy(fleet, caplog):
|
||||
"""root + atlas hold spent RT0; forge already rotated to RT1 on old code."""
|
||||
import logging
|
||||
from agent.credential_pool import load_pool
|
||||
|
||||
forge = _fork(fleet, "forge", rotated_to=1)
|
||||
atlas = _fork(fleet, "atlas")
|
||||
assert fleet["rows"](forge)[0]["refresh_token"] == "sk-ant-ort-RT1"
|
||||
assert fleet["rows"](atlas)[0]["refresh_token"] == "sk-ant-ort-RT0"
|
||||
|
||||
with caplog.at_level(logging.INFO, logger="hermes_cli.auth"):
|
||||
fleet["use"](forge)
|
||||
sel = load_pool("anthropic").select()
|
||||
assert sel is not None and sel.access_token == "sk-ant-oat01-AT2"
|
||||
# forge's live pair was adopted by ROOT, then rotated there; forge holds nothing.
|
||||
assert fleet["rows"](forge) is None
|
||||
assert fleet["rows"](fleet["root"])[0]["refresh_token"] == "sk-ant-ort-RT2"
|
||||
assert fleet["rows"](fleet["root"])[0]["id"] == "abc123"
|
||||
healed = [r.message for r in caplog.records if "consolidated forked anthropic OAuth grant" in r.message]
|
||||
assert len(healed) == 1 and "profile forge" in healed[0] and "root updated" in healed[0]
|
||||
|
||||
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-AT2", home
|
||||
assert fleet["rows"](atlas) is None and fleet["rows"](forge) is None
|
||||
# Exactly one rotation by us (RT1 -> RT2); the spent RT0 was never replayed.
|
||||
assert [e[0] for e in fleet["server"]["log"]] == ["ROTATE"], fleet["server"]["log"]
|
||||
# API-key rows in the profiles were not touched.
|
||||
for home in (forge, atlas):
|
||||
store = json.loads((home / "auth.json").read_text())
|
||||
assert store["credential_pool"]["openai"][0]["access_token"] == "sk-static-key"
|
||||
|
||||
|
||||
def test_heal_is_idempotent_and_logs_once(fleet, caplog):
|
||||
import logging
|
||||
from agent.credential_pool import load_pool
|
||||
from hermes_cli.auth import consume_oauth_heal_notices, heal_forked_single_use_oauth_grants
|
||||
|
||||
kid = _fork(fleet, "kid")
|
||||
fleet["use"](kid)
|
||||
with caplog.at_level(logging.INFO, logger="hermes_cli.auth"):
|
||||
load_pool("anthropic")
|
||||
assert fleet["rows"](kid) is None
|
||||
notices = consume_oauth_heal_notices()
|
||||
assert len(notices) == 1 and "profile kid" in notices[0]
|
||||
root_before = (fleet["root"] / "auth.json").read_text()
|
||||
# Second and third loads: nothing to do, nothing written, nothing logged.
|
||||
assert heal_forked_single_use_oauth_grants("anthropic") is None
|
||||
load_pool("anthropic")
|
||||
assert consume_oauth_heal_notices() == []
|
||||
assert (fleet["root"] / "auth.json").read_text() == root_before
|
||||
assert sum("consolidated forked" in r.message for r in caplog.records) == 1
|
||||
|
||||
|
||||
def test_heal_never_deletes_the_only_surviving_copy(fleet):
|
||||
"""Root lost its grant (user ran `hermes auth remove` at root); the profile's
|
||||
copy is the only one left — and an independent second account stays put."""
|
||||
from agent.credential_pool import load_pool
|
||||
|
||||
kid = _fork(fleet, "kid", rotated_to=1)
|
||||
store = json.loads((fleet["root"] / "auth.json").read_text())
|
||||
del store["credential_pool"]["anthropic"]
|
||||
(fleet["root"] / "auth.json").write_text(json.dumps(store))
|
||||
|
||||
fleet["use"](kid)
|
||||
sel = load_pool("anthropic").select()
|
||||
assert sel is not None and sel.access_token == "sk-ant-oat01-AT2"
|
||||
assert fleet["rows"](kid) and fleet["rows"](kid)[0]["refresh_token"] == "sk-ant-ort-RT2"
|
||||
assert "anthropic" not in (json.loads((fleet["root"] / "auth.json").read_text())["credential_pool"])
|
||||
|
||||
|
||||
@pytest.mark.parametrize("shape", ["pool", "provider"])
|
||||
@pytest.mark.parametrize("claims", [True, False])
|
||||
def test_heal_preserves_independent_grants_for_same_account(fleet, shape, claims):
|
||||
"""An account can have independent device logins; identity is not lineage."""
|
||||
import base64
|
||||
from hermes_cli.auth import heal_forked_single_use_oauth_grants
|
||||
|
||||
def pair(tag):
|
||||
payload = base64.urlsafe_b64encode(json.dumps({
|
||||
"sub": "same-account", "exp": int(time.time()) + 3600, "jti": tag,
|
||||
}).encode()).decode().rstrip("=")
|
||||
return {"access_token": "h." + payload + ".s" if claims else tag,
|
||||
"refresh_token": "independent-" + tag}
|
||||
|
||||
def store(tag):
|
||||
tokens = pair(tag)
|
||||
if shape == "provider":
|
||||
return {"version": 1, "providers": {"openai-codex": {"tokens": tokens}}}
|
||||
return {"version": 1, "providers": {}, "credential_pool": {"openai-codex": [{
|
||||
"id": tag, "auth_type": "oauth", "source": "manual:device_code", **tokens,
|
||||
}]}}
|
||||
|
||||
root = fleet["root"] / "auth.json"
|
||||
kid = _profile(fleet, "independent")
|
||||
kid.mkdir(parents=True, exist_ok=True)
|
||||
profile = kid / "auth.json"
|
||||
root.write_text(json.dumps(store("root-grant")))
|
||||
profile.write_text(json.dumps(store("profile-grant")))
|
||||
before = (root.read_bytes(), profile.read_bytes())
|
||||
fleet["use"](kid)
|
||||
assert heal_forked_single_use_oauth_grants("openai-codex") is None
|
||||
assert (root.read_bytes(), profile.read_bytes()) == before
|
||||
if claims:
|
||||
from agent.credential_pool import load_pool
|
||||
for _ in range(3):
|
||||
selected = load_pool("openai-codex").select()
|
||||
assert selected is not None
|
||||
assert selected.refresh_token == "independent-profile-grant"
|
||||
assert root.read_bytes() == before[0]
|
||||
|
||||
|
||||
def test_heal_rotated_fork_moves_provider_block_with_the_pool_row(fleet):
|
||||
"""Copied pool-row id proves the fork even after both sides rotated past token equality.
|
||||
|
||||
Root's load_pool() re-seeds its device_code row FROM providers.<id>.tokens, so root's block
|
||||
must carry the fresher pair too or the next root load resurrects the spent one.
|
||||
"""
|
||||
from agent.credential_pool import load_pool
|
||||
from hermes_cli.auth import heal_forked_single_use_oauth_grants
|
||||
|
||||
def store(tag, exp_off):
|
||||
tokens = {"access_token": "at-" + tag, "refresh_token": "rt-" + tag}
|
||||
issued = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime(time.time() + exp_off - 3600))
|
||||
return {"version": 1,
|
||||
"providers": {"openai-codex": {"tokens": tokens, "last_refresh": issued}},
|
||||
"credential_pool": {"openai-codex": [{
|
||||
"id": "shared-id", "auth_type": "oauth", "source": "device_code", **tokens,
|
||||
"expires_at_ms": int((time.time() + exp_off) * 1000)}]}}
|
||||
|
||||
root = fleet["root"] / "auth.json"
|
||||
kid = _profile(fleet, "rotated")
|
||||
kid.mkdir(parents=True, exist_ok=True)
|
||||
root.write_text(json.dumps(store("old", 100)))
|
||||
(kid / "auth.json").write_text(json.dumps(store("new", 3600)))
|
||||
fleet["use"](kid)
|
||||
assert heal_forked_single_use_oauth_grants("openai-codex")["adopted"] is True
|
||||
r, p = json.loads(root.read_text()), json.loads((kid / "auth.json").read_text())
|
||||
assert r["credential_pool"]["openai-codex"][0]["refresh_token"] == "rt-new"
|
||||
assert r["providers"]["openai-codex"]["tokens"]["refresh_token"] == "rt-new"
|
||||
assert "openai-codex" not in p["providers"]
|
||||
assert "openai-codex" not in p.get("credential_pool", {})
|
||||
fleet["use"](fleet["root"])
|
||||
assert {e.refresh_token for e in load_pool("openai-codex").entries()} == {"rt-new"}
|
||||
|
||||
|
||||
def test_heal_leaves_a_different_account_alone(fleet):
|
||||
"""A profile row whose JWT identity names ANOTHER account is not root's grant."""
|
||||
import base64
|
||||
from agent.credential_pool import load_pool
|
||||
|
||||
def jwt(sub):
|
||||
payload = base64.urlsafe_b64encode(json.dumps({"sub": sub, "exp": int(time.time()) + 3600}).encode()).rstrip(b"=")
|
||||
return "h." + payload.decode() + ".s"
|
||||
|
||||
root_store = json.loads((fleet["root"] / "auth.json").read_text())
|
||||
root_store["credential_pool"]["xai-oauth"] = [{
|
||||
"id": "rootx", "auth_type": "oauth", "priority": 0, "source": "manual:device_code",
|
||||
"access_token": jwt("alice"), "refresh_token": "xr-alice",
|
||||
}]
|
||||
(fleet["root"] / "auth.json").write_text(json.dumps(root_store))
|
||||
kid = _profile(fleet, "kid")
|
||||
kid.mkdir(parents=True, exist_ok=True)
|
||||
(kid / "auth.json").write_text(json.dumps({
|
||||
"version": 1, "providers": {},
|
||||
"credential_pool": {"xai-oauth": [
|
||||
{"id": "kidx", "auth_type": "oauth", "priority": 0, "source": "manual:device_code",
|
||||
"access_token": jwt("bob"), "refresh_token": "xr-bob"},
|
||||
{"id": "kidk", "auth_type": "api_key", "priority": 1, "source": "manual",
|
||||
"access_token": "xai-static"},
|
||||
]},
|
||||
}))
|
||||
fleet["use"](kid)
|
||||
load_pool("xai-oauth")
|
||||
rows = (json.loads((kid / "auth.json").read_text())["credential_pool"])["xai-oauth"]
|
||||
assert [r["id"] for r in rows] == ["kidx", "kidk"]
|
||||
assert json.loads((fleet["root"] / "auth.json").read_text())["credential_pool"]["xai-oauth"][0]["refresh_token"] == "xr-alice"
|
||||
|
||||
|
||||
def test_heal_pkce_singleton_shape_commits_live_pair_to_root_singleton(fleet):
|
||||
"""`hermes auth` PKCE shape: root + profile each have .anthropic_oauth.json +
|
||||
a hermes_pkce-seeded row; the profile's copy is the rotated (live) one."""
|
||||
from agent.credential_pool import load_pool
|
||||
|
||||
root = fleet["root"]
|
||||
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))
|
||||
(root / ".anthropic_oauth.json").write_text(json.dumps({
|
||||
"accessToken": "sk-ant-oat01-AT0", "refreshToken": "sk-ant-ort-RT0",
|
||||
"expiresAt": int((time.time() - 3600) * 1000),
|
||||
}))
|
||||
fleet["use"](root)
|
||||
load_pool("anthropic") # seeds root's hermes_pkce row from the singleton
|
||||
|
||||
kid = _profile(fleet, "kid")
|
||||
kid.mkdir(parents=True, exist_ok=True)
|
||||
import shutil
|
||||
shutil.copy2(root / "auth.json", kid / "auth.json")
|
||||
(kid / ".anthropic_oauth.json").write_text(json.dumps({
|
||||
"accessToken": "sk-ant-oat01-AT1", "refreshToken": "sk-ant-ort-RT1",
|
||||
"expiresAt": int((time.time() - 60) * 1000),
|
||||
}))
|
||||
kstore = json.loads((kid / "auth.json").read_text())
|
||||
kstore["credential_pool"]["anthropic"][0].update(
|
||||
access_token="sk-ant-oat01-AT1", refresh_token="sk-ant-ort-RT1",
|
||||
expires_at_ms=int((time.time() - 60) * 1000),
|
||||
)
|
||||
(kid / "auth.json").write_text(json.dumps(kstore))
|
||||
srv = fleet["server"]
|
||||
srv["spent"].add("sk-ant-ort-RT0"); srv["valid"] = {"sk-ant-ort-RT1"}; srv["n"] = 1
|
||||
|
||||
fleet["use"](kid)
|
||||
sel = load_pool("anthropic").select()
|
||||
assert sel is not None and sel.access_token == "sk-ant-oat01-AT2"
|
||||
assert not (kid / ".anthropic_oauth.json").exists()
|
||||
assert fleet["rows"](kid) is None
|
||||
assert json.loads((root / ".anthropic_oauth.json").read_text())["refreshToken"] == "sk-ant-ort-RT2"
|
||||
fleet["use"](root)
|
||||
sel = load_pool("anthropic").select()
|
||||
assert sel is not None and sel.access_token == "sk-ant-oat01-AT2"
|
||||
assert [e[0] for e in srv["log"]] == ["ROTATE"], srv["log"]
|
||||
|
||||
|
||||
def test_heal_is_a_noop_in_classic_mode(fleet):
|
||||
from hermes_cli.auth import heal_forked_single_use_oauth_grants
|
||||
fleet["use"](fleet["root"])
|
||||
before = (fleet["root"] / "auth.json").read_text()
|
||||
assert heal_forked_single_use_oauth_grants("anthropic") is None
|
||||
assert (fleet["root"] / "auth.json").read_text() == before
|
||||
|
||||
|
||||
# ── C. a SHARED root store is not a fork (#101356) ───────────────────────
|
||||
|
||||
def _seed_codex_grant(root):
|
||||
"""Give the root store an openai-codex pool row AND a providers block."""
|
||||
fresh = int((time.time() + 3600) * 1000)
|
||||
@@ -614,197 +275,3 @@ def _shared_profile(fleet, name, *, link):
|
||||
alias.unlink()
|
||||
link(fleet["root"] / "auth.json", alias)
|
||||
return pdir
|
||||
|
||||
|
||||
def test_heal_skips_profile_auth_json_symlinked_to_the_root_store(fleet):
|
||||
"""#101356: `ln -s ~/.hermes/auth.json <profile>/auth.json` shares ONE store.
|
||||
Both sides of the consolidation read the same file, so every row looks like
|
||||
a fork of itself — healing would strip the shared grant through the link."""
|
||||
from hermes_cli.auth import consume_oauth_heal_notices, heal_forked_single_use_oauth_grants
|
||||
|
||||
root = fleet["root"]
|
||||
_seed_codex_grant(root)
|
||||
before = (root / "auth.json").read_text()
|
||||
|
||||
shared = _shared_profile(fleet, "shared", link=lambda target, alias: alias.symlink_to(target))
|
||||
fleet["use"](shared)
|
||||
|
||||
assert heal_forked_single_use_oauth_grants("openai-codex") is None
|
||||
assert (root / "auth.json").read_text() == before
|
||||
assert (shared / "auth.json").is_symlink()
|
||||
assert consume_oauth_heal_notices() == []
|
||||
store = json.loads((root / "auth.json").read_text())
|
||||
assert [r["id"] for r in store["credential_pool"]["openai-codex"]] == ["cdx001"]
|
||||
assert store["providers"]["openai-codex"]["tokens"]["refresh_token"] == "cdx-RT0"
|
||||
|
||||
|
||||
def test_heal_skips_profile_auth_json_hardlinked_to_the_root_store(fleet):
|
||||
"""Same class as the symlink: a hardlink resolves to a different name but
|
||||
is the same inode, so it is still one store, not a forked copy."""
|
||||
from hermes_cli.auth import heal_forked_single_use_oauth_grants
|
||||
|
||||
root = fleet["root"]
|
||||
_seed_codex_grant(root)
|
||||
before = (root / "auth.json").read_text()
|
||||
|
||||
shared = _shared_profile(fleet, "twin", link=lambda target, alias: os.link(target, alias))
|
||||
fleet["use"](shared)
|
||||
|
||||
assert heal_forked_single_use_oauth_grants("openai-codex") is None
|
||||
assert (root / "auth.json").read_text() == before
|
||||
assert (shared / "auth.json").samefile(root / "auth.json")
|
||||
|
||||
|
||||
def test_heal_leaves_an_aliased_anthropic_singleton_alone(fleet):
|
||||
"""Separate auth.jsons but a profile `.anthropic_oauth.json` symlinked to
|
||||
root's: one shared grant, not a fork. The heal must not self-compare it
|
||||
or unlink the alias (#101356 sibling site)."""
|
||||
from hermes_cli.auth import heal_forked_single_use_oauth_grants
|
||||
|
||||
root = fleet["root"]
|
||||
(root / ".anthropic_oauth.json").write_text(json.dumps({
|
||||
"accessToken": "AT-shared", "refreshToken": "RT-shared",
|
||||
"expiresAt": int((time.time() + 3600) * 1000),
|
||||
}))
|
||||
kid = _profile(fleet, "kid")
|
||||
kid.mkdir(parents=True, exist_ok=True)
|
||||
(kid / "auth.json").write_text(json.dumps({"providers": {}, "credential_pool": {}}))
|
||||
(kid / ".anthropic_oauth.json").symlink_to(root / ".anthropic_oauth.json")
|
||||
before = (root / ".anthropic_oauth.json").read_text()
|
||||
|
||||
fleet["use"](kid)
|
||||
assert heal_forked_single_use_oauth_grants("anthropic") is None
|
||||
assert (kid / ".anthropic_oauth.json").is_symlink()
|
||||
assert (root / ".anthropic_oauth.json").read_text() == before
|
||||
|
||||
|
||||
def test_heal_same_store_skip_is_memoized_off_the_hot_path(fleet, monkeypatch):
|
||||
"""The shared-store skip must record the clean mark so load_pool()'s
|
||||
per-call heal does not re-stat/resolve both paths every model call."""
|
||||
from hermes_cli import auth as auth_mod
|
||||
|
||||
root = fleet["root"]
|
||||
_seed_codex_grant(root)
|
||||
shared = _shared_profile(fleet, "shared", link=lambda target, alias: alias.symlink_to(target))
|
||||
fleet["use"](shared)
|
||||
|
||||
assert auth_mod.heal_forked_single_use_oauth_grants("openai-codex") is None
|
||||
assert "openai-codex" in auth_mod._oauth_heal_clean_marks
|
||||
calls = []
|
||||
monkeypatch.setattr(auth_mod, "_is_same_auth_store", lambda *a: calls.append(a) or True)
|
||||
assert auth_mod.heal_forked_single_use_oauth_grants("openai-codex") is None
|
||||
assert calls == [], "same-store check ran again despite the clean mark"
|
||||
|
||||
|
||||
# ── E. the clean mark outlives the process ──────────────────────────────
|
||||
#
|
||||
# The in-memory mark only silences the heal for one process, so every fresh
|
||||
# `hermes` invocation re-paid its two nested EXCLUSIVE auth-store locks to
|
||||
# rediscover a store it had already cleared. Persisting the mark removes that,
|
||||
# but a mark that outlives the process must also invalidate on anything the
|
||||
# heal reads -- including the ROOT store, which the in-memory fingerprint
|
||||
# could safely ignore precisely because it died with the process.
|
||||
|
||||
def _new_process(auth_mod):
|
||||
"""Simulate a fresh `hermes` invocation: in-memory state gone, disk kept."""
|
||||
auth_mod._oauth_heal_clean_marks.clear()
|
||||
auth_mod._global_auth_store_cache = None
|
||||
|
||||
|
||||
def _count_locks(monkeypatch):
|
||||
"""Count _auth_store_lock acquisitions, still really taking them.
|
||||
|
||||
The heal imports the lock from ``hermes_cli.auth`` inside the function, so
|
||||
patching it on that module is what the call site actually resolves.
|
||||
"""
|
||||
import contextlib
|
||||
|
||||
import hermes_cli.auth as auth_mod
|
||||
|
||||
taken = []
|
||||
real = auth_mod._auth_store_lock
|
||||
|
||||
@contextlib.contextmanager
|
||||
def counting(*a, **k):
|
||||
taken.append(k.get("target_path"))
|
||||
with real(*a, **k):
|
||||
yield
|
||||
|
||||
monkeypatch.setattr(auth_mod, "_auth_store_lock", counting)
|
||||
return taken
|
||||
|
||||
|
||||
def _kid_with_api_key_only(fleet, name="kid"):
|
||||
"""Profile whose store exists and is genuinely fork-free, so the heal has
|
||||
to run its locked body to find that out (not the no-files fast path)."""
|
||||
pdir = _profile(fleet, name)
|
||||
pdir.mkdir(parents=True, exist_ok=True)
|
||||
(pdir / "auth.json").write_text(json.dumps({
|
||||
"version": 1, "providers": {},
|
||||
"credential_pool": {"openai": [{
|
||||
"id": "k1", "label": "static", "auth_type": "api_key",
|
||||
"priority": 0, "source": "manual", "access_token": "sk-local",
|
||||
}]},
|
||||
}))
|
||||
return pdir
|
||||
|
||||
|
||||
def test_clean_mark_persists_so_a_fresh_process_takes_no_auth_lock(fleet, monkeypatch):
|
||||
import hermes_cli.auth as auth_mod
|
||||
from hermes_cli import auth_oauth_grants as grants
|
||||
|
||||
kid = _kid_with_api_key_only(fleet)
|
||||
fleet["use"](kid)
|
||||
first = _count_locks(monkeypatch)
|
||||
assert auth_mod.heal_forked_single_use_oauth_grants("anthropic") is None
|
||||
assert len(first) == 2, "cold heal should take the profile and root locks"
|
||||
assert grants._oauth_heal_clean_mark_path().exists(), "clean mark not written"
|
||||
|
||||
_new_process(auth_mod)
|
||||
second = _count_locks(monkeypatch)
|
||||
assert auth_mod.heal_forked_single_use_oauth_grants("anthropic") is None
|
||||
assert second == [], "a fresh process re-locked the auth store to redo a clean heal"
|
||||
|
||||
|
||||
def test_persisted_mark_still_re_heals_when_the_root_store_gains_a_grant(fleet):
|
||||
"""The mark may not outlive the facts. Root acquiring a counterpart turns
|
||||
a row the heal deliberately KEPT into a fork it must strip -- with the
|
||||
profile's own files untouched, so only root's stamp can catch it."""
|
||||
import hermes_cli.auth as auth_mod
|
||||
from hermes_cli import auth_oauth_grants as grants
|
||||
|
||||
root = fleet["root"]
|
||||
store = json.loads((root / "auth.json").read_text())
|
||||
store["credential_pool"].pop("anthropic")
|
||||
(root / "auth.json").write_text(json.dumps(store))
|
||||
|
||||
kid = _kid_with_api_key_only(fleet, "kid2")
|
||||
fork = {
|
||||
"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": int((time.time() + 3600) * 1000),
|
||||
"base_url": "https://api.anthropic.com",
|
||||
}
|
||||
kid_store = json.loads((kid / "auth.json").read_text())
|
||||
kid_store["credential_pool"]["anthropic"] = [dict(fork)]
|
||||
(kid / "auth.json").write_text(json.dumps(kid_store))
|
||||
|
||||
fleet["use"](kid)
|
||||
assert auth_mod.heal_forked_single_use_oauth_grants("anthropic") is None
|
||||
assert fleet["rows"](kid), "the only surviving copy must not be stripped"
|
||||
marked = grants._oauth_heal_clean_mark_path().read_text()
|
||||
|
||||
store["credential_pool"]["anthropic"] = [dict(fork)]
|
||||
(root / "auth.json").write_text(json.dumps(store))
|
||||
_new_process(auth_mod)
|
||||
assert auth_mod.heal_forked_single_use_oauth_grants("anthropic") is not None, (
|
||||
"the persisted mark skipped a heal that had become necessary")
|
||||
assert not fleet["rows"](kid), "the fork survived in the profile store"
|
||||
|
||||
# A heal that actually did work writes no mark, so the one on disk is now
|
||||
# stale -- it describes the pre-heal files and can no longer match. The
|
||||
# next process re-checks, finds the store clean, and re-stamps.
|
||||
_new_process(auth_mod)
|
||||
assert auth_mod.heal_forked_single_use_oauth_grants("anthropic") is None
|
||||
assert grants._oauth_heal_clean_mark_path().read_text() != marked
|
||||
@@ -1,383 +0,0 @@
|
||||
"""Tests for cross-profile auth fallback.
|
||||
|
||||
When ``HERMES_HOME`` points to a named profile, ``read_credential_pool()``
|
||||
and ``get_provider_auth_state()`` fall back to the global-root
|
||||
``auth.json`` per-provider when the profile has no entries for that
|
||||
provider. Writes still target the profile only.
|
||||
|
||||
See the #18594 follow-up report: profile workers couldn't see providers
|
||||
authenticated only at the global root.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import time
|
||||
from contextlib import contextmanager
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
|
||||
def _make_auth_store(pool: dict | None = None, providers: dict | None = None) -> dict:
|
||||
store: dict = {"version": 1}
|
||||
if pool is not None:
|
||||
store["credential_pool"] = pool
|
||||
if providers is not None:
|
||||
store["providers"] = providers
|
||||
return store
|
||||
|
||||
|
||||
@pytest.fixture()
|
||||
def profile_env(tmp_path, monkeypatch):
|
||||
"""Set up a global root + an active profile under Path.home()/.hermes/profiles/coder.
|
||||
|
||||
* Path.home() -> tmp_path
|
||||
* Global root -> tmp_path/.hermes (has its own auth.json fixture)
|
||||
* Profile -> tmp_path/.hermes/profiles/coder (active, HERMES_HOME points here)
|
||||
|
||||
This mirrors the real "named profile mounted under the default root"
|
||||
layout that profile users actually have on disk.
|
||||
"""
|
||||
monkeypatch.setattr(Path, "home", lambda: tmp_path)
|
||||
global_root = tmp_path / ".hermes"
|
||||
global_root.mkdir()
|
||||
profile_dir = global_root / "profiles" / "coder"
|
||||
profile_dir.mkdir(parents=True)
|
||||
monkeypatch.setenv("HERMES_HOME", str(profile_dir))
|
||||
return {"global": global_root, "profile": profile_dir}
|
||||
|
||||
|
||||
def _write(path: Path, payload: dict) -> None:
|
||||
path.write_text(json.dumps(payload, indent=2))
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# read_credential_pool — provider-slice reads
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
def test_missing_global_auth_file_is_safe(profile_env):
|
||||
"""Profile processes that never had a global auth.json still work."""
|
||||
from hermes_cli.auth import read_credential_pool
|
||||
|
||||
# No global auth.json written at all.
|
||||
_write(profile_env["profile"] / "auth.json", _make_auth_store(pool={
|
||||
"openrouter": [{
|
||||
"id": "prof-1",
|
||||
"label": "profile",
|
||||
"auth_type": "api_key",
|
||||
"priority": 0,
|
||||
"source": "manual",
|
||||
"access_token": "sk-profile",
|
||||
}],
|
||||
}))
|
||||
|
||||
assert read_credential_pool("openrouter")[0]["id"] == "prof-1"
|
||||
assert read_credential_pool("anthropic") == []
|
||||
|
||||
|
||||
def test_malformed_global_auth_file_does_not_break_profile_read(profile_env):
|
||||
(profile_env["global"] / "auth.json").write_text("{not valid json")
|
||||
_write(profile_env["profile"] / "auth.json", _make_auth_store(pool={
|
||||
"openrouter": [{
|
||||
"id": "prof-1",
|
||||
"label": "profile",
|
||||
"auth_type": "api_key",
|
||||
"priority": 0,
|
||||
"source": "manual",
|
||||
"access_token": "sk-profile",
|
||||
}],
|
||||
}))
|
||||
|
||||
from hermes_cli.auth import read_credential_pool
|
||||
|
||||
# Profile reads still work; malformed global is silently ignored.
|
||||
assert read_credential_pool("openrouter")[0]["id"] == "prof-1"
|
||||
# And no fallback for anthropic since global is unreadable.
|
||||
assert read_credential_pool("anthropic") == []
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# read_credential_pool — whole-pool reads (provider_id=None)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# get_provider_auth_state — singleton fallback
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_provider_auth_state_falls_back_to_global_when_profile_has_none(profile_env):
|
||||
from hermes_cli.auth import get_provider_auth_state
|
||||
|
||||
_write(profile_env["global"] / "auth.json", _make_auth_store(providers={
|
||||
"nous": {"access_token": "nous-global", "refresh_token": "rt-global"},
|
||||
}))
|
||||
_write(profile_env["profile"] / "auth.json", _make_auth_store(providers={}))
|
||||
|
||||
state = get_provider_auth_state("nous")
|
||||
assert state is not None
|
||||
assert state["access_token"] == "nous-global"
|
||||
|
||||
|
||||
def test_provider_auth_state_returns_none_when_neither_has_it(profile_env):
|
||||
from hermes_cli.auth import get_provider_auth_state
|
||||
|
||||
_write(profile_env["global"] / "auth.json", _make_auth_store(providers={}))
|
||||
_write(profile_env["profile"] / "auth.json", _make_auth_store(providers={}))
|
||||
|
||||
assert get_provider_auth_state("nous") is None
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# _load_provider_state — internal global fallback (issue #18594 follow-up)
|
||||
#
|
||||
# Several runtime helpers (notably ``resolve_nous_runtime_credentials`` and
|
||||
# ``resolve_nous_access_token``) call ``_load_provider_state`` directly with
|
||||
# a profile-loaded auth store rather than going through
|
||||
# ``get_provider_auth_state``. Without the fallback wired into
|
||||
# ``_load_provider_state`` itself, those helpers raise ``"Hermes is not
|
||||
# logged into Nous Portal"`` even though the user has a valid global Nous
|
||||
# login. These tests pin the per-provider shadowing into the helper.
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_codex_runtime_uses_global_pool_when_profile_singleton_is_empty(profile_env):
|
||||
"""Stale empty profile Codex state must not block the global credential pool."""
|
||||
from hermes_cli.auth import resolve_codex_runtime_credentials
|
||||
|
||||
_write(profile_env["global"] / "auth.json", _make_auth_store(pool={
|
||||
"openai-codex": [{
|
||||
"id": "glob-codex",
|
||||
"label": "global-codex",
|
||||
"auth_type": "oauth",
|
||||
"priority": 0,
|
||||
"source": "manual:device_code",
|
||||
"access_token": "global-codex-access-token",
|
||||
"refresh_token": "global-codex-refresh-token",
|
||||
}],
|
||||
}))
|
||||
_write(profile_env["profile"] / "auth.json", _make_auth_store(
|
||||
providers={
|
||||
"openai-codex": {
|
||||
"auth_mode": "chatgpt",
|
||||
"tokens": {"access_token": "", "refresh_token": ""},
|
||||
},
|
||||
},
|
||||
pool={"openai-codex": []},
|
||||
))
|
||||
|
||||
creds = resolve_codex_runtime_credentials(refresh_if_expiring=False)
|
||||
|
||||
assert creds["source"] == "credential_pool"
|
||||
assert creds["api_key"] == "global-codex-access-token"
|
||||
|
||||
# Profile rows shadow the root the moment they exist (read_credential_pool precedence).
|
||||
_write(profile_env["profile"] / "auth.json", _make_auth_store(pool={
|
||||
"openai-codex": [{"id": "prof", "auth_type": "oauth", "priority": 0,
|
||||
"access_token": "profile-codex-access-token", "refresh_token": "r"}],
|
||||
}))
|
||||
assert resolve_codex_runtime_credentials(refresh_if_expiring=False)["api_key"] == "profile-codex-access-token"
|
||||
|
||||
|
||||
def test_codex_cooldown_clear_writes_to_the_store_that_owns_the_borrowed_pool(profile_env):
|
||||
"""A restored quota must unfreeze the ROOT row a profile borrows; clearing the (empty)
|
||||
profile store would leave every later resolve stuck on the stale cooldown."""
|
||||
from hermes_cli.auth_codex import clear_codex_pool_quota_cooldowns
|
||||
|
||||
_write(profile_env["global"] / "auth.json", _make_auth_store(pool={
|
||||
"openai-codex": [{"id": "glob", "auth_type": "oauth", "priority": 0,
|
||||
"access_token": "global-codex-access-token", "refresh_token": "r",
|
||||
"last_status": "exhausted", "last_error_reason": "rate_limit",
|
||||
"last_error_reset_at": 4_102_444_800}],
|
||||
}))
|
||||
_write(profile_env["profile"] / "auth.json", _make_auth_store(pool={"openai-codex": []}))
|
||||
|
||||
assert clear_codex_pool_quota_cooldowns() == 1
|
||||
root_rows = json.loads((profile_env["global"] / "auth.json").read_text())["credential_pool"]["openai-codex"]
|
||||
assert root_rows[0].get("last_error_reset_at") is None
|
||||
|
||||
|
||||
def test_codex_cooldown_clear_never_touches_root_when_profile_owns_rows(profile_env):
|
||||
"""A profile with its own Codex rows is the owner: the root's cooldown state is not ours to
|
||||
clear, even when none of the profile's rows are exhausted (0 cleared, root byte-identical)."""
|
||||
from hermes_cli.auth_codex import clear_codex_pool_quota_cooldowns
|
||||
|
||||
root_file = profile_env["global"] / "auth.json"
|
||||
_write(root_file, _make_auth_store(pool={
|
||||
"openai-codex": [{"id": "glob", "auth_type": "oauth", "priority": 0,
|
||||
"access_token": "global-codex-access-token", "refresh_token": "r",
|
||||
"last_status": "exhausted", "last_error_reason": "rate_limit",
|
||||
"last_error_reset_at": 4_102_444_800}],
|
||||
}))
|
||||
_write(profile_env["profile"] / "auth.json", _make_auth_store(pool={
|
||||
"openai-codex": [{"id": "prof", "auth_type": "oauth", "priority": 0,
|
||||
"access_token": "profile-codex-access-token", "refresh_token": "r"}],
|
||||
}))
|
||||
before = root_file.read_bytes()
|
||||
|
||||
assert clear_codex_pool_quota_cooldowns() == 0
|
||||
assert root_file.read_bytes() == before
|
||||
|
||||
|
||||
def test_root_write_through_is_visible_to_the_next_fallback_read(profile_env):
|
||||
"""``_save_auth_store(target_path=root)`` must invalidate the mtime memo: a same-tick
|
||||
read-after-write (coarse-mtime filesystems) would otherwise keep serving the stale root."""
|
||||
import os
|
||||
from hermes_cli.auth import _save_auth_store, read_credential_pool
|
||||
|
||||
root_file = profile_env["global"] / "auth.json"
|
||||
_write(root_file, _make_auth_store(pool={"openai-codex": [{"id": "glob", "access_token": "old"}]}))
|
||||
_write(profile_env["profile"] / "auth.json", _make_auth_store(pool={"openai-codex": []}))
|
||||
assert read_credential_pool("openai-codex")[0]["access_token"] == "old" # primes the memo
|
||||
stat = root_file.stat()
|
||||
|
||||
_save_auth_store(_make_auth_store(pool={"openai-codex": [{"id": "glob", "access_token": "new"}]}),
|
||||
target_path=root_file)
|
||||
os.utime(root_file, ns=(stat.st_atime_ns, stat.st_mtime_ns)) # simulate a same-tick write
|
||||
|
||||
assert read_credential_pool("openai-codex")[0]["access_token"] == "new"
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Classic mode — no fallback path should ever trigger
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Writes stay scoped to the profile
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_write_credential_pool_targets_profile_not_global(profile_env):
|
||||
from hermes_cli.auth import read_credential_pool, write_credential_pool
|
||||
|
||||
_write(profile_env["global"] / "auth.json", _make_auth_store(pool={
|
||||
"openrouter": [{
|
||||
"id": "glob-1",
|
||||
"label": "global",
|
||||
"auth_type": "api_key",
|
||||
"priority": 0,
|
||||
"source": "manual",
|
||||
"access_token": "sk-global",
|
||||
}],
|
||||
}))
|
||||
|
||||
write_credential_pool("openrouter", [{
|
||||
"id": "prof-new",
|
||||
"label": "profile-new",
|
||||
"auth_type": "api_key",
|
||||
"priority": 0,
|
||||
"source": "manual",
|
||||
"access_token": "sk-profile-new",
|
||||
}])
|
||||
|
||||
# Global auth.json unchanged.
|
||||
global_data = json.loads((profile_env["global"] / "auth.json").read_text())
|
||||
assert global_data["credential_pool"]["openrouter"][0]["id"] == "glob-1"
|
||||
|
||||
# Profile auth.json holds the new entry.
|
||||
profile_data = json.loads((profile_env["profile"] / "auth.json").read_text())
|
||||
assert profile_data["credential_pool"]["openrouter"][0]["id"] == "prof-new"
|
||||
|
||||
# Subsequent read returns profile (shadows global).
|
||||
assert [e["id"] for e in read_credential_pool("openrouter")] == ["prof-new"]
|
||||
|
||||
|
||||
|
||||
|
||||
def test_auth_lock_reentrancy_is_scoped_after_profile_context_switch(profile_env):
|
||||
"""Changing profile context cannot inherit another store's lock depth."""
|
||||
import hermes_cli.auth as auth
|
||||
from hermes_constants import reset_hermes_home_override, set_hermes_home_override
|
||||
|
||||
profile_b = profile_env["global"] / "profiles" / "reviewer"
|
||||
profile_b.mkdir(parents=True)
|
||||
profile_b_lock = profile_b / "auth.lock"
|
||||
|
||||
with auth._auth_store_lock():
|
||||
holder_a = auth._auth_lock_holder_for(profile_env["profile"] / "auth.json")
|
||||
assert getattr(holder_a, "depth", 0) == 1
|
||||
|
||||
token = set_hermes_home_override(profile_b)
|
||||
try:
|
||||
holder_b = auth._auth_lock_holder_for(profile_b / "auth.json")
|
||||
assert holder_b is not holder_a
|
||||
assert getattr(holder_b, "depth", 0) == 0
|
||||
assert not profile_b_lock.exists()
|
||||
|
||||
with auth._auth_store_lock():
|
||||
assert profile_b_lock.exists()
|
||||
assert getattr(holder_b, "depth", 0) == 1
|
||||
finally:
|
||||
reset_hermes_home_override(token)
|
||||
|
||||
assert getattr(holder_a, "depth", 0) == 0
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# write_credential_pool — stale-snapshot cooldown merge
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
@pytest.fixture()
|
||||
def classic_env(tmp_path, monkeypatch):
|
||||
"""Classic single-root layout (HERMES_HOME != ~/.hermes, no profiles)."""
|
||||
fake_home = tmp_path / "home"
|
||||
fake_home.mkdir()
|
||||
monkeypatch.setattr(Path, "home", lambda: fake_home)
|
||||
hermes_home = tmp_path / "classic"
|
||||
hermes_home.mkdir()
|
||||
monkeypatch.setenv("HERMES_HOME", str(hermes_home))
|
||||
return hermes_home
|
||||
|
||||
|
||||
def _pool_entry(**overrides) -> dict:
|
||||
entry = {
|
||||
"id": "cred-x",
|
||||
"label": "key-x",
|
||||
"auth_type": "api_key",
|
||||
"priority": 0,
|
||||
"source": "manual",
|
||||
"access_token": "sk-x",
|
||||
}
|
||||
entry.update(overrides)
|
||||
return entry
|
||||
|
||||
|
||||
|
||||
|
||||
def test_write_pool_never_merges_cooldown_onto_reauthed_entry(classic_env):
|
||||
"""A token change means re-auth: the old cooldown must never carry over.
|
||||
|
||||
A fresh login intentionally clears the entry's status; resurrecting the
|
||||
stale cooldown onto the new credentials would bench a just-authorized key.
|
||||
"""
|
||||
from hermes_cli.auth import write_credential_pool
|
||||
|
||||
_write(classic_env / "auth.json", _make_auth_store(pool={
|
||||
"openrouter": [_pool_entry(
|
||||
access_token="sk-old",
|
||||
last_status="exhausted",
|
||||
last_status_at=time.time() - 60, # newer AND unexpired
|
||||
last_error_code=429,
|
||||
)],
|
||||
}))
|
||||
|
||||
# Same entry id, freshly re-authed with a new token and cleared status.
|
||||
write_credential_pool("openrouter", [_pool_entry(access_token="sk-new")])
|
||||
|
||||
data = json.loads((classic_env / "auth.json").read_text())
|
||||
persisted = data["credential_pool"]["openrouter"][0]
|
||||
assert persisted["access_token"] == "sk-new"
|
||||
assert persisted.get("last_status") != "exhausted"
|
||||
assert persisted.get("last_error_code") is None
|
||||
@@ -0,0 +1,221 @@
|
||||
"""Every profile owns its credentials.
|
||||
|
||||
A named profile (``HERMES_HOME`` under ``profiles/<name>``) resolves provider state and the
|
||||
credential pool from ITS OWN ``auth.json`` only. The root ``~/.hermes/auth.json`` is never a
|
||||
read fallback and never a write-through target (#111724): an isolated service profile must fail
|
||||
closed instead of acting — and rotating tokens — as the owner. Writes stay scoped to the profile.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
|
||||
def _make_auth_store(pool: dict | None = None, providers: dict | None = None) -> dict:
|
||||
store: dict = {"version": 1}
|
||||
if pool is not None:
|
||||
store["credential_pool"] = pool
|
||||
if providers is not None:
|
||||
store["providers"] = providers
|
||||
return store
|
||||
|
||||
|
||||
@pytest.fixture()
|
||||
def profile_env(tmp_path, monkeypatch):
|
||||
"""Global root + an active named profile under Path.home()/.hermes/profiles/coder.
|
||||
|
||||
* Path.home() -> tmp_path
|
||||
* Global root -> tmp_path/.hermes (has its own auth.json fixture)
|
||||
* Profile -> tmp_path/.hermes/profiles/coder (active, HERMES_HOME points here)
|
||||
"""
|
||||
monkeypatch.setattr(Path, "home", lambda: tmp_path)
|
||||
global_root = tmp_path / ".hermes"
|
||||
global_root.mkdir()
|
||||
profile_dir = global_root / "profiles" / "coder"
|
||||
profile_dir.mkdir(parents=True)
|
||||
monkeypatch.setenv("HERMES_HOME", str(profile_dir))
|
||||
return {"global": global_root, "profile": profile_dir}
|
||||
|
||||
|
||||
def _write(path: Path, payload: dict) -> None:
|
||||
path.write_text(json.dumps(payload, indent=2))
|
||||
|
||||
|
||||
_ROOT_STORE = _make_auth_store(
|
||||
providers={
|
||||
"nous": {"access_token": "nous-root", "refresh_token": "rt-root"},
|
||||
"xai-oauth": {"auth_mode": "oauth_pkce",
|
||||
"tokens": {"access_token": "xai-root-access", "refresh_token": "xai-root-refresh"}},
|
||||
},
|
||||
pool={
|
||||
"openrouter": [{"id": "glob-1", "label": "root", "auth_type": "api_key", "priority": 0,
|
||||
"source": "manual", "access_token": "sk-root"}],
|
||||
"openai-codex": [{"id": "glob-codex", "auth_type": "oauth", "priority": 0,
|
||||
"source": "manual:device_code", "access_token": "root-codex-access",
|
||||
"refresh_token": "root-codex-refresh"}],
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
def test_named_profile_never_reads_the_root_store(profile_env):
|
||||
"""Provider state, pool slices and the whole-pool read all stop at the profile's own auth.json;
|
||||
the profile's own rows are what it sees, and a root-only provider resolves to nothing."""
|
||||
from hermes_cli.auth import get_provider_auth_state, read_credential_pool, resolve_codex_runtime_credentials
|
||||
from hermes_cli.auth_xai import _read_xai_oauth_tokens
|
||||
from hermes_cli.auth import AuthError
|
||||
|
||||
_write(profile_env["global"] / "auth.json", _ROOT_STORE)
|
||||
_write(profile_env["profile"] / "auth.json", _make_auth_store(
|
||||
providers={},
|
||||
pool={"openrouter": [{"id": "prof-1", "auth_type": "api_key", "priority": 0,
|
||||
"source": "manual", "access_token": "sk-profile"}]},
|
||||
))
|
||||
|
||||
assert get_provider_auth_state("nous") is None
|
||||
assert read_credential_pool("openai-codex") == []
|
||||
assert [e["id"] for e in read_credential_pool("openrouter")] == ["prof-1"]
|
||||
assert set(read_credential_pool()) == {"openrouter"}
|
||||
with pytest.raises(AuthError):
|
||||
_read_xai_oauth_tokens()
|
||||
with pytest.raises(AuthError):
|
||||
resolve_codex_runtime_credentials(refresh_if_expiring=False)
|
||||
|
||||
# Control: a home that owns the store (single-profile layout) resolves its credentials.
|
||||
own = profile_env["profile"].parent / "owner"
|
||||
own.mkdir()
|
||||
_write(own / "auth.json", _ROOT_STORE)
|
||||
from hermes_constants import reset_hermes_home_override, set_hermes_home_override
|
||||
token = set_hermes_home_override(own)
|
||||
try:
|
||||
assert get_provider_auth_state("nous")["access_token"] == "nous-root"
|
||||
assert read_credential_pool("openrouter")[0]["id"] == "glob-1"
|
||||
finally:
|
||||
reset_hermes_home_override(token)
|
||||
|
||||
|
||||
def test_profile_refresh_never_writes_through_to_the_root_store(profile_env):
|
||||
"""A token save inside a profile lands in the profile's auth.json; the root store is
|
||||
byte-identical afterwards (xAI OAuth save, Codex save, pool write, cooldown clear)."""
|
||||
from hermes_cli.auth import write_credential_pool
|
||||
from hermes_cli.auth_codex import _save_codex_tokens, clear_codex_pool_quota_cooldowns
|
||||
from hermes_cli.auth_xai import _save_xai_oauth_tokens
|
||||
|
||||
root_file = profile_env["global"] / "auth.json"
|
||||
root_store = json.loads(json.dumps(_ROOT_STORE))
|
||||
root_store["credential_pool"]["openai-codex"][0].update(
|
||||
last_status="exhausted", last_error_reason="rate_limit", last_error_reset_at=4_102_444_800)
|
||||
_write(root_file, root_store)
|
||||
_write(profile_env["profile"] / "auth.json", _make_auth_store(providers={}, pool={}))
|
||||
before = root_file.read_bytes()
|
||||
|
||||
_save_xai_oauth_tokens({"access_token": "xai-new", "refresh_token": "xai-new-rt"}, set_active=False)
|
||||
_save_codex_tokens({"access_token": "codex-new", "refresh_token": "codex-new-rt"})
|
||||
write_credential_pool("openrouter", [{"id": "prof-new", "auth_type": "api_key", "priority": 0,
|
||||
"source": "manual", "access_token": "sk-profile-new"}])
|
||||
assert clear_codex_pool_quota_cooldowns() == 0 # the root's exhausted row is not ours to clear
|
||||
|
||||
assert root_file.read_bytes() == before
|
||||
profile_store = json.loads((profile_env["profile"] / "auth.json").read_text())
|
||||
assert profile_store["providers"]["xai-oauth"]["tokens"]["refresh_token"] == "xai-new-rt"
|
||||
assert profile_store["providers"]["openai-codex"]["tokens"]["refresh_token"] == "codex-new-rt"
|
||||
assert [e["id"] for e in profile_store["credential_pool"]["openrouter"]] == ["prof-new"]
|
||||
|
||||
|
||||
def test_malformed_or_missing_root_store_never_breaks_a_profile_read(profile_env):
|
||||
from hermes_cli.auth import read_credential_pool
|
||||
|
||||
(profile_env["global"] / "auth.json").write_text("{not valid json")
|
||||
_write(profile_env["profile"] / "auth.json", _make_auth_store(pool={
|
||||
"openrouter": [{"id": "prof-1", "auth_type": "api_key", "priority": 0,
|
||||
"source": "manual", "access_token": "sk-profile"}]}))
|
||||
assert read_credential_pool("openrouter")[0]["id"] == "prof-1"
|
||||
|
||||
|
||||
def test_auth_lock_reentrancy_is_scoped_after_profile_context_switch(profile_env):
|
||||
"""Changing profile context cannot inherit another store's lock depth."""
|
||||
import hermes_cli.auth as auth
|
||||
from hermes_constants import reset_hermes_home_override, set_hermes_home_override
|
||||
|
||||
profile_b = profile_env["global"] / "profiles" / "reviewer"
|
||||
profile_b.mkdir(parents=True)
|
||||
profile_b_lock = profile_b / "auth.lock"
|
||||
|
||||
with auth._auth_store_lock():
|
||||
holder_a = auth._auth_lock_holder_for(profile_env["profile"] / "auth.json")
|
||||
assert getattr(holder_a, "depth", 0) == 1
|
||||
|
||||
token = set_hermes_home_override(profile_b)
|
||||
try:
|
||||
holder_b = auth._auth_lock_holder_for(profile_b / "auth.json")
|
||||
assert holder_b is not holder_a
|
||||
assert getattr(holder_b, "depth", 0) == 0
|
||||
assert not profile_b_lock.exists()
|
||||
|
||||
with auth._auth_store_lock():
|
||||
assert profile_b_lock.exists()
|
||||
assert getattr(holder_b, "depth", 0) == 1
|
||||
finally:
|
||||
reset_hermes_home_override(token)
|
||||
|
||||
assert getattr(holder_a, "depth", 0) == 0
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# write_credential_pool — stale-snapshot cooldown merge
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
@pytest.fixture()
|
||||
def classic_env(tmp_path, monkeypatch):
|
||||
"""Classic single-root layout (HERMES_HOME != ~/.hermes, no profiles)."""
|
||||
fake_home = tmp_path / "home"
|
||||
fake_home.mkdir()
|
||||
monkeypatch.setattr(Path, "home", lambda: fake_home)
|
||||
hermes_home = tmp_path / "classic"
|
||||
hermes_home.mkdir()
|
||||
monkeypatch.setenv("HERMES_HOME", str(hermes_home))
|
||||
return hermes_home
|
||||
|
||||
|
||||
def _pool_entry(**overrides) -> dict:
|
||||
entry = {
|
||||
"id": "cred-x",
|
||||
"label": "key-x",
|
||||
"auth_type": "api_key",
|
||||
"priority": 0,
|
||||
"source": "manual",
|
||||
"access_token": "sk-x",
|
||||
}
|
||||
entry.update(overrides)
|
||||
return entry
|
||||
|
||||
|
||||
def test_write_pool_never_merges_cooldown_onto_reauthed_entry(classic_env):
|
||||
"""A token change means re-auth: the old cooldown must never carry over.
|
||||
|
||||
A fresh login intentionally clears the entry's status; resurrecting the
|
||||
stale cooldown onto the new credentials would bench a just-authorized key.
|
||||
"""
|
||||
from hermes_cli.auth import write_credential_pool
|
||||
|
||||
_write(classic_env / "auth.json", _make_auth_store(pool={
|
||||
"openrouter": [_pool_entry(
|
||||
access_token="sk-old",
|
||||
last_status="exhausted",
|
||||
last_status_at=time.time() - 60, # newer AND unexpired
|
||||
last_error_code=429,
|
||||
)],
|
||||
}))
|
||||
|
||||
# Same entry id, freshly re-authed with a new token and cleared status.
|
||||
write_credential_pool("openrouter", [_pool_entry(access_token="sk-new")])
|
||||
|
||||
data = json.loads((classic_env / "auth.json").read_text())
|
||||
persisted = data["credential_pool"]["openrouter"][0]
|
||||
assert persisted["access_token"] == "sk-new"
|
||||
assert persisted.get("last_status") != "exhausted"
|
||||
assert persisted.get("last_error_code") is None
|
||||
@@ -1,147 +0,0 @@
|
||||
"""Codex OAuth refresh writes back to the store the grant was resolved FROM (#87503).
|
||||
|
||||
Codex refresh tokens are single-use with rotation-family reuse detection: a profile that refreshed
|
||||
a root-borrowed grant must land the rotated chain in root — singleton AND ``credential_pool`` —
|
||||
or root keeps the consumed refresh token and the next reader gets the whole family revoked.
|
||||
Token values are synthetic placeholders.
|
||||
"""
|
||||
|
||||
import json
|
||||
import threading
|
||||
from pathlib import Path
|
||||
|
||||
import httpx
|
||||
import pytest
|
||||
|
||||
from hermes_cli import auth, auth_codex
|
||||
|
||||
|
||||
def _pair(prefix: str) -> dict:
|
||||
return {"access_token": f"{prefix}-at", "refresh_token": f"{prefix}-rt"}
|
||||
|
||||
|
||||
def _write(path: Path, store: dict) -> None:
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
path.write_text(json.dumps(store), encoding="utf-8")
|
||||
|
||||
|
||||
def _read(path: Path) -> dict:
|
||||
return json.loads(path.read_text(encoding="utf-8"))
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def profile_env(tmp_path, monkeypatch):
|
||||
"""Global root at tmp/.hermes, active profile at tmp/.hermes/profiles/work (real on-disk layout)."""
|
||||
monkeypatch.setattr(Path, "home", lambda: tmp_path)
|
||||
monkeypatch.setenv("LOCALAPPDATA", str(tmp_path)) # Windows resolves the native root from here
|
||||
root = tmp_path / ".hermes"
|
||||
profile = root / "profiles" / "work"
|
||||
profile.mkdir(parents=True)
|
||||
monkeypatch.setenv("HERMES_HOME", str(profile))
|
||||
return profile / "auth.json", root / "auth.json"
|
||||
|
||||
|
||||
def test_profile_refresh_of_root_grant_writes_through_to_root(profile_env):
|
||||
profile_path, root_path = profile_env
|
||||
_write(root_path, {
|
||||
"version": 1,
|
||||
"providers": {"openai-codex": {"auth_mode": "chatgpt", "tokens": _pair("old")}},
|
||||
"credential_pool": {"openai-codex": [
|
||||
{"provider": "openai-codex", "source": "device_code", **_pair("old")}]},
|
||||
})
|
||||
_write(profile_path, {"version": 1, "providers": {}})
|
||||
|
||||
rotated = _pair("new")
|
||||
auth._save_codex_tokens(rotated, last_refresh="2026-08-16T00:00:00Z", write_through=True)
|
||||
|
||||
root = _read(root_path)
|
||||
assert root["providers"]["openai-codex"]["tokens"] == rotated
|
||||
assert root["credential_pool"]["openai-codex"][0]["refresh_token"] == rotated["refresh_token"]
|
||||
assert root["credential_pool"]["openai-codex"][0]["access_token"] == rotated["access_token"]
|
||||
# A profile copy would shadow root and disable the write-through on the next refresh (#74339).
|
||||
assert "openai-codex" not in _read(profile_path).get("providers", {})
|
||||
|
||||
|
||||
def test_profile_owned_grant_stays_local(profile_env):
|
||||
profile_path, root_path = profile_env
|
||||
_write(profile_path, {
|
||||
"version": 1,
|
||||
"providers": {"openai-codex": {"auth_mode": "chatgpt", "tokens": _pair("prof")}},
|
||||
})
|
||||
_write(root_path, {"version": 1, "providers": {}})
|
||||
|
||||
rotated = _pair("next")
|
||||
auth._save_codex_tokens(rotated, last_refresh="2026-08-16T00:00:00Z", write_through=True)
|
||||
|
||||
assert _read(profile_path)["providers"]["openai-codex"]["tokens"] == rotated
|
||||
assert "openai-codex" not in _read(root_path).get("providers", {})
|
||||
|
||||
# A fresh login under a profile that was borrowing root's grant is the profile's own account,
|
||||
# never a rewrite of root's.
|
||||
_write(profile_path, {"version": 1, "providers": {}})
|
||||
_write(root_path, {"version": 1, "providers": {"openai-codex": {"auth_mode": "chatgpt", "tokens": _pair("root")}}})
|
||||
auth._save_codex_tokens(_pair("login"))
|
||||
assert _read(profile_path)["providers"]["openai-codex"]["tokens"] == _pair("login")
|
||||
assert _read(root_path)["providers"]["openai-codex"]["tokens"] == _pair("root")
|
||||
|
||||
|
||||
class _RotatingEndpoint:
|
||||
"""Token endpoint that rotates ``old-rt`` once and rejects any replay of a consumed token."""
|
||||
|
||||
def __init__(self, hold_seconds: float):
|
||||
self.hold_seconds = hold_seconds
|
||||
self.seen: list = []
|
||||
self._guard = threading.Lock()
|
||||
|
||||
def __enter__(self):
|
||||
return self
|
||||
|
||||
def __exit__(self, *exc):
|
||||
return False
|
||||
|
||||
def post(self, url, *, headers=None, data=None):
|
||||
import time
|
||||
with self._guard:
|
||||
replay = data["refresh_token"] in self.seen
|
||||
self.seen.append(data["refresh_token"])
|
||||
time.sleep(self.hold_seconds) # a concurrent refresher must wait on the lock, not overlap
|
||||
if replay:
|
||||
return httpx.Response(400, json={"error": "refresh_token_reused"})
|
||||
return httpx.Response(200, json={"access_token": "new-at", "refresh_token": "new-rt"})
|
||||
|
||||
|
||||
def test_concurrent_refreshes_of_shared_root_grant_submit_old_token_once(profile_env, monkeypatch):
|
||||
"""Two refreshers holding the same stale pre-read pair: the second re-reads ROOT under its lock,
|
||||
sees the peer's rotated pair and adopts it instead of replaying the single-use token."""
|
||||
profile_path, root_path = profile_env
|
||||
_write(root_path, {
|
||||
"version": 1,
|
||||
"providers": {"openai-codex": {"auth_mode": "chatgpt", "tokens": _pair("old")}},
|
||||
})
|
||||
_write(profile_path, {"version": 1, "providers": {}})
|
||||
endpoint = _RotatingEndpoint(hold_seconds=1.5) # longer than the lock floor (1 s)
|
||||
monkeypatch.setattr(auth_codex, "_codex_http_client", lambda **kw: endpoint)
|
||||
# The waiter must outlive the peer's endpoint call on BOTH locks: with the default lock
|
||||
# timeout shorter than the POST, the second profile would raise TimeoutError instead of adopt.
|
||||
monkeypatch.setattr(auth._auth_store_lock.__wrapped__, "__defaults__", (1.0,))
|
||||
monkeypatch.setattr(auth_codex, "AUTH_LOCK_TIMEOUT_SECONDS", 1.0)
|
||||
|
||||
results, errors = {}, {}
|
||||
|
||||
def _refresh(name):
|
||||
try:
|
||||
results[name] = auth._refresh_codex_auth_tokens(_pair("old"), timeout_seconds=1.0)
|
||||
except Exception as exc: # pragma: no cover - surfaced via the assertion below
|
||||
errors[name] = exc
|
||||
|
||||
workers = [threading.Thread(target=_refresh, args=(n,)) for n in ("a", "b")]
|
||||
for w in workers:
|
||||
w.start()
|
||||
for w in workers:
|
||||
w.join(timeout=10)
|
||||
|
||||
assert errors == {}
|
||||
assert endpoint.seen == ["old-rt"]
|
||||
assert results == {"a": _pair("new"), "b": _pair("new")}
|
||||
assert _read(root_path)["providers"]["openai-codex"]["tokens"] == _pair("new")
|
||||
assert "openai-codex" not in _read(profile_path).get("providers", {})
|
||||
@@ -1,114 +0,0 @@
|
||||
"""Measured-work pins for the _load_global_auth_store() memo.
|
||||
|
||||
read_credential_pool() -> load_pool() runs _load_global_auth_store() once per
|
||||
provider row in the /model picker, and the global-store JSON read + parse
|
||||
cost ~60-100us+ per call even when nothing changed. The memo keyed on the
|
||||
global auth file's path+mtime makes repeat reads a dict lookup. The store
|
||||
only changes when the user authenticates at global scope (writes always go
|
||||
through _save_auth_store, which touches the file), so the mtime key keeps
|
||||
the memo freshness-correct.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
|
||||
import pytest
|
||||
|
||||
import hermes_cli.auth as auth_mod
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _reset_cache(monkeypatch):
|
||||
# raising=False: on pre-fix code the memo attribute doesn't exist (that
|
||||
# IS the fix); the reset is a no-op there so the measured-work assertions
|
||||
# fail genuinely instead of erroring.
|
||||
monkeypatch.setattr(
|
||||
auth_mod, "_global_auth_store_cache", None, raising=False
|
||||
)
|
||||
yield
|
||||
monkeypatch.setattr(
|
||||
auth_mod, "_global_auth_store_cache", None, raising=False
|
||||
)
|
||||
|
||||
|
||||
def _make_global_store(tmp_path) -> "os.PathLike[str]":
|
||||
"""Write a realistic global auth.json and return its path."""
|
||||
path = tmp_path / "global-hermes" / "auth.json"
|
||||
path.parent.mkdir(parents=True)
|
||||
path.write_text(
|
||||
json.dumps(
|
||||
{
|
||||
"version": 1,
|
||||
"providers": {
|
||||
"openai": {"api_key": "sk-x"},
|
||||
"anthropic": {"api_key": "an-x"},
|
||||
},
|
||||
"credential_pool": {
|
||||
"openai": [{"id": "1", "access_token": "t"}],
|
||||
"anthropic": [{"id": "2", "access_token": "u"}],
|
||||
},
|
||||
}
|
||||
),
|
||||
encoding="utf-8",
|
||||
)
|
||||
return path
|
||||
|
||||
|
||||
class TestLoadGlobalAuthStoreMemo:
|
||||
def test_repeated_calls_read_store_once(self, tmp_path, monkeypatch):
|
||||
"""Repeated calls must not re-read/re-parse the global store."""
|
||||
global_path = _make_global_store(tmp_path)
|
||||
monkeypatch.setattr(
|
||||
auth_mod, "_global_auth_file_path", lambda: global_path
|
||||
)
|
||||
reads = {"n": 0}
|
||||
orig = auth_mod._load_auth_store
|
||||
|
||||
def counting_load(store_path=None):
|
||||
reads["n"] += 1
|
||||
return orig(store_path)
|
||||
|
||||
monkeypatch.setattr(auth_mod, "_load_auth_store", counting_load)
|
||||
|
||||
first = auth_mod._load_global_auth_store()
|
||||
for _ in range(10):
|
||||
auth_mod._load_global_auth_store()
|
||||
assert reads["n"] == 1, (
|
||||
"repeated calls must be memo hits (store read once), "
|
||||
f"got {reads['n']}"
|
||||
)
|
||||
assert first.get("providers", {}).get("openai") == {"api_key": "sk-x"}
|
||||
|
||||
def test_mtime_change_re_reads_once(self, tmp_path, monkeypatch):
|
||||
"""A store file change on disk invalidates the memo."""
|
||||
global_path = _make_global_store(tmp_path)
|
||||
monkeypatch.setattr(
|
||||
auth_mod, "_global_auth_file_path", lambda: global_path
|
||||
)
|
||||
reads = {"n": 0}
|
||||
orig = auth_mod._load_auth_store
|
||||
|
||||
def counting_load(store_path=None):
|
||||
reads["n"] += 1
|
||||
return orig(store_path)
|
||||
|
||||
monkeypatch.setattr(auth_mod, "_load_auth_store", counting_load)
|
||||
|
||||
auth_mod._load_global_auth_store()
|
||||
assert reads["n"] == 1
|
||||
|
||||
# Bump the file mtime -> memo invalidates -> re-read once.
|
||||
os.utime(global_path, (1_700_000_000, 1_700_000_000))
|
||||
auth_mod._load_global_auth_store()
|
||||
assert reads["n"] == 2, "mtime change must force exactly one re-read"
|
||||
|
||||
def test_absent_global_store_returns_empty_without_error(self, tmp_path, monkeypatch):
|
||||
"""No global fallback (classic mode) returns {} and stays cheap."""
|
||||
missing = tmp_path / "no-such" / "auth.json"
|
||||
monkeypatch.setattr(
|
||||
auth_mod, "_global_auth_file_path", lambda: missing
|
||||
)
|
||||
assert auth_mod._load_global_auth_store() == {}
|
||||
assert auth_mod._global_auth_store_cache is None
|
||||
@@ -28,7 +28,6 @@ def test_read_xai_oauth_tokens_uses_credential_pool_when_provider_tokens_empty(m
|
||||
},
|
||||
}
|
||||
monkeypatch.setattr(auth, "_load_auth_store", lambda: store)
|
||||
monkeypatch.setattr(auth, "_load_global_auth_store", lambda: {})
|
||||
|
||||
resolved = auth._read_xai_oauth_tokens(_lock=False)
|
||||
|
||||
|
||||
@@ -1,90 +0,0 @@
|
||||
"""Regression tests for xAI OAuth refresh write-through to the global root.
|
||||
|
||||
Companion to ``test_xai_oauth_profile_auth.py``. That file covers the READ
|
||||
fallback (profile -> credential pool -> global root). These cover the WRITE
|
||||
side: when a profile that has no own ``providers.xai-oauth`` block refreshes
|
||||
the (rotating) grant it resolved from the root fallback, the rotated tokens
|
||||
must be written back to the global root too. Otherwise root keeps a revoked
|
||||
refresh token and every other profile reading root's stale grant dies with
|
||||
``invalid_grant`` once its access token expires (issue #43589).
|
||||
|
||||
The tests drive the real ``_save_xai_oauth_tokens`` against real on-disk auth
|
||||
stores (profile + root under ``tmp_path``) rather than mocking the save
|
||||
boundary, so they exercise the actual atomic write path.
|
||||
"""
|
||||
|
||||
import json
|
||||
|
||||
import pytest
|
||||
|
||||
from hermes_cli import auth
|
||||
|
||||
|
||||
def _write_store(path, store):
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
path.write_text(json.dumps(store), encoding="utf-8")
|
||||
|
||||
|
||||
def _read_store(path):
|
||||
return json.loads(path.read_text(encoding="utf-8"))
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def profile_and_root(tmp_path, monkeypatch):
|
||||
"""Wire a profile auth store + a distinct global-root auth store on disk.
|
||||
|
||||
Returns (profile_path, root_path). The pytest seat belt in
|
||||
``_write_through_xai_oauth_to_global_root`` only refuses the *real* user's
|
||||
``$HOME/.hermes/auth.json``; a tmp_path root is allowed, so we point HOME
|
||||
away from the tmp root to keep the guard from tripping on these fixtures.
|
||||
"""
|
||||
profile_path = tmp_path / "profiles" / "work" / "auth.json"
|
||||
root_path = tmp_path / "root" / "auth.json"
|
||||
|
||||
monkeypatch.setattr(auth, "_auth_file_path", lambda: profile_path)
|
||||
monkeypatch.setattr(auth, "_global_auth_file_path", lambda: root_path)
|
||||
# Keep the pytest write seat belt from matching our tmp root.
|
||||
monkeypatch.setenv("HOME", str(tmp_path / "not-the-root"))
|
||||
return profile_path, root_path
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
def test_write_through_is_noop_in_classic_mode(tmp_path, monkeypatch):
|
||||
"""Classic mode (profile == root) already saves to root; no double write."""
|
||||
profile_path = tmp_path / "auth.json"
|
||||
monkeypatch.setattr(auth, "_auth_file_path", lambda: profile_path)
|
||||
# Classic mode: _global_auth_file_path returns None.
|
||||
monkeypatch.setattr(auth, "_global_auth_file_path", lambda: None)
|
||||
_write_store(profile_path, {"version": 1, "providers": {}})
|
||||
|
||||
# Should not raise and should persist to the single store.
|
||||
auth._save_xai_oauth_tokens(
|
||||
{"access_token": "a", "refresh_token": "r"}
|
||||
)
|
||||
store = _read_store(profile_path)
|
||||
assert store["providers"]["xai-oauth"]["tokens"]["refresh_token"] == "r"
|
||||
|
||||
|
||||
def test_write_through_failure_does_not_break_profile_save(profile_and_root, monkeypatch):
|
||||
"""A failed root write-through must not break the profile's own save."""
|
||||
profile_path, root_path = profile_and_root
|
||||
_write_store(profile_path, {"version": 1, "providers": {}})
|
||||
_write_store(root_path, {"version": 1, "providers": {}})
|
||||
|
||||
# Make the root write blow up; the profile save must still succeed.
|
||||
real_save = auth._save_auth_store
|
||||
|
||||
def _exploding_save(store, target_path=None):
|
||||
if target_path is not None and target_path == root_path:
|
||||
raise OSError("simulated root write failure")
|
||||
return real_save(store, target_path)
|
||||
|
||||
monkeypatch.setattr(auth, "_save_auth_store", _exploding_save)
|
||||
|
||||
auth._save_xai_oauth_tokens({"access_token": "a", "refresh_token": "r"})
|
||||
|
||||
profile = _read_store(profile_path)
|
||||
assert profile["providers"]["xai-oauth"]["tokens"]["refresh_token"] == "r"
|
||||
@@ -69,9 +69,8 @@ class TestGetDefaultHermesRoot:
|
||||
"""Repeated calls reuse the memo; HERMES_HOME / home changes invalidate.
|
||||
|
||||
get_default_hermes_root() resolves HERMES_HOME against the native
|
||||
home (~80us of path resolution) and is called at 31+ sites — every
|
||||
_load_global_auth_store() (per provider row in the /model picker),
|
||||
kanban, backup, gateway, update. The memo is keyed on
|
||||
home (~80us of path resolution) and is called at 31+ sites — kanban,
|
||||
backup, gateway, update, profile enumeration. The memo is keyed on
|
||||
(native home, HERMES_HOME) compared for free each call.
|
||||
"""
|
||||
# HERMES_HOME set to a Docker-profile path: every call resolves the
|
||||
|
||||
@@ -210,16 +210,15 @@ def test_default_bearer_gate_accepts_both_deployed_hosts_only():
|
||||
assert not managed_gateway_auth.is_managed_nous_gateway_url(untrusted)
|
||||
|
||||
|
||||
def test_read_nous_provider_state_falls_back_to_global_root_for_share_auth_profiles(tmp_path, monkeypatch):
|
||||
# A profile created with ``share_auth`` has no auth.json of its own; it signs in with the
|
||||
# root identity. The connector gate must see that identity, or manage_connections vanishes
|
||||
# from the profile's tool list while every other credential reader still works.
|
||||
def test_read_nous_provider_state_reads_only_the_profiles_own_store(tmp_path, monkeypatch):
|
||||
# Every profile owns its credentials (#111724): a named profile with an empty auth.json has
|
||||
# no Nous identity, even when the root is signed in; its own login is what the gate sees.
|
||||
root = tmp_path / ".hermes"
|
||||
profile = root / "profiles" / "hermes-setup"
|
||||
profile.mkdir(parents=True)
|
||||
(root / "auth.json").write_text(json.dumps({
|
||||
"version": 1,
|
||||
"providers": {"nous": {"auth_method": "anonymous", "access_token": "tok"}},
|
||||
"providers": {"nous": {"auth_method": "anonymous", "access_token": "root-tok"}},
|
||||
}))
|
||||
monkeypatch.setenv("HERMES_HOME", str(profile))
|
||||
monkeypatch.setenv("HERMES_GUEST_ONBOARDING", "1")
|
||||
@@ -230,10 +229,13 @@ def test_read_nous_provider_state_falls_back_to_global_root_for_share_auth_profi
|
||||
|
||||
monkeypatch.setattr(hermes_constants, "get_default_hermes_root", lambda: root)
|
||||
monkeypatch.setattr(auth_mod, "get_hermes_home", lambda: profile)
|
||||
monkeypatch.setattr(auth_mod, "_global_auth_store_cache", None)
|
||||
monkeypatch.setattr(auth_mod, "_auth_file_path", lambda: profile / "auth.json")
|
||||
|
||||
state = managed_tool_gateway._read_nous_provider_state()
|
||||
assert managed_tool_gateway._read_nous_provider_state() is None
|
||||
|
||||
assert state is not None
|
||||
assert state["auth_method"] == "anonymous"
|
||||
(profile / "auth.json").write_text(json.dumps({
|
||||
"version": 1,
|
||||
"providers": {"nous": {"auth_method": "anonymous", "access_token": "profile-tok"}},
|
||||
}))
|
||||
state = managed_tool_gateway._read_nous_provider_state()
|
||||
assert state is not None and state["access_token"] == "profile-tok"
|
||||
@@ -42,10 +42,8 @@ def _read_nous_provider_state() -> Optional[dict]:
|
||||
with ``nous.guest: false`` it is invisible here, so no cached or refreshed token of it is ever
|
||||
attached to a request.
|
||||
|
||||
Resolves through the same profile-then-global-root fallback every other credential reader
|
||||
uses: a profile created with ``share_auth`` has no ``auth.json`` of its own and signs in with
|
||||
the root identity. Reading only ``HERMES_HOME/auth.json`` made that profile look signed out to
|
||||
the connector gate alone, so ``manage_connections`` vanished from its tool list."""
|
||||
Reads the profile's own ``auth.json`` through ``get_provider_auth_state`` like every other
|
||||
credential reader."""
|
||||
try:
|
||||
from hermes_cli.auth import get_provider_auth_state
|
||||
|
||||
|
||||
@@ -9,7 +9,6 @@ histories on the serving backend; ``subagent.*`` is the session-scoped roster of
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Literal
|
||||
|
||||
from pydantic import Field
|
||||
|
||||
@@ -189,15 +188,15 @@ class ProfilesCreateParams(ProfileParams):
|
||||
soul: str | None = None
|
||||
model: str | None = None
|
||||
provider: str | None = None
|
||||
share_auth: bool | str | None = None
|
||||
share_auth: bool | str | None = None # accepted from older clients; ignored (#111724)
|
||||
mirror_credentials: bool | str | None = None
|
||||
|
||||
|
||||
class ProfileMirrored(Result):
|
||||
"""What was copied from the launch profile; ``auth`` is ``"shared"`` under ``share_auth``."""
|
||||
"""What was copied from the launch profile."""
|
||||
|
||||
env: bool = False
|
||||
auth: bool | Literal["shared"] = False
|
||||
auth: bool = False
|
||||
model_inherited: bool = False
|
||||
voice: bool = False
|
||||
|
||||
|
||||
@@ -315,11 +315,11 @@ def _inherit_launch_model(path) -> bool:
|
||||
|
||||
def _mirror_launch_credentials(path, params: dict) -> dict:
|
||||
"""Copy launch .env / auth.json / voice sections into a new profile (best-effort per item).
|
||||
``share_auth`` reports ``auth: "shared"`` and skips the auth copy; ``mirror_credentials``
|
||||
false skips everything. ``model_inherited`` is filled in by the caller."""
|
||||
share_auth = is_truthy_value(params.get("share_auth", False))
|
||||
mirrored = {"env": False, "auth": "shared" if share_auth else False, "model_inherited": False,
|
||||
"voice": False}
|
||||
``mirror_credentials`` false skips everything. ``model_inherited`` is filled in by the caller.
|
||||
|
||||
``share_auth`` is accepted from older clients and ignored: a profile never reads the launch
|
||||
profile's auth.json (#111724), so "shared" auth would leave it with no provider at all."""
|
||||
mirrored = {"env": False, "auth": False, "model_inherited": False, "voice": False}
|
||||
if not is_truthy_value(params.get("mirror_credentials", True)):
|
||||
return mirrored
|
||||
launch_home = get_hermes_home()
|
||||
@@ -330,13 +330,12 @@ def _mirror_launch_credentials(path, params: dict) -> dict:
|
||||
# Provider/tool keys are what "mirror credentials" means; the launch profile's bot tokens
|
||||
# and allowlists would make the new bot collide with it over one Telegram/Discord bot.
|
||||
_best_effort(lambda: _lazy("hermes_cli.profile_channels", "strip_channel_env_file")(path / ".env"))
|
||||
if not share_auth: # a copy forks token state: the first refresh in either store strands the other
|
||||
mirrored["auth"] = _try(lambda: _mirror_secret(path, launch_home, "auth.json",
|
||||
lambda src, dst: not dst.exists()), False)
|
||||
if mirrored["auth"]:
|
||||
# Drop single-use OAuth grants (first refresh strands every sibling); they read from the
|
||||
# root grant via the pool fallback. API keys stay.
|
||||
_best_effort(lambda: _lazy("hermes_cli.auth", "strip_cloned_single_use_oauth_grants")(path))
|
||||
mirrored["auth"] = _try(lambda: _mirror_secret(path, launch_home, "auth.json",
|
||||
lambda src, dst: not dst.exists()), False)
|
||||
if mirrored["auth"]:
|
||||
# Drop single-use OAuth grants (a copy forks token state: the first refresh in either store
|
||||
# strands the other); the new profile signs into those providers itself. API keys stay.
|
||||
_best_effort(lambda: _lazy("hermes_cli.auth", "strip_cloned_single_use_oauth_grants")(path))
|
||||
mirrored["voice"] = _mirror_voice_sections(path)
|
||||
return mirrored
|
||||
|
||||
@@ -346,8 +345,9 @@ def _(rid, params: dict) -> dict:
|
||||
"""Create a profile (ws twin of POST /api/profiles). Params: ``name``, ``description``,
|
||||
``clone_from`` (omitted = fresh + bundled skills), ``clone_all``, ``clone_channels`` (opt-in: keep the
|
||||
source's bot tokens/allowlists — default strips them so two profiles never hold one bot), ``no_skills``, ``soul``,
|
||||
``model`` + ``provider``, ``share_auth``, ``no_alias``, ``mirror_credentials`` (default true: a bare
|
||||
``create_profile()`` seeds a comment-only .env and no auth.json = NO provider headless)."""
|
||||
``model`` + ``provider``, ``no_alias``, ``mirror_credentials`` (default true: a bare
|
||||
``create_profile()`` seeds a comment-only .env and no auth.json = NO provider headless);
|
||||
``share_auth`` is accepted from older clients and ignored."""
|
||||
name = str(params.get("name") or "").strip()
|
||||
if not name:
|
||||
return _err(rid, 4061, "name required")
|
||||
|
||||
@@ -451,6 +451,7 @@ profile and never shares with the default or any sibling:
|
||||
| Concern | Resolved from | Behaviour when the profile lacks it |
|
||||
|---|---|---|
|
||||
| Provider keys, bot tokens, `${VAR}` refs in `config.yaml` | The profile's own `.env` (its secret scope) | Unresolved / no adapter — never the default profile's value |
|
||||
| Provider logins and the credential pool (`auth.json`: OAuth tokens, `hermes auth add` keys) | The profile's own `auth.json` | "Not connected to any AI provider" with the `hermes -p <name> model` hint — never the default profile's login, and a refresh never writes to the root store |
|
||||
| Authorization (`GATEWAY_ALLOW_ALL_USERS`, `GATEWAY_ALLOWED_USERS`, per-platform allowlists and allow-all opt-ins) | The owning profile's `.env` and `config.yaml` | Closed — a default-profile opt-in never opens a secondary's bot |
|
||||
| HTTP endpoints (`/p/<profile>/api/...`, `/p/<profile>/webhooks/...`, platform event callbacks) | The named profile's `API_SERVER_KEY`, `profile:`-bound webhook routes, and its own adapter | `401`/`404`; delivery without an adapter is `502`/`503`, never another profile's bot |
|
||||
| Inbound-port platforms (`/p/<profile>/webhooks/twilio`, `/p/<profile>/line/webhook`, `/p/<profile>/api/messages`, …) | The named profile's own adapter and its secret (Twilio auth token, LINE channel secret, Teams app, BlueBubbles password, …); replies leave through that adapter | `401`/`403` on a wrong secret, `404` when the profile has no such adapter — never the default profile's adapter |
|
||||
|
||||
@@ -75,10 +75,14 @@ hermes profile create backup --clone-all
|
||||
|
||||
Copies **everything** — config, API keys, personality, all memories, skills, 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. When cloning from the default profile, the local-model runtime trees (`models/`, `runtimes/`, `node/` — downloaded weights and managed binaries, re-fetched on demand) are skipped too, as `hermes backup` already does. **Cron jobs are not cloned** either: they are scheduled work bound to the source profile and its delivery channel, and a clone that inherited them would run every job twice (two gateways, same job ids). The new profile starts with an empty `cron/`. For a full backup including history and cron jobs, 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.
|
||||
:::note OAuth logins are never 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. Static API keys are copied as usual. Sign the new profile into the OAuth provider itself: `hermes -p <name> auth add <provider>` (or `hermes -p <name> model`).
|
||||
:::
|
||||
|
||||
### Every profile owns its credentials
|
||||
|
||||
A named profile resolves providers from **its own** `auth.json` and `.env` only. It never inherits the root profile's logins or API keys, and a token refresh inside a profile never writes to the root store. A profile with no provider of its own is asked to set one up (`hermes -p <name> model`, or `hermes -p <name> auth add <provider>`) — it does not silently act as the owner. `hermes update` lists every profile that has no provider of its own so a bot never goes quiet unannounced.
|
||||
|
||||
### Clone from a specific profile
|
||||
|
||||
```bash
|
||||
|
||||
Reference in new issue
Block a user