diff --git a/CHANGELOG.md b/CHANGELOG.md index 06cf6da..969a36c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,10 @@ All user-visible bugs and enhancements should be recorded here. ## Unreleased +### Fixed +- OAuth2 refreshes sharing a token store now lock across processes and reload the latest grant before refreshing. This prevents independent MCP clients from redeeming the same stale refresh token. Token-store writes replace the file atomically, and a forced refresh reuses a token another process already replaced. +- If an earlier refresh race has already invalidated the stored refresh token, reauthenticate once after upgrading. The fix cannot restore an invalidated grant. + ## v1.3.4 - 2026-09-29 ### Fixed diff --git a/auth/auth.go b/auth/auth.go index 32a6eaa..2eed0a3 100644 --- a/auth/auth.go +++ b/auth/auth.go @@ -434,6 +434,30 @@ func (a *Auth) ForceRefreshOAuth2Token(username string) (string, error) { } func (a *Auth) refreshOAuth2Token(username string, force bool) (string, error) { + // Lock the grant across processes, then reload: a sibling bridge may have + // rotated it after this process started. Keep the lock through persistence. + // Deliberately lock and reload even for a locally valid token: a removed or + // replaced grant must take effect on the next request. This can delay a valid + // reader behind a sibling's refresh; an mtime-only fast path could miss a + // replacement on filesystems with coarse timestamp resolution. + _, previous := a.getOAuth2TokenRecord(username) + previousAccess := "" + if previous != nil && previous.OAuth2 != nil { + previousAccess = previous.OAuth2.AccessToken + } + unlock, err := lockRefreshStore(a.TokenStore.FilePath) + if err != nil { + return "", err + } + defer unlock() + if err := a.TokenStore.Reload(); err != nil { + return "", err + } + _, current := a.getOAuth2TokenRecord(username) + if force && current != nil && current.OAuth2 != nil && current.OAuth2.AccessToken != previousAccess { + force = false // A sibling already replaced the rejected token. + } + storedUsername, token := a.getOAuth2TokenRecord(username) if token == nil || token.OAuth2 == nil { return "", xurlErrors.NewAuthError("TokenNotFound", errors.New("oauth2 token not found")) @@ -457,7 +481,9 @@ func (a *Auth) refreshOAuth2Token(username string, force bool) (string, error) { }, } - tokenSource := config.TokenSource(context.Background(), &oauth2.Token{ + ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) + defer cancel() + tokenSource := config.TokenSource(ctx, &oauth2.Token{ RefreshToken: token.OAuth2.RefreshToken, }) diff --git a/auth/refresh_lock.go b/auth/refresh_lock.go new file mode 100644 index 0000000..ea5c83c --- /dev/null +++ b/auth/refresh_lock.go @@ -0,0 +1,34 @@ +package auth + +import ( + "fmt" + "os" + "time" +) + +// The sidecar inode stays stable while the token file is replaced atomically. +func lockRefreshStore(path string) (func(), error) { + if path == "" { + return nil, fmt.Errorf("token store has no path") + } + f, err := os.OpenFile(path+".refresh.lock", os.O_CREATE|os.O_RDWR, 0600) + if err != nil { + return nil, fmt.Errorf("open refresh lock: %w", err) + } + deadline := time.Now().Add(30 * time.Second) + for { + acquired, err := tryRefreshLock(f) + if err != nil { + _ = f.Close() + return nil, fmt.Errorf("acquire refresh lock: %w", err) + } + if acquired { + return func() { _ = releaseRefreshLock(f); _ = f.Close() }, nil + } + if time.Now().After(deadline) { + _ = f.Close() + return nil, fmt.Errorf("refresh lock timed out") + } + time.Sleep(20 * time.Millisecond) + } +} diff --git a/auth/refresh_lock_unix.go b/auth/refresh_lock_unix.go new file mode 100644 index 0000000..55d72ae --- /dev/null +++ b/auth/refresh_lock_unix.go @@ -0,0 +1,20 @@ +//go:build darwin || linux || dragonfly || freebsd || netbsd || openbsd + +package auth + +import ( + "errors" + "os" + + "golang.org/x/sys/unix" +) + +func tryRefreshLock(f *os.File) (bool, error) { + err := unix.Flock(int(f.Fd()), unix.LOCK_EX|unix.LOCK_NB) + if errors.Is(err, unix.EWOULDBLOCK) || errors.Is(err, unix.EAGAIN) || errors.Is(err, unix.EINTR) { + return false, nil + } + return err == nil, err +} + +func releaseRefreshLock(f *os.File) error { return unix.Flock(int(f.Fd()), unix.LOCK_UN) } diff --git a/auth/refresh_lock_windows.go b/auth/refresh_lock_windows.go new file mode 100644 index 0000000..759db0a --- /dev/null +++ b/auth/refresh_lock_windows.go @@ -0,0 +1,21 @@ +package auth + +import ( + "errors" + "golang.org/x/sys/windows" + "os" +) + +func tryRefreshLock(f *os.File) (bool, error) { + var overlapped windows.Overlapped + err := windows.LockFileEx(windows.Handle(f.Fd()), windows.LOCKFILE_EXCLUSIVE_LOCK|windows.LOCKFILE_FAIL_IMMEDIATELY, 0, 1, 0, &overlapped) + if errors.Is(err, windows.ERROR_LOCK_VIOLATION) { + return false, nil + } + return err == nil, err +} + +func releaseRefreshLock(f *os.File) error { + var overlapped windows.Overlapped + return windows.UnlockFileEx(windows.Handle(f.Fd()), 0, 1, 0, &overlapped) +} diff --git a/auth/shared_refresh_test.go b/auth/shared_refresh_test.go new file mode 100644 index 0000000..d73b85a --- /dev/null +++ b/auth/shared_refresh_test.go @@ -0,0 +1,147 @@ +package auth + +import ( + "encoding/json" + "net/http" + "net/http/httptest" + "os" + "os/exec" + "path/filepath" + "sync/atomic" + "testing" + "time" + + "github.com/stretchr/testify/require" + "github.com/xdevplatform/xurl/store" + "gopkg.in/yaml.v3" +) + +// Independent bridge processes all load the expired grant BEFORE any refresh. +// The fake provider rotates it once and rejects subsequent uses of the old grant. +func TestSharedRefreshAcrossProcesses(t *testing.T) { + if os.Getenv("XURL_FIX_HELPER") == "1" { + data, err := os.ReadFile(os.Getenv("XURL_FIX_FILE")) + require.NoError(t, err) + ts := &store.TokenStore{} + require.NoError(t, yaml.Unmarshal(data, ts)) + ts.FilePath = os.Getenv("XURL_FIX_FILE") + a := &Auth{TokenStore: ts, tokenURL: os.Getenv("XURL_FIX_URL")} + ready := os.Getenv("XURL_FIX_READY") + require.NoError(t, os.WriteFile(ready, []byte("ready"), 0600)) + deadline := time.Now().Add(10 * time.Second) + for { + if _, err := os.Stat(os.Getenv("XURL_FIX_GATE")); err == nil { + break + } + if time.Now().After(deadline) { + t.Fatal("gate timed out") + } + time.Sleep(10 * time.Millisecond) + } + _, err = a.GetValidOAuth2Token("alice") + if err != nil { + t.Fatal("shared refresh failed") + } + return + } + var calls atomic.Int32 + provider := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if err := r.ParseForm(); err != nil { + http.Error(w, "invalid form", http.StatusBadRequest) + return + } + w.Header().Set("Content-Type", "application/json") + if calls.Add(1) != 1 || r.Form.Get("refresh_token") != "old-refresh" { + w.WriteHeader(400) + json.NewEncoder(w).Encode(map[string]string{"error": "invalid_grant"}) + return + } + time.Sleep(80 * time.Millisecond) + json.NewEncoder(w).Encode(map[string]any{"access_token": "new-access", "refresh_token": "new-refresh", "token_type": "Bearer", "expires_in": 7200}) + })) + defer provider.Close() + ts, dir := createTempTokenStore(t) + defer os.RemoveAll(dir) + require.NoError(t, ts.SaveOAuth2TokenForApp("default", "alice", "old-access", "old-refresh", uint64(time.Now().Add(-time.Hour).Unix()))) + gate := filepath.Join(dir, "gate") + var children []*exec.Cmd + for i := 0; i < 4; i++ { + ready := filepath.Join(dir, string(rune('a'+i))+".ready") + c := exec.Command(os.Args[0], "-test.run=^TestSharedRefreshAcrossProcesses$", "-test.timeout=15s") + c.Env = append(os.Environ(), "XURL_FIX_HELPER=1", "XURL_FIX_FILE="+ts.FilePath, "XURL_FIX_URL="+provider.URL, "XURL_FIX_READY="+ready, "XURL_FIX_GATE="+gate) + require.NoError(t, c.Start()) + children = append(children, c) + t.Cleanup(func() { + if c.ProcessState == nil { + _ = c.Process.Kill() + _ = c.Wait() + } + }) + deadline := time.Now().Add(10 * time.Second) + for { + if _, err := os.Stat(ready); err == nil { + break + } + require.True(t, time.Now().Before(deadline), "helper did not load grant") + time.Sleep(10 * time.Millisecond) + } + } + require.NoError(t, os.WriteFile(gate, []byte("go"), 0600)) + for _, c := range children { + require.NoError(t, c.Wait(), "independent process must reuse the refreshed grant") + } + require.Equal(t, int32(1), calls.Load(), "only one process may redeem the old refresh token") +} + +func TestForceRefreshReusesSiblingToken(t *testing.T) { + ts, dir := createTempTokenStore(t) + defer os.RemoveAll(dir) + future := uint64(time.Now().Add(time.Hour).Unix()) + require.NoError(t, ts.SaveOAuth2TokenForApp("default", "alice", "old-access", "old-refresh", future)) + a := &Auth{TokenStore: ts, tokenURL: "http://127.0.0.1:1"} + data, err := os.ReadFile(ts.FilePath) + require.NoError(t, err) + sibling := &store.TokenStore{} + require.NoError(t, yaml.Unmarshal(data, sibling)) + sibling.FilePath = ts.FilePath + require.NoError(t, sibling.SaveOAuth2TokenForApp("default", "alice", "sibling-access", "sibling-refresh", future)) + got, err := a.ForceRefreshOAuth2Token("alice") + require.NoError(t, err) + require.Equal(t, "sibling-access", got) +} + +func TestRefreshDoesNotResurrectRemovedGrant(t *testing.T) { + ts, dir := createTempTokenStore(t) + defer os.RemoveAll(dir) + require.NoError(t, ts.SaveOAuth2TokenForApp("default", "alice", "cached-access", "cached-refresh", uint64(time.Now().Add(time.Hour).Unix()))) + a := &Auth{TokenStore: ts, tokenURL: "http://127.0.0.1:1"} + require.NoError(t, os.Remove(ts.FilePath)) + _, err := a.GetValidOAuth2Token("alice") + require.Error(t, err) + require.Contains(t, err.Error(), "TokenNotFound") + _, err = os.Stat(ts.FilePath) + require.True(t, os.IsNotExist(err)) +} + +// A long-lived bridge must observe removal of the last app as a missing grant, +// not a corrupt store, without restoring its previously cached credentials. +func TestRefreshAfterLastAppRemoved(t *testing.T) { + ts, dir := createTempTokenStore(t) + defer os.RemoveAll(dir) + future := uint64(time.Now().Add(time.Hour).Unix()) + require.NoError(t, ts.SaveOAuth2TokenForApp("default", "alice", "cached-access", "cached-refresh", future)) + a := &Auth{TokenStore: ts, tokenURL: "http://127.0.0.1:1"} + data, err := os.ReadFile(ts.FilePath) + require.NoError(t, err) + sibling := &store.TokenStore{} + require.NoError(t, yaml.Unmarshal(data, sibling)) + sibling.FilePath = ts.FilePath + require.NoError(t, sibling.RemoveApp("default")) + empty, err := os.ReadFile(ts.FilePath) + require.NoError(t, err) + _, err = a.GetValidOAuth2Token("alice") + require.ErrorContains(t, err, "TokenNotFound") + after, err := os.ReadFile(ts.FilePath) + require.NoError(t, err) + require.Equal(t, empty, after, "reader must not restore the removed app") +} diff --git a/store/tokens.go b/store/tokens.go index 5eb2be4..72c98ac 100644 --- a/store/tokens.go +++ b/store/tokens.go @@ -620,7 +620,40 @@ func (s *TokenStore) HasBearerToken() bool { // ─── Persistence ──────────────────────────────────────────────────── -// Saves the token store to ~/.xurl in YAML format. +// Reload replaces the cached store only after a complete valid read. +func (s *TokenStore) Reload() error { + data, err := os.ReadFile(s.FilePath) + if os.IsNotExist(err) { + // Do not resurrect a grant removed from disk using a stale process snapshot. + s.Apps = make(map[string]*App) + s.DefaultApp = "" + return nil + } + if err != nil { + return errors.NewIOError(err) + } + var sf storeFile + if err = yaml.Unmarshal(data, &sf); err != nil { + return errors.NewJSONError(err) + } + if len(sf.Apps) == 0 { + // Removing the last app is a valid empty state, not a malformed store. + sf.Apps = make(map[string]*App) + sf.DefaultApp = "" + } + for _, app := range sf.Apps { + if app == nil { + return errors.NewError(errors.ErrTypeTokenStore, "invalid app record", nil) + } + if app.OAuth2Tokens == nil { + app.OAuth2Tokens = make(map[string]Token) + } + } + s.Apps = sf.Apps + s.DefaultApp = sf.DefaultApp + return nil +} + func (s *TokenStore) saveToFile() error { sf := storeFile{ Apps: s.Apps, @@ -631,10 +664,25 @@ func (s *TokenStore) saveToFile() error { return errors.NewJSONError(err) } - err = os.WriteFile(s.FilePath, data, 0600) + // Readers see either complete version, never a truncated YAML file. + f, err := os.CreateTemp(filepath.Dir(s.FilePath), ".xurl-auth-*") if err != nil { return errors.NewIOError(err) } - + defer os.Remove(f.Name()) + if _, err = f.Write(data); err != nil { + _ = f.Close() + return errors.NewIOError(err) + } + if err = f.Sync(); err != nil { + _ = f.Close() + return errors.NewIOError(err) + } + if err = f.Close(); err != nil { + return errors.NewIOError(err) + } + if err = os.Rename(f.Name(), s.FilePath); err != nil { + return errors.NewIOError(err) + } return nil }