diff --git a/internal/provider/account.go b/internal/provider/account.go index b2e0cd731..1015eb201 100644 --- a/internal/provider/account.go +++ b/internal/provider/account.go @@ -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 diff --git a/internal/provider/signedout_test.go b/internal/provider/signedout_test.go index de287ce33..f1765e47f 100644 --- a/internal/provider/signedout_test.go +++ b/internal/provider/signedout_test.go @@ -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.