From 0b7d5f3a209dfb4fdcc7ba5f8bb5c4d882bc41e2 Mon Sep 17 00:00:00 2001 From: yetone Date: Sun, 1 Nov 2026 15:02:31 +0800 Subject: [PATCH] claude: a switch waits for Claude Code's own refresh locks (#4532) A switch read the sign-in it was replacing while Claude Code could be refreshing it. Claude Code 2.1.316 refreshes under two mkdir locks, /.oauth_refresh.lock then .lock (~/.claude.lock), both stale after 60s, and saves the rotated pair with a compare-and-swap on the refresh token. So the outgoing account's token was not written over the incoming one, but magpie kept the outgoing account with the refresh token that refresh spent, and it was signed out of magpie on its next use. switchSavedLogin and addLogin (Claude) now take both locks the way Claude Code takes them (claude_lock.go: mkdir, touch while held, take over one untouched past the stale time, let go in reverse order) before reading the live sign-in, and hold them until the new one is written. putClaudeLogin's ~/.claude.json rewrite takes .lock (stale 10s), after the refresh locks, the order Claude Code saves in. A lock held past 20s fails the switch with nothing written. Read from Claude Code 2.1.316's bundled source: lgr/Cki/cl (refresh locks, owner record, retries), Vno (CAS write), gi (config save lock). Run (mote, -tags nogui): - TestClaudeSwitchWaitsForClaudeCodesRefresh (refresh/legacy/config) and TestClaudeSwitchStaleAndHeldLocks: red on the old code (switched while each lock was held; no error when held), green now. Also green on Windows (win-run). - Broken by hand: no stale takeover -> stale subtest red (20s, locked). - go test ./internal/provider -run 'TestClaudeSwitch|TestClaudeAccount|Login' - go vet ./internal/provider for darwin, linux, windows; gofmt clean. Not tried: a real Claude Code refreshing while a real switch runs (its refresh fires only near expiry). magpie writes no .oauth_refresh.lock.owner, so Claude Code takes over a lock magpie left only by its 60s stale time. The Library's MCP writes to ~/.claude.json don't take the config lock yet: #4747. --- docs/subsystems/providers-accounts.md | 17 +++ internal/provider/claude_lock.go | 133 ++++++++++++++++++++++ internal/provider/claude_lock_test.go | 154 ++++++++++++++++++++++++++ internal/provider/logins.go | 18 +++ internal/provider/signin.go | 10 ++ 5 files changed, 332 insertions(+) create mode 100644 internal/provider/claude_lock.go create mode 100644 internal/provider/claude_lock_test.go diff --git a/docs/subsystems/providers-accounts.md b/docs/subsystems/providers-accounts.md index adc3eb98c..177306d00 100644 --- a/docs/subsystems/providers-accounts.md +++ b/docs/subsystems/providers-accounts.md @@ -339,6 +339,23 @@ and `TestHistoricalWindowHoldsUsesEachWindowsOwnReading`. the bridge's turns hold the restart back, so the two don't overlap there. `TestCodexRefreshWaitsForAnotherMagpie`, `TestChatGPTAPIRefreshWaitsForAnotherMagpie`. +- A switch of Claude Code's sign-in (`switchSavedLogin`) and a sign-in + that may write it (`addLogin`) take Claude Code's own refresh locks + first ([claude_lock.go](../../internal/provider/claude_lock.go)), as + Claude Code 2.1.316 takes them: the directory + `/.oauth_refresh.lock`, then `.lock` + (`~/.claude.lock`), each made with mkdir, touched while held and taken + over once untouched for 60s. Rewriting `~/.claude.json`'s + `oauthAccount` (`putClaudeLogin`) takes `.lock` (10s stale) + after them, the order Claude Code saves it in. A switch read during a + refresh kept the outgoing account with the refresh token that refresh + spent, so it was signed out of magpie on its next use (#4532). A lock + held past 20s fails the switch with nothing written (`errClaudeLocked`). + magpie writes no `.oauth_refresh.lock.owner`, so Claude Code waits out a + lock magpie left only by its stale time. Other `~/.claude.json` writers + (the Library's MCP servers) don't take the lock yet (#4747). + `TestClaudeSwitchWaitsForClaudeCodesRefresh`, + `TestClaudeSwitchStaleAndHeldLocks`. ## Verification diff --git a/internal/provider/claude_lock.go b/internal/provider/claude_lock.go new file mode 100644 index 000000000..a98a8eab1 --- /dev/null +++ b/internal/provider/claude_lock.go @@ -0,0 +1,133 @@ +package provider + +import ( + "errors" + "fmt" + "os" + "path/filepath" + "time" + + "github.com/yetone/magpie/internal/appdir" +) + +// Claude Code's own locks, taken as Claude Code takes them (2.1.316, its +// bundled proper-lockfile): a lock is a directory made with mkdir, held +// while it stands and let go by removing it. Its holder touches it every +// few seconds; one not touched for longer than the lock's stale time is +// left by a holder that died, and is taken over. +// +// Claude Code refreshes its sign-in under two of them, in this order: +// /.oauth_refresh.lock, then the older .lock +// (~/.claude.lock), both stale after 60s. Under them it reads the sign-in +// again, posts the refresh token, and writes back the new pair. A switch +// that read the sign-in it was replacing while a refresh ran kept that +// account's refresh token as it was before the refresh: spent, and the +// account signed out of magpie on its next use (#4532). It saves +// ~/.claude.json under .lock, stale after 10s, while it may +// hold the refresh locks: so it is taken after them, as Claude Code does. + +var ( + // claudeLockWait is how long a switch waits for Claude Code to let a + // lock go. A refresh holds them for one token request; Claude Code + // itself gives up after five tries a second or two apart. + claudeLockWait = 20 * time.Second + // claudeLockPoll is how often a held lock is looked at again. + claudeLockPoll = 100 * time.Millisecond + // claudeLockTouch is how often a lock magpie holds is touched, as + // Claude Code's update (5s for the refresh locks, half the stale + // time for ~/.claude.json's), so it never reads as left behind. + claudeLockTouch = 2 * time.Second +) + +const ( + claudeRefreshStale = 60 * time.Second + claudeConfigStale = 10 * time.Second +) + +// errClaudeLocked is a lock Claude Code held past claudeLockWait. +var errClaudeLocked = errors.New("Claude Code is refreshing its sign-in: try again in a moment") + +// claudeRefreshLocks takes the locks Claude Code refreshes its sign-in +// under, for the config directory magpie reads the sign-in of. The +// release lets them go in the reverse order. A directory not there yet +// (Claude Code never run) has no refresh to wait for. +func claudeRefreshLocks() (release func(), err error) { + dir := appdir.ClaudeDir() + if fi, err := os.Stat(dir); err != nil || !fi.IsDir() { + return func() {}, nil + } + first, err := takeClaudeLock(filepath.Join(dir, ".oauth_refresh.lock"), claudeRefreshStale) + if err != nil { + return nil, err + } + resolved := dir + if r, err := filepath.EvalSymlinks(dir); err == nil { + resolved = r + } + legacy, err := takeClaudeLock(resolved+".lock", claudeRefreshStale) + if err != nil { + first() + return nil, err + } + return func() { legacy(); first() }, nil +} + +// claudeConfigLock takes the lock Claude Code saves ~/.claude.json under: +// at the file's real path (proper-lockfile resolves it) plus ".lock". +func claudeConfigLock() (release func(), err error) { + p := claudeProfilePath() + if r, err := filepath.EvalSymlinks(p); err == nil { + p = r + } + if fi, err := os.Stat(filepath.Dir(p)); err != nil || !fi.IsDir() { + return func() {}, nil + } + return takeClaudeLock(p+".lock", claudeConfigStale) +} + +// takeClaudeLock makes the lock directory path, waiting while another +// holds it and taking over one left stale. Held, it is touched until +// released. +func takeClaudeLock(path string, stale time.Duration) (release func(), err error) { + deadline := time.Now().Add(claudeLockWait) + for { + err := os.Mkdir(path, 0o755) + if err == nil { + break + } + if !os.IsExist(err) { + return nil, fmt.Errorf("take Claude Code's lock %s: %w", path, err) + } + if fi, serr := os.Stat(path); serr == nil && time.Since(fi.ModTime()) > stale { + // its holder died without letting it go: Claude Code takes + // such a lock over the same way + if os.Remove(path) == nil { + continue + } + } + if time.Now().After(deadline) { + return nil, errClaudeLocked + } + time.Sleep(claudeLockPoll) + } + stop, done := make(chan struct{}), make(chan struct{}) + go func() { + defer close(done) + t := time.NewTicker(claudeLockTouch) + defer t.Stop() + for { + select { + case <-stop: + return + case <-t.C: + now := time.Now() + _ = os.Chtimes(path, now, now) + } + } + }() + return func() { + close(stop) + <-done + _ = os.Remove(path) + }, nil +} diff --git a/internal/provider/claude_lock_test.go b/internal/provider/claude_lock_test.go new file mode 100644 index 000000000..4cceda394 --- /dev/null +++ b/internal/provider/claude_lock_test.go @@ -0,0 +1,154 @@ +package provider + +import ( + "errors" + "os" + "path/filepath" + "strings" + "testing" + "time" +) + +// claudeLockAccounts signs Claude Code in to b, with a saved beside it, +// and answers the path of Claude Code's credentials. +func claudeLockAccounts(t *testing.T) (home, cred string) { + t.Helper() + home = claudeHome(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": "a@example.com", "accountUuid": "u-a"}}) + rememberLogins(true) + claudeWriteB(t, cred, "b") + writeFile(t, profile, map[string]any{"oauthAccount": map[string]any{"emailAddress": "b@example.com", "accountUuid": "u-b"}}) + forgetClaudeCredential() + rememberLogins(true) + old := ClaudeHandedOver + t.Cleanup(func() { ClaudeHandedOver = old }) + ClaudeHandedOver = func(string) {} + return home, cred +} + +func claudeWriteB(t *testing.T, cred, rt string) { + t.Helper() + writeFile(t, cred, map[string]any{"claudeAiOauth": map[string]any{"accessToken": "sk-ant-oat01-" + rt, "refreshToken": "sk-ant-ort01-" + rt, + "expiresAt": time.Now().Add(time.Hour).UnixMilli(), "subscriptionType": "pro"}}) +} + +func savedAuth(t *testing.T, user string) string { + t.Helper() + for _, l := range readLogins() { + if l.Agent == "claude" && l.User == user { + return string(l.Auth) + } + } + t.Fatalf("%s not saved", user) + return "" +} + +// #4532: a switch while Claude Code refreshes b's sign-in under its +// .oauth_refresh.lock waits for the refresh, and saves b as refreshed: read +// before, b's refresh token was the one the refresh spent, and b was +// signed out of magpie on its next use. +func TestClaudeSwitchWaitsForClaudeCodesRefresh(t *testing.T) { + for _, name := range []string{"refresh", "legacy", "config"} { + t.Run(name, func(t *testing.T) { + home, cred := claudeLockAccounts(t) + lock := map[string]string{ + "refresh": filepath.Join(home, ".claude", ".oauth_refresh.lock"), + "legacy": filepath.Join(home, ".claude.lock"), + "config": filepath.Join(home, ".claude.json.lock"), + }[name] + if err := os.Mkdir(lock, 0o755); err != nil { // Claude Code holds it + t.Fatal(err) + } + done := make(chan error, 1) + go func() { done <- SwitchLogin("claude", "a@example.com") }() + // it waits as long as the lock is held, and touched + for range 5 { + select { + case err := <-done: + t.Fatalf("switched while Claude Code held %s: %v", filepath.Base(lock), err) + case <-time.After(100 * time.Millisecond): + } + now := time.Now() + _ = os.Chtimes(lock, now, now) + } + if name != "config" { + // the refresh: a new pair written, the old refresh token spent + claudeWriteB(t, cred, "b2") + } + if err := os.Remove(lock); err != nil { + t.Fatal(err) + } + select { + case err := <-done: + if err != nil { + t.Fatal(err) + } + case <-time.After(30 * time.Second): + t.Fatal("the switch never went on after the lock was let go") + } + if name != "config" { + if a := savedAuth(t, "b@example.com"); !strings.Contains(a, "sk-ant-ort01-b2") { + t.Fatalf("b saved with the refresh token Claude Code spent: %s", a) + } + } + b, _ := os.ReadFile(filepath.Join(home, ".claude.json")) + if !strings.Contains(string(b), "a@example.com") { + t.Fatalf("Claude Code not signed in to a: %s", b) + } + // every lock let go + for _, l := range []string{".claude/.oauth_refresh.lock", ".claude.lock", ".claude.json.lock"} { + if _, err := os.Stat(filepath.Join(home, l)); !os.IsNotExist(err) { + t.Fatalf("%s left behind: %v", l, err) + } + } + }) + } +} + +// A lock its holder left (not touched for longer than Claude Code's stale +// time) is taken over, as Claude Code does; one held past the wait leaves +// the sign-in as it was and says why. +func TestClaudeSwitchStaleAndHeldLocks(t *testing.T) { + t.Run("stale", func(t *testing.T) { + home, _ := claudeLockAccounts(t) + lock := filepath.Join(home, ".claude", ".oauth_refresh.lock") + if err := os.Mkdir(lock, 0o755); err != nil { + t.Fatal(err) + } + old := time.Now().Add(-2 * time.Minute) + _ = os.Chtimes(lock, old, old) + done := make(chan error, 1) + go func() { done <- SwitchLogin("claude", "a@example.com") }() + select { + case err := <-done: + if err != nil { + t.Fatal(err) + } + case <-time.After(30 * time.Second): + t.Fatal("a stale lock held the switch") + } + }) + t.Run("held", func(t *testing.T) { + home, cred := claudeLockAccounts(t) + w := claudeLockWait + claudeLockWait = 300 * time.Millisecond + t.Cleanup(func() { claudeLockWait = w }) + if err := os.Mkdir(home+"/.claude.lock", 0o755); err != nil { + t.Fatal(err) + } + err := SwitchLogin("claude", "a@example.com") + if !errors.Is(err, errClaudeLocked) { + t.Fatalf("got %v", err) + } + b, _ := os.ReadFile(cred) + if !strings.Contains(string(b), "sk-ant-ort01-b") { + t.Fatalf("Claude Code's sign-in written over while it held its lock: %s", b) + } + // the first lock, taken, is let go when the second can't be + if _, err := os.Stat(filepath.Join(home, ".claude", ".oauth_refresh.lock")); !os.IsNotExist(err) { + t.Fatalf(".oauth_refresh.lock left behind: %v", err) + } + }) +} diff --git a/internal/provider/logins.go b/internal/provider/logins.go index 79f1ded63..cd0b78eb0 100644 --- a/internal/provider/logins.go +++ b/internal/provider/logins.go @@ -1271,6 +1271,15 @@ func switchSavedLogin(agent, user string) (from string, _ error) { } want := *target if agent == "claude" { + // not while Claude Code refreshes its sign-in: the one read below + // to keep would be the refresh token that refresh is spending + // (#4532). Held till the new sign-in is written, so the refresh + // that follows starts from it. + release, err := claudeRefreshLocks() + if err != nil { + return "", err + } + defer release() // the credentials as Claude Code has them this moment, not as last // looked at: one it refreshed since has a new refresh token and the // old one is dead (0xAncientTwo on X: signed out again and again) @@ -1321,6 +1330,8 @@ func switchSavedLogin(agent, user string) (from string, _ error) { return from, nil } +// putClaudeLogin signs Claude Code in to l. The caller holds Claude Code's +// refresh locks (claudeRefreshLocks). func putClaudeLogin(l savedLogin) error { if claudeSetupToken(l.Auth) != "" { return fmt.Errorf(errClaudeTokenSwitch, l.User) @@ -1347,6 +1358,13 @@ func putClaudeLogin(l savedLogin) error { if len(l.Profile) == 0 { return nil } + // read and written back under the lock Claude Code saves the file + // under, or a save of its own between the two is lost + release, err := claudeConfigLock() + if err != nil { + return err + } + defer release() m, err := readClaudeProfile() if err != nil { if !os.IsNotExist(err) { diff --git a/internal/provider/signin.go b/internal/provider/signin.go index bd187163d..224248449 100644 --- a/internal/provider/signin.go +++ b/internal/provider/signin.go @@ -888,6 +888,16 @@ func addLogin(l savedLogin) (using bool, err error) { }() loginsMu.Lock() defer loginsMu.Unlock() + if l.Agent == "claude" { + // the sign-in Claude Code has is read, kept and maybe written + // over below: not while it refreshes it (#4532) + release, err := claudeRefreshLocks() + if err != nil { + return false, err + } + defer release() + forgetClaudeCredential() + } l.Seen = time.Now().UTC().Truncate(time.Second) live, signedIn := liveLogin(l.Agent) ls := readLogins()