The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(auth): harden claude_code refresh lock and remove dashboard Anthropic OAuth
joaomarcose1a210652a4c
diff --git a/ANTHROPIC_ISSUES.md b/ANTHROPIC_ISSUES.mdindex 5a5829e7025..05c692c188b 100644--- a/ANTHROPIC_ISSUES.md+++ b/ANTHROPIC_ISSUES.md@@ -2,6 +2,8 @@> **Atualização:** todos os 5 bugs abaixo (incluindo o Bug 5, achado pelo teste de esforço) foram **corrigidos** nesta sessão.> Issues: [#87887](https://github.com/NousResearch/hermes-agent/issues/87887) (bugs 1-2) · [#87888](https://github.com/NousResearch/hermes-agent/issues/87888) (bugs 3-4) · [#87889](https://github.com/NousResearch/hermes-agent/issues/87889) (bug 5).+>+> **Atualização 2 (review do PR #87891):** em vez de manter os patches dos bugs 1, 2 e 4 abaixo, o fluxo de login OAuth do **dashboard web** (`_start_anthropic_pkce` / `_submit_anthropic_pkce` / `_save_anthropic_oauth_creds` em `hermes_cli/web_server.py`) foi **removido por completo**. Um endpoint HTTP não-supervisionado emitindo tokens de assinatura Claude Pro/Max fora do cliente oficial da Anthropic esbarra nas políticas de uso da Anthropic para credenciais OAuth, então a correção mais segura é eliminar essa superfície em vez de só corrigi-la. O catálogo de providers do dashboard agora marca `anthropic` como `flow: "external"`, apontando para `hermes auth add anthropic` (o fluxo PKCE via terminal, fora do escopo desta mudança e não afetado). Bugs 3 e 5 (race condition no refresh cross-processo e o `PermissionError` no lock do Windows) continuam corrigidos como descrito abaixo — são bugs do fluxo de login `claude_code`/CLI, que permanece.**Data:** 2026-08-16**Branch:** `fix/update-orphan-history-guard-87694`diff --git a/RELATORIO_ANTHROPIC_OAUTH_BUGS.md b/RELATORIO_ANTHROPIC_OAUTH_BUGS.mdindex 6942ee6a2c1..460c78b8e85 100644--- a/RELATORIO_ANTHROPIC_OAUTH_BUGS.md+++ b/RELATORIO_ANTHROPIC_OAUTH_BUGS.md@@ -1,5 +1,7 @@# Relatório de Investigação — Bugs no fluxo OAuth da Anthropic (hermes-agent)+> **Atualização (review do PR #87891):** o fluxo de login OAuth do **dashboard web** (`_start_anthropic_pkce` / `_submit_anthropic_pkce` / `_save_anthropic_oauth_creds` em `hermes_cli/web_server.py`) foi **removido por completo**, em vez de mantido com os patches dos bugs 1, 2 e 4 descritos abaixo. Um endpoint HTTP não-supervisionado emitindo tokens de assinatura Claude Pro/Max fora do cliente oficial da Anthropic esbarra nas políticas de uso da Anthropic para credenciais OAuth. O catálogo de providers do dashboard agora marca `anthropic` como `flow: "external"`, apontando para `hermes auth add anthropic` (fluxo PKCE via terminal, fora do escopo desta mudança). Os testes `tests/hermes_cli/test_anthropic_dashboard_pkce_csrf.py` e `tests/hermes_cli/test_web_server_oauth_write.py` foram removidos por testarem exclusivamente código agora inexistente. Bugs 3 e 5 (race condition no refresh cross-processo e o `PermissionError` no lock do Windows) seguem corrigidos como descrito abaixo — afetam o fluxo de login `claude_code`/CLI, que permanece.+**Data:** 2026-08-16**Branch:** `fix/update-orphan-history-guard-87694`**Escopo investigado:** `agent/anthropic_adapter.py`, `agent/credential_pool.py`, `hermes_cli/auth.py`, `hermes_cli/auth_commands.py`, `hermes_cli/web_server.py`diff --git a/agent/anthropic_adapter.py b/agent/anthropic_adapter.pyindex ce311fa1e35..b870cad3fe7 100644--- a/agent/anthropic_adapter.py+++ b/agent/anthropic_adapter.py@@ -1080,12 +1080,24 @@ def _read_claude_code_credentials_from_keychain() -> Optional[Dict[str, Any]]:return None+def claude_code_credentials_path() -> Path:+ """Location Claude Code CLI writes its shared OAuth credentials file.++ This file is not profile-owned: every Hermes profile's credential pool+ reads and writes the *same* path, so cross-profile refresh races on a+ ``claude_code`` pool entry must be serialized against this exact path+ (see ``CredentialPool._claude_code_credentials_lock`` in+ ``agent/credential_pool.py``).+ """+ return Path.home() / ".claude" / ".credentials.json"++def _read_claude_code_credentials_from_file() -> Optional[Dict[str, Any]]:"""Read Claude Code OAuth credentials from ~/.claude/.credentials.json.Returns dict with {accessToken, refreshToken?, expiresAt?, source} or None."""- cred_path = Path.home() / ".claude" / ".credentials.json"+ cred_path = claude_code_credentials_path()if not cred_path.exists():return Nonetry:@@ -1294,7 +1306,7 @@ def _write_claude_code_credentials(as valid. Claude Code >=2.1.81 gates on the presence of ``"user:inference"``in the stored scopes before it will use the token."""- cred_path = Path.home() / ".claude" / ".credentials.json"+ cred_path = claude_code_credentials_path()try:# Read existing file to preserve other fieldsexisting = {}diff --git a/agent/credential_pool.py b/agent/credential_pool.pyindex e41ffe67ed8..4c802ac7bd2 100644--- a/agent/credential_pool.py+++ b/agent/credential_pool.py@@ -1457,9 +1457,46 @@ class CredentialPool:or synced.refresh_token != entry.refresh_token):return synced+ if self.provider == "anthropic" and synced.source == "claude_code":+ # claude_code entries are NOT profile-owned: the refresh+ # token lives in a single shared ~/.claude/.credentials.json+ # (or macOS Keychain) that every Hermes profile's pool+ # reads from. The profile-scoped lock above only protects+ # THIS profile's auth.json, so two different profiles (or+ # a fleet worker + a CLI session) racing to refresh the+ # same shared token would still both POST it. Take the+ # dedicated shared-file lock (inner, per the ordering+ # invariant documented on ``_auth_store_lock``) so the+ # whole sync -> POST -> write-back sequence for this+ # source is atomic across profiles too, not just within+ # one. This does not (and cannot) protect against the+ # official `claude` CLI itself rotating the token+ # out-of-band — that race is handled by the existing+ # sync-and-retry-once fallback in ``_refresh_entry_impl``.+ with self._claude_code_credentials_lock():+ synced = self._sync_anthropic_entry_from_credentials_file(synced)+ if synced.refresh_token != entry.refresh_token:+ return synced+ return self._refresh_entry_impl(synced, force=force)return self._refresh_entry_impl(synced, force=force)return self._refresh_entry_impl(entry, force=force)+ def _claude_code_credentials_lock(self):+ """Cross-process lock over the shared claude_code credentials file.++ Distinct from the per-profile ``_auth_store_lock()`` above: this one+ is keyed to ``claude_code_credentials_path()`` itself, so it+ serializes every profile (and every Hermes process) that might+ refresh a ``claude_code``-sourced Anthropic entry, not just callers+ sharing one profile's ``auth.json``.+ """+ from agent.anthropic_adapter import claude_code_credentials_path++ return _auth_store_lock(+ timeout_seconds=self._single_use_refresh_lock_timeout(),+ target_path=claude_code_credentials_path(),+ )+def _single_use_refresh_lock_timeout(self) -> float:"""Lock timeout for single-use-refresh-token providers.diff --git a/hermes_cli/web_server.py b/hermes_cli/web_server.pyindex f879fd4350b..cc89a19c3e1 100644--- a/hermes_cli/web_server.py+++ b/hermes_cli/web_server.py@@ -10994,13 +10994,21 @@ _OAUTH_PROVIDER_CATALOG: tuple[Dict[str, Any], ...] = ("docs_url": "https://docs.github.com/en/copilot","status_fn": _copilot_acp_status,},- # ── Anthropic / Claude entries sit at the bottom: the API-key path- # first, then the subscription OAuth path (which only works with extra- # usage credits on top of a Claude Max plan — see disclaimer in name).+ # ── Anthropic / Claude entries sit at the bottom.+ #+ # This card is deliberately flow == "external" (no in-dashboard "Connect"+ # button walking the user through claude.ai/oauth/authorize from the web+ # server). Hermes previously reimplemented that subscription-OAuth PKCE+ # dance itself for the dashboard (issues #87887/#87888); that surface was+ # removed because it lets an unattended, scriptable HTTP endpoint mint+ # Claude Pro/Max subscription tokens outside Anthropic's own client,+ # which sits on the wrong side of Anthropic's usage policies for OAuth+ # credentials. Login still works via the terminal (`hermes auth add+ # anthropic`, unaffected by this change) or a plain API key below.{"id": "anthropic","name": "Anthropic API Key",- "flow": "pkce",+ "flow": "external","cli_command": "hermes auth add anthropic","docs_url": "https://docs.claude.com/en/api/getting-started","status_fn": _anthropic_oauth_status,@@ -11139,7 +11147,14 @@ def _oauth_provider_disconnect_command(provider: Dict[str, Any]) -> Optional[strdef _oauth_provider_disconnect_hint(provider: Dict[str, Any], status: Dict[str, Any]) -> Optional[str]:"""Return the manual disconnect path when the API cannot clear this provider."""- if provider.get("flow") == "external":+ # "anthropic" is flow == "external" (no in-dashboard OAuth login, see the+ # catalog entry) but, unlike other external providers, Hermes still OWNS+ # the credential it can show here: the Hermes-managed PKCE file+ # (~/.hermes/.anthropic_oauth.json) and its credential-pool entry, both+ # written by `hermes auth add anthropic` in the terminal. Those are ours+ # to clear via the API, so this provider is excluded from the generic+ # "external providers can't be auto-disconnected" rule below.+ if provider.get("flow") == "external" and provider.get("id") != "anthropic":if _oauth_provider_disconnect_command(provider):# The GUI offers a one-click "run in terminal" path; this hint is the# fallback wording for surfaces that only show text.@@ -11318,21 +11333,16 @@ async def disconnect_oauth_provider(# ----------------------------------------------------------------------------# OAuth Phase 2 — in-browser PKCE & device-code flows+# OAuth Phase 2 — in-browser device-code flows# ---------------------------------------------------------------------------#-# Two flow shapes are supported:-#-# PKCE (Anthropic):-# 1. POST /api/providers/oauth/anthropic/start-# → server generates code_verifier + challenge, builds claude.ai-# authorize URL, stashes verifier in _oauth_sessions[session_id]-# → returns { session_id, flow: "pkce", auth_url }-# 2. UI opens auth_url in a new tab. User authorizes, copies code.-# 3. POST /api/providers/oauth/anthropic/submit { session_id, code }-# → server exchanges (code + verifier) → tokens at console.anthropic.com-# → persists to ~/.hermes/.anthropic_oauth.json AND credential pool-# → returns { ok: true, status: "approved" }+# Anthropic previously had a dashboard-triggered PKCE flow here too (server+# generates a claude.ai/oauth/authorize URL, exchanges the code for tokens at+# the Anthropic token endpoint, persists them). It was removed: an unattended+# HTTP endpoint minting Claude Pro/Max subscription tokens outside Anthropic's+# own client sits on the wrong side of Anthropic's usage policies for OAuth+# credentials. The "anthropic" catalog entry is now flow == "external" and+# points at `hermes auth add anthropic` (terminal PKCE, unaffected) instead.## Device code (Nous, OpenAI Codex):# 1. POST /api/providers/oauth/{nous|openai-codex}/start@@ -11357,24 +11367,6 @@ _OAUTH_SESSION_TTL_SECONDS = 15 * 60_oauth_sessions: Dict[str, Dict[str, Any]] = {}_oauth_sessions_lock = threading.Lock()-# Import OAuth constants from canonical source instead of duplicating.-# Guarded so hermes web still starts if anthropic_adapter is unavailable;-# Phase 2 endpoints will return 501 in that case.-try:- from agent.anthropic_adapter import (- _OAUTH_CLIENT_ID as _ANTHROPIC_OAUTH_CLIENT_ID,- _OAUTH_TOKEN_URL as _ANTHROPIC_OAUTH_TOKEN_URL,- _OAUTH_TOKEN_URLS as _ANTHROPIC_OAUTH_TOKEN_URLS,- _OAUTH_REDIRECT_URI as _ANTHROPIC_OAUTH_REDIRECT_URI,- _OAUTH_SCOPES as _ANTHROPIC_OAUTH_SCOPES,- _generate_pkce as _generate_pkce_pair,- )- _ANTHROPIC_OAUTH_AVAILABLE = True-except ImportError:- _ANTHROPIC_OAUTH_AVAILABLE = False-_ANTHROPIC_OAUTH_AUTHORIZE_URL = "https://claude.ai/oauth/authorize"--def _gc_oauth_sessions() -> None:"""Drop expired sessions. Called opportunistically on /start."""cutoff = time.time() - _OAUTH_SESSION_TTL_SECONDS@@ -11430,201 +11422,6 @@ def _oauth_session_profile(return profile or _oauth_profile_name(fallback)-def _save_anthropic_oauth_creds(access_token: str, refresh_token: str, expires_at_ms: int) -> None:- """Persist Anthropic PKCE creds to both Hermes file AND credential pool.-- Mirrors what auth_commands.add_command does so the dashboard flow leaves- the system in the same state as ``hermes auth add anthropic``.- """- from agent.anthropic_adapter import _get_hermes_oauth_file- oauth_file = _get_hermes_oauth_file()- payload = {- "accessToken": access_token,- "refreshToken": refresh_token,- "expiresAt": expires_at_ms,- }- # atomic_json_write creates the temp with mode 0o600 (via mkstemp) *before*- # any content is written, then fsyncs and atomically replaces the target.- # The previous os.replace + post-hoc chmod left a TOCTOU window in which the- # OAuth token file was world-readable at the default umask (0o644 on most- # hosts) between the rename and the chmod. atomic_json_write also preserves- # the existing file's owner and cleans up its temp on failure.- from utils import atomic_json_write-- atomic_json_write(oauth_file, payload, indent=2, mode=0o600)- # Clear a stale ANTHROPIC_API_KEY so it cannot keep shadowing this fresh- # OAuth login. resolve_anthropic_token() deliberately prefers an explicit- # ANTHROPIC_API_KEY over the credential-pool OAuth entry (priority 3 vs- # 5) — so without this, a leftover/forgotten API key from an earlier- # setup makes every subsequent OAuth login through the dashboard silently- # inert: the user re-authenticates with their Claude Pro/Max plan, but- # Hermes keeps billing pay-per-token against the old key. The CLI flow- # (save_anthropic_oauth_token in hermes_cli/config.py) already clears- # this slot on OAuth save; this mirrors that for the dashboard flow.- try:- save_env_value("ANTHROPIC_API_KEY", "")- except Exception as e:- _log.warning("anthropic dashboard oauth: failed to clear stale ANTHROPIC_API_KEY: %s", e)- # Best-effort credential-pool insert. Failure here doesn't invalidate- # the file write — pool registration only matters for the rotation- # strategy, not for runtime credential resolution.- try:- from agent.credential_pool import (- PooledCredential,- load_pool,- AUTH_TYPE_OAUTH,- SOURCE_MANUAL,- )- import uuid- pool = load_pool("anthropic")- # Avoid duplicate entries: delete any prior dashboard-issued OAuth entry- existing = [e for e in pool.entries() if getattr(e, "source", "").startswith(f"{SOURCE_MANUAL}:dashboard_pkce")]- for e in existing:- try:- pool.remove_entry(getattr(e, "id", ""))- except Exception:- pass- entry = PooledCredential(- provider="anthropic",- id=uuid.uuid4().hex[:6],- label="dashboard PKCE",- auth_type=AUTH_TYPE_OAUTH,- priority=0,- source=f"{SOURCE_MANUAL}:dashboard_pkce",- access_token=access_token,- refresh_token=refresh_token,- expires_at_ms=expires_at_ms,- )- pool.add_entry(entry)- except Exception as e:- _log.warning("anthropic pool add (dashboard) failed: %s", e)---def _start_anthropic_pkce(profile: Optional[str] = None) -> Dict[str, Any]:- """Begin PKCE flow. Returns the auth URL the UI should open."""- if not _ANTHROPIC_OAUTH_AVAILABLE:- raise HTTPException(status_code=501, detail="Anthropic OAuth not available (missing adapter)")- verifier, challenge = _generate_pkce_pair()- sid, sess = _new_oauth_session("anthropic", "pkce", profile=profile)- sess["verifier"] = verifier- # Independent anti-CSRF token. Do NOT reuse the PKCE verifier as state:- # that leaks the (supposed to stay confidential, RFC 7636 SS7.2) verifier- # via the authorization URL (browser history, Referer headers, auth-server- # logs) and collapses the CSRF check to nothing, since anyone who- # observes the leaked verifier also "knows" the state. Mirrors the fix- # already applied to the CLI flow in agent/anthropic_adapter.py- # (run_hermes_oauth_login_pure) for PR #10699 / issue #10693.- oauth_state = secrets.token_urlsafe(32)- sess["state"] = oauth_state- params = {- "code": "true",- "client_id": _ANTHROPIC_OAUTH_CLIENT_ID,- "response_type": "code",- "redirect_uri": _ANTHROPIC_OAUTH_REDIRECT_URI,- "scope": _ANTHROPIC_OAUTH_SCOPES,- "code_challenge": challenge,- "code_challenge_method": "S256",- "state": oauth_state,- }- auth_url = f"{_ANTHROPIC_OAUTH_AUTHORIZE_URL}?{urllib.parse.urlencode(params)}"- return {- "session_id": sid,- "flow": "pkce",- "auth_url": auth_url,- "expires_in": _OAUTH_SESSION_TTL_SECONDS,- }---def _submit_anthropic_pkce(- session_id: str,- code_input: str,- profile: Optional[str] = None,-) -> Dict[str, Any]:- """Exchange authorization code for tokens. Persists on success."""- with _oauth_sessions_lock:- sess = _oauth_sessions.get(session_id)- if not sess or sess["provider"] != "anthropic" or sess["flow"] != "pkce":- raise HTTPException(status_code=404, detail="Unknown or expired session")- if sess["status"] != "pending":- return {"ok": False, "status": sess["status"], "message": sess.get("error_message")}-- # Anthropic's redirect callback page formats the code as `<code>#<state>`.- # Strip the state suffix if present (we already have the verifier server-side).- parts = code_input.strip().split("#", 1)- code = parts[0].strip()- if not code:- return {"ok": False, "status": "error", "message": "No code provided"}- state_from_callback = parts[1] if len(parts) > 1 else ""-- # CSRF guard (RFC 6749 SS10.12): the state echoed back on the callback- # must match the state this session issued. Without this check, an- # attacker who completes their OWN authorization can get the victim to- # paste that code/state pair, binding the attacker's Anthropic account- # to the victim's Hermes session. Mirrors the CLI flow's- # "received_state != oauth_state" guard in agent/anthropic_adapter.py.- if not state_from_callback or state_from_callback != sess["state"]:- with _oauth_sessions_lock:- sess["status"] = "error"- sess["error_message"] = "OAuth state mismatch"- return {"ok": False, "status": "error", "message": "OAuth state mismatch"}-- exchange_data = json.dumps({- "grant_type": "authorization_code",- "client_id": _ANTHROPIC_OAUTH_CLIENT_ID,- "code": code,- "state": state_from_callback,- "redirect_uri": _ANTHROPIC_OAUTH_REDIRECT_URI,- "code_verifier": sess["verifier"],- }).encode()- # Anthropic migrated the OAuth token endpoint to platform.claude.com;- # console.anthropic.com now 404s. Try the new host first, then fall back.- result = None- last_exc = None- for _endpoint in _ANTHROPIC_OAUTH_TOKEN_URLS:- req = urllib.request.Request(- _endpoint,- data=exchange_data,- headers={- "Content-Type": "application/json",- "User-Agent": "hermes-dashboard/1.0",- },- method="POST",- )- try:- with urllib.request.urlopen(req, timeout=20) as resp:- result = json.loads(resp.read().decode())- break- except Exception as e:- last_exc = e- continue- if result is None:- with _oauth_sessions_lock:- sess["status"] = "error"- sess["error_message"] = f"Token exchange failed: {last_exc}"- return {"ok": False, "status": "error", "message": sess["error_message"]}-- access_token = result.get("access_token", "")- refresh_token = result.get("refresh_token", "")- expires_in = int(result.get("expires_in") or 3600)- if not access_token:- with _oauth_sessions_lock:- sess["status"] = "error"- sess["error_message"] = "No access token returned"- return {"ok": False, "status": "error", "message": sess["error_message"]}-- expires_at_ms = int(time.time() * 1000) + (expires_in * 1000)- try:- with _profile_scope(_oauth_session_profile(session_id, profile)):- _save_anthropic_oauth_creds(access_token, refresh_token, expires_at_ms)- except Exception as e:- with _oauth_sessions_lock:- sess["status"] = "error"- sess["error_message"] = f"Save failed: {e}"- return {"ok": False, "status": "error", "message": sess["error_message"]}- with _oauth_sessions_lock:- sess["status"] = "approved"- _log.info("oauth/pkce: anthropic login completed (session=%s)", session_id)- return {"ok": True, "status": "approved"}async def _start_device_code_flow(@@ -12269,14 +12066,6 @@ async def start_oauth_login(detail=f"{provider_id} uses an external CLI; run `{catalog_entry['cli_command']}` manually",)try:- # The pkce branch is gated on provider_id == "anthropic" because- # `_start_anthropic_pkce()` is hardcoded to the Anthropic flow.- # Routing any other future pkce-flagged provider through it would- # silently launch the Anthropic OAuth flow (the bug fixed in this- # change for MiniMax). New PKCE providers must add their own- # start function and an explicit branch here.- if catalog_entry["flow"] == "pkce" and provider_id == "anthropic":- return _start_anthropic_pkce(profile=profile)if catalog_entry["flow"] == "device_code":return await _start_device_code_flow(provider_id, profile=profile)except HTTPException:@@ -12296,10 +12085,6 @@ async def submit_oauth_code():"""Submit the auth code for PKCE flows. Token-protected."""_require_token(request)- if provider_id == "anthropic":- return await asyncio.get_running_loop().run_in_executor(- None, _submit_anthropic_pkce, body.session_id, body.code, profile,- )raise HTTPException(status_code=400, detail=f"submit not supported for {provider_id}")diff --git a/tests/agent/test_anthropic_oauth_stress.py b/tests/agent/test_anthropic_oauth_stress.pyindex 89be74266db..0598548942c 100644--- a/tests/agent/test_anthropic_oauth_stress.py+++ b/tests/agent/test_anthropic_oauth_stress.py@@ -1,23 +1,15 @@-"""Load / stress tests for the Anthropic OAuth fixes.--Companion to ``tests/agent/test_credential_pool_anthropic_refresh_race.py``-and ``tests/hermes_cli/test_anthropic_dashboard_pkce_csrf.py``, which prove-each bug in isolation with two racers. These tests scale the same scenarios-up to look for bottlenecks and degradation under real concurrency:--1. Many "Hermes processes" (threads, each with its own ``CredentialPool``- instance) hammering the same single-use Anthropic refresh token at once,- against the REAL cross-process file lock (``_auth_store_lock``) and REAL- credential-pool persistence (not mocked) under a throwaway- ``HERMES_HOME`` -- only the network call to Anthropic is faked. This- checks the fix does not deadlock, does not lose updates, and does not- degrade into a "thundering herd" of redundant refresh POSTs as- concurrency grows.-2. A burst of dashboard PKCE login starts, checking the anti-CSRF `state`- generator has no collisions at scale and that the in-memory session- table's GC actually bounds memory growth (an unbounded- ``_oauth_sessions`` dict is a latent DoS surface if many `/start` calls- never get a matching `/submit`).+"""Load / stress test for the Anthropic OAuth cross-process refresh race fix.++Companion to ``tests/agent/test_credential_pool_anthropic_refresh_race.py``,+which proves the bug in isolation with two racers. This test scales the same+scenario up to look for bottlenecks and degradation under real concurrency:+many "Hermes processes" (threads, each with its own ``CredentialPool``+instance) hammering the same single-use Anthropic refresh token at once,+against the REAL cross-process file lock (``_auth_store_lock``) and REAL+credential-pool persistence (not mocked) under a throwaway ``HERMES_HOME`` --+only the network call to Anthropic is faked. This checks the fix does not+deadlock, does not lose updates, and does not degrade into a "thundering+herd" of redundant refresh POSTs as concurrency grows."""from __future__ import annotations@@ -173,63 +165,3 @@ def test_high_concurrency_anthropic_refresh_no_lost_updates_no_deadlock(f"processes -- expected well under {naive_serial_upper_bound:.2f}s ""if the lock + pool-store adoption path is working efficiently")---def test_dashboard_pkce_start_burst_state_uniqueness_and_session_gc(monkeypatch):- """Burst-start the dashboard PKCE flow and check for two failure modes- that would only show up at scale:-- 1. ``state``/``verifier`` collisions (entropy bug in the token- generator would be invisible with 1-2 samples but show up over many).- 2. Unbounded growth of the in-memory ``_oauth_sessions`` dict -- a- latent memory-exhaustion vector if many browser tabs/bots hit- ``/start`` without ever completing ``/submit``. GC must actually- reclaim expired entries.- """- pytest.importorskip("hermes_cli.web_server")- from hermes_cli import web_server-- if not web_server._ANTHROPIC_OAUTH_AVAILABLE:- pytest.skip("Anthropic OAuth adapter unavailable in this environment")-- with web_server._oauth_sessions_lock:- web_server._oauth_sessions.clear()-- N = 500- states = []- verifiers = []- for _ in range(N):- session = web_server._start_anthropic_pkce()- with web_server._oauth_sessions_lock:- sess = web_server._oauth_sessions[session["session_id"]]- states.append(sess["state"])- verifiers.append(sess["verifier"])-- assert len(set(states)) == N, "state collisions detected across a burst of PKCE starts"- assert len(set(verifiers)) == N, "verifier collisions detected across a burst of PKCE starts"- # The fix for the CSRF bug depends on these two pools never overlapping.- assert not (set(states) & set(verifiers)), (- "a state value collided with a verifier value from a DIFFERENT "- "session -- would make the leak/CSRF bug's blast radius worse"- )-- with web_server._oauth_sessions_lock:- assert len(web_server._oauth_sessions) == N-- # Simulate all N sessions having aged past the TTL, then run the same- # GC the /start route triggers opportunistically.- with web_server._oauth_sessions_lock:- for sess in web_server._oauth_sessions.values():- sess["created_at"] = time.time() - web_server._OAUTH_SESSION_TTL_SECONDS - 1-- web_server._gc_oauth_sessions()-- with web_server._oauth_sessions_lock:- remaining = len(web_server._oauth_sessions)- assert remaining == 0, (- f"{remaining}/{N} expired OAuth sessions survived _gc_oauth_sessions() "- "-- the in-memory session table can grow without bound"- )-- with web_server._oauth_sessions_lock:- web_server._oauth_sessions.clear()diff --git a/tests/hermes_cli/test_anthropic_dashboard_pkce_csrf.py b/tests/hermes_cli/test_anthropic_dashboard_pkce_csrf.pydeleted file mode 100644index 2e87410e05f..00000000000--- a/tests/hermes_cli/test_anthropic_dashboard_pkce_csrf.py+++ /dev/null@@ -1,208 +0,0 @@-"""Regression tests for the Anthropic OAuth PKCE flow served by the web dashboard.--``hermes_cli.web_server._start_anthropic_pkce`` / ``_submit_anthropic_pkce``-implement a *second*, independent copy of the Anthropic PKCE login flow-(the first lives in ``agent.anthropic_adapter.run_hermes_oauth_login_pure``,-used by the CLI). The CLI copy was hardened by PR #10699 (issue #10693)-after PR #2647 silently reintroduced a vulnerable pattern that reused the-PKCE ``code_verifier`` as the OAuth ``state`` parameter — see-``tests/agent/test_anthropic_oauth_pkce.py``.--That hardening was never ported to the dashboard copy. This file proves the-dashboard flow currently:--1. Sends the PKCE ``code_verifier`` verbatim as the ``state`` query- parameter on the authorization URL handed to the browser- (``hermes_cli/web_server.py`` ``_start_anthropic_pkce``), leaking a value- that must stay confidential (RFC 7636 §7.2) via browser history, Referer- headers, and Anthropic's own access logs.-2. Never compares the ``state`` echoed back on the callback against the- session-stored value in ``_submit_anthropic_pkce`` — the CSRF check- required by RFC 6749 §10.12 is entirely absent on this path, unlike the- CLI flow which aborts on ``received_state != oauth_state``.--Each test below asserts the *secure* behavior. Under the current code they-are expected to FAIL, which is the evidence that the bug is real.-"""--from __future__ import annotations--import json-from typing import Any, Dict-from urllib.parse import parse_qs, urlparse--import pytest---def _import_web_server():- pytest.importorskip("hermes_cli.web_server")- from hermes_cli import web_server-- if not web_server._ANTHROPIC_OAUTH_AVAILABLE:- pytest.skip("Anthropic OAuth adapter unavailable in this environment")- return web_server---class _FakeResponse:- def __init__(self, body: bytes) -> None:- self._body = body-- def __enter__(self):- return self-- def __exit__(self, *_exc):- return False-- def read(self) -> bytes:- return self._body--[email protected](autouse=True)-def _clean_oauth_sessions():- """Every test gets a pristine in-memory session table."""- web_server = _import_web_server()- with web_server._oauth_sessions_lock:- web_server._oauth_sessions.clear()- yield- with web_server._oauth_sessions_lock:- web_server._oauth_sessions.clear()---def test_authorization_url_state_is_not_pkce_verifier():- """The ``state`` query param must NOT equal the PKCE ``code_verifier``.-- Reusing the verifier as state leaks it via the authorization URL- (browser history, Referer headers, auth-server access logs), defeating- RFC 7636's confidentiality requirement for the verifier.- """- web_server = _import_web_server()-- session = web_server._start_anthropic_pkce()- auth_url = session["auth_url"]- qs = parse_qs(urlparse(auth_url).query)- state_in_url = qs.get("state", [""])[0]-- with web_server._oauth_sessions_lock:- stored_verifier = web_server._oauth_sessions[session["session_id"]]["verifier"]-- assert state_in_url != stored_verifier, (- "Dashboard Anthropic PKCE flow sends the code_verifier as the "- "OAuth 'state' parameter -- the exact pattern fixed for the CLI "- "flow by PR #10699 (issue #10693), but never ported here. The "- "verifier now leaks via the authorization URL."- )---def test_verifier_never_appears_anywhere_in_auth_url():- """Defense in depth: the verifier must not appear in ANY query value."""- web_server = _import_web_server()-- session = web_server._start_anthropic_pkce()- auth_url = session["auth_url"]-- with web_server._oauth_sessions_lock:- stored_verifier = web_server._oauth_sessions[session["session_id"]]["verifier"]-- assert stored_verifier not in auth_url, (- "PKCE code_verifier leaked verbatim into the authorization URL "- "returned to the browser by _start_anthropic_pkce()."- )---def test_state_is_cryptographically_independent_of_verifier():- """``state`` should be an independently generated anti-CSRF token.-- A compliant implementation (mirroring- ``agent.anthropic_adapter.run_hermes_oauth_login_pure``) generates- ``state`` via a separate ``secrets.token_urlsafe(...)`` call rather than- deriving it from the verifier/challenge at all.- """- web_server = _import_web_server()-- session_a = web_server._start_anthropic_pkce()- session_b = web_server._start_anthropic_pkce()-- with web_server._oauth_sessions_lock:- verifier_a = web_server._oauth_sessions[session_a["session_id"]]["verifier"]- state_a = web_server._oauth_sessions[session_a["session_id"]]["state"]- verifier_b = web_server._oauth_sessions[session_b["session_id"]]["verifier"]- state_b = web_server._oauth_sessions[session_b["session_id"]]["state"]-- assert state_a != verifier_a, "session A: state == verifier (leak)"- assert state_b != verifier_b, "session B: state == verifier (leak)"---def test_submit_pkce_rejects_state_mismatch(monkeypatch):- """The token exchange must NOT proceed when the callback state does not- match the state issued for this session (RFC 6749 Section 10.12 CSRF guard).-- This mirrors ``tests/agent/test_anthropic_oauth_pkce.py``'s state-mismatch- coverage for the CLI flow, applied to the dashboard's HTTP-facing- equivalent.- """- web_server = _import_web_server()-- session = web_server._start_anthropic_pkce()- session_id = session["session_id"]-- captured_request: Dict[str, Any] = {}-- def fake_urlopen(req, *_a, **_kw):- captured_request["url"] = req.full_url- captured_request["data"] = json.loads(req.data.decode())- return _FakeResponse(json.dumps({- "access_token": "sk-ant-attacker-exchanged",- "refresh_token": "sk-ant-refresh",- "expires_in": 3600,- }).encode())-- monkeypatch.setattr("urllib.request.urlopen", fake_urlopen)-- # Attacker completes their OWN authorization and gets the victim to- # paste a code carrying a state that does not match what- # _start_anthropic_pkce issued for the victim's session (classic OAuth- # login-CSRF: the attacker's code gets bound to the victim's account- # because the callback endpoint never checks state).- result = web_server._submit_anthropic_pkce(- session_id, "attacker-code#attacker-controlled-state"- )-- assert not captured_request, (- "Token exchange proceeded with a callback 'state' that did not "- "match the session's issued state -- _submit_anthropic_pkce() "- "performs no CSRF validation at all, unlike the CLI flow's "- "'received_state != oauth_state' guard."- )- assert result.get("ok") is False---def test_submit_pkce_with_no_state_suffix_does_not_silently_succeed(monkeypatch):- """Pasting a bare code (no ``#state`` suffix) must not bypass the CSRF- check by silently falling back to the session's own state value.- """- web_server = _import_web_server()-- session = web_server._start_anthropic_pkce()- session_id = session["session_id"]-- captured_request: Dict[str, Any] = {}-- def fake_urlopen(req, *_a, **_kw):- captured_request["url"] = req.full_url- captured_request["data"] = json.loads(req.data.decode())- return _FakeResponse(json.dumps({- "access_token": "sk-ant-should-not-be-issued",- "refresh_token": "sk-ant-refresh",- "expires_in": 3600,- }).encode())-- monkeypatch.setattr("urllib.request.urlopen", fake_urlopen)-- result = web_server._submit_anthropic_pkce(session_id, "some-code-with-no-state")-- assert not captured_request, (- "_submit_anthropic_pkce() fell back to sess['state'] when the "- "callback carried no state suffix at all -- this makes the state "- "check a no-op rather than a genuine CSRF guard."- )- assert result.get("ok") is Falsediff --git a/tests/hermes_cli/test_web_server_oauth_write.py b/tests/hermes_cli/test_web_server_oauth_write.pydeleted file mode 100644index 31a29c1130b..00000000000--- a/tests/hermes_cli/test_web_server_oauth_write.py+++ /dev/null@@ -1,58 +0,0 @@-import os--import pytest--from hermes_cli.web_server import _save_anthropic_oauth_creds---class _DummyPool:- def entries(self):- return []-- def remove_entry(self, _id):- return None-- def add_entry(self, _entry):- return None---def oauth_file(monkeypatch, tmp_path):- target = tmp_path / '.anthropic_oauth.json'- monkeypatch.setattr('agent.anthropic_adapter._get_hermes_oauth_file', lambda: target)- monkeypatch.setattr('agent.credential_pool.load_pool', lambda _provider: _DummyPool())- return target---def test_dashboard_oauth_write_uses_owner_only_permissions(oauth_file):- old_umask = os.umask(0o022)- try:- _save_anthropic_oauth_creds('access-token', 'refresh-token', 123456)- finally:- os.umask(old_umask)-- assert oauth_file.exists()- mode = oauth_file.stat().st_mode & 0o777- assert mode == 0o600---def test_dashboard_oauth_write_uses_atomic_json_write_with_owner_only_mode(oauth_file, monkeypatch):- """The OAuth token file must be written 0o600 from creation via- ``atomic_json_write(mode=0o600)``, so it is never briefly world-readable- (the old ``os.replace`` + post-hoc ``chmod`` TOCTOU)."""- import utils-- calls = {}- real = utils.atomic_json_write-- def spy(path, data, **kwargs):- calls['mode'] = kwargs.get('mode')- return real(path, data, **kwargs)-- monkeypatch.setattr(utils, 'atomic_json_write', spy)-- _save_anthropic_oauth_creds('access-token', 'refresh-token', 123456)-- assert calls.get('mode') == 0o600, \- 'OAuth creds must be written 0o600 atomically (no chmod-after-replace window)'- assert oauth_file.exists()