Skip to content

The agent that grows with you

fix(agent): mirror Claude Code OAuth refresh into the macOS Keychain (#98334)

salch-cred6d4ca15d38fe
diff --git a/agent/anthropic_credentials.py b/agent/anthropic_credentials.py
index b03aee1b862..5956361384d 100644
--- a/agent/anthropic_credentials.py
+++ b/agent/anthropic_credentials.py
@@ -12,6 +12,7 @@ re-reads them on every ``load_pool()``, so a failed write here is a failed refre
import base64
import contextlib
import functools
+import getpass
import hashlib
import json
import logging
@@ -41,6 +42,10 @@ _OAUTH_TOKEN_URLS = [
_OAUTH_TOKEN_USER_AGENT = "axios/1.7.9"
_OAUTH_REDIRECT_URI = "https://console.anthropic.com/oauth/code/callback"
_OAUTH_SCOPES = "org:create_api_key user:profile user:inference"
+# Claude Code's macOS Keychain entry (generic password). Hermes reads it
+# (_read_claude_code_credentials_from_keychain) and, since #98334, mirrors the
+# refresh write into it so the two stores stop diverging on a single-use rotation.
+_CLAUDE_CODE_KEYCHAIN_SERVICE = "Claude Code-credentials"
def _getenv(name: str, default: str = "") -> str:
@@ -204,27 +209,41 @@ def _claude_oauth_record(data: Any, source: str) -> Optional[Dict[str, Any]]:
}
-def _read_claude_code_credentials_from_keychain() -> Optional[Dict[str, Any]]:
- """Read the "Claude Code-credentials" macOS Keychain entry (Claude Code >=2.1.114)."""
+def _read_claude_code_keychain_payload() -> Optional[Dict[str, Any]]:
+ """Raw ``{"claudeAiOauth": {...}, ...}`` payload from the macOS Keychain, or None.
+
+ Returns the full entry (not the normalised credential record) so a refresh
+ write can merge the rotated token triple over the existing metadata
+ (``subscriptionType`` / ``rateLimitTier`` / ``scopes``) instead of clobbering it.
+ """
if platform.system() != "Darwin":
return None
try:
result = subprocess.run(
- ["security", "find-generic-password", "-s", "Claude Code-credentials", "-w"],
+ ["security", "find-generic-password", "-s", _CLAUDE_CODE_KEYCHAIN_SERVICE, "-w"],
capture_output=True, text=True, encoding='utf-8', errors='replace', timeout=5, stdin=subprocess.DEVNULL,
)
except (OSError, subprocess.TimeoutExpired):
logger.debug("Keychain: security command not available or timed out")
return None
if result.returncode != 0:
- logger.debug("Keychain: no entry found for 'Claude Code-credentials'")
+ logger.debug("Keychain: no entry found for %r", _CLAUDE_CODE_KEYCHAIN_SERVICE)
return None
raw = result.stdout.strip()
+ if not raw:
+ return None
try:
- return _claude_oauth_record(json.loads(raw), "macos_keychain") if raw else None
+ payload = json.loads(raw)
except json.JSONDecodeError:
logger.debug("Keychain: credentials payload is not valid JSON")
return None
+ return payload if isinstance(payload, dict) else None
+
+
+def _read_claude_code_credentials_from_keychain() -> Optional[Dict[str, Any]]:
+ """Read the "Claude Code-credentials" macOS Keychain entry (Claude Code >=2.1.114)."""
+ payload = _read_claude_code_keychain_payload()
+ return _claude_oauth_record(payload, "macos_keychain") if payload else None
def claude_code_credentials_path() -> Path:
@@ -441,6 +460,68 @@ def _write_claude_code_credentials(
oauth_data["scopes"] = existing["claudeAiOauth"]["scopes"]
existing["claudeAiOauth"] = oauth_data
_commit_private_json(cred_path, existing, "credentials")
+ _mirror_claude_code_credentials_to_keychain(access_token, refresh_token, expires_at_ms)
+
+
+def _merge_keychain_credential_payload(
+ existing_payload: Dict[str, Any], access_token: str, refresh_token: str, expires_at_ms: int
+) -> Dict[str, Any]:
+ """Rotate the ``claudeAiOauth`` token triple over the existing Keychain payload,
+ preserving its metadata (``subscriptionType`` / ``rateLimitTier`` / ``scopes``).
+
+ Pure and host-agnostic so the merge semantics are unit-testable without a Keychain.
+ """
+ merged = dict(existing_payload)
+ oauth = dict(existing_payload.get("claudeAiOauth") or {})
+ oauth.update({"accessToken": access_token, "refreshToken": refresh_token, "expiresAt": expires_at_ms})
+ merged["claudeAiOauth"] = oauth
+ return merged
+
+
+def _mirror_claude_code_credentials_to_keychain(
+ access_token: str, refresh_token: str, expires_at_ms: int
+) -> None:
+ """Mirror a committed refresh into the macOS Keychain when an entry already exists.
+
+ On Darwin the Keychain is Claude Code's authoritative store, but Hermes historically
+ only wrote ``~/.claude/.credentials.json``. Because the refresh token is single-use and
+ rotating, that left the Keychain holding an already-invalidated token, which Claude Code
+ then spent into ``invalid_grant`` and discarded (``Login: Expired``). Mirror the rotated
+ pair back with ``security add-generic-password -U`` so both stores agree.
+
+ Fail-soft: a Keychain mirror failure is logged, never raised. The file commit has already
+ succeeded and the resolver still resolves from it; only the secondary store stays stale.
+ No-op off Darwin and when no entry exists (we never create one the user has not).
+ """
+ if platform.system() != "Darwin":
+ return
+ try:
+ existing = _read_claude_code_keychain_payload()
+ if not existing:
+ return
+ payload = _merge_keychain_credential_payload(existing, access_token, refresh_token, expires_at_ms)
+ encoded = json.dumps(payload)
+ # The bare ``-w`` (no value) tells ``security`` to read the password from
+ # stdin, so the live secret never lands on argv (process-table visible).
+ result = subprocess.run(
+ [
+ "security", "add-generic-password", "-U",
+ "-a", getpass.getuser(),
+ "-s", _CLAUDE_CODE_KEYCHAIN_SERVICE,
+ "-w",
+ ],
+ input=encoded,
+ capture_output=True,
+ text=True,
+ encoding="utf-8",
+ errors="replace",
+ timeout=10,
+ )
+ except (OSError, subprocess.TimeoutExpired) as e:
+ logger.debug("Keychain mirror skipped (%s)", e)
+ return
+ if result.returncode != 0:
+ logger.debug("Keychain mirror failed (rc=%s): %s", result.returncode, (result.stderr or "").strip()[:200])
# ── Resolution ──
diff --git a/tests/agent/test_anthropic_keychain.py b/tests/agent/test_anthropic_keychain.py
index 3b7cfffecaf..69c333cd569 100644
--- a/tests/agent/test_anthropic_keychain.py
+++ b/tests/agent/test_anthropic_keychain.py
@@ -1,13 +1,21 @@
"""Tests for Bug #12905 fixes in agent/anthropic_adapter.py — macOS Keychain support."""
import json
+import platform
+import subprocess
import threading
import time
from unittest.mock import patch, MagicMock
import pytest
-from agent.anthropic_credentials import _read_claude_code_credentials_from_keychain, read_claude_code_credentials, _refresh_oauth_token
+from agent.anthropic_credentials import (
+ _read_claude_code_credentials_from_keychain,
+ read_claude_code_credentials,
+ _refresh_oauth_token,
+ _merge_keychain_credential_payload,
+ _mirror_claude_code_credentials_to_keychain,
+)
# This module exercises the reader itself with explicit platform and subprocess
@@ -343,3 +351,128 @@ class TestRefreshOAuthTokenAdoptsFreshCredential:
assert results == {"a": "fresh-access", "b": "fresh-access"}
assert calls == ["stale-refresh"], calls
+
+class TestMergeKeychainCredentialPayload:
+ """``_merge_keychain_credential_payload`` — the pure merge that a Keychain
+ refresh write performs over the existing entry. Host-agnostic, so it runs
+ on every lane and pins the #98334 invariant: rotate the token triple while
+ preserving the metadata Claude Code gates on."""
+
+ _EXISTING = {
+ "claudeAiOauth": {
+ "accessToken": "old-access",
+ "refreshToken": "old-refresh",
+ "expiresAt": 1,
+ "scopes": ["user:inference", "user:profile"],
+ "subscriptionType": "max",
+ },
+ "rateLimitTier": "tier-1",
+ }
+
+ def test_rotates_triple_preserves_metadata(self):
+ merged = _merge_keychain_credential_payload(self._EXISTING, "new-access", "new-refresh", 42)
+ oauth = merged["claudeAiOauth"]
+ assert oauth["accessToken"] == "new-access"
+ assert oauth["refreshToken"] == "new-refresh"
+ assert oauth["expiresAt"] == 42
+ # The fields Claude Code >=2.1.81 gates on survive the merge.
+ assert oauth["scopes"] == ["user:inference", "user:profile"]
+ assert oauth["subscriptionType"] == "max"
+ assert merged["rateLimitTier"] == "tier-1"
+ # Input payload is not mutated (no aliasing surprise).
+ assert self._EXISTING["claudeAiOauth"]["refreshToken"] == "old-refresh"
+
+ def test_tolerates_missing_oauth_block(self):
+ merged = _merge_keychain_credential_payload({"other": 1}, "a", "b", 7)
+ assert merged["claudeAiOauth"] == {"accessToken": "a", "refreshToken": "b", "expiresAt": 7}
+ assert merged["other"] == 1
+
+
+class TestMirrorClaudeCodeCredentialsToKeychain:
+ """``_mirror_claude_code_credentials_to_keychain`` — the #98334 write mirror.
+
+ The write path is gated on ``platform.system() == "Darwin"`` and shells out
+ to ``security``. We force the gate to "Darwin" so the logic runs on every
+ lane, and mock only the raw reader and ``subprocess.run`` — no real Keychain
+ is ever touched and no real ``security`` binary is required.
+ """
+
+ @pytest.fixture(autouse=True)
+ def _darwin_gate(self, monkeypatch):
+ monkeypatch.setattr(platform, "system", lambda: "Darwin")
+
+ def test_writes_via_stdin_not_argv_when_entry_exists(self, monkeypatch):
+ """The rotated pair must reach the existing Keychain item via
+ ``add-generic-password -U`` with the payload on stdin — never as a
+ ``-w`` argv token (a live secret would be visible in the process table)."""
+ existing = {
+ "claudeAiOauth": {"accessToken": "old", "refreshToken": "old-ref",
+ "expiresAt": 1, "scopes": ["user:inference"],
+ "subscriptionType": "max"},
+ }
+ monkeypatch.setattr(
+ "agent.anthropic_credentials._read_claude_code_keychain_payload", lambda: existing)
+ calls = []
+
+ def fake_run(argv, **kwargs):
+ calls.append((list(argv), kwargs))
+ return MagicMock(returncode=0, stdout="", stderr="")
+
+ monkeypatch.setattr(subprocess, "run", fake_run)
+
+ _mirror_claude_code_credentials_to_keychain("new-access", "new-ref", 99)
+
+ assert len(calls) == 1
+ argv, kwargs = calls[0]
+ assert "add-generic-password" in argv
+ assert "-U" in argv
+ assert "-s" in argv and "Claude Code-credentials" in argv
+ # The bare -w flag reads the password from stdin, so the secret must NOT
+ # appear anywhere on the command line.
+ assert "-w" in argv
+ joined = " ".join(argv)
+ assert "new-access" not in joined
+ assert "new-ref" not in joined
+ # The payload goes to stdin and carries the rotated triple + preserved metadata.
+ payload = json.loads(kwargs["input"])
+ assert payload["claudeAiOauth"]["refreshToken"] == "new-ref"
+ assert payload["claudeAiOauth"]["accessToken"] == "new-access"
+ assert payload["claudeAiOauth"]["subscriptionType"] == "max"
+
+ def test_no_write_when_no_entry_exists(self, monkeypatch):
+ """Never create a Keychain item the user has not."""
+ monkeypatch.setattr(
+ "agent.anthropic_credentials._read_claude_code_keychain_payload", lambda: None)
+ called = []
+ monkeypatch.setattr(subprocess, "run", lambda *a, **k: called.append(a))
+
+ _mirror_claude_code_credentials_to_keychain("a", "b", 1)
+
+ assert called == []
+
+ def test_fail_soft_when_security_raises(self, monkeypatch):
+ """A mirror failure is logged, never raised: the file commit already
+ succeeded and the resolver still resolves from it."""
+ monkeypatch.setattr(
+ "agent.anthropic_credentials._read_claude_code_keychain_payload",
+ lambda: {"claudeAiOauth": {"accessToken": "x"}})
+
+ def boom(*a, **k):
+ raise OSError("security not available")
+
+ monkeypatch.setattr(subprocess, "run", boom)
+
+ # Must not raise.
+ _mirror_claude_code_credentials_to_keychain("a", "b", 1)
+
+ def test_fail_soft_on_nonzero_exit(self, monkeypatch):
+ monkeypatch.setattr(
+ "agent.anthropic_credentials._read_claude_code_keychain_payload",
+ lambda: {"claudeAiOauth": {"accessToken": "x"}})
+ monkeypatch.setattr(
+ subprocess, "run",
+ lambda *a, **k: MagicMock(returncode=1, stdout="", stderr="duplicate item"))
+
+ # Must not raise.
+ _mirror_claude_code_credentials_to_keychain("a", "b", 1)
+
diff --git a/tests/conftest.py b/tests/conftest.py
index b25f8a3bff0..5c647e59d78 100644
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@ -729,6 +729,14 @@ def _neutralize_macos_keychain_creds(request, monkeypatch):
lambda *_args, **_kwargs: None,
raising=False,
)
+ # The #98334 refresh write also mirrors into the Keychain; keep that out of
+ # the real store in any test that hasn't explicitly opted in.
+ monkeypatch.setattr(
+ _mod,
+ "_mirror_claude_code_credentials_to_keychain",
+ lambda *_args, **_kwargs: None,
+ raising=False,
+ )
return None