claude: a fresh sign-in goes into the keychain item Claude Code reads, not beside it (#1742, #1842, iefnaf)

What changed: readClaudeCredential asked the Keychain only when the
credentials file held no sign-in. On a Mac whose "Claude Code-credentials"
item is there but emptied (what Claude Code leaves of a sign-in Anthropic
refused to refresh), an older, parseable ~/.claude/.credentials.json was
taken for the sign-in: a sign-in made in magpie was written into that file,
the dead item stayed, Claude Code stayed signed out, and a minute later
claudeIdentity's loggedIn: false lapsed the account and took the provider
out. Now the item under the account ($USER) is read first, emptied or not,
as Claude Code reads it: its own storage asks the Keychain first and reads
the file only when the item is absent, empty or no JSON — the rule
readClaudeDir already applies, with its own test, to the item in a saved
account's config directory. putClaudeLogin, reusing what was found, puts a
fresh sign-in into the item. The item is asked by service alone only after
the file has no sign-in, as before (an earlier sign-in's leftover,
58b67666).

Amended in review (yetone): the patch as sent took an item magpie wrote
over lines, which `security -w` prints as hex (#70), for the sign-in ahead
of the file and rewrote it on one line. Claude Code 2.1.296's keychain leg
JSON-parses what `security` prints, so hex reads as no item and it goes by
the file: the account's hex item now comes after the file, and is only
rewritten when the file has no sign-in either, as before. The two reads are
one claudeKeychainItem value instead of a four-result helper.
TestClaudeHexKeychainItemIsNoneBesideAFile covers it.

Checked against Claude Code 2.1.296's binary: its secure storage is
M(keychain, plaintext); the fallback leg's read returns the keychain's
result whenever it is not null, and the keychain leg returns
JSON.parse(`security find-generic-password -a $USER -w -s
"Claude Code-credentials"`) when that prints anything, else null (a parse
error is caught as null). Every HOME reader in magpie (liveLogin,
claudeAccount, Usage, claude_auth, putClaudeLogin) goes through
readClaudeCredential via claudeCredential, so they all follow the one order.

Run: TestClaudeEmptiedKeychainItemIsTheSignInBesideAFile fails with main's
order (the account's item not asked first) and passes with the change;
TestClaudeHexKeychainItemIsNoneBesideAFile fails with the patch as sent
(hex item taken over the file) and passes with the amendment;
TestClaudeFileSignInWhenNoKeychainItem guards the file fallback. All with a
sandbox HOME and a fake `security` on PATH. Full checks are in the next
commit's body. Not run: no real Keychain, no real emptied item, no real
sign-in from the GUI.

Co-authored-by: yetone <yetoneful@gmail.com>
This commit is contained in:
ggbdpq
2026-10-13 00:38:09 +08:00
committed by yetone
co-authored by yetone
parent 552e974f22
commit 31956b92f0
2 changed files with 179 additions and 24 deletions
+61 -24
View File
@@ -432,6 +432,17 @@ func readClaudeCredential() (claudeCredentials, claudeCredentialLocation, bool)
if settings.AccountDiscoveryOff() {
return claudeCredentials{}, claudeCredentialLocation{}, false
}
var mine claudeKeychainItem
if claudeKeychain {
// the item under the account ($USER) is the sign-in Claude Code goes
// by, emptied or not: it reads no file beside it, so an emptied item
// is a sign-out even where an older file still parses, and a sign-in
// made in magpie is put in the item, not beside it (#1742)
mine = readClaudeKeychainItem(claudeKeychainAccount())
if mine.found && !mine.hex {
return mine.c, mine.loc, mine.ok
}
}
path := claudeCredentialsPath()
if b, err := readAccountFile(path); err == nil {
if c, ok := parseClaudeCredentials(b); ok {
@@ -441,34 +452,60 @@ func readClaudeCredential() (claudeCredentials, claudeCredentialLocation, bool)
if !claudeKeychain {
return claudeCredentials{}, claudeCredentialLocation{}, false
}
// Claude Code reads the item under its account ($USER); by service
// alone the keychain may hand back another one — left from an earlier
// sign-in — which isn't the sign-in in use
account := claudeKeychainAccount()
var c claudeCredentials
var ok, wasHex bool
for _, args := range [][]string{{"-a", account}, nil} {
out, err := proc.Command("security", append([]string{"find-generic-password", "-s", "Claude Code-credentials", "-w"}, args...)...).Output()
if err != nil {
continue
}
var b []byte
b, wasHex = keychainText(bytes.TrimSpace(out))
if c, ok = parseClaudeCredentials(b); ok {
break
}
// neither the account's item, as Claude Code reads it, nor the file
// holds a sign-in. Left: the account's item as magpie wrote it before,
// over lines that `security -w` prints as hex (#70) — Claude Code reads
// that as no item, hence the file first — which is written again on one
// line, as Claude Code writes it; else by service alone another item,
// left from an earlier sign-in, that Claude Code never reads (58b67666)
i := mine
if !i.ok {
i = readClaudeKeychainItem("")
}
if !ok {
if !i.ok {
return claudeCredentials{}, claudeCredentialLocation{}, false
}
loc := claudeCredentialLocation{keychain: true, account: account}
if wasHex {
// written by magpie before it wrote them on one line: Claude Code
// reads that hex as no sign-in, so it is written again as it
// writes it
saveClaudeCredential(loc, c)
if i.hex {
saveClaudeCredential(i.loc, i.c)
}
return i.c, i.loc, true
}
// claudeKeychainItem is what `security` reads of the "Claude Code-credentials"
// item. found says an item is there that reads as a JSON object — the sign-in
// Claude Code goes by, emptied or not (an item that reads as none it takes
// for an absent one, and so does readClaudeDir of the item in a config
// directory); ok, that it holds tokens to run on; hex, that magpie wrote it
// over more than one line, which `security -w` prints as hex and Claude Code
// reads as none (#70).
type claudeKeychainItem struct {
c claudeCredentials
loc claudeCredentialLocation
ok, found bool
hex bool
}
// readClaudeKeychainItem reads the item for a keychain account, or by
// service alone when the account is "". Either way it is the one under
// $USER that a sign-in is written back to.
func readClaudeKeychainItem(account string) claudeKeychainItem {
args := []string{"find-generic-password", "-s", "Claude Code-credentials", "-w"}
if account != "" {
args = append(args, "-a", account)
}
out, err := proc.Command("security", args...).Output()
if err != nil {
return claudeKeychainItem{}
}
b, wasHex := keychainText(bytes.TrimSpace(out))
c, ok := parseClaudeCredentials(b)
if c.raw == nil {
return claudeKeychainItem{}
}
return claudeKeychainItem{
c: c, ok: ok, found: true, hex: wasHex,
loc: claudeCredentialLocation{keychain: true, account: claudeKeychainAccount()},
}
return c, loc, ok
}
// claudeKeychainAccount is the account Claude Code keeps its sign-in
+118
View File
@@ -1,6 +1,7 @@
package provider
import (
"encoding/hex"
"os"
"path/filepath"
"strings"
@@ -116,6 +117,123 @@ func TestSavedButSignedOutCanBeRemoved(t *testing.T) {
}
}
// The keychain item under the account is the sign-in Claude Code goes by,
// emptied or not: it reads no file beside it (yetone/magpie#1742). So an
// emptied item beside a still-parseable file is signed out, and a sign-in
// made in magpie is put in the item, not beside it.
func TestClaudeEmptiedKeychainItemIsTheSignInBesideAFile(t *testing.T) {
shellFakes(t)
home := claudeHome(t)
t.Setenv("CLAUDE_CONFIG_DIR", "")
t.Setenv("USER", "tester")
creds := claudeSignIn(t, home, time.Now().Add(time.Hour))
bin := filepath.Join(home, "bin")
os.MkdirAll(bin, 0o755)
added := filepath.Join(home, "added.log")
// what Claude Code left of a refused refresh: the item is there, and it
// reads as JSON, only with no tokens in it
testenv.Program(t, filepath.Join(bin, "security"), `#!/bin/sh
case "$1" in
find-generic-password)
case "$*" in
*"-a tester"*) echo '{"claudeAiOauth":{"accessToken":"","refreshToken":"","expiresAt":0,"refreshTokenExpiresAt":1791392301433}}' ;;
*) exit 1 ;;
esac ;;
add-generic-password)
echo "$*" >> '`+added+`' ;;
*) exit 1 ;;
esac
`)
t.Setenv("PATH", bin+string(os.PathListSeparator)+os.Getenv("PATH"))
claudeKeychain = true
forgetClaudeCredential()
if _, loc, ok := readClaudeCredential(); ok {
t.Fatalf("an emptied keychain item was passed over for the file beside it (%+v)", loc)
} else if !loc.keychain || loc.account != "tester" {
t.Fatalf("the emptied item is not where a sign-in would go: %+v", loc)
}
if err := putClaudeLogin(savedLogin{Agent: "claude", User: "fresh@example.com", Auth: mustJSONRaw(t, map[string]any{
"claudeAiOauth": map[string]any{
"accessToken": "fresh-access", "refreshToken": "fresh-refresh",
"expiresAt": time.Now().Add(time.Hour).UnixMilli(), "subscriptionType": "max",
}})}); err != nil {
t.Fatal(err)
}
if b, _ := os.ReadFile(creds); strings.Contains(string(b), "fresh-access") {
t.Fatal("the fresh sign-in went into the file beside the item Claude Code reads")
}
if b, _ := os.ReadFile(added); !strings.Contains(string(b), "fresh-access") {
t.Fatalf("the fresh sign-in was not put in the keychain item: %s", b)
}
}
// With no item under the account, the file beside it is the sign-in, as
// Claude Code reads it.
func TestClaudeFileSignInWhenNoKeychainItem(t *testing.T) {
shellFakes(t)
home := claudeHome(t)
t.Setenv("CLAUDE_CONFIG_DIR", "")
t.Setenv("USER", "tester")
creds := claudeSignIn(t, home, time.Now().Add(time.Hour))
bin := filepath.Join(home, "bin")
os.MkdirAll(bin, 0o755)
testenv.Program(t, filepath.Join(bin, "security"), "#!/bin/sh\nexit 1\n")
t.Setenv("PATH", bin+string(os.PathListSeparator)+os.Getenv("PATH"))
claudeKeychain = true
forgetClaudeCredential()
c, loc, ok := readClaudeCredential()
if !ok || c.OAuth.AccessToken != "sk-ant-oat01-old" || loc.keychain || loc.path != creds {
t.Fatalf("the file is not the sign-in where no keychain item is: %v %+v %+v", ok, c.OAuth, loc)
}
}
// An item magpie wrote over lines comes back from `security -w` as hex,
// which Claude Code reads as no item at all (#70): beside a file that holds
// a sign-in, the file is the one it goes by, and the item is left alone.
// With no file, the item is the sign-in, written again on one line.
func TestClaudeHexKeychainItemIsNoneBesideAFile(t *testing.T) {
shellFakes(t)
home := claudeHome(t)
t.Setenv("CLAUDE_CONFIG_DIR", "")
t.Setenv("USER", "tester")
creds := claudeSignIn(t, home, time.Now().Add(time.Hour))
bin := filepath.Join(home, "bin")
os.MkdirAll(bin, 0o755)
added := filepath.Join(home, "added.log")
item := hex.EncodeToString([]byte("{\n \"claudeAiOauth\": {\"accessToken\": \"hexed\", \"refreshToken\": \"r\"}\n}"))
testenv.Program(t, filepath.Join(bin, "security"), `#!/bin/sh
case "$1" in
find-generic-password)
case "$*" in
*"-a tester"*) echo '`+item+`' ;;
*) exit 1 ;;
esac ;;
add-generic-password)
echo "$*" >> '`+added+`' ;;
*) exit 1 ;;
esac
`)
t.Setenv("PATH", bin+string(os.PathListSeparator)+os.Getenv("PATH"))
claudeKeychain = true
forgetClaudeCredential()
c, loc, ok := readClaudeCredential()
if !ok || c.OAuth.AccessToken != "sk-ant-oat01-old" || loc.keychain || loc.path != creds {
t.Fatalf("a hex item Claude Code can't read was taken over the file beside it: %v %+v %+v", ok, c.OAuth, loc)
}
if b, _ := os.ReadFile(added); len(b) > 0 {
t.Fatalf("the hex item was written while the file is the sign-in: %s", b)
}
os.Remove(creds)
forgetClaudeCredential()
c, loc, ok = readClaudeCredential()
if !ok || c.OAuth.AccessToken != "hexed" || !loc.keychain || loc.account != "tester" {
t.Fatalf("with no file the hex item is not the sign-in: %v %+v %+v", ok, c.OAuth, loc)
}
if b, _ := os.ReadFile(added); !strings.Contains(string(b), `{"claudeAiOauth":{"accessToken":"hexed"`) {
t.Fatalf("the hex item was not written again on one line: %s", b)
}
}
// Claude Code's sign-in is read from the keychain as Claude Code reads it,
// under its account: another item for the same service (one an earlier
// sign-in left) that comes first by service alone isn't taken for it.