Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/invalid-grant-retry-skips-refresh.md
Original file line number Diff line number Diff line change
@@ -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.
21 changes: 18 additions & 3 deletions packages/client/src/client/auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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())`
Expand All @@ -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<OAuthClientProvider, string>();

/**
* Orchestrates the full auth flow with a server.
*
Expand Down Expand Up @@ -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 {
Expand All @@ -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
Expand Down
64 changes: 56 additions & 8 deletions packages/client/test/client/auth.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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++;
Expand All @@ -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();
});

Expand Down
5 changes: 4 additions & 1 deletion packages/client/test/client/sse.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);
});
});

Expand Down
Loading