diff --git a/.changeset/invalid-grant-retry-skips-refresh.md b/.changeset/invalid-grant-retry-skips-refresh.md new file mode 100644 index 0000000000..cb2e1b93a4 --- /dev/null +++ b/.changeset/invalid-grant-retry-skips-refresh.md @@ -0,0 +1,5 @@ +--- +'@modelcontextprotocol/client': patch +--- + +`auth()` no longer sends a refresh token to the token endpoint again after the authorization server rejected it with `invalid_grant` or `invalid_dpop_proof`. It remembers the rejected token per provider and goes straight to a new authorization, both in the immediate retry and in later `auth()` calls, until a different refresh token is stored. Before this change, a provider that does not implement `invalidateCredentials()` kept returning the rejected token from `tokens()`, so the retry refreshed with it a second time and `auth()` threw the authorization server's error instead of returning `'REDIRECT'`. Providers that implement `invalidateCredentials()` behave as before. diff --git a/packages/client/src/client/auth.ts b/packages/client/src/client/auth.ts index 53a5b7e62e..d21f98c150 100644 --- a/packages/client/src/client/auth.ts +++ b/packages/client/src/client/auth.ts @@ -1080,8 +1080,8 @@ export interface AuthOptions { */ function warnCredentialInvalidation(provider: OAuthClientProvider, error: OAuthError, invalidated: string): void { // `invalidateCredentials` is optional. When a provider omits it nothing is actually - // discarded, so do not claim otherwise — the stale credential is still in storage and - // will be replayed on the next call, which is the thing worth telling the operator. + // discarded, so do not claim otherwise — the stale credential is still in storage, which is + // the thing worth telling the operator. const action = provider.invalidateCredentials === undefined ? `retrying authorization without discarding the stored ${invalidated} (provider implements no invalidateCredentials())` @@ -1094,6 +1094,14 @@ function warnCredentialInvalidation(provider: OAuthClientProvider, error: OAuthE ); } +/** + * The last refresh token each provider had rejected with `invalid_grant` or `invalid_dpop_proof`. + * `invalidateCredentials()` is optional, so a provider may keep returning a rejected token from + * `tokens()` until a new authorization saves a different one. Sending it again cannot succeed + * (RFC 6749 §5.2), so the refresh branch skips it, in the retry and in every later call. + */ +const rejectedRefreshTokens = new WeakMap(); + /** * Orchestrates the full auth flow with a server. * @@ -1426,7 +1434,8 @@ async function authInternal( // `forceReauthorization` when the requested scope strictly exceeds the // current token's granted scope — refreshing would not widen it (RFC 6749 // §6), so skip straight to a fresh authorization request. - if (tokens?.refresh_token && !forceReauthorization) { + const refreshTokenRejected = tokens?.refresh_token !== undefined && rejectedRefreshTokens.get(provider) === tokens.refresh_token; + if (tokens?.refresh_token && !forceReauthorization && !refreshTokenRejected) { const refreshScope = await provider.scopeForRefresh?.(tokens); let newTokens: OAuthTokens | undefined; try { @@ -1448,6 +1457,12 @@ async function authInternal( if (error instanceof InsecureTokenEndpointError) { throw error; } + if ( + error instanceof OAuthError && + (error.code === OAuthErrorCode.InvalidGrant || error.code === OAuthErrorCode.InvalidDpopProof) + ) { + rejectedRefreshTokens.set(provider, tokens.refresh_token); + } // If this is a ServerError, or an unknown type, log it out and try to continue. Otherwise, escalate so we can fix things and retry. if (!(error instanceof OAuthError) || error.code === OAuthErrorCode.ServerError) { // Could not refresh OAuth tokens. The fallthrough to a fresh authorization diff --git a/packages/client/test/client/auth.test.ts b/packages/client/test/client/auth.test.ts index 56f4134e89..995240f76a 100644 --- a/packages/client/test/client/auth.test.ts +++ b/packages/client/test/client/auth.test.ts @@ -3312,7 +3312,9 @@ describe('OAuth Authorization', () => { expect(warn).toHaveBeenCalled(); }); - it('warns, and cannot recover, when invalid_grant hits a provider with no invalidateCredentials (#2034)', async () => { + it('warns, and starts a fresh authorization, when invalid_grant hits a provider with no invalidateCredentials (#2915)', async () => { + // Its own provider object: auth() remembers rejected refresh tokens per provider. + const provider: OAuthClientProvider = { ...mockProvider }; let tokenPosts = 0; mockDiscoveryWithTokenEndpoint(() => { tokenPosts++; @@ -3327,18 +3329,64 @@ describe('OAuth Authorization', () => { const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}); // invalid_grant is rethrown out of the refresh block into auth()'s outer catch, - // which retries authInternal. Nothing was invalidated, so the retry replays the - // same dead refresh token and the second failure propagates to the caller. - await expect(auth(mockProvider, { serverUrl: 'https://api.example.com/mcp-server' })).rejects.toThrow('Refresh token expired'); + // which retries authInternal. The retry must not replay the refresh token the + // authorization server just rejected, so it goes straight to a new authorization. + await expect(auth(provider, { serverUrl: 'https://api.example.com/mcp-server' })).resolves.toBe('REDIRECT'); expect(warn).toHaveBeenCalledWith(expect.stringContaining('OAuth "invalid_grant"')); expect(warn).toHaveBeenCalledWith(expect.stringContaining('Refresh token expired')); // The warn must not claim a discard that never happened. expect(warn).toHaveBeenCalledWith(expect.stringContaining('without discarding the stored tokens')); - // The retry is futile for this provider shape: the dead refresh token goes to the - // token endpoint a second time and no authorization is ever started. - expect(tokenPosts).toBe(2); - expect(mockProvider.redirectToAuthorization).not.toHaveBeenCalled(); + // The dead refresh token goes to the token endpoint once, not twice. + expect(tokenPosts).toBe(1); + expect(mockProvider.redirectToAuthorization).toHaveBeenCalledTimes(1); + warn.mockRestore(); + }); + + it('does not resend a rejected refresh token on a later auth() call either (#2915)', async () => { + // Its own provider object: auth() remembers rejected refresh tokens per provider. + const provider: OAuthClientProvider = { ...mockProvider }; + let tokenPosts = 0; + mockDiscoveryWithTokenEndpoint(() => { + tokenPosts++; + return oauthErrorResponse(OAuthErrorCode.InvalidGrant, 'Refresh token expired'); + }); + (mockProvider.clientInformation as Mock).mockResolvedValue({ client_id: 'test-client', client_secret: 'test-secret' }); + // No invalidateCredentials(): every read returns the same dead refresh token. + (mockProvider.tokens as Mock).mockResolvedValue({ ...storedTokens, refresh_token: 'rejected-later-call' }); + (mockProvider.saveTokens as Mock).mockResolvedValue(undefined); + const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}); + + await expect(auth(provider, { serverUrl: 'https://api.example.com/mcp-server' })).resolves.toBe('REDIRECT'); + // A second call before a new authorization has replaced the stored tokens. + await expect(auth(provider, { serverUrl: 'https://api.example.com/mcp-server' })).resolves.toBe('REDIRECT'); + + expect(tokenPosts).toBe(1); + expect(mockProvider.redirectToAuthorization).toHaveBeenCalledTimes(2); + warn.mockRestore(); + }); + + it('refreshes again once a different refresh token is stored after a rejection (#2915)', async () => { + // Its own provider object: auth() remembers rejected refresh tokens per provider. + const provider: OAuthClientProvider = { ...mockProvider }; + const posted: string[] = []; + mockDiscoveryWithTokenEndpoint(() => { + const body = String(mockFetch.mock.calls.at(-1)![1].body); + posted.push(new URLSearchParams(body).get('refresh_token') ?? ''); + return posted.length === 1 + ? oauthErrorResponse(OAuthErrorCode.InvalidGrant, 'Refresh token expired') + : refreshedWithoutScope(); + }); + (mockProvider.clientInformation as Mock).mockResolvedValue({ client_id: 'test-client' }); + (mockProvider.tokens as Mock).mockResolvedValue({ ...storedTokens, refresh_token: 'rejected-then-replaced' }); + (mockProvider.saveTokens as Mock).mockResolvedValue(undefined); + const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}); + + await expect(auth(provider, { serverUrl: 'https://api.example.com/mcp-server' })).resolves.toBe('REDIRECT'); + (mockProvider.tokens as Mock).mockResolvedValue({ ...storedTokens, refresh_token: 'fresh-refresh' }); + await expect(auth(provider, { serverUrl: 'https://api.example.com/mcp-server' })).resolves.toBe('AUTHORIZED'); + + expect(posted).toEqual(['rejected-then-replaced', 'fresh-refresh']); warn.mockRestore(); }); diff --git a/packages/client/test/client/sse.test.ts b/packages/client/test/client/sse.test.ts index c9ceb23c3d..e0b89a403e 100644 --- a/packages/client/test/client/sse.test.ts +++ b/packages/client/test/client/sse.test.ts @@ -1321,8 +1321,11 @@ describe('SSEClientTransport', () => { authProvider: mockAuthProvider }); - await expect(() => transport.start()).rejects.toMatchObject(expectedError); + // The retry does not send the rejected refresh token again (this mock's + // invalidateCredentials() clears nothing): it starts a new authorization. + await expect(() => transport.start()).rejects.toThrow(UnauthorizedError); expect(mockAuthProvider.invalidateCredentials).toHaveBeenCalledWith('tokens'); + expect(mockAuthProvider.redirectToAuthorization).toHaveBeenCalledTimes(1); }); });