Skip to content

The agent that grows with you

fix(anthropic): mirror only the Keychain item that held the spent pair; parse both `security` attribute encodings

kshitijk4poor14a346345486
diff --git a/agent/anthropic_credentials.py b/agent/anthropic_credentials.py
index ef43cf6d0c3..424b9cfa255 100644
--- a/agent/anthropic_credentials.py
+++ b/agent/anthropic_credentials.py
@@ -209,6 +209,52 @@ def _claude_oauth_record(data: Any, source: str) -> Optional[Dict[str, Any]]:
}
+_KEYCHAIN_ATTR = r'(?:0x(?P<hex>[0-9A-Fa-f]+)\b.*|"(?P<text>.*)")'
+
+
+def _decode_keychain_attr(match: Optional["re.Match[str]"]) -> str:
+ """``security`` prints an attribute as ``"text"`` when it is plain printable ASCII and as
+ ``0x<HEX> "<octal-escaped echo>"`` otherwise; the quoted form is NOT escaped (an embedded
+ ``"`` appears raw), so the text group must run to the last quote on the line."""
+ if match is None:
+ return ""
+ if match.group("hex"):
+ try:
+ return bytes.fromhex(match.group("hex")).decode("utf-8")
+ except ValueError:
+ return ""
+ return match.group("text") or ""
+
+
+def _find_claude_code_keychain_item() -> Optional[tuple[str, Dict[str, Any]]]:
+ """``(account, payload)`` of the ``Claude Code-credentials`` login Keychain item, or None.
+
+ One ``find-generic-password -g`` call: attributes on stdout, ``password: …`` on stderr. The
+ account matters because ``add-generic-password -U`` matches on account AND service — writing
+ under another account would create a second item instead of updating the one Claude Code reads.
+ """
+ if platform.system() != "Darwin":
+ return None
+ try:
+ result = subprocess.run(
+ ["security", "find-generic-password", "-s", _CLAUDE_CODE_KEYCHAIN_SERVICE, "-g"],
+ capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=5, stdin=subprocess.DEVNULL,
+ )
+ except (OSError, subprocess.TimeoutExpired):
+ return None
+ if result.returncode != 0:
+ return None
+ account = _decode_keychain_attr(re.search(r'^\s*"acct"<blob>=' + _KEYCHAIN_ATTR + r"\s*$", result.stdout, re.M))
+ raw = _decode_keychain_attr(re.search(r"^password: " + _KEYCHAIN_ATTR + r"\s*$", result.stderr, re.M))
+ if not account or not raw:
+ return None
+ try:
+ payload = json.loads(raw)
+ except ValueError:
+ return None
+ return (account, payload) if isinstance(payload, dict) else None
+
+
def _read_claude_code_keychain_payload() -> Optional[Dict[str, Any]]:
"""Raw ``{"claudeAiOauth": {...}, ...}`` payload from the macOS Keychain, or None.
@@ -240,23 +286,6 @@ def _read_claude_code_keychain_payload() -> Optional[Dict[str, Any]]:
return payload if isinstance(payload, dict) else None
-def _claude_code_keychain_account() -> str:
- """The ``acct`` attribute of the existing Keychain item (``""`` when unreadable).
-
- ``add-generic-password -U`` matches on account AND service; writing under a different
- account would create a second item instead of updating the one Claude Code reads.
- """
- try:
- result = subprocess.run(
- ["security", "find-generic-password", "-s", _CLAUDE_CODE_KEYCHAIN_SERVICE],
- capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=5, stdin=subprocess.DEVNULL,
- )
- except (OSError, subprocess.TimeoutExpired):
- return ""
- match = re.search(r'"acct"<blob>="((?:[^"\\]|\\.)*)"', result.stdout) if result.returncode == 0 else None
- return match.group(1) if match else ""
-
-
def _keychain_mirror_command(account: str, payload: Dict[str, Any]) -> tuple[list[str], str]:
"""``(argv, stdin)`` that updates the Claude Code Keychain item with ``payload``.
@@ -265,8 +294,10 @@ def _keychain_mirror_command(account: str, payload: Dict[str, Any]) -> tuple[lis
no terminal, reads only the first line and stores an EMPTY password when the confirmation
read hits EOF — either way the live token must never sit on argv.
"""
- quoted = lambda v: '"' + v.replace("\\", "\\\\").replace('"', '\\"') + '"' # noqa: E731 - security -i tokenizer
- encoded = json.dumps(payload, separators=(",", ":")).encode("utf-8").hex()
+ def quoted(value: str) -> str: # the ``security -i`` tokenizer: double quotes, backslash escapes
+ return '"' + value.replace("\\", "\\\\").replace('"', '\\"') + '"'
+
+ encoded = json.dumps(payload, separators=(",", ":"), ensure_ascii=True).encode("utf-8").hex()
line = f"add-generic-password -U -a {quoted(account)} -s {quoted(_CLAUDE_CODE_KEYCHAIN_SERVICE)} -X {encoded}\n"
return ["security", "-i"], line
@@ -451,7 +482,10 @@ def _refresh_oauth_token(creds: Dict[str, Any]) -> Optional[str]:
# The POST spent ``refresh_token``; this write is the commit step. On failure, fail closed and
# mark the pre-rotation pair as spent.
try:
- _write_claude_code_credentials(refreshed["access_token"], refreshed["refresh_token"], refreshed["expires_at_ms"])
+ _write_claude_code_credentials(
+ refreshed["access_token"], refreshed["refresh_token"], refreshed["expires_at_ms"],
+ spent_refresh_token=refresh_token,
+ )
except Exception as e:
logger.error(
"Anthropic OAuth refresh rotated the single-use token but could not "
@@ -473,7 +507,8 @@ def _refresh_oauth_token(creds: Dict[str, Any]) -> Optional[str]:
def _write_claude_code_credentials(
- access_token: str, refresh_token: str, expires_at_ms: int, *, scopes: Optional[list] = None
+ access_token: str, refresh_token: str, expires_at_ms: int, *, scopes: Optional[list] = None,
+ spent_refresh_token: str = "",
) -> None:
"""Commit refreshed credentials to ~/.claude/.credentials.json; ``CredentialPersistError`` on any failure (a
corrupt existing file included). *scopes* (or the previously stored scopes) are persisted because Claude Code
@@ -491,7 +526,8 @@ 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)
+ _mirror_claude_code_credentials_to_keychain(
+ access_token, refresh_token, expires_at_ms, spent_refresh_token=spent_refresh_token)
def _merge_keychain_credential_payload(
@@ -510,33 +546,33 @@ def _merge_keychain_credential_payload(
def _mirror_claude_code_credentials_to_keychain(
- access_token: str, refresh_token: str, expires_at_ms: int
+ access_token: str, refresh_token: str, expires_at_ms: int, *, spent_refresh_token: str
) -> None:
- """Mirror a committed refresh into the macOS Keychain when an entry already exists.
+ """After a Hermes refresh, write the rotated pair into the Claude Code Keychain item too (#98334).
- 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 ``add-generic-password -U`` (through ``security -i``) 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).
+ Claude Code on macOS reads the login Keychain first. Refresh tokens are single-use, so a refresh
+ that only updates the file leaves the Keychain holding a spent token and Claude Code logs itself
+ out. Only the item that held the pair we just spent is updated — a different pair there means a
+ different login (``CLAUDE_CONFIG_DIR``) or a rotation Claude Code already made, and clobbering it
+ would be the bug in the other direction. Best-effort: never raises, never creates an item.
"""
if platform.system() != "Darwin":
return
try:
- existing = _read_claude_code_keychain_payload()
- account = _claude_code_keychain_account() if existing else ""
- if not existing or not account:
+ item = _find_claude_code_keychain_item()
+ if item is None:
+ return
+ account, existing = item
+ oauth = existing.get("claudeAiOauth")
+ if not isinstance(oauth, dict) or oauth.get("refreshToken") != spent_refresh_token:
+ logger.debug("Keychain mirror skipped: item does not hold the pair that was just rotated")
return
argv, line = _keychain_mirror_command(
account, _merge_keychain_credential_payload(existing, access_token, refresh_token, expires_at_ms))
result = subprocess.run(
argv, input=line, capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=10,
)
- except (OSError, subprocess.TimeoutExpired) as e:
+ except Exception as e: # the file commit already succeeded; a Keychain hiccup must not fail the rotation
logger.debug("Keychain mirror skipped (%s)", e)
return
if result.returncode != 0:
diff --git a/agent/credential_pool.py b/agent/credential_pool.py
index ede5f7d0e1b..4eee11c0e39 100644
--- a/agent/credential_pool.py
+++ b/agent/credential_pool.py
@@ -1372,7 +1372,7 @@ class CredentialPool(CredentialPoolAdminMixin, CredentialPoolModelCooldownMixin)
from agent import anthropic_credentials as ac
args = (refreshed["access_token"], refreshed["refresh_token"], refreshed["expires_at_ms"])
if entry.source == "claude_code":
- ac._write_claude_code_credentials(*args)
+ ac._write_claude_code_credentials(*args, spent_refresh_token=entry.refresh_token or "")
else:
ac._write_hermes_oauth_credentials(*args)
except Exception as wexc:
diff --git a/tests/agent/test_anthropic_borrowed_row_authority.py b/tests/agent/test_anthropic_borrowed_row_authority.py
index 1d320378f3a..938a1d25b48 100644
--- a/tests/agent/test_anthropic_borrowed_row_authority.py
+++ b/tests/agent/test_anthropic_borrowed_row_authority.py
@@ -163,9 +163,9 @@ def test_refresh_from_persisted_sanitized_row_keeps_the_full_pair(
real_write = AA._write_claude_code_credentials
- def _counting_write(access_token, refresh_token, expires_at_ms):
+ def _counting_write(access_token, refresh_token, expires_at_ms, **kwargs):
writes.append(refresh_token)
- return real_write(access_token, refresh_token, expires_at_ms)
+ return real_write(access_token, refresh_token, expires_at_ms, **kwargs)
monkeypatch.setattr(AA, "refresh_anthropic_oauth_pure", _counting_refresh)
monkeypatch.setattr(AA, "_write_claude_code_credentials", _counting_write)
diff --git a/tests/agent/test_anthropic_keychain.py b/tests/agent/test_anthropic_keychain.py
index 50b67547c8b..4bf04e38502 100644
--- a/tests/agent/test_anthropic_keychain.py
+++ b/tests/agent/test_anthropic_keychain.py
@@ -13,6 +13,7 @@ from agent.anthropic_credentials import (
_read_claude_code_credentials_from_keychain,
read_claude_code_credentials,
_refresh_oauth_token,
+ _find_claude_code_keychain_item,
_keychain_mirror_command,
_merge_keychain_credential_payload,
_mirror_claude_code_credentials_to_keychain,
@@ -397,6 +398,28 @@ class TestKeychainMirrorCommand:
assert json.loads(bytes.fromhex(hex_blob)) == payload
+class TestFindClaudeCodeKeychainItem:
+ """``_find_claude_code_keychain_item`` parses one ``find-generic-password -g`` call. ``security``
+ prints plain-ASCII attributes quoted but UNescaped, anything else as ``0x<HEX> "<echo>"``."""
+
+ @pytest.mark.macos_only
+ @pytest.mark.parametrize(
+ "acct_line, expected_account",
+ [
+ (' "acct"<blob>="bob"', "bob"),
+ (' "acct"<blob>="my "user" name"', 'my "user" name'), # embedded quote, printed raw
+ (' "acct"<blob>=0x616C2269636520C3BC "al\\"ice \\303\\274"', 'al"ice \u00fc'), # non-ASCII → hex form
+ ],
+ )
+ def test_reads_account_and_payload_in_both_output_encodings(self, monkeypatch, acct_line, expected_account):
+ payload = {"claudeAiOauth": {"refreshToken": "r"}, "mcpOAuth": {"a": 1}}
+ fake = MagicMock(returncode=0, stdout=f'keychain: "/Users/x/Library/Keychains/login.keychain-db"\n{acct_line}\n',
+ stderr=f"password: 0x{json.dumps(payload).encode().hex()} \"...\"\n")
+ monkeypatch.setattr(subprocess, "run", lambda argv, **k: fake)
+
+ assert _find_claude_code_keychain_item() == (expected_account, payload)
+
+
class TestMirrorClaudeCodeCredentialsToKeychain:
"""The #98334 write mirror shells out to ``security``; ``subprocess.run`` is mocked so no
real Keychain is touched."""
@@ -404,10 +427,28 @@ class TestMirrorClaudeCodeCredentialsToKeychain:
@pytest.mark.macos_only
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))
+ monkeypatch.setattr("agent.anthropic_credentials._find_claude_code_keychain_item", lambda: None)
+ run = MagicMock(return_value=MagicMock(returncode=0))
+ monkeypatch.setattr(subprocess, "run", run)
- _mirror_claude_code_credentials_to_keychain("a", "b", 1)
+ _mirror_claude_code_credentials_to_keychain("a", "b", 1, spent_refresh_token="old")
- assert called == []
+ run.assert_not_called()
+
+ @pytest.mark.macos_only
+ def test_only_the_item_holding_the_spent_pair_is_updated(self, monkeypatch):
+ """A different pair in the Keychain is another login or a rotation Claude Code already made;
+ overwriting it would be the bug in the other direction."""
+ item = ("bob", {"claudeAiOauth": {"accessToken": "A0", "refreshToken": "R0"}})
+ monkeypatch.setattr("agent.anthropic_credentials._find_claude_code_keychain_item", lambda: item)
+ run = MagicMock(return_value=MagicMock(returncode=0))
+ monkeypatch.setattr(subprocess, "run", run)
+
+ _mirror_claude_code_credentials_to_keychain("A1", "R1", 1, spent_refresh_token="not-R0")
+ run.assert_not_called()
+
+ _mirror_claude_code_credentials_to_keychain("A1", "R1", 1, spent_refresh_token="R0")
+ (argv,), kwargs = run.call_args
+ assert argv == ["security", "-i"]
+ assert json.loads(bytes.fromhex(kwargs["input"].split(" -X ", 1)[1].strip()))["claudeAiOauth"] == {
+ "accessToken": "A1", "refreshToken": "R1", "expiresAt": 1}
diff --git a/tests/agent/test_auxiliary_client.py b/tests/agent/test_auxiliary_client.py
index fcb8028ab5a..06570e42fef 100644
--- a/tests/agent/test_auxiliary_client.py
+++ b/tests/agent/test_auxiliary_client.py
@@ -2940,7 +2940,8 @@ class TestAuxiliaryAuthRefreshRetry:
assert cache_key not in aux._client_cache # evicted, not closed (in-flight users)
mock_refresh_oauth.assert_called_once_with("refresh-token", use_json=False)
- mock_write.assert_called_once_with("fresh-token", "refresh-token-2", 9999999999999)
+ mock_write.assert_called_once_with(
+ "fresh-token", "refresh-token-2", 9999999999999, spent_refresh_token="refresh-token")
stale_client.close.assert_not_called()
def test_refresh_provider_credentials_remints_vertex_token_and_evicts_cache(self):