provider: a Claude sign-in read mid-write on Windows is no sign-out
xbpb6 on X (0.1.4281, Windows 11, TUI mode): the account Claude Code is signed in to said "Sign-in required" with "can't read the allowance"; signing in again fixed it for a while, then it came back. Claude Code on Windows writes .credentials.json and .claude.json through a temp file and a rename. Go's os.ReadFile opens without FILE_SHARE_DELETE, so while magpie reads the file the rename gets EPERM. Claude Code then truncates the file and writes it in place (xO in its writer). A read in between finds the file empty or cut short. - rememberLogins took that read as a sign-out. claudeLoggedOut marked the Held account lapsed with claudeLogoutLapse, which breaks the rule that a failed read means unknown. - The account then read as not in use. Then claudeSavedDir, which has no Held check, could copy Claude Code's own sign-in into claude-accounts/<id> for a warm-up, a usage read or a request. Two Claude Codes then held one rotating refresh token, so whichever refreshed second signed the other out for good. That is why the account comes back as signed out again and again. Now: - claudeSignInUnsure reads the files again. The account counts as signed out only if the file is gone, Claude Code emptied it, `claude auth status` says logged out, or no account is named. A file that can't be read or isn't whole JSON is unknown for up to claudeUnsureGrace (2 minutes). - Meanwhile, rememberLogins doesn't lapse the Held account, and Logins and renewLogins keep it active. - claudeSavedDir refuses a Held account with errClaudeHeld, whose text is not one ClaudeSignInRequired matches. - The Mac keychain path is unchanged. Run: - TestClaudeHalfWrittenSignInIsNoLogout was red on the old code on mote, in two ways (logs kept). An empty credentials file gave Active:false with claudeLogoutLapse, the screenshot's state. claudeSavedDir put the Held account in .config/magpie/claude-accounts/7f327d2462d8fb58 with no error. Green after. - mote: go test ./internal/provider ./internal/gateway -count=1 -timeout 45m: ok, 142s and 913s. - win-run (xiaomi-gpu, Windows 11): TestClaudeHalfWrittenSignInIsNoLogout, TestClaudeAccountsOutliveLogout and TestClaudeSwitchIsNoLogout pass. - gofmt -l is clean. GOOS=windows and GOOS=linux go vet ./internal/provider pass. Not tried: - No real Claude account on Windows. The EPERM rewrite was read from Claude Code 2.1.316's source, not watched. - No full ./... suite. - A Claude Code killed mid-refresh on Windows is not covered.
This commit is contained in:
File diff suppressed because one or more lines are too long
@@ -261,6 +261,12 @@ func claudeSavedDir(user string) (string, error) {
|
||||
if i < 0 {
|
||||
return "", fmt.Errorf("no saved claude account %q", user)
|
||||
}
|
||||
if ls[i].Held {
|
||||
// Claude Code's own, though a read just now found it signed in to
|
||||
// none (claudeSignInUnsure): put here too, a second Claude Code
|
||||
// would refresh the refresh token it holds and sign it out
|
||||
return "", fmt.Errorf(errClaudeHeld, user)
|
||||
}
|
||||
if claudeSetupToken(ls[i].Auth) != "" {
|
||||
// no sign-in to put there: the token goes in Claude Code's
|
||||
// environment (ClaudeDirToken)
|
||||
@@ -543,6 +549,94 @@ const legacyClaudeLogoutLapse = "Claude Code's /logout signed it out (it revokes
|
||||
// be used.
|
||||
const claudeGoneLapse = "its sign-in is gone; sign in again"
|
||||
|
||||
// errClaudeHeld is why the account Claude Code itself is signed in to gets
|
||||
// no config directory of magpie's.
|
||||
const errClaudeHeld = "Claude Code itself is signed in to %s; magpie runs it there, not in a folder of its own"
|
||||
|
||||
// claudeUnsureGrace is how long a sign-in of Claude Code's that can't be
|
||||
// read is taken for one being written. Claude Code on Windows rewrites
|
||||
// .credentials.json and .claude.json in place while magpie has the file
|
||||
// open (its rename over it gets EPERM), and a read between the truncate
|
||||
// and the write finds it empty or cut short. A write takes milliseconds;
|
||||
// one unreadable for longer is gone.
|
||||
var claudeUnsureGrace = 2 * time.Minute
|
||||
|
||||
var claudeUnsure struct {
|
||||
sync.Mutex
|
||||
since time.Time
|
||||
}
|
||||
|
||||
// claudeSignInUnsure says, once liveLogin found Claude Code signed in to
|
||||
// no account, that this isn't known: what it keeps its sign-in in can't be
|
||||
// read whole now (claudeSignInUnread), and has been so for less than
|
||||
// claudeUnsureGrace. The account it held stays its own meanwhile, neither
|
||||
// lapsed (claudeLoggedOut) nor run elsewhere (claudeSavedDir). A sign-in in
|
||||
// the Mac's keychain is read whole or not at all, and is left as it was.
|
||||
func claudeSignInUnsure() bool {
|
||||
if settings.AccountDiscoveryOff() || claudeKeychain {
|
||||
return false
|
||||
}
|
||||
unread := claudeSignInUnread()
|
||||
claudeUnsure.Lock()
|
||||
defer claudeUnsure.Unlock()
|
||||
if !unread {
|
||||
claudeUnsure.since = time.Time{}
|
||||
return false
|
||||
}
|
||||
now := time.Now()
|
||||
if claudeUnsure.since.IsZero() {
|
||||
claudeUnsure.since = now
|
||||
}
|
||||
return now.Sub(claudeUnsure.since) < claudeUnsureGrace
|
||||
}
|
||||
|
||||
// claudeSignInUnread says Claude Code's sign-in isn't known to be gone:
|
||||
// gone is no credentials file, one Claude Code emptied, `claude auth
|
||||
// status` saying it is logged out, or no account named for it. A file
|
||||
// that can't be read or isn't whole JSON is one being written, and so is
|
||||
// a sign-in read whole now, which a read a moment ago (claudeCredential's)
|
||||
// didn't find.
|
||||
func claudeSignInUnread() bool {
|
||||
b, err := readAccountFile(claudeCredentialsPath())
|
||||
if err != nil {
|
||||
return !os.IsNotExist(err)
|
||||
}
|
||||
c, ok := parseClaudeCredentials(b)
|
||||
if c.raw == nil {
|
||||
return true
|
||||
}
|
||||
if !ok {
|
||||
return false
|
||||
}
|
||||
user, _, signedOut := claudeIdentity()
|
||||
if signedOut {
|
||||
return false
|
||||
}
|
||||
b, err = os.ReadFile(claudeProfilePath())
|
||||
if err != nil {
|
||||
return !os.IsNotExist(err) || user != ""
|
||||
}
|
||||
var m struct {
|
||||
OAuthAccount map[string]any `json:"oauthAccount"`
|
||||
}
|
||||
if json.Unmarshal(b, &m) != nil {
|
||||
return true
|
||||
}
|
||||
email, _ := m.OAuthAccount["emailAddress"].(string)
|
||||
return strings.TrimSpace(email) != "" || user != ""
|
||||
}
|
||||
|
||||
// claudeHeldUser is the account Claude Code was signed in to when last
|
||||
// looked at, "" for none.
|
||||
func claudeHeldUser(ls []savedLogin) string {
|
||||
for _, l := range ls {
|
||||
if l.Agent == "claude" && l.Held {
|
||||
return l.User
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// claudeLoggedOut marks the account Claude Code held, now that it holds no
|
||||
// sign-in, as lapsed: magpie's copy of that account is the same sign-in,
|
||||
// gone too — revoked by a /logout (POST <token URL>/revoke, Claude Code
|
||||
|
||||
@@ -0,0 +1,99 @@
|
||||
package provider
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Claude Code on Windows rewrites ~/.claude/.credentials.json and
|
||||
// ~/.claude.json in place when magpie has the file open (its rename gets
|
||||
// EPERM, and it truncates and writes the file instead), so a read can find
|
||||
// it empty or cut short. That is no sign-out: the account Claude Code holds
|
||||
// stays its own and in use, never marked "Sign-in required", and its
|
||||
// sign-in is never put in a config directory of magpie's, where a second
|
||||
// Claude Code would refresh the same refresh token and sign the first out
|
||||
// (xbpb6 on X: signed out again and again on Windows). One unreadable for
|
||||
// longer than a write takes is gone after all.
|
||||
func TestClaudeHalfWrittenSignInIsNoLogout(t *testing.T) {
|
||||
home := claudeHome(t)
|
||||
t.Setenv("CLAUDE_CONFIG_DIR", "")
|
||||
noAnthropic(t)
|
||||
cred := claudeSignIn(t, home, time.Now().Add(time.Hour))
|
||||
profile := filepath.Join(home, ".claude.json")
|
||||
writeFile(t, profile, map[string]any{"oauthAccount": map[string]any{"emailAddress": "own@example.com"}})
|
||||
good, err := os.ReadFile(cred)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
goodProfile, err := os.ReadFile(profile)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ForgetAccounts()
|
||||
own := func(when string) Login {
|
||||
t.Helper()
|
||||
ForgetAccounts()
|
||||
forgetClaudeCredential()
|
||||
for _, l := range Logins("claude") {
|
||||
if l.User == "own@example.com" {
|
||||
return l
|
||||
}
|
||||
}
|
||||
t.Fatalf("%s: no own account in %+v", when, Logins("claude"))
|
||||
return Login{}
|
||||
}
|
||||
if l := own("signed in"); !l.Active || l.Lapsed != "" {
|
||||
t.Fatalf("signed in: %+v", l)
|
||||
}
|
||||
// whatever reads the account as not in use for a moment (warm-up, a
|
||||
// card's reading, a request served beside it) is given no folder of
|
||||
// its own for it while Claude Code holds it
|
||||
if dir, err := claudeSavedDir("own@example.com"); err == nil || ClaudeSignInRequired(err.Error()) {
|
||||
t.Fatalf("Claude Code's own sign-in put in %q: %v", dir, err)
|
||||
}
|
||||
if _, err := os.Stat(claudeAccountDir("own@example.com")); !os.IsNotExist(err) {
|
||||
t.Fatalf("a second holder of Claude Code's refresh token: %v", err)
|
||||
}
|
||||
|
||||
for _, c := range []struct {
|
||||
name string
|
||||
path string
|
||||
half, restore []byte
|
||||
}{
|
||||
{"credentials empty", cred, nil, good},
|
||||
{"credentials cut short", cred, good[:len(good)/2], good},
|
||||
{"profile cut short", profile, goodProfile[:len(goodProfile)/2], goodProfile},
|
||||
} {
|
||||
if err := os.WriteFile(c.path, c.half, 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if l := own(c.name); !l.Active || l.Lapsed != "" {
|
||||
t.Fatalf("%s: taken for a sign-out: %+v", c.name, l)
|
||||
}
|
||||
if dir, err := claudeSavedDir("own@example.com"); err == nil {
|
||||
t.Fatalf("%s: Claude Code's own sign-in put in %s", c.name, dir)
|
||||
}
|
||||
if _, err := os.Stat(claudeAccountDir("own@example.com")); !os.IsNotExist(err) {
|
||||
t.Fatalf("%s: a second holder of Claude Code's refresh token: %v", c.name, err)
|
||||
}
|
||||
if err := os.WriteFile(c.path, c.restore, 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if l := own(c.name + ", written"); !l.Active || l.Lapsed != "" {
|
||||
t.Fatalf("%s, written: %+v", c.name, l)
|
||||
}
|
||||
}
|
||||
|
||||
// unreadable past what a write takes: gone after all
|
||||
old := claudeUnsureGrace
|
||||
claudeUnsureGrace = 0
|
||||
t.Cleanup(func() { claudeUnsureGrace = old })
|
||||
if err := os.WriteFile(cred, nil, 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if l := own("left empty"); l.Active || l.Lapsed != claudeLogoutLapse {
|
||||
t.Fatalf("left empty: %+v", l)
|
||||
}
|
||||
}
|
||||
@@ -124,6 +124,10 @@ func renewLogins(ctx context.Context, every time.Duration, atOnce int) []Renewal
|
||||
}
|
||||
ls := readLogins()
|
||||
loginsMu.Unlock()
|
||||
if _, ok := active["claude"]; !ok && claudeSignInUnsure() {
|
||||
// Claude Code's own still, its sign-in read mid-write
|
||||
active["claude"] = claudeHeldUser(ls)
|
||||
}
|
||||
out := []Renewal{}
|
||||
tried := 0
|
||||
for _, l := range ls {
|
||||
|
||||
@@ -1051,7 +1051,9 @@ func rememberLogins(force bool) {
|
||||
}
|
||||
}
|
||||
if !ok {
|
||||
if agent == "claude" && claudeLoggedOut(ls) {
|
||||
// half-written as Claude Code rewrites it on Windows: unknown,
|
||||
// not a sign-out (claudeSignInUnsure)
|
||||
if agent == "claude" && !claudeSignInUnsure() && claudeLoggedOut(ls) {
|
||||
changed = true
|
||||
}
|
||||
continue
|
||||
@@ -1231,6 +1233,12 @@ func loginsNow(agent string) []Login {
|
||||
}
|
||||
var out []Login
|
||||
ls := readLogins()
|
||||
if _, ok := active["claude"]; !ok && claudeSignInUnsure() {
|
||||
// read as Claude Code writes it: the account it held is still its own
|
||||
if u := claudeHeldUser(ls); u != "" {
|
||||
active["claude"] = u
|
||||
}
|
||||
}
|
||||
standIn := ""
|
||||
if _, ok := active["claude"]; !ok {
|
||||
// the one the provider is listed on (claudeStandInAccount), a
|
||||
|
||||
Reference in New Issue
Block a user