llmswap-cli 1.0.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- claude_swap/__init__.py +24 -0
- claude_swap/__main__.py +6 -0
- claude_swap/app_bundle.py +330 -0
- claude_swap/appearance.py +219 -0
- claude_swap/autoswitch.py +3065 -0
- claude_swap/cache.py +44 -0
- claude_swap/claude_locks.py +279 -0
- claude_swap/cli.py +2265 -0
- claude_swap/credentials.py +2156 -0
- claude_swap/exceptions.py +102 -0
- claude_swap/fsutil.py +409 -0
- claude_swap/json_output.py +455 -0
- claude_swap/launch_agent.py +862 -0
- claude_swap/lines.py +153 -0
- claude_swap/list_view.py +371 -0
- claude_swap/locking.py +87 -0
- claude_swap/logging_config.py +64 -0
- claude_swap/macos_keychain.py +240 -0
- claude_swap/mappings.py +127 -0
- claude_swap/menubar.py +1433 -0
- claude_swap/migrations.py +360 -0
- claude_swap/models.py +329 -0
- claude_swap/oauth.py +1628 -0
- claude_swap/pace.py +161 -0
- claude_swap/paths.py +250 -0
- claude_swap/poll_policy.py +337 -0
- claude_swap/printer.py +252 -0
- claude_swap/process_detection.py +370 -0
- claude_swap/session.py +2696 -0
- claude_swap/settings.py +827 -0
- claude_swap/signin.py +238 -0
- claude_swap/snapshot_source.py +121 -0
- claude_swap/spawn.py +135 -0
- claude_swap/subscription.py +349 -0
- claude_swap/switcher.py +9807 -0
- claude_swap/transfer.py +807 -0
- claude_swap/tui/__init__.py +43 -0
- claude_swap/tui/app.py +482 -0
- claude_swap/tui/autoview.py +381 -0
- claude_swap/tui/cswap.tcss +205 -0
- claude_swap/tui/dashboard.py +434 -0
- claude_swap/tui/data.py +194 -0
- claude_swap/tui/modals.py +159 -0
- claude_swap/tui/theme.py +88 -0
- claude_swap/tui/widgets.py +544 -0
- claude_swap/update_check.py +509 -0
- claude_swap/usage_bars.py +208 -0
- claude_swap/usage_rows.py +160 -0
- claude_swap/usage_store.py +1429 -0
- llmswap/AGENTS.md +11 -0
- llmswap/__init__.py +3 -0
- llmswap/__main__.py +4 -0
- llmswap/cli.py +535 -0
- llmswap/config.py +101 -0
- llmswap/httpjson.py +50 -0
- llmswap/jwt.py +20 -0
- llmswap/menubar.py +218 -0
- llmswap/model.py +172 -0
- llmswap/paths.py +41 -0
- llmswap/providers/AGENTS.md +12 -0
- llmswap/providers/base.py +619 -0
- llmswap/providers/claude.py +187 -0
- llmswap/providers/codex.py +274 -0
- llmswap/providers/gemini.py +80 -0
- llmswap/providers/registry.py +30 -0
- llmswap/render.py +127 -0
- llmswap/rotate.py +102 -0
- llmswap/store.py +138 -0
- llmswap/tui.py +182 -0
- llmswap/usage_cache.py +72 -0
- llmswap/warm/plan.py +118 -0
- llmswap/warm/runner.py +175 -0
- llmswap/warm/schedule.py +264 -0
- llmswap_cli-1.0.0.dist-info/METADATA +181 -0
- llmswap_cli-1.0.0.dist-info/RECORD +78 -0
- llmswap_cli-1.0.0.dist-info/WHEEL +4 -0
- llmswap_cli-1.0.0.dist-info/entry_points.txt +5 -0
- llmswap_cli-1.0.0.dist-info/licenses/LICENSE +22 -0
|
@@ -0,0 +1,2156 @@
|
|
|
1
|
+
"""Credential storage layer for claude-swap.
|
|
2
|
+
|
|
3
|
+
Owns *where* credentials live and *how* they are read/written — the macOS
|
|
4
|
+
Keychain-vs-file routing, per-process capability detection and sticky fallback,
|
|
5
|
+
and the ``.enc``-wins backup reconciliation that landed in #66. Split out of
|
|
6
|
+
``switcher.py`` so the switcher reads as account orchestration again.
|
|
7
|
+
|
|
8
|
+
``CredentialStore`` is a leaf collaborator: it imports only the OS-primitive and
|
|
9
|
+
path helpers (``macos_keychain``, ``paths``) and never imports ``switcher``. It
|
|
10
|
+
reads its live configuration (``platform``, ``_logger``, ``credentials_dir``)
|
|
11
|
+
from a host *view* — a small data-only window onto the switcher that constructs
|
|
12
|
+
it — and must never call a switcher *method* through that host, or storage and
|
|
13
|
+
orchestration would re-couple. The store owns only its two pieces of state:
|
|
14
|
+
``_keychain_usable_cache`` (sticky, process-local) and
|
|
15
|
+
``_last_active_credentials_backend`` (for the post-switch follow-up message).
|
|
16
|
+
"""
|
|
17
|
+
|
|
18
|
+
from __future__ import annotations
|
|
19
|
+
|
|
20
|
+
import base64
|
|
21
|
+
import json
|
|
22
|
+
import logging
|
|
23
|
+
import os
|
|
24
|
+
import sys
|
|
25
|
+
import threading
|
|
26
|
+
import time
|
|
27
|
+
from pathlib import Path
|
|
28
|
+
from typing import NamedTuple, Protocol
|
|
29
|
+
|
|
30
|
+
from claude_swap import macos_keychain
|
|
31
|
+
from claude_swap.exceptions import (
|
|
32
|
+
CredentialError,
|
|
33
|
+
CredentialReadError,
|
|
34
|
+
CredentialWriteError,
|
|
35
|
+
)
|
|
36
|
+
from claude_swap.fsutil import atomic_write_text
|
|
37
|
+
from claude_swap.models import Platform
|
|
38
|
+
from claude_swap.paths import (
|
|
39
|
+
get_claude_config_home,
|
|
40
|
+
get_credentials_path,
|
|
41
|
+
get_default_claude_config_home,
|
|
42
|
+
get_global_config_path,
|
|
43
|
+
)
|
|
44
|
+
|
|
45
|
+
_logger = logging.getLogger("claude-swap")
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def _active_profile_is_default() -> bool:
|
|
49
|
+
"""Whether the active config home is the default profile's.
|
|
50
|
+
|
|
51
|
+
``CLAUDE_CONFIG_DIR`` pointed at the default profile is still the default
|
|
52
|
+
profile, so this keys on where the path resolves rather than on the
|
|
53
|
+
variable being set. Resolution also collapses symlinks, which is how a
|
|
54
|
+
profile reached through one shows up as itself.
|
|
55
|
+
|
|
56
|
+
Unresolvable paths answer False: treating an unknown profile as the default
|
|
57
|
+
is what licenses reading another account's credential, and that is the
|
|
58
|
+
failure this guards.
|
|
59
|
+
"""
|
|
60
|
+
try:
|
|
61
|
+
return (
|
|
62
|
+
get_claude_config_home().resolve()
|
|
63
|
+
== get_default_claude_config_home().resolve()
|
|
64
|
+
)
|
|
65
|
+
except Exception:
|
|
66
|
+
return False
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def _active_oauth_keychain_services() -> list[str]:
|
|
70
|
+
"""Keychain services holding the OAuth credential for the active environment.
|
|
71
|
+
|
|
72
|
+
Resolved exactly the way :meth:`ClaudeAccountSwitcher._read_capture_credentials`
|
|
73
|
+
resolves it, so the active read and the capture read agree about which
|
|
74
|
+
profile's store they are looking at. Claude (2.1.220
|
|
75
|
+
``getMacOsKeychainStorageServiceName``) sources secure storage from
|
|
76
|
+
``CLAUDE_SECURESTORAGE_CONFIG_DIR`` when that is *defined*, else
|
|
77
|
+
``CLAUDE_CONFIG_DIR``; defined-but-empty selects the *default* secure store,
|
|
78
|
+
whose item is the unsuffixed one.
|
|
79
|
+
|
|
80
|
+
Returned in try-order rather than as a single name for one case: an explicit
|
|
81
|
+
``CLAUDE_CONFIG_DIR`` naming the default profile. Claude hashes the exported
|
|
82
|
+
string, so it would write a *suffixed* item there, but a user who has always
|
|
83
|
+
used the default profile may only have the unsuffixed one. Capture handles
|
|
84
|
+
that with the same fallback (``_same_directory`` → ``_read_credentials``).
|
|
85
|
+
A defined ``CLAUDE_SECURESTORAGE_CONFIG_DIR`` gets no fallback: it names the
|
|
86
|
+
only store claude will read for this environment, so a miss means claude
|
|
87
|
+
sees a logged-out profile and reaching into another store would report a
|
|
88
|
+
credential claude is not using.
|
|
89
|
+
|
|
90
|
+
The first name is the item claude reads for this environment, and the only
|
|
91
|
+
one cswap deletes. A second name is a read-only fallback: claude started
|
|
92
|
+
without the variable keeps its own login there, which a switch in this
|
|
93
|
+
environment has neither backed up nor been asked to change.
|
|
94
|
+
"""
|
|
95
|
+
# Local import: session imports from this module, so a top-level import
|
|
96
|
+
# would close the cycle. _read_capture_credentials does the same.
|
|
97
|
+
from claude_swap.session import keychain_service_name
|
|
98
|
+
|
|
99
|
+
secure_env = os.environ.get("CLAUDE_SECURESTORAGE_CONFIG_DIR")
|
|
100
|
+
if secure_env is not None:
|
|
101
|
+
if not secure_env:
|
|
102
|
+
return [CLAUDE_CODE_KEYCHAIN_SERVICE]
|
|
103
|
+
return [keychain_service_name(secure_env)]
|
|
104
|
+
|
|
105
|
+
config_dir = os.environ.get("CLAUDE_CONFIG_DIR")
|
|
106
|
+
if not config_dir:
|
|
107
|
+
return [CLAUDE_CODE_KEYCHAIN_SERVICE]
|
|
108
|
+
|
|
109
|
+
services = [keychain_service_name(config_dir)]
|
|
110
|
+
if _active_profile_is_default():
|
|
111
|
+
services.append(CLAUDE_CODE_KEYCHAIN_SERVICE)
|
|
112
|
+
return services
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def _active_store_is_the_default_secure_store() -> bool:
|
|
116
|
+
"""Whether the unsuffixed Keychain item IS this environment's OAuth store.
|
|
117
|
+
|
|
118
|
+
The write may only touch ``CLAUDE_CODE_KEYCHAIN_SERVICE`` when claude
|
|
119
|
+
resolves that same item for this environment. Under any other profile that
|
|
120
|
+
item holds a login cswap was not asked to touch, and the switch's outgoing
|
|
121
|
+
backup reads the ACTIVE profile — so overwriting it destroys a refresh
|
|
122
|
+
token that has no copy anywhere (#206).
|
|
123
|
+
|
|
124
|
+
Keyed on the FIRST name :func:`_active_oauth_keychain_services` resolves,
|
|
125
|
+
not on membership: an explicit ``CLAUDE_CONFIG_DIR`` naming the default
|
|
126
|
+
profile also lists the unsuffixed item, but only as the read's
|
|
127
|
+
compatibility fallback for users who never had a hashed one. Claude hashes
|
|
128
|
+
whatever is exported, so writing the unsuffixed item there lands where
|
|
129
|
+
neither claude nor our own read looks first.
|
|
130
|
+
"""
|
|
131
|
+
return _active_oauth_keychain_services()[0] == CLAUDE_CODE_KEYCHAIN_SERVICE
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
# Service name for per-account backup credentials now managed via the ``security``
|
|
135
|
+
# CLI on macOS. Deliberately distinct from KEYRING_SERVICE so old keyring items and
|
|
136
|
+
# new security items coexist during migration (safe write → verify → delete).
|
|
137
|
+
SECURITY_SERVICE = "claude-swap"
|
|
138
|
+
|
|
139
|
+
# Service name of Claude Code's *active* OAuth credential in the macOS Keychain
|
|
140
|
+
# (read by Claude Code itself; we read/write it when switching accounts).
|
|
141
|
+
CLAUDE_CODE_KEYCHAIN_SERVICE = "Claude Code-credentials"
|
|
142
|
+
|
|
143
|
+
# Service name of Claude Code's *active* managed API key (``/login`` with an
|
|
144
|
+
# ``sk-ant-…`` key) in the macOS Keychain. Distinct from the OAuth service above
|
|
145
|
+
# (no ``-credentials`` suffix); Claude Code resolves it on a separate auth axis
|
|
146
|
+
# (``getApiKeyFromConfigOrMacOSKeychain``). On non-macOS the managed key instead
|
|
147
|
+
# lives in ``~/.claude.json`` as ``primaryApiKey`` (see below).
|
|
148
|
+
CLAUDE_CODE_MANAGED_KEYCHAIN_SERVICE = "Claude Code"
|
|
149
|
+
|
|
150
|
+
# Bounded retry for the active OAuth-credential Keychain read. A locked/contended
|
|
151
|
+
# login Keychain can fail a single `security` call transiently — e.g. just after
|
|
152
|
+
# wake while the keychain is still settling, or under contention with Claude Code's
|
|
153
|
+
# own statusline polling the same item — and a second attempt a moment later
|
|
154
|
+
# usually succeeds. This is an I/O backoff between retries of an external CLI, NOT
|
|
155
|
+
# a sleep papering over an internal race.
|
|
156
|
+
_ACTIVE_READ_ATTEMPTS = 2
|
|
157
|
+
_ACTIVE_READ_RETRY_DELAY = 0.3 # seconds between attempts
|
|
158
|
+
|
|
159
|
+
# After a Keychain failure the store drops to file mode so one CLI invocation
|
|
160
|
+
# can't split-brain between backends. A long-running daemon (menu bar / TUI)
|
|
161
|
+
# instead re-probes this long after the last failure: far longer than any CLI
|
|
162
|
+
# command runs (so the guarantee holds — a sub-second command never re-probes),
|
|
163
|
+
# short enough that a transient `security` timeout self-heals within a minute
|
|
164
|
+
# instead of disabling the Keychain for the whole process lifetime.
|
|
165
|
+
KEYCHAIN_RECHECK_COOLDOWN_S = 60.0
|
|
166
|
+
|
|
167
|
+
# Display/eligibility reads of per-account BACKUP credentials may be served
|
|
168
|
+
# from a short-lived per-slot cache (`_kc_read_backup(cached=True)`): a
|
|
169
|
+
# dashboard repainting every few seconds must not spawn `security` for every
|
|
170
|
+
# slot on every pass (#496: ~8 spawns/s at 11 accounts, and a stream of killed
|
|
171
|
+
# unlock dialogs once the login keychain locks). Below the usage store's fetch
|
|
172
|
+
# floor (poll_policy.SERVE_TTL_S, 180 s), so a slot's next fetch always
|
|
173
|
+
# re-reads after a rotation that happened inside another process's fetch —
|
|
174
|
+
# and the consume gate re-reads under its lock regardless. Bounds the
|
|
175
|
+
# display's lag behind an external rotation to a minute.
|
|
176
|
+
BACKUP_READ_CACHE_TTL_S = 60.0
|
|
177
|
+
|
|
178
|
+
|
|
179
|
+
class KeychainBackedOff(macos_keychain.KeychainError):
|
|
180
|
+
"""A backup read skipped inside the failure cooldown — not a new failure.
|
|
181
|
+
|
|
182
|
+
Raised by ``_kc_read_backup`` instead of spawning ``security``. Still a
|
|
183
|
+
``KeychainError``, so every existing handler keeps treating it as
|
|
184
|
+
"unreadable" (the verdict must not change); distinct, so the normal reader
|
|
185
|
+
can stay quiet about it — logging each skip as a failure meant 31 warnings
|
|
186
|
+
per snapshot at 11 accounts, ~600 a minute on the TUI's 3 s tick. The
|
|
187
|
+
cooldown announces itself once, when the first read skips.
|
|
188
|
+
"""
|
|
189
|
+
|
|
190
|
+
|
|
191
|
+
class ActiveCredentials(NamedTuple):
|
|
192
|
+
"""Outcome of reading Claude Code's active credential.
|
|
193
|
+
|
|
194
|
+
``value`` is the credential string (OAuth JSON or a raw managed key), ``""``
|
|
195
|
+
when none exists in any backend, or ``None`` on a plaintext-file read error.
|
|
196
|
+
``keychain_unavailable`` is True only when the macOS OAuth Keychain read failed
|
|
197
|
+
(locked / denied / timeout) and nothing else covered it — letting callers
|
|
198
|
+
distinguish a transiently unreadable Keychain from a genuinely empty slot,
|
|
199
|
+
instead of collapsing both into a misleading "no credentials".
|
|
200
|
+
``degraded`` is True whenever the OAuth Keychain read failed, even when a
|
|
201
|
+
fallback covered it: the bytes served may then be a stale generation (on
|
|
202
|
+
macOS Claude Code rotates keychain-only, so the plaintext file can lag).
|
|
203
|
+
A degraded credential may be adopted or served, but its refresh token
|
|
204
|
+
must never be consumed — POSTing a superseded one-time rt yields
|
|
205
|
+
invalid_grant and a false dead-token strike on a live account.
|
|
206
|
+
"""
|
|
207
|
+
|
|
208
|
+
value: str | None
|
|
209
|
+
keychain_unavailable: bool
|
|
210
|
+
degraded: bool = False
|
|
211
|
+
|
|
212
|
+
|
|
213
|
+
# Prefixes of Anthropic OAuth tokens: the access/setup-token and the refresh token.
|
|
214
|
+
# A bare value carrying one is OAuth material, never a managed API key, however it
|
|
215
|
+
# arrived. Mirrors Claude Code's own ``isAnthropicOAuthToken`` (``sk-ant-oat`` is
|
|
216
|
+
# the only prefix it ever tests for; its API-key validation is charset-only).
|
|
217
|
+
_OAUTH_TOKEN_PREFIXES = ("sk-ant-oat", "sk-ant-ort")
|
|
218
|
+
|
|
219
|
+
|
|
220
|
+
def looks_like_api_key(credentials: str | None) -> bool:
|
|
221
|
+
"""Whether a stored active credential is a raw managed API key vs OAuth JSON.
|
|
222
|
+
|
|
223
|
+
A managed key is a bare ``sk-ant-…`` string, while every OAuth/setup-token
|
|
224
|
+
credential is a JSON object (``{"claudeAiOauth": …}``). The Console issues
|
|
225
|
+
several key families — legacy workspace keys (``sk-ant-api03-…``), personal
|
|
226
|
+
keys (``sk-ant-usr-…``) and service-account keys — and Claude Code never
|
|
227
|
+
inspects the prefix of a key it stores, so neither does this: any bare
|
|
228
|
+
``sk-ant-`` value is a key UNLESS it carries an OAuth token prefix. That
|
|
229
|
+
exclusion (rather than an allowlist of key prefixes) is what keeps a raw or
|
|
230
|
+
garbled ``sk-ant-oat…`` setup token from ever being misclassified — and
|
|
231
|
+
activated — as an API key; an allowlist instead wrapped every newer key family
|
|
232
|
+
as a setup-token, which is the #465 failure.
|
|
233
|
+
"""
|
|
234
|
+
if not credentials:
|
|
235
|
+
return False
|
|
236
|
+
text = credentials.strip()
|
|
237
|
+
if text.startswith("{"):
|
|
238
|
+
return False
|
|
239
|
+
return text.startswith("sk-ant-") and not text.startswith(_OAUTH_TOKEN_PREFIXES)
|
|
240
|
+
|
|
241
|
+
|
|
242
|
+
def _credential_object(credentials: str | None) -> dict | None:
|
|
243
|
+
"""Parse a JSON credential object, excluding managed API keys."""
|
|
244
|
+
if not credentials or looks_like_api_key(credentials):
|
|
245
|
+
return None
|
|
246
|
+
try:
|
|
247
|
+
data = json.loads(credentials)
|
|
248
|
+
except (json.JSONDecodeError, TypeError):
|
|
249
|
+
return None
|
|
250
|
+
return data if isinstance(data, dict) else None
|
|
251
|
+
|
|
252
|
+
|
|
253
|
+
# The credential object's siblings of claudeAiOauth are not uniformly owned:
|
|
254
|
+
# these keys hold machine-shared OAuth integrations that rotate independently
|
|
255
|
+
# of any account slot, so on activation the live copy is authoritative.
|
|
256
|
+
# Everything else — known (trustedDeviceToken is enrolled per-account and
|
|
257
|
+
# re-enrolled on every login) or unknown — stays with the target slot: a
|
|
258
|
+
# stale restore of an unlisted shared field merely re-prompts for auth,
|
|
259
|
+
# while carrying a live account-bound field across a switch would present
|
|
260
|
+
# one account's credential under another. keychainOverflow (Claude Code
|
|
261
|
+
# 2.1.331+) points at a machine-level Keychain item cswap never swaps. It
|
|
262
|
+
# follows the machine only while it holds nothing but slot and key; otherwise
|
|
263
|
+
# the target slot's own pointer is kept as stored.
|
|
264
|
+
SHARED_CREDENTIAL_KEYS = frozenset({
|
|
265
|
+
"mcpOAuth",
|
|
266
|
+
"mcpOAuthClientConfig",
|
|
267
|
+
"mcpXaaIdp",
|
|
268
|
+
"mcpXaaIdpConfig",
|
|
269
|
+
"pluginSecrets",
|
|
270
|
+
"keychainOverflow",
|
|
271
|
+
})
|
|
272
|
+
|
|
273
|
+
# Account-scoped siblings cswap knows about, named so the unrecognized-key
|
|
274
|
+
# probe below doesn't flag them: claudeAiOauth is the login itself,
|
|
275
|
+
# trustedDeviceToken is enrolled per (device, account) at /login.
|
|
276
|
+
ACCOUNT_CREDENTIAL_KEYS = frozenset({
|
|
277
|
+
"claudeAiOauth",
|
|
278
|
+
"trustedDeviceToken",
|
|
279
|
+
})
|
|
280
|
+
|
|
281
|
+
|
|
282
|
+
def shared_credential_fields(credentials: str | None) -> dict | None:
|
|
283
|
+
"""Return the machine-shared fields of a Claude OAuth credential object.
|
|
284
|
+
|
|
285
|
+
Only the ``SHARED_CREDENTIAL_KEYS`` allowlist is machine-shared; other
|
|
286
|
+
siblings of ``claudeAiOauth`` are account-scoped or unknown and stay
|
|
287
|
+
slot-owned. ``None`` means the input is not a JSON credential object
|
|
288
|
+
(missing, malformed, or a managed API key). A dictionary — including
|
|
289
|
+
``{}`` — is authoritative for every allowlisted key: a key absent here
|
|
290
|
+
is absent from the machine's current shared state.
|
|
291
|
+
"""
|
|
292
|
+
data = _credential_object(credentials)
|
|
293
|
+
if data is None:
|
|
294
|
+
return None
|
|
295
|
+
if "claudeAiOauth" in data:
|
|
296
|
+
# A sibling key cswap doesn't know defaults to slot-owned (fails
|
|
297
|
+
# safe), but silently: if Claude Code grows a new *shared* key,
|
|
298
|
+
# that default quietly reintroduces the stale-restore papercut for
|
|
299
|
+
# it — leave a trace so it gets noticed.
|
|
300
|
+
unrecognized = data.keys() - SHARED_CREDENTIAL_KEYS - ACCOUNT_CREDENTIAL_KEYS
|
|
301
|
+
if unrecognized:
|
|
302
|
+
_logger.debug(
|
|
303
|
+
"Live credential has sibling keys cswap does not recognize "
|
|
304
|
+
"(a newer Claude Code?), treating them as slot-owned: %s",
|
|
305
|
+
sorted(unrecognized),
|
|
306
|
+
)
|
|
307
|
+
return {key: data[key] for key in SHARED_CREDENTIAL_KEYS if key in data}
|
|
308
|
+
|
|
309
|
+
|
|
310
|
+
def merge_shared_credential_fields(
|
|
311
|
+
target_credentials: str, shared_fields: dict
|
|
312
|
+
) -> str:
|
|
313
|
+
"""Compose a target Claude login with the machine's shared fields.
|
|
314
|
+
|
|
315
|
+
The allowlisted keys are wholly live-owned, presence and absence alike:
|
|
316
|
+
the target's copies are discarded and ``shared_fields`` supplies the
|
|
317
|
+
current generation, so a shared key the machine no longer holds is not
|
|
318
|
+
resurrected from the slot's snapshot. The exception is a
|
|
319
|
+
``keychainOverflow`` pointer on either side that carries more than
|
|
320
|
+
``slot`` and ``key`` (or is not a dict): the target's own pointer, or
|
|
321
|
+
none, is kept as stored. All other target fields pass
|
|
322
|
+
through untouched. Returns ``target_credentials`` unchanged when it is
|
|
323
|
+
not a JSON credential object carrying a Claude login (managed API keys
|
|
324
|
+
and opaque legacy shapes stay activatable verbatim).
|
|
325
|
+
"""
|
|
326
|
+
target = _credential_object(target_credentials)
|
|
327
|
+
if target is None or "claudeAiOauth" not in target:
|
|
328
|
+
return target_credentials
|
|
329
|
+
|
|
330
|
+
composed = {
|
|
331
|
+
key: value
|
|
332
|
+
for key, value in target.items()
|
|
333
|
+
if key not in SHARED_CREDENTIAL_KEYS
|
|
334
|
+
}
|
|
335
|
+
composed.update(shared_fields)
|
|
336
|
+
pointers = (
|
|
337
|
+
shared_fields.get("keychainOverflow", {}),
|
|
338
|
+
target.get("keychainOverflow", {}),
|
|
339
|
+
)
|
|
340
|
+
if any(
|
|
341
|
+
not isinstance(p, dict) or not p.keys() <= {"slot", "key"}
|
|
342
|
+
for p in pointers
|
|
343
|
+
):
|
|
344
|
+
composed.pop("keychainOverflow", None)
|
|
345
|
+
if "keychainOverflow" in target:
|
|
346
|
+
composed["keychainOverflow"] = target["keychainOverflow"]
|
|
347
|
+
return json.dumps(composed)
|
|
348
|
+
|
|
349
|
+
|
|
350
|
+
def approved_form(api_key: str) -> str:
|
|
351
|
+
"""The value Claude Code stores in ``customApiKeyResponses.approved``.
|
|
352
|
+
|
|
353
|
+
Mirrors Claude Code's ``normalizeApiKeyForConfig`` (``apiKey.slice(-20)``): the
|
|
354
|
+
last 20 chars. Storing anything else makes Claude Code's "is this key approved?"
|
|
355
|
+
check miss and re-prompt the user to approve the key.
|
|
356
|
+
"""
|
|
357
|
+
return api_key.strip()[-20:]
|
|
358
|
+
|
|
359
|
+
|
|
360
|
+
class _StoreHost(Protocol):
|
|
361
|
+
"""The live configuration view ``CredentialStore`` reads from its owner.
|
|
362
|
+
|
|
363
|
+
Data only — the store reads these attributes at call time so post-construction
|
|
364
|
+
overrides (e.g. tests setting ``switcher.platform``) are honored. The store
|
|
365
|
+
must not reach for any *method* here.
|
|
366
|
+
"""
|
|
367
|
+
|
|
368
|
+
platform: Platform
|
|
369
|
+
credentials_dir: Path
|
|
370
|
+
# The account registry (``sequence.json``): its stat is the "did the
|
|
371
|
+
# account set change?" signal the backup read cache is keyed on.
|
|
372
|
+
sequence_file: Path
|
|
373
|
+
_logger: logging.Logger
|
|
374
|
+
|
|
375
|
+
|
|
376
|
+
class CredentialStore:
|
|
377
|
+
"""Owns the active and per-account backup credential stores.
|
|
378
|
+
|
|
379
|
+
One store per switcher: the capability cache is per-process, learned from real
|
|
380
|
+
``security`` calls, and a fresh process re-evaluates from scratch.
|
|
381
|
+
"""
|
|
382
|
+
|
|
383
|
+
def __init__(self, host: _StoreHost):
|
|
384
|
+
self._host = host
|
|
385
|
+
# macOS Keychain usability, learned per-process from real `security`
|
|
386
|
+
# calls (see _kc_call / _use_keychain). None = not yet probed; True/False
|
|
387
|
+
# once an op has run. _last_active_credentials_backend records where the
|
|
388
|
+
# most recent active-credential write landed ("keychain" | "file"), for the
|
|
389
|
+
# post-switch follow-up message.
|
|
390
|
+
self._keychain_usable_cache: bool | None = None
|
|
391
|
+
# When file mode was entered by a real failure, the epoch after which to
|
|
392
|
+
# re-probe the Keychain (see KEYCHAIN_RECHECK_COOLDOWN_S). 0.0 = no
|
|
393
|
+
# pending re-probe (never failed, or forced to file mode deliberately).
|
|
394
|
+
self._keychain_disabled_until: float = 0.0
|
|
395
|
+
# Whether file mode was CHOSEN by us (a write fell back and we
|
|
396
|
+
# deleted the Keychain item) rather than forced by a failed read. Both
|
|
397
|
+
# stick, but only the failure means the file may be behind Claude
|
|
398
|
+
# Code's own writes — see _read_active_credentials.
|
|
399
|
+
self._file_mode_is_ours: bool = False
|
|
400
|
+
# Whether any Keychain op has actually FAILED this process. Distinct
|
|
401
|
+
# from _keychain_usable_cache, which is where ops should be ROUTED and
|
|
402
|
+
# which _pin_file_mode sets deliberately: a routing choice must not
|
|
403
|
+
# erase an observation. See _keychain_unreadable.
|
|
404
|
+
self._keychain_op_failed: bool = False
|
|
405
|
+
# Set by the ACTIVE OAuth read when THAT read could not reach the
|
|
406
|
+
# Keychain. Per-item, not per-process: `_kc_call` clears
|
|
407
|
+
# `_keychain_op_failed` on any success, and a backup read for an idle
|
|
408
|
+
# slot goes straight through it — so one readable backup erased the
|
|
409
|
+
# verdict recorded when the active read failed, and `degraded` flipped
|
|
410
|
+
# False while the plaintext file still held the superseded generation.
|
|
411
|
+
# "The Keychain answers" and "this active read succeeded" are different
|
|
412
|
+
# facts; `degraded` needs the second.
|
|
413
|
+
self._active_read_failed: bool = False
|
|
414
|
+
# What _pin_file_mode OBSERVED about the residual active Keychain item.
|
|
415
|
+
# None: never pinned. True: the delete returned, so nothing can shadow
|
|
416
|
+
# the file. False: the delete could not run, so the file may be the
|
|
417
|
+
# superseded generation. A fact about THIS item, which is why neither
|
|
418
|
+
# flag above can stand in for it.
|
|
419
|
+
self._residual_verdict: bool | None = None
|
|
420
|
+
# Whether the current pin came from the OAuth write fallback, i.e. it
|
|
421
|
+
# points at ``.credentials.json``. The managed-key fallback pins too,
|
|
422
|
+
# but onto ``primaryApiKey`` — a different file, and no reason to
|
|
423
|
+
# expect the OAuth one. See _lift_pin_if_oauth_file_gone.
|
|
424
|
+
self._pinned_to_oauth_file: bool = False
|
|
425
|
+
# The menu bar's display worker and its engine thread share one store;
|
|
426
|
+
# the lift's check-then-reset must not interleave with a fresh pin.
|
|
427
|
+
# Held around every pin and every flag change outside __init__; never
|
|
428
|
+
# taken inside _pin_file_mode itself, so callers can hold it across it.
|
|
429
|
+
self._pin_lock = threading.Lock()
|
|
430
|
+
self._last_active_credentials_backend: str | None = None
|
|
431
|
+
# Per-slot cache for DISPLAY reads of backup Keychain items (see
|
|
432
|
+
# `_kc_read_backup`): (num, email) -> (value or "", monotonic read_at).
|
|
433
|
+
# The lock guards dict and epoch; the epoch voids fills that raced a
|
|
434
|
+
# drop; the generation is sequence.json's (inode, mtime_ns, size) the
|
|
435
|
+
# entries were read under.
|
|
436
|
+
self._backup_read_cache: dict[tuple[str, str], tuple[str, float]] = {}
|
|
437
|
+
self._backup_read_cache_lock = threading.Lock()
|
|
438
|
+
self._backup_read_cache_epoch = 0
|
|
439
|
+
self._backup_read_cache_gen: tuple[int, int, int] | None = None
|
|
440
|
+
# The cooldown deadline already announced in the log (see
|
|
441
|
+
# KeychainBackedOff): one line per cooldown, not one per skipped read.
|
|
442
|
+
self._backoff_announced_until: float = 0.0
|
|
443
|
+
|
|
444
|
+
def _kc_call(self, fn, *args):
|
|
445
|
+
"""Run a ``macos_keychain`` wrapper call, learning Keychain usability.
|
|
446
|
+
|
|
447
|
+
A success (including ``get_password`` returning ``None`` for a missing
|
|
448
|
+
item) marks the Keychain usable — but only flips the cache ``None -> True``,
|
|
449
|
+
never ``False -> True``: once a call has failed this run we stay in file
|
|
450
|
+
mode so one invocation can't split-brain between backends. A
|
|
451
|
+
``KeychainError`` / ``TimeoutExpired`` / ``OSError`` (binary missing) marks
|
|
452
|
+
it unusable and re-raises so the caller can fall back. Only those three are
|
|
453
|
+
caught — a programming error propagates.
|
|
454
|
+
|
|
455
|
+
Do NOT route ``item_exists`` through here: it returns ``False`` for both
|
|
456
|
+
"absent" and "failed", so a timeout would be misread as a usable Keychain.
|
|
457
|
+
"""
|
|
458
|
+
try:
|
|
459
|
+
result = fn(*args)
|
|
460
|
+
except macos_keychain.KEYCHAIN_ERRORS:
|
|
461
|
+
# A Keychain op FAILED. Recorded separately from the capability
|
|
462
|
+
# cache because that cache is a routing decision others overwrite —
|
|
463
|
+
# `_pin_file_mode` clears it deliberately — while this is an
|
|
464
|
+
# observation, and an observation cannot be undone by a later
|
|
465
|
+
# choice. See `_keychain_unreadable`.
|
|
466
|
+
self._keychain_op_failed = True
|
|
467
|
+
self._keychain_usable_cache = False
|
|
468
|
+
# Monotonic so a wall-clock jump can't expire the cooldown early/late.
|
|
469
|
+
self._keychain_disabled_until = (
|
|
470
|
+
time.monotonic() + KEYCHAIN_RECHECK_COOLDOWN_S
|
|
471
|
+
)
|
|
472
|
+
raise
|
|
473
|
+
# A SUCCESS is an observation too, and it is the newer one. Recording
|
|
474
|
+
# only failures made `_keychain_op_failed` monotone, and the cooldown
|
|
475
|
+
# re-probe that normally masks a stale one is zeroed by
|
|
476
|
+
# `_pin_file_mode` — so one transient timeout became permanent for the
|
|
477
|
+
# process the moment any later write fell back. Measured: a read times
|
|
478
|
+
# out, the Keychain recovers and the cooldown lapses (verified
|
|
479
|
+
# `unreadable is False`), then a write pins and it is True forever,
|
|
480
|
+
# with `degraded=True`, "keychain unavailable" on every usage pass, and
|
|
481
|
+
# `cswap add` refused.
|
|
482
|
+
#
|
|
483
|
+
# Cleared unconditionally rather than only when the cache was None: the
|
|
484
|
+
# cache is a ROUTING decision (which backend to use, deliberately
|
|
485
|
+
# sticky), this is a FACT about whether the Keychain answers. A call
|
|
486
|
+
# that just returned is proof it does.
|
|
487
|
+
self._keychain_op_failed = False
|
|
488
|
+
if self._keychain_usable_cache is None:
|
|
489
|
+
self._keychain_usable_cache = True
|
|
490
|
+
return result
|
|
491
|
+
|
|
492
|
+
def _use_keychain(self) -> bool:
|
|
493
|
+
"""Whether credential ops should target the macOS Keychain right now.
|
|
494
|
+
|
|
495
|
+
``False`` off macOS. On macOS, ``True`` until a Keychain op fails, which
|
|
496
|
+
drops to file mode. That failure records a re-probe deadline
|
|
497
|
+
(``KEYCHAIN_RECHECK_COOLDOWN_S``): within one CLI invocation the deadline
|
|
498
|
+
never passes, so a command can't split-brain between backends, but a
|
|
499
|
+
long-running daemon re-probes once the cooldown elapses so a transient
|
|
500
|
+
``security`` timeout self-heals instead of sticking for the whole process.
|
|
501
|
+
A pinned file mode with no deadline (0.0) stays sticky — see
|
|
502
|
+
:meth:`_pin_file_mode` for why a write fallback must never re-probe.
|
|
503
|
+
"""
|
|
504
|
+
if self._host.platform != Platform.MACOS:
|
|
505
|
+
return False
|
|
506
|
+
if (
|
|
507
|
+
self._keychain_usable_cache is False
|
|
508
|
+
and self._keychain_disabled_until
|
|
509
|
+
and time.monotonic() >= self._keychain_disabled_until
|
|
510
|
+
):
|
|
511
|
+
self._keychain_usable_cache = None # cooldown elapsed → re-probe
|
|
512
|
+
self._keychain_disabled_until = 0.0
|
|
513
|
+
return self._keychain_usable_cache is not False
|
|
514
|
+
|
|
515
|
+
def _pin_file_mode(self, *, residual_cleared: bool) -> None:
|
|
516
|
+
"""Pin file mode for the rest of the process — no Keychain re-probe.
|
|
517
|
+
|
|
518
|
+
A read timeout is safe to recover from (re-probe on cooldown), but an
|
|
519
|
+
active-credential *write* that falls back to the file is not: its
|
|
520
|
+
best-effort delete of the old Keychain item may have failed, leaving a
|
|
521
|
+
stale entry. Re-probing later could read that residual and show the wrong
|
|
522
|
+
account, so once a write falls back we never re-probe onto a Keychain we
|
|
523
|
+
could not verify-clear. Clears any re-probe deadline a prior read
|
|
524
|
+
scheduled, which could otherwise still be pending.
|
|
525
|
+
|
|
526
|
+
``residual_cleared`` is the caller's OBSERVATION of that delete. True:
|
|
527
|
+
nothing can shadow the file, so it genuinely is the authority, and the
|
|
528
|
+
two failure flags are settled — whatever failed before cannot bear on a
|
|
529
|
+
file nothing can shadow. False: a residual may survive, and that stays
|
|
530
|
+
true however many unrelated Keychain items answer afterwards. Required,
|
|
531
|
+
with no default — every call site has just run the delete, and a default
|
|
532
|
+
is how an observation gets dropped in favour of a flag.
|
|
533
|
+
|
|
534
|
+
A True verdict settles the PAST, not the future.
|
|
535
|
+
"""
|
|
536
|
+
self._keychain_usable_cache = False
|
|
537
|
+
self._keychain_disabled_until = 0.0
|
|
538
|
+
self._file_mode_is_ours = True
|
|
539
|
+
self._residual_verdict = residual_cleared
|
|
540
|
+
# Only the OAuth write fallback may mark a pin as liftable, and it does
|
|
541
|
+
# so right after this call. Every other pin (the managed-key fallback,
|
|
542
|
+
# whose residual is the "Claude Code" item) resets it here, so a stale
|
|
543
|
+
# True can never lift a pin it does not describe.
|
|
544
|
+
self._pinned_to_oauth_file = False
|
|
545
|
+
if residual_cleared:
|
|
546
|
+
# Settle what happened before; later failures are the flags'
|
|
547
|
+
# question again. `_kc_call` re-arms the cooldown on any failure
|
|
548
|
+
# with no pin check, and backup reads reach it without consulting
|
|
549
|
+
# `_use_keychain`, so the active read IS reachable after a pin.
|
|
550
|
+
# Measured: a stored True made a genuine later failure read
|
|
551
|
+
# degraded=False and disarmed the capture guard.
|
|
552
|
+
self._keychain_op_failed = False
|
|
553
|
+
self._active_read_failed = False
|
|
554
|
+
|
|
555
|
+
def _lift_pin_if_oauth_file_gone(self) -> None:
|
|
556
|
+
"""End a pinned file mode once the file it points at no longer exists.
|
|
557
|
+
|
|
558
|
+
The pin is a claim about ``.credentials.json``: our fallback write put
|
|
559
|
+
the credential there, and a residual Keychain item might shadow it, so
|
|
560
|
+
this process keeps reading the file. With the file gone there is
|
|
561
|
+
nothing left to protect — and nothing left to read. Claude Code removes
|
|
562
|
+
the plaintext file when it stores a rotation in the Keychain, so on a
|
|
563
|
+
long-running process (menu bar, ``cswap auto``, TUI) the pin outlives
|
|
564
|
+
its file within hours, and from then on every active read returns ""
|
|
565
|
+
for the life of the process: usage is unknown, auto-switch fails over
|
|
566
|
+
into a switch that refuses ("credential is empty"), and only a fresh
|
|
567
|
+
process recovers.
|
|
568
|
+
|
|
569
|
+
A residual is not a reason to stay pinned here either. Claude Code
|
|
570
|
+
reads Keychain-first, so with our file gone a surviving item is what
|
|
571
|
+
Claude Code itself is using — the live credential by definition.
|
|
572
|
+
|
|
573
|
+
This only RE-ASKS the Keychain. It records no verdict: the read that
|
|
574
|
+
follows goes through ``_kc_call`` like any other and reports its own
|
|
575
|
+
outcome, including a Keychain that is still unreadable.
|
|
576
|
+
"""
|
|
577
|
+
if not self._pinned_to_oauth_file:
|
|
578
|
+
return
|
|
579
|
+
with self._pin_lock:
|
|
580
|
+
if not self._pinned_to_oauth_file or self._use_keychain():
|
|
581
|
+
return
|
|
582
|
+
if self._keychain_disabled_until:
|
|
583
|
+
return # a later failure re-armed the cooldown; let it run
|
|
584
|
+
try:
|
|
585
|
+
cred_file = get_credentials_path()
|
|
586
|
+
if cred_file.exists() and cred_file.stat().st_size > 0:
|
|
587
|
+
return
|
|
588
|
+
except OSError:
|
|
589
|
+
return # cannot tell; the pin is the conservative answer
|
|
590
|
+
self._keychain_usable_cache = None
|
|
591
|
+
self._file_mode_is_ours = False
|
|
592
|
+
self._pinned_to_oauth_file = False
|
|
593
|
+
self._residual_verdict = None
|
|
594
|
+
self._host._logger.info(
|
|
595
|
+
"Active credentials file is gone; reading the Keychain again "
|
|
596
|
+
"(file mode had been pinned by a failed Keychain write)."
|
|
597
|
+
)
|
|
598
|
+
|
|
599
|
+
@property
|
|
600
|
+
def _keychain_unreadable(self) -> bool:
|
|
601
|
+
"""The Keychain cannot be asked — so an empty read proves nothing.
|
|
602
|
+
|
|
603
|
+
True only when a Keychain op FAILED. A file mode :meth:`_pin_file_mode`
|
|
604
|
+
chose is excluded: nothing failed there, we wrote the credential to the
|
|
605
|
+
file deliberately, and that file is the authority — an empty read means
|
|
606
|
+
the slot really is empty.
|
|
607
|
+
|
|
608
|
+
One predicate, because the two facts have been conflated once per site
|
|
609
|
+
that spelled them out separately: every caller that means "unreadable"
|
|
610
|
+
must ask here rather than read ``_keychain_usable_cache`` raw. The
|
|
611
|
+
platform check belongs here for the same reason — off macOS there is no
|
|
612
|
+
Keychain to be unreadable, and only every call path being macOS-gated
|
|
613
|
+
keeps the cache at ``None`` there today.
|
|
614
|
+
|
|
615
|
+
Asks through :meth:`_use_keychain` rather than the raw cache, because
|
|
616
|
+
the cooldown re-probe lives there and the BACKUP read path never calls
|
|
617
|
+
it: ``_read_account_credentials`` goes straight to ``_kc_read_backup``.
|
|
618
|
+
Reading the flag raw made a single transient failure permanent for the
|
|
619
|
+
process on exactly the paths that matter — a genuinely empty slot kept
|
|
620
|
+
reporting "unreadable, do not re-add" (a dead end) and the consume gate
|
|
621
|
+
kept deferring ``transient`` long after the Keychain answered again.
|
|
622
|
+
A pinned file mode is unaffected: its deadline is 0.0, so
|
|
623
|
+
``_use_keychain`` never re-probes it.
|
|
624
|
+
"""
|
|
625
|
+
if self._host.platform != Platform.MACOS:
|
|
626
|
+
return False
|
|
627
|
+
if self._use_keychain(): # may clear a lapsed cooldown
|
|
628
|
+
return False
|
|
629
|
+
# THE QUESTION IS WHETHER AN OP FAILED AND HAS NOT SINCE SUCCEEDED.
|
|
630
|
+
#
|
|
631
|
+
# It used to be `not self._file_mode_is_ours` — a pinned file mode read
|
|
632
|
+
# as "nothing failed". On macOS that inverts the fact: the pin is
|
|
633
|
+
# reachable ONLY THROUGH a Keychain op that just failed, since both
|
|
634
|
+
# `_pin_file_mode` call sites are in the fallback branch of a write that
|
|
635
|
+
# raised. Measured, identical world, one fallback write apart:
|
|
636
|
+
#
|
|
637
|
+
# state A degraded=True sentinel='keychain unavailable'
|
|
638
|
+
# state B degraded=False sentinel='no credentials'
|
|
639
|
+
#
|
|
640
|
+
# `degraded=False` disarms `_refuse_degraded_capture`, and the sentinel
|
|
641
|
+
# sends the user to re-add a slot whose backup is alive but unread. The
|
|
642
|
+
# pin's own best-effort `_delete_active_keychain_entry()` failed too, so
|
|
643
|
+
# a residual survives and Claude Code reads Keychain-first: our file is
|
|
644
|
+
# the superseded generation, POSTed with the guard off.
|
|
645
|
+
#
|
|
646
|
+
# `_file_mode_is_ours` is NOT part of the answer any more, and saying so
|
|
647
|
+
# matters: on macOS it is True only where `_keychain_op_failed` is also
|
|
648
|
+
# True (measured across every production route to the pin — the OAuth
|
|
649
|
+
# write fallback and the managed-key write fallback, with and without a
|
|
650
|
+
# prior read failure), so `or not self._file_mode_is_ours` was a
|
|
651
|
+
# disjunct that could never fire. Dropping it changes no test. It stays
|
|
652
|
+
# in `_read_active_credentials`, where it answers its own question —
|
|
653
|
+
# WHY we are in file mode — for the deliberate non-macOS and API-key
|
|
654
|
+
# paths where nothing failed and the file really is the authority.
|
|
655
|
+
return self._keychain_op_failed
|
|
656
|
+
|
|
657
|
+
def _read_credentials(self) -> str | None:
|
|
658
|
+
"""Read Claude Code's active credential — OAuth *or* managed API key (value).
|
|
659
|
+
|
|
660
|
+
Thin wrapper over :meth:`_read_active_credentials` preserving the historic
|
|
661
|
+
``str | None`` contract the switch paths rely on: credential string if
|
|
662
|
+
found, ``""`` if not found, ``None`` on a file read error.
|
|
663
|
+
"""
|
|
664
|
+
return self._read_active_credentials().value
|
|
665
|
+
|
|
666
|
+
def _read_active_oauth_keychain(self) -> tuple[str | None, bool]:
|
|
667
|
+
"""Read the OAuth Keychain item claude reads for this environment.
|
|
668
|
+
|
|
669
|
+
That is the first name :func:`_active_oauth_keychain_services` resolves.
|
|
670
|
+
|
|
671
|
+
Returns ``(value, failed)``: ``value`` is the credential string, or
|
|
672
|
+
``None`` when the item was absent (rc-44) or the Keychain was
|
|
673
|
+
unreadable. ``failed`` is True only for unreadable.
|
|
674
|
+
"""
|
|
675
|
+
value, failed = self._read_one_oauth_keychain(
|
|
676
|
+
_active_oauth_keychain_services()[0]
|
|
677
|
+
)
|
|
678
|
+
return (value or None), failed
|
|
679
|
+
|
|
680
|
+
def _read_fallback_oauth_keychain(self) -> tuple[str | None, bool]:
|
|
681
|
+
"""Read the fallback OAuth Keychain item, when this environment has one.
|
|
682
|
+
|
|
683
|
+
Only an explicit ``CLAUDE_CONFIG_DIR`` naming the default profile has
|
|
684
|
+
one: the unsuffixed item, for a user who has never logged in with the
|
|
685
|
+
variable set. See :func:`_active_oauth_keychain_services`. Returns
|
|
686
|
+
``(value, failed)`` as :meth:`_read_active_oauth_keychain` does.
|
|
687
|
+
"""
|
|
688
|
+
for service in _active_oauth_keychain_services()[1:]:
|
|
689
|
+
value, failed = self._read_one_oauth_keychain(service)
|
|
690
|
+
if value:
|
|
691
|
+
return value, False
|
|
692
|
+
if failed:
|
|
693
|
+
return None, True
|
|
694
|
+
return None, False
|
|
695
|
+
|
|
696
|
+
def _read_one_oauth_keychain(self, service: str) -> tuple[str | None, bool]:
|
|
697
|
+
"""Read one OAuth Keychain item with a bounded retry.
|
|
698
|
+
|
|
699
|
+
Returns ``(value, failed)``. ``value`` is the credential string, or
|
|
700
|
+
``None`` when the item is absent (rc-44) or unreadable. ``failed`` is True
|
|
701
|
+
only when *every* attempt raised a KeychainError (locked / denied /
|
|
702
|
+
timeout); a genuinely absent item (rc-44, returned as ``None`` without
|
|
703
|
+
raising) reports ``failed=False`` and is not retried. The retry rides out
|
|
704
|
+
a transient lock/contention — it does not paper over an internal race.
|
|
705
|
+
"""
|
|
706
|
+
last_error: Exception | None = None
|
|
707
|
+
for attempt in range(_ACTIVE_READ_ATTEMPTS):
|
|
708
|
+
try:
|
|
709
|
+
value = self._kc_call(
|
|
710
|
+
macos_keychain.get_password,
|
|
711
|
+
service,
|
|
712
|
+
macos_keychain.keychain_account_name(),
|
|
713
|
+
)
|
|
714
|
+
return value, False
|
|
715
|
+
except macos_keychain.KEYCHAIN_ERRORS as e:
|
|
716
|
+
last_error = e
|
|
717
|
+
if attempt + 1 < _ACTIVE_READ_ATTEMPTS:
|
|
718
|
+
time.sleep(_ACTIVE_READ_RETRY_DELAY)
|
|
719
|
+
# Every attempt failed: _kc_call has flipped routing to file mode.
|
|
720
|
+
self._host._logger.warning(
|
|
721
|
+
f"Keychain read failed after {_ACTIVE_READ_ATTEMPTS} attempt(s), "
|
|
722
|
+
f"trying file: {last_error}"
|
|
723
|
+
)
|
|
724
|
+
return None, True
|
|
725
|
+
|
|
726
|
+
def _read_active_credentials(self) -> ActiveCredentials:
|
|
727
|
+
"""Read Claude Code's active credential, classifying the outcome.
|
|
728
|
+
|
|
729
|
+
Tries the OAuth credential first (Keychain "Claude Code-credentials" on
|
|
730
|
+
macOS when usable — with a bounded retry to ride out a transient
|
|
731
|
+
lock/contention — then the plaintext ``~/.claude/.credentials.json`` Claude
|
|
732
|
+
Code also falls back to), and only then the managed-key locations (macOS
|
|
733
|
+
Keychain "Claude Code", then ``~/.claude.json`` ``primaryApiKey``). Trying
|
|
734
|
+
OAuth fully first means a macOS OAuth login that only has a file fallback
|
|
735
|
+
(Keychain empty) is never misread as an API key. A returned managed key is a
|
|
736
|
+
raw ``sk-ant-…`` string — callers distinguish it via ``looks_like_api_key``.
|
|
737
|
+
Non-mutating.
|
|
738
|
+
|
|
739
|
+
One environment has a last step after those: with ``CLAUDE_CONFIG_DIR``
|
|
740
|
+
naming the default profile, the unsuffixed OAuth item is read when
|
|
741
|
+
nothing else answered (see :func:`_active_oauth_keychain_services`).
|
|
742
|
+
|
|
743
|
+
Reports ``keychain_unavailable`` when the OAuth Keychain read failed and
|
|
744
|
+
nothing else covered it, so the display layer can say "keychain unavailable"
|
|
745
|
+
rather than "no credentials" for a merely-unreadable slot — which would
|
|
746
|
+
otherwise nudge the user into an unnecessary re-login.
|
|
747
|
+
"""
|
|
748
|
+
keychain_failed = False
|
|
749
|
+
# 1. OAuth Keychain (macOS, when usable), with a bounded retry.
|
|
750
|
+
#
|
|
751
|
+
# READ THE ITEM FOR *THIS* PROFILE, NOT THE FIXED NAME.
|
|
752
|
+
# CLAUDE_CODE_KEYCHAIN_SERVICE is a fixed name, but Claude Code stores
|
|
753
|
+
# only the DEFAULT profile's credential under it: with CLAUDE_CONFIG_DIR
|
|
754
|
+
# set it scopes the item to that config dir under a hashed service name.
|
|
755
|
+
# Reading the fixed name from a custom profile therefore returns a
|
|
756
|
+
# credential belonging to a different account, while the identity read
|
|
757
|
+
# one layer up (paths.get_claude_config_home, which does honor
|
|
758
|
+
# CLAUDE_CONFIG_DIR) reports the custom profile's. Pairing an identity
|
|
759
|
+
# with another account's token is silent, and every consumer of this
|
|
760
|
+
# read inherits it.
|
|
761
|
+
#
|
|
762
|
+
# REDIRECTED, NOT SKIPPED. Skipping the keychain under a custom profile
|
|
763
|
+
# would leave macOS mostly blind: claude writes rotations keychain-only
|
|
764
|
+
# there, so the step-2 plaintext file frequently does not exist at all
|
|
765
|
+
# and a logged-in profile would render as "no credentials" — trading a
|
|
766
|
+
# wrong answer for a missing one. The hashed name is not a guess in this
|
|
767
|
+
# codebase either: session.keychain_service_name codifies claude's
|
|
768
|
+
# derivation (pinned against its source) and the delete, session-read
|
|
769
|
+
# and capture paths already depend on it.
|
|
770
|
+
self._lift_pin_if_oauth_file_gone()
|
|
771
|
+
keychain_asked = self._use_keychain()
|
|
772
|
+
if keychain_asked:
|
|
773
|
+
val, keychain_failed = self._read_active_oauth_keychain()
|
|
774
|
+
# THIS read's own verdict, kept so a later success on some OTHER
|
|
775
|
+
# item cannot erase it. Sticky until this read succeeds again,
|
|
776
|
+
# which is what makes it self-heal without being erasable.
|
|
777
|
+
self._active_read_failed = keychain_failed
|
|
778
|
+
if val:
|
|
779
|
+
return ActiveCredentials(val, False)
|
|
780
|
+
elif self._residual_verdict is False or (
|
|
781
|
+
self._active_read_failed or self._keychain_unreadable
|
|
782
|
+
):
|
|
783
|
+
# Keychain already known unusable this process: if nothing is found
|
|
784
|
+
# below, that absence is "keychain unavailable", not an empty slot.
|
|
785
|
+
# An UNVERIFIED clear says so on its own — no later success on some
|
|
786
|
+
# other item speaks for this one. A verified clear does not appear
|
|
787
|
+
# here at all: it settled the flags at the pin, so anything they
|
|
788
|
+
# say now happened AFTER it.
|
|
789
|
+
keychain_failed = True
|
|
790
|
+
|
|
791
|
+
# 2. OAuth plaintext file (Claude Code's own fallback; every platform).
|
|
792
|
+
# After a FAILED keychain read this file may hold a stale generation
|
|
793
|
+
# (CC writes rotations keychain-only on macOS) — the flag travels as
|
|
794
|
+
# ``degraded`` so consume paths refuse these bytes.
|
|
795
|
+
cred_file = get_credentials_path()
|
|
796
|
+
if cred_file.exists():
|
|
797
|
+
try:
|
|
798
|
+
text = cred_file.read_text(encoding="utf-8")
|
|
799
|
+
except Exception as e:
|
|
800
|
+
self._host._logger.error(f"Failed to read credentials file: {e}")
|
|
801
|
+
# `keychain_unavailable` is NOT False here. Keychain denied AND
|
|
802
|
+
# the fallback file unreadable is the most unreadable state
|
|
803
|
+
# there is; hardcoding False made it render as "no credentials"
|
|
804
|
+
# and sent the user to a re-login that cannot help.
|
|
805
|
+
return ActiveCredentials(None, keychain_failed, keychain_failed)
|
|
806
|
+
if text.strip():
|
|
807
|
+
return ActiveCredentials(text, False, keychain_failed)
|
|
808
|
+
|
|
809
|
+
# 3. Managed API key (Keychain "Claude Code" on macOS, then primaryApiKey).
|
|
810
|
+
key = self._read_managed_key()
|
|
811
|
+
if key:
|
|
812
|
+
return ActiveCredentials(key, False, keychain_failed)
|
|
813
|
+
|
|
814
|
+
# 4. The fallback OAuth Keychain item, only when nothing above answered.
|
|
815
|
+
# Claude with the variable set reads its own item and then the file,
|
|
816
|
+
# never this one, so a seed or a key that a switch just wrote for this
|
|
817
|
+
# environment has to win over it. An unreadable Keychain is a property
|
|
818
|
+
# of the Keychain, so a failed read is not retried under a second name.
|
|
819
|
+
if (
|
|
820
|
+
keychain_asked
|
|
821
|
+
and not keychain_failed
|
|
822
|
+
and len(_active_oauth_keychain_services()) > 1
|
|
823
|
+
):
|
|
824
|
+
if self._use_keychain():
|
|
825
|
+
val, keychain_failed = self._read_fallback_oauth_keychain()
|
|
826
|
+
else:
|
|
827
|
+
# The Keychain answered for this environment's own item and has
|
|
828
|
+
# stopped since: the managed-key lookup above failed. The
|
|
829
|
+
# fallback item was never asked, so finding nothing is an
|
|
830
|
+
# unreadable Keychain, not an empty slot.
|
|
831
|
+
val, keychain_failed = None, True
|
|
832
|
+
self._active_read_failed = keychain_failed
|
|
833
|
+
if val:
|
|
834
|
+
return ActiveCredentials(val, False)
|
|
835
|
+
# Nothing anywhere. Flag a failed-and-uncovered OAuth Keychain read so the
|
|
836
|
+
# UI distinguishes it from a real empty slot.
|
|
837
|
+
return ActiveCredentials("", keychain_failed, keychain_failed)
|
|
838
|
+
|
|
839
|
+
def _read_managed_key(self) -> str:
|
|
840
|
+
"""Read the active managed API key, or "" when absent. Non-mutating.
|
|
841
|
+
|
|
842
|
+
macOS Keychain "Claude Code" (when usable) first, then ``~/.claude.json``
|
|
843
|
+
``primaryApiKey`` — mirroring Claude Code's
|
|
844
|
+
``getApiKeyFromConfigOrMacOSKeychain``.
|
|
845
|
+
|
|
846
|
+
The Keychain half is default-profile-only. Unlike the OAuth item above
|
|
847
|
+
this one is gated rather than redirected, because there is no codified
|
|
848
|
+
derivation to redirect it *to*: ``session.keychain_service_name`` covers
|
|
849
|
+
the credentials item, and claude's managed-key service name under a
|
|
850
|
+
custom profile is not pinned anywhere in this repo. Guessing it is the
|
|
851
|
+
thing the OAuth half can avoid and this half cannot.
|
|
852
|
+
|
|
853
|
+
Gating matches what capture already does.
|
|
854
|
+
``_read_capture_credentials`` ends on "only this profile's own
|
|
855
|
+
``primaryApiKey`` — never the unsuffixed 'Claude Code' Keychain item,
|
|
856
|
+
which belongs to the default profile and would answer for a login that
|
|
857
|
+
is not the one being added". Same item, same conclusion; this makes the
|
|
858
|
+
read side agree with the capture side instead of contradicting it.
|
|
859
|
+
|
|
860
|
+
``primaryApiKey`` below is read from the active profile's own config and
|
|
861
|
+
stays, so a custom profile with a managed key is still found.
|
|
862
|
+
"""
|
|
863
|
+
if _active_profile_is_default() and self._use_keychain():
|
|
864
|
+
try:
|
|
865
|
+
val = self._kc_call(
|
|
866
|
+
macos_keychain.get_password,
|
|
867
|
+
CLAUDE_CODE_MANAGED_KEYCHAIN_SERVICE,
|
|
868
|
+
macos_keychain.keychain_account_name(),
|
|
869
|
+
)
|
|
870
|
+
except macos_keychain.KEYCHAIN_ERRORS as e:
|
|
871
|
+
self._host._logger.warning(f"Managed-key Keychain read failed: {e}")
|
|
872
|
+
val = None
|
|
873
|
+
if val:
|
|
874
|
+
return val
|
|
875
|
+
cfg = self._read_global_config()
|
|
876
|
+
if cfg:
|
|
877
|
+
key = cfg.get("primaryApiKey")
|
|
878
|
+
if isinstance(key, str) and key:
|
|
879
|
+
return key
|
|
880
|
+
return ""
|
|
881
|
+
|
|
882
|
+
def _read_global_config(self) -> dict | None:
|
|
883
|
+
"""Read and parse ``~/.claude.json``, or None when absent/unreadable."""
|
|
884
|
+
path = get_global_config_path()
|
|
885
|
+
if not path.exists():
|
|
886
|
+
return None
|
|
887
|
+
try:
|
|
888
|
+
data = json.loads(path.read_text(encoding="utf-8"))
|
|
889
|
+
except Exception as e:
|
|
890
|
+
self._host._logger.warning(f"Failed to read global config: {e}")
|
|
891
|
+
return None
|
|
892
|
+
return data if isinstance(data, dict) else None
|
|
893
|
+
|
|
894
|
+
def _update_global_config(self, mutator) -> None:
|
|
895
|
+
"""Atomically apply ``mutator(dict)`` to ``~/.claude.json``, key-scoped.
|
|
896
|
+
|
|
897
|
+
Reads the current config, lets ``mutator`` change only the keys it owns
|
|
898
|
+
(``primaryApiKey`` / ``customApiKeyResponses``), and writes it back
|
|
899
|
+
atomically — preserving every other key (``oauthAccount``, projects,
|
|
900
|
+
settings). 0o600 mirrors the switcher's ``_write_json``.
|
|
901
|
+
"""
|
|
902
|
+
path = get_global_config_path()
|
|
903
|
+
try:
|
|
904
|
+
data = self._read_global_config()
|
|
905
|
+
except Exception as e: # pragma: no cover - defensive
|
|
906
|
+
raise CredentialWriteError(f"Failed to read global config for update: {e}")
|
|
907
|
+
if data is None and path.exists():
|
|
908
|
+
# UNREADABLE, not absent — the same distinction `_clear_managed_key`
|
|
909
|
+
# makes, on the file carrying the user's whole Claude Code state.
|
|
910
|
+
# `or {}` collapsed the two and the atomic replace then wrote that
|
|
911
|
+
# `{}` over a file it had never read. Measured against a torn config
|
|
912
|
+
# (valid prefix, truncated tail — what a crash mid-write leaves):
|
|
913
|
+
# `oauthAccount`, `projects` and `mcpServers` were gone.
|
|
914
|
+
# An ABSENT config has nothing to preserve and is a genuine start.
|
|
915
|
+
raise CredentialWriteError(
|
|
916
|
+
f"{path} exists but could not be read — refusing to overwrite "
|
|
917
|
+
"it. Move or repair the file, then retry."
|
|
918
|
+
)
|
|
919
|
+
data = data or {}
|
|
920
|
+
mutator(data)
|
|
921
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
922
|
+
atomic_write_text(path, json.dumps(data, indent=2))
|
|
923
|
+
|
|
924
|
+
def _write_active_credentials_file(self, credentials: str) -> None:
|
|
925
|
+
"""Atomically write Claude Code's plaintext active-credentials file."""
|
|
926
|
+
cred_file = get_credentials_path()
|
|
927
|
+
cred_file.parent.mkdir(parents=True, exist_ok=True)
|
|
928
|
+
atomic_write_text(cred_file, credentials)
|
|
929
|
+
|
|
930
|
+
def _delete_active_keychain_entry(self) -> bool:
|
|
931
|
+
"""Best-effort removal of the active-credential Keychain item (macOS only).
|
|
932
|
+
|
|
933
|
+
Claude Code reads the Keychain before the plaintext file, so once we fall
|
|
934
|
+
back to the file we must clear any stale Keychain entry or Claude Code would
|
|
935
|
+
resurrect it (#30337). Best-effort: when the Keychain is down the delete
|
|
936
|
+
can't run, which is the documented recovery residual.
|
|
937
|
+
|
|
938
|
+
Clears the first item :func:`_active_oauth_keychain_services` resolves:
|
|
939
|
+
the one claude reads for this environment, and so the only one that can
|
|
940
|
+
shadow the seed we just wrote for it (#206). A fallback name is left
|
|
941
|
+
alone. With ``CLAUDE_CONFIG_DIR`` naming the default profile it is the
|
|
942
|
+
login of a claude started without the variable, which the switch's
|
|
943
|
+
outgoing backup never read, and the active read takes the file and a
|
|
944
|
+
managed key ahead of it. Deleting a hashed item is sanctioned where
|
|
945
|
+
authoring one is not: ``session.delete_macos_keychain_entry`` retires
|
|
946
|
+
one before every reseed, for this same reason.
|
|
947
|
+
|
|
948
|
+
Returns whether no active item can shadow the file. ``delete_password``
|
|
949
|
+
returns only on rc 0 or rc 44 (already absent) and raises otherwise, so
|
|
950
|
+
a return is proof — which is the fact ``_pin_file_mode`` needs and used
|
|
951
|
+
to discard. Off macOS there is no Keychain item, hence ``True``.
|
|
952
|
+
"""
|
|
953
|
+
if self._host.platform != Platform.MACOS:
|
|
954
|
+
return True
|
|
955
|
+
try:
|
|
956
|
+
macos_keychain.delete_password(
|
|
957
|
+
_active_oauth_keychain_services()[0],
|
|
958
|
+
macos_keychain.keychain_account_name(),
|
|
959
|
+
)
|
|
960
|
+
except Exception:
|
|
961
|
+
return False # best-effort; a down Keychain can't be cleaned now
|
|
962
|
+
return True
|
|
963
|
+
|
|
964
|
+
def _write_credentials(self, credentials: str) -> None:
|
|
965
|
+
"""Write Claude Code's active credential, enforcing a single auth axis.
|
|
966
|
+
|
|
967
|
+
Detects the kind from the payload (raw ``sk-ant-…`` key vs OAuth JSON) and
|
|
968
|
+
mirrors Claude Code's own ``saveApiKey``/``removeApiKey``: activating one axis
|
|
969
|
+
clears the other so a stale credential can't shadow the switch.
|
|
970
|
+
|
|
971
|
+
- **OAuth** → write the OAuth credential (see ``_write_oauth_credentials``),
|
|
972
|
+
then clear any managed key (Keychain "Claude Code" + ``primaryApiKey``;
|
|
973
|
+
``approved`` left intact, as ``removeApiKey`` does).
|
|
974
|
+
- **API key** → record ``key[-20:]`` in ``approved`` and store the key (macOS
|
|
975
|
+
Keychain "Claude Code" when usable, else ``~/.claude.json`` ``primaryApiKey``),
|
|
976
|
+
then clear the OAuth credential (Keychain item + ``.credentials.json``).
|
|
977
|
+
|
|
978
|
+
Raises:
|
|
979
|
+
CredentialWriteError: If writing credentials fails.
|
|
980
|
+
"""
|
|
981
|
+
if looks_like_api_key(credentials):
|
|
982
|
+
self._write_managed_credentials(credentials.strip())
|
|
983
|
+
else:
|
|
984
|
+
self._write_oauth_credentials(credentials)
|
|
985
|
+
self._clear_managed_key()
|
|
986
|
+
|
|
987
|
+
def _write_managed_credentials(self, api_key: str) -> None:
|
|
988
|
+
"""Activate a managed API key, then clear OAuth (mutual exclusion).
|
|
989
|
+
|
|
990
|
+
Always records ``key[-20:]`` in ``customApiKeyResponses.approved`` (Claude
|
|
991
|
+
Code does this on every platform, even on Keychain success — otherwise it
|
|
992
|
+
re-prompts to approve the key). Stores the key in the macOS Keychain when
|
|
993
|
+
usable, else ``~/.claude.json`` ``primaryApiKey`` (matching ``saveApiKey``'s
|
|
994
|
+
keychain-then-config fallback). Finally clears the OAuth credential.
|
|
995
|
+
|
|
996
|
+
Raises:
|
|
997
|
+
CredentialWriteError: If persisting the key fails.
|
|
998
|
+
"""
|
|
999
|
+
wrote_to_keychain = False
|
|
1000
|
+
if self._use_keychain():
|
|
1001
|
+
try:
|
|
1002
|
+
self._kc_call(
|
|
1003
|
+
macos_keychain.set_password,
|
|
1004
|
+
CLAUDE_CODE_MANAGED_KEYCHAIN_SERVICE,
|
|
1005
|
+
macos_keychain.keychain_account_name(),
|
|
1006
|
+
api_key,
|
|
1007
|
+
)
|
|
1008
|
+
except macos_keychain.KEYCHAIN_ERRORS as e:
|
|
1009
|
+
# _kc_call flipped routing to file mode; fall back to config below.
|
|
1010
|
+
self._host._logger.warning(
|
|
1011
|
+
f"Managed-key Keychain write failed, falling back to config: {e}"
|
|
1012
|
+
)
|
|
1013
|
+
else:
|
|
1014
|
+
wrote_to_keychain = True
|
|
1015
|
+
|
|
1016
|
+
approved = approved_form(api_key)
|
|
1017
|
+
|
|
1018
|
+
def _mutate(cfg: dict) -> None:
|
|
1019
|
+
responses = cfg.get("customApiKeyResponses")
|
|
1020
|
+
if not isinstance(responses, dict):
|
|
1021
|
+
responses = {}
|
|
1022
|
+
approved_list = responses.get("approved")
|
|
1023
|
+
if not isinstance(approved_list, list):
|
|
1024
|
+
approved_list = []
|
|
1025
|
+
if approved not in approved_list:
|
|
1026
|
+
approved_list.append(approved)
|
|
1027
|
+
responses["approved"] = approved_list
|
|
1028
|
+
responses.setdefault("rejected", [])
|
|
1029
|
+
cfg["customApiKeyResponses"] = responses
|
|
1030
|
+
if wrote_to_keychain:
|
|
1031
|
+
# Keychain holds the key; keep it out of plaintext config.
|
|
1032
|
+
cfg.pop("primaryApiKey", None)
|
|
1033
|
+
else:
|
|
1034
|
+
cfg["primaryApiKey"] = api_key
|
|
1035
|
+
|
|
1036
|
+
try:
|
|
1037
|
+
self._update_global_config(_mutate)
|
|
1038
|
+
except CredentialWriteError:
|
|
1039
|
+
raise
|
|
1040
|
+
except Exception as e:
|
|
1041
|
+
raise CredentialWriteError(f"Failed to write managed API key: {e}")
|
|
1042
|
+
|
|
1043
|
+
# Mutual exclusion: drop the OAuth credential so it can't shadow the key.
|
|
1044
|
+
self._clear_oauth_credential()
|
|
1045
|
+
if self._host.platform == Platform.MACOS and not wrote_to_keychain:
|
|
1046
|
+
# Same stale-Keychain resurrection guard as the OAuth path: the key
|
|
1047
|
+
# fell back to plaintext ``primaryApiKey`` while a stale "Claude Code"
|
|
1048
|
+
# Keychain item may remain, and managed-key reads check the Keychain
|
|
1049
|
+
# before ``primaryApiKey``. Pin file mode so a cooldown re-probe can't
|
|
1050
|
+
# read that residual over the fresh fallback value.
|
|
1051
|
+
#
|
|
1052
|
+
# ``residual_cleared=False``: the item that would shadow here is the
|
|
1053
|
+
# MANAGED one, and nothing deleted it — ``_clear_oauth_credential``
|
|
1054
|
+
# above removes the OAuth item, a different service. Unverified, so
|
|
1055
|
+
# the conservative verdict is the true one.
|
|
1056
|
+
with self._pin_lock:
|
|
1057
|
+
self._pin_file_mode(residual_cleared=False)
|
|
1058
|
+
self._last_active_credentials_backend = (
|
|
1059
|
+
"keychain" if wrote_to_keychain else "file"
|
|
1060
|
+
)
|
|
1061
|
+
|
|
1062
|
+
def _clear_managed_key(self) -> None:
|
|
1063
|
+
"""Clear any active managed API key (Claude Code ``removeApiKey`` semantics).
|
|
1064
|
+
|
|
1065
|
+
Deletes the macOS Keychain "Claude Code" item (best-effort) and drops
|
|
1066
|
+
``primaryApiKey`` from ``~/.claude.json``. Leaves
|
|
1067
|
+
``customApiKeyResponses.approved`` untouched — ``removeApiKey`` doesn't clear
|
|
1068
|
+
it either, and removing it would force recovering ``key[-20:]`` from the
|
|
1069
|
+
Keychain for no benefit. A no-op (no config rewrite) when no key is present.
|
|
1070
|
+
|
|
1071
|
+
I-2 (round 9): ``_read_global_config`` collapses ABSENT and UNREADABLE
|
|
1072
|
+
into the same ``None`` — without the distinction below, an unreadable
|
|
1073
|
+
config (permissions, mid-unmount) reads exactly like a genuinely
|
|
1074
|
+
keyless profile, so the clear is silently skipped. Best-effort stays
|
|
1075
|
+
best-effort here (never raises — the write path this feeds must not
|
|
1076
|
+
block on a transient read glitch), but a distinguishing warning
|
|
1077
|
+
matters: a stale ``primaryApiKey`` surviving alongside a freshly
|
|
1078
|
+
activated OAuth credential is a live cross-account key that bills
|
|
1079
|
+
per token while it lies, and a caller/log reader must be able to
|
|
1080
|
+
tell "nothing to clear" from "could not check".
|
|
1081
|
+
"""
|
|
1082
|
+
if self._host.platform == Platform.MACOS:
|
|
1083
|
+
try:
|
|
1084
|
+
macos_keychain.delete_password(
|
|
1085
|
+
CLAUDE_CODE_MANAGED_KEYCHAIN_SERVICE,
|
|
1086
|
+
macos_keychain.keychain_account_name(),
|
|
1087
|
+
)
|
|
1088
|
+
except Exception:
|
|
1089
|
+
pass # best-effort; a down Keychain can't be cleaned now
|
|
1090
|
+
cfg = self._read_global_config()
|
|
1091
|
+
if cfg is None and get_global_config_path().exists():
|
|
1092
|
+
self._host._logger.warning(
|
|
1093
|
+
"Could not clear primaryApiKey: the global config exists "
|
|
1094
|
+
"but could not be read (unreadable, not absent) — leaving "
|
|
1095
|
+
"it in place rather than overwriting it unread"
|
|
1096
|
+
)
|
|
1097
|
+
return
|
|
1098
|
+
if cfg is not None and cfg.get("primaryApiKey") is not None:
|
|
1099
|
+
def _drop(c: dict) -> None:
|
|
1100
|
+
c.pop("primaryApiKey", None)
|
|
1101
|
+
|
|
1102
|
+
try:
|
|
1103
|
+
self._update_global_config(_drop)
|
|
1104
|
+
except Exception as e:
|
|
1105
|
+
self._host._logger.warning(f"Failed to clear primaryApiKey: {e}")
|
|
1106
|
+
|
|
1107
|
+
def _clear_oauth_credential(self) -> None:
|
|
1108
|
+
"""Clear the active OAuth credential — Keychain item and plaintext file.
|
|
1109
|
+
|
|
1110
|
+
Best-effort: a down Keychain or missing file is fine. Removing
|
|
1111
|
+
``.credentials.json`` stops Claude Code from falling back to a stale OAuth
|
|
1112
|
+
login over the just-activated API key.
|
|
1113
|
+
|
|
1114
|
+
WE remove the file here, so its absence says nothing about Claude Code
|
|
1115
|
+
having moved the credential to the Keychain — the premise
|
|
1116
|
+
``_lift_pin_if_oauth_file_gone`` rests on. Disarm the lift first.
|
|
1117
|
+
"""
|
|
1118
|
+
with self._pin_lock:
|
|
1119
|
+
self._pinned_to_oauth_file = False
|
|
1120
|
+
self._delete_active_keychain_entry()
|
|
1121
|
+
cred_file = get_credentials_path()
|
|
1122
|
+
try:
|
|
1123
|
+
if cred_file.exists():
|
|
1124
|
+
cred_file.unlink()
|
|
1125
|
+
except OSError as e:
|
|
1126
|
+
self._host._logger.warning(f"Failed to remove credentials file: {e}")
|
|
1127
|
+
|
|
1128
|
+
def _write_oauth_credentials(self, credentials: str) -> None:
|
|
1129
|
+
"""Write Claude Code's active OAuth credentials.
|
|
1130
|
+
|
|
1131
|
+
macOS writes the Keychain when usable (recording backend ``"keychain"``). On
|
|
1132
|
+
a successful Keychain write it then **rewrites an already-present**
|
|
1133
|
+
``.credentials.json`` with the same fresh creds — never *creating* one when
|
|
1134
|
+
absent, never *deleting* one. This bumps the file's mtime so a running Claude
|
|
1135
|
+
Code session's disk-mtime cache invalidation fires and it hot-reloads the new
|
|
1136
|
+
account instead of serving its memoized token until restart (#86); it also
|
|
1137
|
+
keeps the file consistent for the container ``~/.claude`` sharing consumer
|
|
1138
|
+
(#1414) rather than stranding it on stale content. Keychain-only users keep
|
|
1139
|
+
their fileless posture — their absent-file path already hot-reloads via the
|
|
1140
|
+
~30s Keychain TTL — and never gain a plaintext credential on disk. If the
|
|
1141
|
+
Keychain write fails — or the Keychain is already known unusable — it writes
|
|
1142
|
+
the plaintext file and best-effort clears any stale Keychain entry (#30337),
|
|
1143
|
+
recording backend ``"file"``. Linux/WSL/Windows always write the file.
|
|
1144
|
+
|
|
1145
|
+
A custom profile takes that same file path deliberately, not as a
|
|
1146
|
+
fallback (#206): its Keychain item is one cswap must not author — see
|
|
1147
|
+
``session``'s module docstring on why writing claude's hashed format is
|
|
1148
|
+
a hard "logged out" failure when it drifts — so the switch retires the
|
|
1149
|
+
stale item and seeds ``.credentials.json``, exactly as session profiles
|
|
1150
|
+
are seeded, and lets claude migrate it on its first write. That route
|
|
1151
|
+
does not pin file mode once the stale item is verifiably gone: nothing
|
|
1152
|
+
failed, and claude (2.1.322) puts its first rotation back in the
|
|
1153
|
+
Keychain, so the next read has to ask the Keychain first, as claude
|
|
1154
|
+
does. A pin would also move this process's backup writes to ``.enc``
|
|
1155
|
+
files on a Mac whose Keychain works.
|
|
1156
|
+
|
|
1157
|
+
Raises:
|
|
1158
|
+
CredentialWriteError: If writing credentials fails.
|
|
1159
|
+
"""
|
|
1160
|
+
keychain_usable = self._use_keychain()
|
|
1161
|
+
default_store = keychain_usable and _active_store_is_the_default_secure_store()
|
|
1162
|
+
# The Keychain answers and the file is where this profile's write
|
|
1163
|
+
# belongs: a routing choice, as opposed to a fallback after a failure.
|
|
1164
|
+
deliberate_file_route = keychain_usable and not default_store
|
|
1165
|
+
if default_store:
|
|
1166
|
+
try:
|
|
1167
|
+
self._kc_call(
|
|
1168
|
+
macos_keychain.set_password,
|
|
1169
|
+
CLAUDE_CODE_KEYCHAIN_SERVICE,
|
|
1170
|
+
macos_keychain.keychain_account_name(),
|
|
1171
|
+
credentials,
|
|
1172
|
+
)
|
|
1173
|
+
except macos_keychain.KEYCHAIN_ERRORS as e:
|
|
1174
|
+
# _kc_call flipped routing to file mode; fall through to the file.
|
|
1175
|
+
# (A programming error is NOT caught here — it propagates.)
|
|
1176
|
+
self._host._logger.warning(f"Keychain write failed, falling back to file: {e}")
|
|
1177
|
+
else:
|
|
1178
|
+
# Keychain (primary) now holds the fresh credential. Bump an
|
|
1179
|
+
# already-present shadow file's mtime so running sessions hot-reload
|
|
1180
|
+
# (#86); best-effort, never creates one — see the helper.
|
|
1181
|
+
self._refresh_stale_credentials_file(credentials)
|
|
1182
|
+
self._last_active_credentials_backend = "keychain"
|
|
1183
|
+
return
|
|
1184
|
+
|
|
1185
|
+
# File mode: non-macOS, a custom profile on macOS, macOS Keychain known
|
|
1186
|
+
# unusable, or a Keychain write that just failed. Write the plaintext file
|
|
1187
|
+
# and (macOS) best-effort clear any stale Keychain entry so Claude Code's
|
|
1188
|
+
# keychain-first read can't shadow it (#30337).
|
|
1189
|
+
try:
|
|
1190
|
+
self._write_active_credentials_file(credentials)
|
|
1191
|
+
except Exception as e:
|
|
1192
|
+
raise CredentialWriteError(f"Failed to write credentials: {e}")
|
|
1193
|
+
cleared = self._delete_active_keychain_entry()
|
|
1194
|
+
if self._host.platform == Platform.MACOS and not (
|
|
1195
|
+
deliberate_file_route and cleared
|
|
1196
|
+
):
|
|
1197
|
+
# The delete above is best-effort; a stale Keychain item may remain.
|
|
1198
|
+
# Pin file mode so a later read-timeout cooldown can't re-probe onto
|
|
1199
|
+
# that residual and resurrect the wrong account (see _pin_file_mode).
|
|
1200
|
+
# Its outcome is also the answer to whether the file is now the
|
|
1201
|
+
# authority, so hand it over rather than re-deriving it from flags.
|
|
1202
|
+
with self._pin_lock:
|
|
1203
|
+
self._pin_file_mode(residual_cleared=cleared)
|
|
1204
|
+
self._pinned_to_oauth_file = True
|
|
1205
|
+
self._last_active_credentials_backend = "file"
|
|
1206
|
+
|
|
1207
|
+
def _refresh_stale_credentials_file(self, credentials: str) -> None:
|
|
1208
|
+
"""Bump an already-present ``.credentials.json``'s mtime after a Keychain write.
|
|
1209
|
+
|
|
1210
|
+
Rewrite-when-present / never-create (#86). Claude Code invalidates its
|
|
1211
|
+
memoized OAuth token only when this file's mtime changes or the file is
|
|
1212
|
+
absent; a Keychain-only switch leaves a *stale* file's mtime frozen, so a
|
|
1213
|
+
running session serves the old token until restart. Rewriting the existing
|
|
1214
|
+
file with the same fresh creds bumps the mtime (atomic ``os.replace``, so it
|
|
1215
|
+
bumps even when the content is unchanged) and keeps a file-reading consumer
|
|
1216
|
+
(#1414 shared ``~/.claude``) consistent. We never *create* the file when
|
|
1217
|
+
absent — Keychain-only users keep their fileless posture and their absent-file
|
|
1218
|
+
(~30s Keychain-TTL) path already hot-reloads.
|
|
1219
|
+
|
|
1220
|
+
Best-effort: the Keychain write is authoritative on macOS and already
|
|
1221
|
+
succeeded, so a failure here must not fail the switch — it only means a
|
|
1222
|
+
running session may lag until restart.
|
|
1223
|
+
"""
|
|
1224
|
+
cred_file = get_credentials_path()
|
|
1225
|
+
if not cred_file.exists():
|
|
1226
|
+
return
|
|
1227
|
+
try:
|
|
1228
|
+
self._write_active_credentials_file(credentials)
|
|
1229
|
+
except Exception as e:
|
|
1230
|
+
self._host._logger.warning(
|
|
1231
|
+
f"Could not refresh .credentials.json after Keychain write ({e}); "
|
|
1232
|
+
"a running session may not hot-reload until restart"
|
|
1233
|
+
)
|
|
1234
|
+
|
|
1235
|
+
def _uses_file_backup_backend(self) -> bool:
|
|
1236
|
+
"""Whether per-account backup *writes* go to files vs. the Keychain.
|
|
1237
|
+
|
|
1238
|
+
Linux/WSL/Windows always use base64 ``.enc`` files under ``credentials_dir``
|
|
1239
|
+
(Windows moved off the Credential Manager because it rejects entries over
|
|
1240
|
+
~2,500 bytes, #45). macOS uses the Keychain while it's usable and falls back
|
|
1241
|
+
to ``.enc`` files when it isn't (headless/SSH/locked); UNKNOWN platforms have
|
|
1242
|
+
no Keychain, so they use files too. Backup *reads* are ``.enc``-wins
|
|
1243
|
+
regardless (see ``_read_account_credentials``).
|
|
1244
|
+
"""
|
|
1245
|
+
return not self._use_keychain()
|
|
1246
|
+
|
|
1247
|
+
# -- backup credential backends ---------------------------------------
|
|
1248
|
+
#
|
|
1249
|
+
# Two backends for per-account backups: base64 ``.enc`` files under
|
|
1250
|
+
# ``credentials_dir`` and the macOS Keychain (``SECURITY_SERVICE``). On macOS
|
|
1251
|
+
# reads are ``.enc``-wins: a fallback ``.enc`` (written while the Keychain was
|
|
1252
|
+
# unusable) is authoritative over a possibly-stale Keychain copy, so a Keychain
|
|
1253
|
+
# that recovers can't shadow a newer file. A successful Keychain write
|
|
1254
|
+
# therefore reconciles the ``.enc`` away (correctness-critical, not best-effort).
|
|
1255
|
+
|
|
1256
|
+
def _backup_enc_path(self, account_num: str, email: str) -> Path:
|
|
1257
|
+
return self._host.credentials_dir / f".creds-{account_num}-{email}.enc"
|
|
1258
|
+
|
|
1259
|
+
def _backup_username(self, account_num: str, email: str) -> str:
|
|
1260
|
+
return f"account-{account_num}-{email}"
|
|
1261
|
+
|
|
1262
|
+
def _registry_generation(self) -> tuple[int, int, int] | None:
|
|
1263
|
+
"""``sequence.json``'s (inode, mtime_ns, size), or ``None`` when it
|
|
1264
|
+
cannot be stat'ed.
|
|
1265
|
+
|
|
1266
|
+
The cheap "did the account set change?" signal: every registry write
|
|
1267
|
+
(add/remove/swap/move/switch/import, from any process) replaces the
|
|
1268
|
+
file. The display read cache is keyed on it — the same device as the
|
|
1269
|
+
switcher's ``_poll_policy_inputs`` settings stat. The mtime alone can
|
|
1270
|
+
repeat across two writes in one coarse timestamp tick; the atomic
|
|
1271
|
+
write's new inode and the size tell those apart.
|
|
1272
|
+
"""
|
|
1273
|
+
try:
|
|
1274
|
+
st = self._host.sequence_file.stat()
|
|
1275
|
+
return st.st_ino, st.st_mtime_ns, st.st_size
|
|
1276
|
+
except OSError:
|
|
1277
|
+
return None
|
|
1278
|
+
|
|
1279
|
+
def _drop_backup_read_cache(self) -> None:
|
|
1280
|
+
"""Forget every cached backup read (see ``_kc_read_backup``).
|
|
1281
|
+
|
|
1282
|
+
Runs after each own backup write/delete. The epoch bump also voids a
|
|
1283
|
+
fill that was mid-``security`` when the drop landed: its value may
|
|
1284
|
+
predate the mutation, so it must not be stored.
|
|
1285
|
+
"""
|
|
1286
|
+
with self._backup_read_cache_lock:
|
|
1287
|
+
self._backup_read_cache.clear()
|
|
1288
|
+
self._backup_read_cache_epoch += 1
|
|
1289
|
+
|
|
1290
|
+
def _kc_read_backup(
|
|
1291
|
+
self, account_num: str, email: str, *, cached: bool = False
|
|
1292
|
+
) -> str:
|
|
1293
|
+
"""Read a per-account backup from the Keychain only (no file fallback).
|
|
1294
|
+
|
|
1295
|
+
Routes through ``_kc_call`` (so a failure flips the capability cache).
|
|
1296
|
+
Returns ``""`` when the item is absent; raises on a Keychain failure so
|
|
1297
|
+
the caller decides (normal reads swallow it; the migration defers).
|
|
1298
|
+
|
|
1299
|
+
Honours the failure cooldown: within ``KEYCHAIN_RECHECK_COOLDOWN_S`` of
|
|
1300
|
+
the last Keychain failure it raises WITHOUT spawning ``security``. The
|
|
1301
|
+
active read and writes already stay off the Keychain then
|
|
1302
|
+
(``_use_keychain``); backup reads were the one path that kept probing
|
|
1303
|
+
— 31 spawns per 3 s TUI tick against a locked login keychain, each a
|
|
1304
|
+
killed unlock dialog (#496). A pinned file mode zeroes the deadline,
|
|
1305
|
+
so it never blocks backup reads (the backup is Keychain-only by
|
|
1306
|
+
design; see ``_pin_file_mode`` and ``_read_account_credentials_ex``).
|
|
1307
|
+
Several workers may pass the deadline together, so a recovery is a
|
|
1308
|
+
bounded burst, not exactly one probe.
|
|
1309
|
+
|
|
1310
|
+
``cached=True`` serves the value from a per-slot cache for up to
|
|
1311
|
+
``BACKUP_READ_CACHE_TTL_S``. For DISPLAY and ELIGIBILITY reads only —
|
|
1312
|
+
sentinels, the snapshot's ``switchable`` flag, token-status lines.
|
|
1313
|
+
Anything whose bytes are POSTed, written, activated or compared to
|
|
1314
|
+
decide a write reads fresh (the default): the consume gate, the switch
|
|
1315
|
+
path, resync/adopt, session bootstrap, export, migrations, and the
|
|
1316
|
+
strike binding before a heal. Successes only (an absent item caches as
|
|
1317
|
+
``""``); a failure is never cached — the cooldown is what stops
|
|
1318
|
+
re-probing it. Dropped after every own write/delete of a backup item
|
|
1319
|
+
and whenever ``sequence.json`` changes (any process). A rotation
|
|
1320
|
+
another process performs without touching the registry is the one
|
|
1321
|
+
event only the TTL bounds; ≤TTL staleness there only lags the display
|
|
1322
|
+
— the fetch path re-reads (``_consume_backup_grant_locked`` adopts a
|
|
1323
|
+
moved generation rather than consuming a stale snapshot).
|
|
1324
|
+
"""
|
|
1325
|
+
key = (str(account_num), email)
|
|
1326
|
+
if cached:
|
|
1327
|
+
generation = self._registry_generation()
|
|
1328
|
+
now = time.monotonic()
|
|
1329
|
+
with self._backup_read_cache_lock:
|
|
1330
|
+
if generation != self._backup_read_cache_gen:
|
|
1331
|
+
# The account registry changed: any entry may describe a
|
|
1332
|
+
# slot that moved or was re-added. Drop them all.
|
|
1333
|
+
self._backup_read_cache.clear()
|
|
1334
|
+
self._backup_read_cache_epoch += 1
|
|
1335
|
+
self._backup_read_cache_gen = generation
|
|
1336
|
+
hit = self._backup_read_cache.get(key)
|
|
1337
|
+
if hit is not None and now - hit[1] < BACKUP_READ_CACHE_TTL_S:
|
|
1338
|
+
return hit[0]
|
|
1339
|
+
epoch = self._backup_read_cache_epoch
|
|
1340
|
+
deadline = self._keychain_disabled_until
|
|
1341
|
+
if deadline and time.monotonic() < deadline:
|
|
1342
|
+
if self._backoff_announced_until != deadline:
|
|
1343
|
+
self._backoff_announced_until = deadline
|
|
1344
|
+
self._host._logger.info(
|
|
1345
|
+
"Keychain backed off after a failure: backup reads report "
|
|
1346
|
+
"unreadable for up to %.0f s instead of probing",
|
|
1347
|
+
deadline - time.monotonic(),
|
|
1348
|
+
)
|
|
1349
|
+
raise KeychainBackedOff(
|
|
1350
|
+
"backup read skipped: the Keychain is backed off after a "
|
|
1351
|
+
"recent failure"
|
|
1352
|
+
)
|
|
1353
|
+
creds = self._kc_call(
|
|
1354
|
+
macos_keychain.get_password,
|
|
1355
|
+
SECURITY_SERVICE,
|
|
1356
|
+
self._backup_username(account_num, email),
|
|
1357
|
+
)
|
|
1358
|
+
value = creds or ""
|
|
1359
|
+
if cached:
|
|
1360
|
+
with self._backup_read_cache_lock:
|
|
1361
|
+
# Store only if nothing was dropped while `security` ran.
|
|
1362
|
+
if epoch == self._backup_read_cache_epoch:
|
|
1363
|
+
self._backup_read_cache[key] = (value, now)
|
|
1364
|
+
return value
|
|
1365
|
+
|
|
1366
|
+
def _kc_write_backup(self, account_num: str, email: str, credentials: str) -> None:
|
|
1367
|
+
"""Write a per-account backup to the Keychain only. Raises on failure."""
|
|
1368
|
+
try:
|
|
1369
|
+
self._kc_call(
|
|
1370
|
+
macos_keychain.set_password,
|
|
1371
|
+
SECURITY_SERVICE,
|
|
1372
|
+
self._backup_username(account_num, email),
|
|
1373
|
+
credentials,
|
|
1374
|
+
)
|
|
1375
|
+
finally:
|
|
1376
|
+
# AFTER the op, never before: dropping first leaves "drop -> a
|
|
1377
|
+
# cached miss reads the old item and stores it -> the write
|
|
1378
|
+
# lands", which the epoch cannot see. `finally`: a failed op may
|
|
1379
|
+
# still have changed the item.
|
|
1380
|
+
self._drop_backup_read_cache()
|
|
1381
|
+
|
|
1382
|
+
def _kc_delete_backup(self, account_num: str, email: str) -> None:
|
|
1383
|
+
"""Delete a per-account backup Keychain item only. Raises on failure."""
|
|
1384
|
+
try:
|
|
1385
|
+
self._kc_call(
|
|
1386
|
+
macos_keychain.delete_password,
|
|
1387
|
+
SECURITY_SERVICE,
|
|
1388
|
+
self._backup_username(account_num, email),
|
|
1389
|
+
)
|
|
1390
|
+
finally:
|
|
1391
|
+
self._drop_backup_read_cache() # after, not before — see the write
|
|
1392
|
+
|
|
1393
|
+
def _kc_delete_backup_prev(self, account_num: str, email: str) -> None:
|
|
1394
|
+
"""Delete a slot's retained ``.prev`` Keychain item. Raises on failure."""
|
|
1395
|
+
self._kc_call(
|
|
1396
|
+
macos_keychain.delete_password,
|
|
1397
|
+
SECURITY_SERVICE,
|
|
1398
|
+
self._prev_backup_username(account_num, email),
|
|
1399
|
+
)
|
|
1400
|
+
|
|
1401
|
+
def _delete_backup_keychain_quiet(self, account_num: str, email: str) -> None:
|
|
1402
|
+
"""Best-effort backup Keychain delete (never raises)."""
|
|
1403
|
+
try:
|
|
1404
|
+
self._kc_delete_backup(account_num, email)
|
|
1405
|
+
except Exception as e:
|
|
1406
|
+
self._host._logger.warning(f"Failed to delete credentials from Keychain: {e}")
|
|
1407
|
+
|
|
1408
|
+
def _write_backup_enc(self, account_num: str, email: str, credentials: str) -> None:
|
|
1409
|
+
"""Atomically write a per-account backup ``.enc`` (base64) file."""
|
|
1410
|
+
self._atomic_b64_write(self._backup_enc_path(account_num, email), credentials)
|
|
1411
|
+
|
|
1412
|
+
def _atomic_b64_write(self, target: Path, credentials: str) -> None:
|
|
1413
|
+
"""Atomically write a base64-encoded credential file (0600)."""
|
|
1414
|
+
self._host.credentials_dir.mkdir(parents=True, exist_ok=True)
|
|
1415
|
+
encoded = base64.b64encode(credentials.encode("utf-8")).decode("utf-8")
|
|
1416
|
+
atomic_write_text(target, encoded)
|
|
1417
|
+
|
|
1418
|
+
def _reconcile_enc_after_keychain_write(
|
|
1419
|
+
self, account_num: str, email: str, credentials: str
|
|
1420
|
+
) -> None:
|
|
1421
|
+
"""Stop a leftover ``.enc`` from shadowing a just-written Keychain backup.
|
|
1422
|
+
|
|
1423
|
+
``.enc``-wins reads make this correctness-critical: delete the ``.enc``; if
|
|
1424
|
+
the delete fails, atomically rewrite it with the same fresh creds; if that
|
|
1425
|
+
also fails, raise so the inconsistency surfaces rather than serving stale.
|
|
1426
|
+
"""
|
|
1427
|
+
enc_file = self._backup_enc_path(account_num, email)
|
|
1428
|
+
if not enc_file.exists():
|
|
1429
|
+
return
|
|
1430
|
+
try:
|
|
1431
|
+
enc_file.unlink()
|
|
1432
|
+
return
|
|
1433
|
+
except Exception as e:
|
|
1434
|
+
self._host._logger.warning(
|
|
1435
|
+
f"Could not delete .enc after Keychain backup write ({e}); "
|
|
1436
|
+
"rewriting it with the fresh credentials to keep both consistent"
|
|
1437
|
+
)
|
|
1438
|
+
self._write_backup_enc(account_num, email, credentials)
|
|
1439
|
+
|
|
1440
|
+
def _read_account_credentials(
|
|
1441
|
+
self,
|
|
1442
|
+
account_num: str,
|
|
1443
|
+
email: str,
|
|
1444
|
+
failed: list | None = None,
|
|
1445
|
+
*,
|
|
1446
|
+
cached: bool = False,
|
|
1447
|
+
) -> str:
|
|
1448
|
+
"""Read account credentials from backup. ``""`` when missing.
|
|
1449
|
+
|
|
1450
|
+
macOS is ``.enc``-wins (a fallback file beats a possibly-stale Keychain
|
|
1451
|
+
copy); only an absent or corrupt ``.enc`` falls through to the Keychain.
|
|
1452
|
+
Linux/WSL/Windows read the ``.enc`` only. ``cached`` lets the Keychain
|
|
1453
|
+
half be served from the display read cache (see ``_kc_read_backup``:
|
|
1454
|
+
display/eligibility sites only); the ``.enc`` half is always live.
|
|
1455
|
+
"""
|
|
1456
|
+
enc_file = self._backup_enc_path(account_num, email)
|
|
1457
|
+
try:
|
|
1458
|
+
# `stat`, NOT `exists`. `Path.exists()` SWALLOWS OSError from 3.13
|
|
1459
|
+
# on and answers False, so an unsearchable credentials/ dir became
|
|
1460
|
+
# byte-identical to a genuinely absent backup — on 3.12 the raise
|
|
1461
|
+
# reached the handler below and marked the read failed, on 3.13+
|
|
1462
|
+
# nothing did. The platform decided whether a read failure was
|
|
1463
|
+
# reported, and the fleet runs both (3.12 on two machines, 3.14 on
|
|
1464
|
+
# one). `stat` raises on every version, so the distinction the
|
|
1465
|
+
# handler below exists to draw survives on all of them.
|
|
1466
|
+
enc_file.stat()
|
|
1467
|
+
except FileNotFoundError:
|
|
1468
|
+
enc_present = False
|
|
1469
|
+
except OSError as e:
|
|
1470
|
+
# The directory itself could not be searched (permissions, a
|
|
1471
|
+
# mid-unmount, ...) — a real read failure, same as the arm below
|
|
1472
|
+
# that fires once the file is known to exist. Not marking
|
|
1473
|
+
# `failed` here makes an unsearchable dir byte-identical to a
|
|
1474
|
+
# genuinely absent backup, which is exactly what C1 fixed for
|
|
1475
|
+
# the file itself six lines below.
|
|
1476
|
+
if failed is not None:
|
|
1477
|
+
failed.append(True)
|
|
1478
|
+
self._host._logger.warning(f"Failed to read credentials file: {e}")
|
|
1479
|
+
enc_present = False
|
|
1480
|
+
else:
|
|
1481
|
+
enc_present = True
|
|
1482
|
+
if enc_present:
|
|
1483
|
+
try:
|
|
1484
|
+
# BYTES, not text: `read_text` decodes inside the read and
|
|
1485
|
+
# `UnicodeDecodeError` is a `ValueError`, so a .enc of garbled
|
|
1486
|
+
# bytes escaped this arm AND the corrupt-content arm below, and
|
|
1487
|
+
# raised out of a reader whose contract is `""`. Garbled bytes
|
|
1488
|
+
# are what that second arm exists for, and `b64decode` rejects
|
|
1489
|
+
# them there. Same split as `_read_stash_manifest_ex`.
|
|
1490
|
+
encoded = enc_file.read_bytes().strip()
|
|
1491
|
+
except OSError as e:
|
|
1492
|
+
# The .enc EXISTS but could not be read (permissions, a
|
|
1493
|
+
# mid-unmount, ...) — a real read failure, not "no backup".
|
|
1494
|
+
# Reported through the caller's list, the same as the
|
|
1495
|
+
# Keychain OSError arm below: this is the ONLY backend on
|
|
1496
|
+
# Linux/WSL/Windows, and it wins over the Keychain on macOS,
|
|
1497
|
+
# so masking it must not read as "absent" on any platform.
|
|
1498
|
+
if failed is not None:
|
|
1499
|
+
failed.append(True)
|
|
1500
|
+
self._host._logger.warning(f"Failed to read credentials file: {e}")
|
|
1501
|
+
else:
|
|
1502
|
+
try:
|
|
1503
|
+
# validate=True: reject non-alphabet junk (e.g. "!!!!") instead
|
|
1504
|
+
# of silently discarding it to empty bytes, which would let a
|
|
1505
|
+
# corrupt .enc shadow a valid Keychain copy.
|
|
1506
|
+
decoded = base64.b64decode(encoded, validate=True).decode("utf-8")
|
|
1507
|
+
except Exception as e:
|
|
1508
|
+
# Corrupt/garbled .enc → on macOS fall through to the Keychain
|
|
1509
|
+
# copy (documented recovery) — content-level, not a read
|
|
1510
|
+
# failure, so this does NOT mark `failed`.
|
|
1511
|
+
self._host._logger.warning(f"Failed to read credentials file: {e}")
|
|
1512
|
+
else:
|
|
1513
|
+
if decoded:
|
|
1514
|
+
return decoded
|
|
1515
|
+
# Empty/whitespace .enc is not a real backup → try the Keychain.
|
|
1516
|
+
if self._host.platform == Platform.MACOS:
|
|
1517
|
+
try:
|
|
1518
|
+
return self._kc_read_backup(account_num, email, cached=cached)
|
|
1519
|
+
except KeychainBackedOff:
|
|
1520
|
+
# An expected skip inside the cooldown, announced once when
|
|
1521
|
+
# it began — unreadable, but not a new failure to warn about
|
|
1522
|
+
# on every lookup.
|
|
1523
|
+
if failed is not None:
|
|
1524
|
+
failed.append(True)
|
|
1525
|
+
except macos_keychain.KEYCHAIN_ERRORS as e:
|
|
1526
|
+
# Reported through the caller's list, not an instance flag:
|
|
1527
|
+
# that flag was shared by every thread and its window spans a
|
|
1528
|
+
# ~10-50ms `security` subprocess. Measured with one sibling
|
|
1529
|
+
# reader, slot 2 genuinely denied: 2 of 60 reads came back
|
|
1530
|
+
# "readable", and the consume gate then POSTs a spent grant.
|
|
1531
|
+
if failed is not None:
|
|
1532
|
+
failed.append(True)
|
|
1533
|
+
self._host._logger.warning(f"Failed to read credentials from Keychain: {e}")
|
|
1534
|
+
return ""
|
|
1535
|
+
|
|
1536
|
+
def _read_account_credentials_ex(
|
|
1537
|
+
self, account_num: str, email: str, *, cached: bool = False
|
|
1538
|
+
) -> tuple[str, bool]:
|
|
1539
|
+
"""Backup read with an unreadable-vs-absent verdict.
|
|
1540
|
+
|
|
1541
|
+
Returns ``(value, unreadable)``. ``unreadable`` is True when the read
|
|
1542
|
+
that produced ``""`` actually FAILED rather than finding nothing: the
|
|
1543
|
+
``.enc`` exists but raised an ``OSError`` (permissions, a mid-unmount
|
|
1544
|
+
— every platform), or the ``.enc`` had nothing and the macOS Keychain
|
|
1545
|
+
read itself *raised* (locked / denied / timeout). A genuinely absent
|
|
1546
|
+
backup (no .enc, keychain answered "not found") reads as
|
|
1547
|
+
``("", False)``. Callers use the distinction to say "keychain
|
|
1548
|
+
unavailable — retry from a GUI session" instead of nudging the user
|
|
1549
|
+
into an unnecessary re-add/re-login. The ``.enc`` is the ONLY backend
|
|
1550
|
+
on Linux/WSL/Windows, so its own read failure must reach this verdict
|
|
1551
|
+
there too, not only on macOS.
|
|
1552
|
+
"""
|
|
1553
|
+
failed: list = []
|
|
1554
|
+
value = self._read_account_credentials(
|
|
1555
|
+
account_num, email, failed, cached=cached
|
|
1556
|
+
)
|
|
1557
|
+
if value:
|
|
1558
|
+
return value, False
|
|
1559
|
+
if self._host.platform != Platform.MACOS:
|
|
1560
|
+
return "", bool(failed)
|
|
1561
|
+
# Whether THIS read reached the Keychain, observed at the read itself.
|
|
1562
|
+
#
|
|
1563
|
+
# This used to ask `_keychain_unreadable`, which answers a different
|
|
1564
|
+
# question: has any Keychain op failed and not been superseded. It gets
|
|
1565
|
+
# overwritten by an unrelated event. `_pin_file_mode` sets
|
|
1566
|
+
# `_file_mode_is_ours` and clears the re-probe deadline, and on macOS it
|
|
1567
|
+
# is only reachable THROUGH a Keychain op that just failed — both call
|
|
1568
|
+
# sites are in the fallback branch of a write that raised. So one
|
|
1569
|
+
# active-credential write fallback flipped this answer for the rest of
|
|
1570
|
+
# the process while the Keychain stayed locked:
|
|
1571
|
+
#
|
|
1572
|
+
# state A _read_account_credentials_ex('3') -> ('', True)
|
|
1573
|
+
# ...one fallback write...
|
|
1574
|
+
# state B _read_account_credentials_ex('3') -> ('', False)
|
|
1575
|
+
#
|
|
1576
|
+
# The pin's premise ("we wrote the credential to the file, that file is
|
|
1577
|
+
# the authority") holds for the ACTIVE credential and says nothing about
|
|
1578
|
+
# the BACKUP, which is Keychain-only by design —
|
|
1579
|
+
# `_reconcile_enc_after_keychain_write` deletes the `.enc` after a
|
|
1580
|
+
# successful Keychain write. So the consume gate read "genuinely empty",
|
|
1581
|
+
# POSTed the caller's possibly-superseded snapshot, took invalid_grant,
|
|
1582
|
+
# and quarantined a slot whose live refresh token was sitting unread.
|
|
1583
|
+
#
|
|
1584
|
+
# Cleared above rather than trusted from a previous call: a caller that
|
|
1585
|
+
# substitutes `_read_account_credentials` never reaches the setter, and
|
|
1586
|
+
# a stale True there would defer forever.
|
|
1587
|
+
#
|
|
1588
|
+
# Swapping this for `_keychain_unreadable` was once believed to leave
|
|
1589
|
+
# the suite green on a single thread (the process flag supposedly
|
|
1590
|
+
# agreeing with `_kc_read_backup`'s own `_kc_call`-routed verdict on
|
|
1591
|
+
# every state one thread can reach) — re-measured directly (swap the
|
|
1592
|
+
# return value, run the full suite) and that does NOT reproduce:
|
|
1593
|
+
# `TestOurOwnFileModeIsNotAKeychainFailure::
|
|
1594
|
+
# test_two_concurrent_backup_reads_keep_their_own_verdicts` and
|
|
1595
|
+
# `TestEncPermissionDeniedIsUnreadable::
|
|
1596
|
+
# test_unreadable_enc_is_not_absent_on_macos` both fail on a single
|
|
1597
|
+
# thread. Concurrently it is wrong for the additional reason above
|
|
1598
|
+
# (the sentinel calls this seam unlocked while the consume gate holds
|
|
1599
|
+
# a per-slot lock, and the TUI runs three workers on one store) — but
|
|
1600
|
+
# the single-thread case was never actually safe either.
|
|
1601
|
+
return "", bool(failed)
|
|
1602
|
+
|
|
1603
|
+
def _write_account_credentials(
|
|
1604
|
+
self, account_num: str, email: str, credentials: str
|
|
1605
|
+
) -> None:
|
|
1606
|
+
"""Write account credentials to backup (pure I/O — no session invalidation).
|
|
1607
|
+
|
|
1608
|
+
macOS writes the Keychain when usable, then reconciles the ``.enc`` away
|
|
1609
|
+
(see ``_reconcile_enc_after_keychain_write``). When the Keychain is unusable
|
|
1610
|
+
it writes the ``.enc`` atomically, then best-effort deletes any stale
|
|
1611
|
+
Keychain copy so a recovered Keychain can't shadow the fresh file.
|
|
1612
|
+
Linux/WSL/Windows write the ``.enc`` only.
|
|
1613
|
+
|
|
1614
|
+
Raises on a file-write failure **before** returning, so the switcher wrapper
|
|
1615
|
+
runs ``_post_backup_write`` exactly once and only after a successful write.
|
|
1616
|
+
|
|
1617
|
+
Before overwriting, the current generation is retained as a ``.prev`` file
|
|
1618
|
+
(one generation, best-effort): a refresh token exists in exactly one place,
|
|
1619
|
+
giving a misclassified overwrite a best-effort chance of recovery without
|
|
1620
|
+
a /login.
|
|
1621
|
+
"""
|
|
1622
|
+
self._retain_previous_backup(account_num, email, credentials)
|
|
1623
|
+
if self._use_keychain():
|
|
1624
|
+
try:
|
|
1625
|
+
self._kc_write_backup(account_num, email, credentials)
|
|
1626
|
+
except macos_keychain.KEYCHAIN_ERRORS as e:
|
|
1627
|
+
# Keychain unusable; _kc_call flipped routing to file mode.
|
|
1628
|
+
# (A programming error is NOT caught here — it propagates.)
|
|
1629
|
+
self._host._logger.warning(
|
|
1630
|
+
f"Keychain backup write failed, falling back to file: {e}"
|
|
1631
|
+
)
|
|
1632
|
+
else:
|
|
1633
|
+
self._reconcile_enc_after_keychain_write(account_num, email, credentials)
|
|
1634
|
+
return
|
|
1635
|
+
|
|
1636
|
+
# File mode: write the .enc atomically, then (macOS) best-effort drop the
|
|
1637
|
+
# stale Keychain copy so a recovered Keychain can't shadow the fresh file.
|
|
1638
|
+
try:
|
|
1639
|
+
self._write_backup_enc(account_num, email, credentials)
|
|
1640
|
+
except Exception as e:
|
|
1641
|
+
self._host._logger.warning(f"Failed to write credentials file: {e}")
|
|
1642
|
+
raise
|
|
1643
|
+
if self._host.platform == Platform.MACOS:
|
|
1644
|
+
self._delete_backup_keychain_quiet(account_num, email)
|
|
1645
|
+
|
|
1646
|
+
def _delete_account_credentials(self, account_num: str, email: str) -> None:
|
|
1647
|
+
"""Delete account credentials from backup (both backends on macOS).
|
|
1648
|
+
|
|
1649
|
+
Removes the ``.enc`` file(s) and, on macOS, the Keychain item(s). The
|
|
1650
|
+
Keychain delete is best-effort: if it's locked the item may linger as
|
|
1651
|
+
harmless unreferenced cruft (the slot is gone from sequence.json; a re-add
|
|
1652
|
+
overwrites it via ``-U``; purge sweeps it). Includes the legacy
|
|
1653
|
+
``account-None-{email}`` alias.
|
|
1654
|
+
"""
|
|
1655
|
+
nums = [account_num]
|
|
1656
|
+
if str(account_num) != "None":
|
|
1657
|
+
nums.append("None")
|
|
1658
|
+
for num in nums:
|
|
1659
|
+
enc_file = self._backup_enc_path(num, email)
|
|
1660
|
+
try:
|
|
1661
|
+
if enc_file.exists():
|
|
1662
|
+
enc_file.unlink()
|
|
1663
|
+
except Exception as e:
|
|
1664
|
+
self._host._logger.warning(f"Failed to delete credentials file: {e}")
|
|
1665
|
+
if self._host.platform == Platform.MACOS:
|
|
1666
|
+
self._delete_backup_keychain_quiet(num, email)
|
|
1667
|
+
self.delete_previous_backup(num, email)
|
|
1668
|
+
|
|
1669
|
+
def delete_account_credentials_strict(
|
|
1670
|
+
self, account_num: str, email: str
|
|
1671
|
+
) -> None:
|
|
1672
|
+
"""Clear a slot key, failing closed: raise unless emptiness is assured.
|
|
1673
|
+
|
|
1674
|
+
For transactional pre-commit clears (the swap/move write-or-clear
|
|
1675
|
+
step and rollback restoration): a destination that must be empty but
|
|
1676
|
+
may still serve material is exactly the wrong-credential state the
|
|
1677
|
+
transaction exists to prevent, so backend failures must abort the
|
|
1678
|
+
commit rather than be logged away. A read-back alone cannot provide
|
|
1679
|
+
this: the normal reader converts Keychain errors to ``""``, which
|
|
1680
|
+
conflates "absent" with "unreadable" — a locked Keychain holding a
|
|
1681
|
+
stale item would pass verification and resurface on unlock. So the
|
|
1682
|
+
served backends are deleted with errors propagating; absence itself
|
|
1683
|
+
counts as success on both (missing ``.enc``; Keychain rc 44). The
|
|
1684
|
+
Keychain delete runs even when routing says file mode, for the same
|
|
1685
|
+
reason. Legacy-alias and ``.prev`` sweeps stay best-effort — reads
|
|
1686
|
+
never serve them. The best-effort variant remains right for
|
|
1687
|
+
post-commit cleanup, where a failure only leaks an unreferenced file.
|
|
1688
|
+
"""
|
|
1689
|
+
# Best-effort sweep first: same cruft cleanup (legacy alias, .prev,
|
|
1690
|
+
# quiet Keychain) a normal delete performs.
|
|
1691
|
+
self._delete_account_credentials(account_num, email)
|
|
1692
|
+
# Then assure the served key really is gone, propagating failures.
|
|
1693
|
+
# Unconditional unlink: exists() returns False on an inaccessible
|
|
1694
|
+
# directory, which would fail open here — missing is fine
|
|
1695
|
+
# (missing_ok), permission/I/O errors must abort the commit.
|
|
1696
|
+
try:
|
|
1697
|
+
self._backup_enc_path(account_num, email).unlink(missing_ok=True)
|
|
1698
|
+
if self._host.platform == Platform.MACOS:
|
|
1699
|
+
self._kc_delete_backup(account_num, email)
|
|
1700
|
+
except (OSError, *macos_keychain.KEYCHAIN_ERRORS) as e:
|
|
1701
|
+
raise CredentialError(
|
|
1702
|
+
f"Could not clear stored credentials for slot {account_num} "
|
|
1703
|
+
f"({email}) — aborting before commit: {e}"
|
|
1704
|
+
) from e
|
|
1705
|
+
# Final belt: catches any backend view the deletes above missed. The
|
|
1706
|
+
# plain reader cannot serve this — it is the exact reader this
|
|
1707
|
+
# docstring says "conflates absent with unreadable" — so an
|
|
1708
|
+
# unreadable-but-present view (a locked Keychain, a permission
|
|
1709
|
+
# glitch on the .enc) would pass verification and resurface later.
|
|
1710
|
+
# `_ex` distinguishes the two; either a served value OR an
|
|
1711
|
+
# unreadable verdict aborts the commit.
|
|
1712
|
+
value, unreadable = self._read_account_credentials_ex(account_num, email)
|
|
1713
|
+
if value or unreadable:
|
|
1714
|
+
raise CredentialError(
|
|
1715
|
+
f"Could not clear stored credentials for slot {account_num} "
|
|
1716
|
+
f"({email}) — aborting before commit"
|
|
1717
|
+
)
|
|
1718
|
+
|
|
1719
|
+
def delete_previous_backup(self, account_num: str, email: str) -> None:
|
|
1720
|
+
"""Drop a slot key's retained ``.prev`` generation (both backends).
|
|
1721
|
+
|
|
1722
|
+
Best-effort, like retention itself. Called from full-key deletion,
|
|
1723
|
+
and on its own when a key's history stops belonging to its account —
|
|
1724
|
+
a renumber (swap/move) writes another account's material through the
|
|
1725
|
+
key, and recovery must never resurrect the displaced generation onto
|
|
1726
|
+
the key's new owner.
|
|
1727
|
+
"""
|
|
1728
|
+
prev_file = self._prev_backup_path(account_num, email)
|
|
1729
|
+
try:
|
|
1730
|
+
if prev_file.exists():
|
|
1731
|
+
prev_file.unlink()
|
|
1732
|
+
except Exception as e:
|
|
1733
|
+
self._host._logger.warning(f"Failed to delete .prev file: {e}")
|
|
1734
|
+
if self._host.platform == Platform.MACOS:
|
|
1735
|
+
try:
|
|
1736
|
+
self._kc_delete_backup_prev(account_num, email)
|
|
1737
|
+
except Exception as e:
|
|
1738
|
+
self._host._logger.warning(
|
|
1739
|
+
f"Failed to delete .prev from Keychain: {e}"
|
|
1740
|
+
)
|
|
1741
|
+
|
|
1742
|
+
# -- previous-generation retention -------------------------------------
|
|
1743
|
+
#
|
|
1744
|
+
# One retained generation per slot, routed by the same rule as the backup
|
|
1745
|
+
# itself: Keychain when the Keychain is in use, ``.enc.prev`` file
|
|
1746
|
+
# otherwise. Retention must not *weaken* the user's storage posture — a
|
|
1747
|
+
# Mac whose credentials live in the Keychain must not grow a plaintext
|
|
1748
|
+
# copy just for recovery. Best-effort by design: the *primary* safety
|
|
1749
|
+
# boundary is the switch-time provenance check + unclaimed stash (whose
|
|
1750
|
+
# failure aborts); ``.prev`` is defense in depth for writes that were
|
|
1751
|
+
# classified as safe but weren't.
|
|
1752
|
+
|
|
1753
|
+
def _prev_backup_path(self, account_num: str, email: str) -> Path:
|
|
1754
|
+
return self._host.credentials_dir / f".creds-{account_num}-{email}.enc.prev"
|
|
1755
|
+
|
|
1756
|
+
def _prev_backup_username(self, account_num: str, email: str) -> str:
|
|
1757
|
+
return f"{self._backup_username(account_num, email)}.prev"
|
|
1758
|
+
|
|
1759
|
+
def _retain_previous_backup(
|
|
1760
|
+
self, account_num: str, email: str, new_credentials: str
|
|
1761
|
+
) -> None:
|
|
1762
|
+
"""Retain the slot's current backup as ``.prev`` before it is replaced.
|
|
1763
|
+
|
|
1764
|
+
C1: when the current generation can't be read (a locked Keychain, an
|
|
1765
|
+
unreadable ``.enc``), the caller's overwrite proceeds regardless — the
|
|
1766
|
+
write this retention protects is never conditional on retention
|
|
1767
|
+
succeeding. No ``.prev`` is written in that case (see the WITHDRAWN
|
|
1768
|
+
comment below for why a checkpoint of the incoming bytes was tried
|
|
1769
|
+
and reverted).
|
|
1770
|
+
"""
|
|
1771
|
+
try:
|
|
1772
|
+
current, unreadable = self._read_account_credentials_ex(account_num, email)
|
|
1773
|
+
except Exception as e: # pragma: no cover - _read swallows its own errors
|
|
1774
|
+
self._host._logger.warning(f"Could not read backup for retention: {e}")
|
|
1775
|
+
return
|
|
1776
|
+
if unreadable:
|
|
1777
|
+
# WITHDRAWN (round 10): rounds 8 and 9 tried to salvage this path by
|
|
1778
|
+
# checkpointing the INCOMING bytes as `.prev`. Both attempts shipped
|
|
1779
|
+
# a regression, each found by the next review:
|
|
1780
|
+
#
|
|
1781
|
+
# r8 overwrote a real `.prev` holding a genuine previous
|
|
1782
|
+
# generation with a duplicate of the incoming bytes.
|
|
1783
|
+
# r9 guarded that with `_read_previous_backup`, which collapses
|
|
1784
|
+
# absent / unreadable / corrupt to `""` -- so on a LOCKED
|
|
1785
|
+
# Keychain (the very scenario this branch names) the guard
|
|
1786
|
+
# reads "" and fires anyway, writing a plaintext `.enc.prev`
|
|
1787
|
+
# that then WINS over the real Keychain `.prev` by the
|
|
1788
|
+
# .enc-wins rule and shadows it even after the lock clears.
|
|
1789
|
+
#
|
|
1790
|
+
# Measured, r9 tree, controls first:
|
|
1791
|
+
# readable + real .prev exists -> wrote NOTHING (guard works)
|
|
1792
|
+
# readable + no prior .prev -> wrote kc (checkpoint)
|
|
1793
|
+
# LOCKED + real Keychain .prev-> wrote FILE (SHADOWS IT)
|
|
1794
|
+
#
|
|
1795
|
+
# The honest position is that the true previous generation is
|
|
1796
|
+
# unrecoverable here, and a checkpoint that can silently outrank a
|
|
1797
|
+
# real one is worse than the absence it was meant to fill. Log and
|
|
1798
|
+
# decline. `upstream/main` has no `.prev` at all, so this is no
|
|
1799
|
+
# worse there; what it is not is a cushion that lies.
|
|
1800
|
+
#
|
|
1801
|
+
# INFO, not WARNING: the reader already reported the read failure
|
|
1802
|
+
# (or the Keychain cooldown announced it once), the write proceeds
|
|
1803
|
+
# and the slot's existing `.prev` is left untouched.
|
|
1804
|
+
self._host._logger.info(
|
|
1805
|
+
f"Could not retain previous credential generation for "
|
|
1806
|
+
f"account {account_num}: the current backup exists but "
|
|
1807
|
+
"could not be read (not absent) — no .prev recovery copy "
|
|
1808
|
+
"will exist for this write"
|
|
1809
|
+
)
|
|
1810
|
+
return
|
|
1811
|
+
if not current or current == new_credentials:
|
|
1812
|
+
return
|
|
1813
|
+
try:
|
|
1814
|
+
if self._use_keychain():
|
|
1815
|
+
self._kc_call(
|
|
1816
|
+
macos_keychain.set_password,
|
|
1817
|
+
SECURITY_SERVICE,
|
|
1818
|
+
self._prev_backup_username(account_num, email),
|
|
1819
|
+
current,
|
|
1820
|
+
)
|
|
1821
|
+
else:
|
|
1822
|
+
self._atomic_b64_write(
|
|
1823
|
+
self._prev_backup_path(account_num, email), current
|
|
1824
|
+
)
|
|
1825
|
+
except Exception as e:
|
|
1826
|
+
self._host._logger.warning(
|
|
1827
|
+
f"Failed to retain previous credential generation for "
|
|
1828
|
+
f"account {account_num}: {e}"
|
|
1829
|
+
)
|
|
1830
|
+
|
|
1831
|
+
def _read_previous_backup(self, account_num: str, email: str) -> str:
|
|
1832
|
+
"""Read the retained previous generation. ``""`` when absent/corrupt.
|
|
1833
|
+
|
|
1834
|
+
``.enc.prev``-wins like the main backup read: a file written while the
|
|
1835
|
+
Keychain was unusable beats a possibly-stale Keychain copy.
|
|
1836
|
+
"""
|
|
1837
|
+
prev_file = self._prev_backup_path(account_num, email)
|
|
1838
|
+
if prev_file.exists():
|
|
1839
|
+
try:
|
|
1840
|
+
encoded = prev_file.read_text(encoding="utf-8").strip()
|
|
1841
|
+
decoded = base64.b64decode(encoded, validate=True).decode("utf-8")
|
|
1842
|
+
if decoded:
|
|
1843
|
+
return decoded
|
|
1844
|
+
except Exception as e:
|
|
1845
|
+
self._host._logger.warning(f"Failed to read .prev file: {e}")
|
|
1846
|
+
if self._host.platform == Platform.MACOS:
|
|
1847
|
+
try:
|
|
1848
|
+
return self._kc_call(
|
|
1849
|
+
macos_keychain.get_password,
|
|
1850
|
+
SECURITY_SERVICE,
|
|
1851
|
+
self._prev_backup_username(account_num, email),
|
|
1852
|
+
) or ""
|
|
1853
|
+
except macos_keychain.KEYCHAIN_ERRORS as e:
|
|
1854
|
+
self._host._logger.warning(f"Failed to read .prev from Keychain: {e}")
|
|
1855
|
+
return ""
|
|
1856
|
+
|
|
1857
|
+
# -- internal safety copies (unclaimed credentials) ----------------------
|
|
1858
|
+
#
|
|
1859
|
+
# Write-only preservation for live credential bytes a switch positively
|
|
1860
|
+
# attributed to someone other than the outgoing slot (invariant: never
|
|
1861
|
+
# overwrite the live store without preserving what was in it — the bytes
|
|
1862
|
+
# may be the only live copy of some account's refresh token). Entries are
|
|
1863
|
+
# append-only base64 files with a JSON manifest carrying the
|
|
1864
|
+
# classification evidence; nothing consumes them automatically — recovery
|
|
1865
|
+
# is the documented `cswap login N`, and these files are
|
|
1866
|
+
# forensic material for maintainers.
|
|
1867
|
+
#
|
|
1868
|
+
# Deliberately 0600 files on every platform, unlike the slot backups and
|
|
1869
|
+
# ``.prev``, which route to the macOS Keychain when it is in use: a failed
|
|
1870
|
+
# safety-copy write aborts the switch by design, and that abort path must
|
|
1871
|
+
# not inherit the Keychain's failure modes (#101/#106 — a flaky Keychain
|
|
1872
|
+
# would start blocking switches). On macOS this means these rare files
|
|
1873
|
+
# sit outside the Keychain, base64-encoded with owner-only permissions.
|
|
1874
|
+
|
|
1875
|
+
def _stash_manifest_path(self) -> Path:
|
|
1876
|
+
return self._host.credentials_dir / ".unclaimed-manifest.json"
|
|
1877
|
+
|
|
1878
|
+
def _stash_entry_path(self, entry_id: str) -> Path:
|
|
1879
|
+
return self._host.credentials_dir / f".unclaimed-{entry_id}.enc"
|
|
1880
|
+
|
|
1881
|
+
def _read_stash_manifest_ex(self) -> tuple[dict, str]:
|
|
1882
|
+
"""Manifest read with a three-way verdict: ok / unreadable / corrupt.
|
|
1883
|
+
|
|
1884
|
+
Returns ``(entries, verdict)``. The verdict exists because "no rows"
|
|
1885
|
+
and "could not establish the rows" have opposite consequences here: a
|
|
1886
|
+
stash row is the SOLE record of a generation a prior gate pass already
|
|
1887
|
+
consumed, so a caller that reads a failure as "nothing stashed" POSTs
|
|
1888
|
+
the spent generation — the one POST the consume gate exists to
|
|
1889
|
+
prevent. The failure is also CORRELATED rather than independent: the
|
|
1890
|
+
stash exists *because* storage I/O already failed once.
|
|
1891
|
+
|
|
1892
|
+
A bool cannot carry it, because the two failure modes need different
|
|
1893
|
+
answers and one of them is caller-dependent:
|
|
1894
|
+
|
|
1895
|
+
- ``"unreadable"`` — the bytes exist and could not be read (locked
|
|
1896
|
+
keychain, EIO, a mode). Transient by nature and self-clearing, so
|
|
1897
|
+
every caller defers: it costs a pass and spends nothing.
|
|
1898
|
+
- ``"corrupt"`` — the bytes were read and are not a manifest. This is
|
|
1899
|
+
PERMANENT, so a blanket fail-closed would deadlock the slot: the
|
|
1900
|
+
repair is ``_write_stash_manifest`` renaming the bad file aside, and
|
|
1901
|
+
that runs only on a manifest WRITE, which deferring prevents. The
|
|
1902
|
+
adopt scan therefore decides by whether any entry bytes are actually
|
|
1903
|
+
at risk (see ``_stash_entry_files_exist``), and the mutator proceeds
|
|
1904
|
+
so the set-aside can happen at all.
|
|
1905
|
+
- ``"ok"`` — includes a genuinely absent manifest; no rows and nothing
|
|
1906
|
+
to protect read the same to every caller.
|
|
1907
|
+
|
|
1908
|
+
The read, not ``exists()``, decides. ``Path.exists()`` answers False
|
|
1909
|
+
for an unsearchable directory on 3.13+ and RAISES on 3.12, so gating
|
|
1910
|
+
on it makes this verdict depend on the interpreter — the same trap
|
|
1911
|
+
this branch removes from the backup reader.
|
|
1912
|
+
"""
|
|
1913
|
+
path = self._stash_manifest_path()
|
|
1914
|
+
# BYTES, so the two failure classes cannot cross. `read_text` decodes
|
|
1915
|
+
# inside the read, and ``UnicodeDecodeError`` is a ``ValueError``, not
|
|
1916
|
+
# an ``OSError`` — undecodable bytes would escape an OSError-only
|
|
1917
|
+
# split entirely, where the single ``except Exception`` this replaces
|
|
1918
|
+
# swallowed them. Decoding below puts them where they belong: the
|
|
1919
|
+
# bytes were readable, their content is garbage. That is corrupt.
|
|
1920
|
+
try:
|
|
1921
|
+
raw = path.read_bytes()
|
|
1922
|
+
except FileNotFoundError:
|
|
1923
|
+
return {}, "ok"
|
|
1924
|
+
except OSError as e:
|
|
1925
|
+
self._host._logger.warning(f"Unclaimed manifest unreadable: {e}")
|
|
1926
|
+
return {}, "unreadable"
|
|
1927
|
+
try:
|
|
1928
|
+
entries = json.loads(raw.decode("utf-8")).get("entries")
|
|
1929
|
+
except Exception as e:
|
|
1930
|
+
self._host._logger.warning(f"Failed to read unclaimed manifest: {e}")
|
|
1931
|
+
return {}, "corrupt"
|
|
1932
|
+
if not isinstance(entries, dict):
|
|
1933
|
+
# Parseable, but structurally not a manifest: ``entries`` missing
|
|
1934
|
+
# or the wrong type. Reading that as ok-with-no-rows re-opens the
|
|
1935
|
+
# gap the corrupt verdict closes — orphan entry files would bypass
|
|
1936
|
+
# the fail-closed condition because the verdict said nothing was
|
|
1937
|
+
# wrong. The rows are as unestablishable as under unparseable
|
|
1938
|
+
# bytes, so it gets the same verdict.
|
|
1939
|
+
self._host._logger.warning(
|
|
1940
|
+
"Unclaimed manifest parses but has no valid 'entries' member"
|
|
1941
|
+
)
|
|
1942
|
+
return {}, "corrupt"
|
|
1943
|
+
return entries, "ok"
|
|
1944
|
+
|
|
1945
|
+
def _stash_entry_files_exist(self) -> bool:
|
|
1946
|
+
"""Is there any stashed credential's BYTES on disk?
|
|
1947
|
+
|
|
1948
|
+
Asked only when the manifest is corrupt, to tell "the mapping is gone
|
|
1949
|
+
and there is nothing it could have mapped" from "the mapping is gone
|
|
1950
|
+
and a consumed generation's only copy is sitting right here". The
|
|
1951
|
+
entry files are named independently of the manifest, so they answer
|
|
1952
|
+
even when it cannot.
|
|
1953
|
+
|
|
1954
|
+
Unknowable answers TRUE: a directory we cannot list is not evidence
|
|
1955
|
+
that nothing is at risk, and the caller uses this to decide whether to
|
|
1956
|
+
spend a grant.
|
|
1957
|
+
|
|
1958
|
+
``iterdir``, NOT ``glob``. ``Path.glob`` SUPPRESSES directory-scan
|
|
1959
|
+
``OSError``s, so the guard's except arm never ran: measured on 3.14.6,
|
|
1960
|
+
a searchable-but-unlistable credentials dir (mode 0o311) returned
|
|
1961
|
+
``[]`` with a real orphan sitting right there — the manifest and the
|
|
1962
|
+
entry bytes stay readable through the searchable dir, so corrupt+
|
|
1963
|
+
orphans read as corrupt+empty and the gate POSTed the spent grant.
|
|
1964
|
+
``iterdir`` raises on the same state. The same interpreter-suppression
|
|
1965
|
+
trap as ``Path.exists()``, third appearance in this file.
|
|
1966
|
+
|
|
1967
|
+
A MISSING directory is the one ``OSError`` that answers False: no
|
|
1968
|
+
credentials dir means provably nothing was ever stashed.
|
|
1969
|
+
"""
|
|
1970
|
+
try:
|
|
1971
|
+
for entry in self._host.credentials_dir.iterdir():
|
|
1972
|
+
name = entry.name
|
|
1973
|
+
if name.startswith(".unclaimed-") and name.endswith(".enc"):
|
|
1974
|
+
return True
|
|
1975
|
+
except FileNotFoundError:
|
|
1976
|
+
return False
|
|
1977
|
+
except OSError:
|
|
1978
|
+
return True
|
|
1979
|
+
return False
|
|
1980
|
+
|
|
1981
|
+
def _read_stash_manifest(self) -> dict:
|
|
1982
|
+
return self._read_stash_manifest_ex()[0]
|
|
1983
|
+
|
|
1984
|
+
def _write_stash_manifest(self, entries: dict) -> None:
|
|
1985
|
+
from claude_swap.settings import atomic_write_json
|
|
1986
|
+
|
|
1987
|
+
self._host.credentials_dir.mkdir(parents=True, exist_ok=True)
|
|
1988
|
+
path = self._stash_manifest_path()
|
|
1989
|
+
# A corrupt manifest read as {} must not be silently clobbered — the
|
|
1990
|
+
# rows are classification evidence. Set it aside (the entry *bytes*
|
|
1991
|
+
# are separate files and keep being listed as orphans either way).
|
|
1992
|
+
# Failing closed instead would brick switching: a stash-write failure
|
|
1993
|
+
# aborts the switch by design.
|
|
1994
|
+
if path.exists():
|
|
1995
|
+
try:
|
|
1996
|
+
json.loads(path.read_text(encoding="utf-8"))
|
|
1997
|
+
except Exception:
|
|
1998
|
+
aside = path.with_name(
|
|
1999
|
+
f"{path.name}.corrupt-{int(time.time())}"
|
|
2000
|
+
)
|
|
2001
|
+
try:
|
|
2002
|
+
path.rename(aside)
|
|
2003
|
+
self._host._logger.warning(
|
|
2004
|
+
f"Unreadable unclaimed manifest preserved as {aside.name}"
|
|
2005
|
+
)
|
|
2006
|
+
except OSError as e:
|
|
2007
|
+
self._host._logger.warning(
|
|
2008
|
+
f"Could not preserve corrupt unclaimed manifest: {e}"
|
|
2009
|
+
)
|
|
2010
|
+
atomic_write_json(path, {"schemaVersion": 1, "entries": entries})
|
|
2011
|
+
|
|
2012
|
+
def _mutate_stash_manifest(self, mutate) -> None:
|
|
2013
|
+
"""Apply ``mutate(entries)`` to the manifest as one atomic step.
|
|
2014
|
+
|
|
2015
|
+
The manifest is a single whole-file rewrite, so read-modify-write is
|
|
2016
|
+
only safe under mutual exclusion. Its own lock, deliberately NOT the
|
|
2017
|
+
slot lock: the stash writer at ``switcher.py``'s ``except LockError``
|
|
2018
|
+
runs precisely BECAUSE the slot lock was unavailable, so it can never
|
|
2019
|
+
take it, while the retire it races runs under it. Unsynchronized, the
|
|
2020
|
+
two rewrite the whole file from snapshots taken before the other's
|
|
2021
|
+
write and each drops the other's row -- measured 50 of 80 rows lost
|
|
2022
|
+
with three real concurrent workers, 0 lost with the same workload
|
|
2023
|
+
serialized.
|
|
2024
|
+
|
|
2025
|
+
Losing a row is not cosmetic: ``_adopt_stashed_successor`` iterates
|
|
2026
|
+
manifest rows only, so a row-less entry can never be adopted, while
|
|
2027
|
+
``_list_unclaimed_credentials``' glob keeps listing its bytes forever.
|
|
2028
|
+
|
|
2029
|
+
This raises on failure -- ``LockError`` on a lock timeout, ``OSError``
|
|
2030
|
+
from ``_write_stash_manifest``'s ``atomic_write_json`` (full disk,
|
|
2031
|
+
read-only mount) -- and the two callers want opposite things from
|
|
2032
|
+
that, so neither may assume the other's handling.
|
|
2033
|
+
|
|
2034
|
+
A failed STASH must be loud: callers treat a successful one as the
|
|
2035
|
+
license to overwrite the live store.
|
|
2036
|
+
|
|
2037
|
+
A failed RETIRE must not be. It is housekeeping, and its call sites in
|
|
2038
|
+
``_adopt_stashed_successor`` run after a store write that already
|
|
2039
|
+
advanced the slot, so a raise there would report a failed refresh for
|
|
2040
|
+
a slot that is in fact freshened and make the caller re-POST a spent
|
|
2041
|
+
generation. ``_retire_stash_entry`` therefore swallows and logs.
|
|
2042
|
+
"""
|
|
2043
|
+
from claude_swap.locking import FileLock
|
|
2044
|
+
|
|
2045
|
+
self._host.credentials_dir.mkdir(parents=True, exist_ok=True)
|
|
2046
|
+
with FileLock(self._stash_manifest_path().with_suffix(".lock")):
|
|
2047
|
+
entries, verdict = self._read_stash_manifest_ex()
|
|
2048
|
+
if verdict == "unreadable":
|
|
2049
|
+
# Reading an unreadable-but-VALID manifest as `{}` does not
|
|
2050
|
+
# merely miss rows. ``_write_stash_manifest`` below finds the
|
|
2051
|
+
# same file unparseable, renames the healthy manifest aside,
|
|
2052
|
+
# and writes a fresh one holding only this mutation's row —
|
|
2053
|
+
# orphaning every previously mapped successor in one step,
|
|
2054
|
+
# in exactly the correlated setting where a stash is being
|
|
2055
|
+
# written because storage already misbehaved.
|
|
2056
|
+
#
|
|
2057
|
+
# Raising suits both callers: a failed STASH must be loud (a
|
|
2058
|
+
# successful one is the licence to overwrite the live store),
|
|
2059
|
+
# and a failed RETIRE is already swallowed by
|
|
2060
|
+
# ``_retire_stash_entry``.
|
|
2061
|
+
#
|
|
2062
|
+
# CORRUPT deliberately falls through: the set-aside below is
|
|
2063
|
+
# the only repair, and it can only happen on a write.
|
|
2064
|
+
raise CredentialReadError(
|
|
2065
|
+
"the unclaimed manifest is unreadable; refusing to rewrite "
|
|
2066
|
+
"it from an empty read, which would orphan every stashed "
|
|
2067
|
+
"successor it maps"
|
|
2068
|
+
)
|
|
2069
|
+
mutate(entries)
|
|
2070
|
+
self._write_stash_manifest(entries)
|
|
2071
|
+
|
|
2072
|
+
def _write_unclaimed_credential(self, credentials: str, context: dict) -> str:
|
|
2073
|
+
"""Stash a credential of unknown provenance. Returns the entry id.
|
|
2074
|
+
|
|
2075
|
+
Raises on any failure — callers use a successful stash as the license
|
|
2076
|
+
to overwrite the live store, so a failed one must be loud. The entry
|
|
2077
|
+
file is written before the manifest: an entry without manifest metadata
|
|
2078
|
+
is recoverable; a manifest row without bytes is not.
|
|
2079
|
+
"""
|
|
2080
|
+
import hashlib
|
|
2081
|
+
import secrets
|
|
2082
|
+
from datetime import datetime, timezone
|
|
2083
|
+
|
|
2084
|
+
ts = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%S")
|
|
2085
|
+
digest = hashlib.sha256(credentials.encode("utf-8")).hexdigest()[:12]
|
|
2086
|
+
# Nonce keeps ids unique even for identical bytes preserved in the
|
|
2087
|
+
# same second — append-only means no write may ever land on an
|
|
2088
|
+
# existing id.
|
|
2089
|
+
entry_id = f"{ts}-{digest}-{secrets.token_hex(3)}"
|
|
2090
|
+
self._atomic_b64_write(self._stash_entry_path(entry_id), credentials)
|
|
2091
|
+
row = {
|
|
2092
|
+
"createdAt": datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"),
|
|
2093
|
+
**context,
|
|
2094
|
+
}
|
|
2095
|
+
self._mutate_stash_manifest(lambda entries: entries.update({entry_id: row}))
|
|
2096
|
+
return entry_id
|
|
2097
|
+
|
|
2098
|
+
def _list_unclaimed_credentials(self) -> dict[str, dict]:
|
|
2099
|
+
"""Manifest entries by id, including orphaned entry files (no metadata)."""
|
|
2100
|
+
entries = dict(self._read_stash_manifest())
|
|
2101
|
+
try:
|
|
2102
|
+
for path in self._host.credentials_dir.glob(".unclaimed-*.enc"):
|
|
2103
|
+
entry_id = path.name[len(".unclaimed-"):-len(".enc")]
|
|
2104
|
+
entries.setdefault(entry_id, {"createdAt": None})
|
|
2105
|
+
except OSError:
|
|
2106
|
+
pass
|
|
2107
|
+
return entries
|
|
2108
|
+
|
|
2109
|
+
def _read_unclaimed_credential(self, entry_id: str) -> tuple[str, bool]:
|
|
2110
|
+
"""Decode one stashed credential's bytes.
|
|
2111
|
+
|
|
2112
|
+
Returns ``(value, unreadable)`` -- the same shape as
|
|
2113
|
+
``_read_account_credentials_ex``. ``unreadable`` is True when the
|
|
2114
|
+
entry file EXISTS but its bytes could not be read (locked
|
|
2115
|
+
Keychain-adjacent volume, mid-unmount, transient EIO/permissions).
|
|
2116
|
+
A stash entry exists only because a prior gate pass already
|
|
2117
|
+
consumed a grant and could not persist the successor -- the entry
|
|
2118
|
+
is the SOLE copy of that generation, so the caller must not treat
|
|
2119
|
+
a transient read failure as "nothing to adopt".
|
|
2120
|
+
|
|
2121
|
+
A genuinely ABSENT entry, or one that exists but is CORRUPT
|
|
2122
|
+
(undecodable base64 -- its bytes are unrecoverable, not merely
|
|
2123
|
+
inaccessible right now), both return ``("", False)``: there is
|
|
2124
|
+
nothing a retry could ever adopt either way.
|
|
2125
|
+
"""
|
|
2126
|
+
path = self._stash_entry_path(entry_id)
|
|
2127
|
+
try:
|
|
2128
|
+
# BYTES for the same reason as the backup read above: undecodable
|
|
2129
|
+
# bytes are a CORRUPT entry, the verdict the base64 arm below
|
|
2130
|
+
# already gives, not an exception out of the reader the adopt path
|
|
2131
|
+
# relies on to answer.
|
|
2132
|
+
encoded = path.read_bytes().strip()
|
|
2133
|
+
except FileNotFoundError:
|
|
2134
|
+
return "", False
|
|
2135
|
+
except OSError as e:
|
|
2136
|
+
self._host._logger.warning(
|
|
2137
|
+
f"Unclaimed credential {entry_id} unreadable: {e}"
|
|
2138
|
+
)
|
|
2139
|
+
return "", True
|
|
2140
|
+
try:
|
|
2141
|
+
return base64.b64decode(encoded, validate=True).decode("utf-8"), False
|
|
2142
|
+
except Exception as e:
|
|
2143
|
+
self._host._logger.warning(
|
|
2144
|
+
f"Failed to decode unclaimed credential {entry_id}: {e}"
|
|
2145
|
+
)
|
|
2146
|
+
return "", False
|
|
2147
|
+
|
|
2148
|
+
def _remove_unclaimed_credential(self, entry_id: str) -> None:
|
|
2149
|
+
"""Delete a stash entry (bytes + manifest row) after it was adopted."""
|
|
2150
|
+
try:
|
|
2151
|
+
self._stash_entry_path(entry_id).unlink(missing_ok=True)
|
|
2152
|
+
except OSError as e:
|
|
2153
|
+
self._host._logger.warning(
|
|
2154
|
+
f"Failed to remove unclaimed credential {entry_id}: {e}"
|
|
2155
|
+
)
|
|
2156
|
+
self._mutate_stash_manifest(lambda entries: entries.pop(entry_id, None))
|