Repository navigation
fix(auth): treat null optional fields in token responses as absent #2462
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Changes from all commits
97ee7bd
1639827
20893fb
8d9dee8
4e62b73
e3d7aab
0c105c1
791c379
3219818
3501e62
8a715bf
1142f7f
80adfcf
0e4a6f1
db68fb0
7000109
b29a6cc
bc45c34
9f961de
f8b576a
e309da0
8d8e277
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,42 @@ | ||
| --- | ||
| '@modelcontextprotocol/core': minor | ||
| '@modelcontextprotocol/core-internal': patch | ||
| '@modelcontextprotocol/client': patch | ||
| '@modelcontextprotocol/server-legacy': patch | ||
| '@modelcontextprotocol/codemod': patch | ||
| --- | ||
|
|
||
| OAuth token responses with null-valued optional members no longer fail | ||
| validation. Some authorization servers serialize absent optional members as | ||
| JSON `null` (nonconformant with RFC 6749 §5.1, but common in the wild); | ||
| previously `refresh_token`, `scope`, or `id_token` set to `null` failed token | ||
| exchange and refresh, and `expires_in: null` silently coerced to `0`, yielding | ||
| an instantly-expired token. The SDK's own token-response parse sites (client | ||
| token exchange/refresh, JWT-grant cross-app exchange, and the server-legacy | ||
| proxy provider) now validate with a new `OAuthTokenResponseSchema` (defined in | ||
| `@modelcontextprotocol/core`'s auth schema module and forwarded through | ||
| `core-internal`'s re-export shim) that removes | ||
| null-valued optional members before validation, so they are strictly absent | ||
| from the parsed output. The exported `OAuthTokensSchema` is unchanged — still a | ||
| plain object schema, with its `.shape`/`.extend` and input types intact: it | ||
| rejects `null` for its string-typed optional members, though `expires_in: null` | ||
| still coerces to `0` there (use `OAuthTokenResponseSchema` for raw wire | ||
| input). `refreshAuthorization` additionally hardens its merge with the | ||
| previously-stored refresh token, so an explicitly `undefined` `refresh_token` | ||
| in a parsed response can never clobber the preserved token. Likewise, `auth()` | ||
| now keeps the previously stored `scope` in the `saveTokens` payload when a | ||
| refresh response omits `scope` (an unchanged grant per RFC 6749 §5.1/§6); the | ||
| member is strictly absent only when neither the response nor the stored tokens | ||
| have one. Note that a | ||
| stripped null `scope` is thereafter indistinguishable from an omitted `scope` | ||
| — which RFC 6749 §5.1 defines as an assertion that the granted scope is | ||
| identical to the requested scope — so consumers should not infer the granted | ||
| scope from its absence. | ||
|
|
||
| `OAuthTokenResponseSchema` is also a public export from | ||
| `@modelcontextprotocol/core`'s root, since the sibling v1 release exports it | ||
| from `@modelcontextprotocol/sdk/shared/auth.js` and migrating code needs a v2 | ||
| home for it. The v1-to-v2 codemod's auth schema allowlist now includes the | ||
| name, so `import { OAuthTokenResponseSchema } from | ||
| '@modelcontextprotocol/sdk/shared/auth.js'` rewrites to | ||
| `@modelcontextprotocol/core` alongside the other auth schema constants. | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -2038,6 +2038,39 @@ describe('OAuth Authorization', () => { | |
| expect(body.get('redirect_uri')).toBe('http://localhost:3000/callback'); | ||
| expect(body.get('resource')).toBe('https://api.example.com/mcp-server'); | ||
| }); | ||
| it('treats null optional fields as absent (some auth servers serialize absent members as null)', async () => { | ||
| mockFetch.mockResolvedValueOnce({ | ||
| ok: true, | ||
| status: 200, | ||
| json: async () => ({ | ||
| access_token: 'access123', | ||
| token_type: 'Bearer', | ||
| expires_in: null, | ||
| scope: null, | ||
| refresh_token: null, | ||
| id_token: null | ||
| }) | ||
| }); | ||
|
|
||
| const tokens = await exchangeAuthorization('https://auth.example.com', { | ||
| clientInformation: validClientInfo, | ||
| authorizationCode: 'code123', | ||
| codeVerifier: 'verifier123', | ||
| redirectUri: 'http://localhost:3000/callback', | ||
| resource: new URL('https://api.example.com/mcp-server') | ||
| }); | ||
|
|
||
| // toStrictEqual pins the null-valued members as strictly ABSENT keys, not | ||
| // present-but-undefined: refreshAuthorization spreads the parsed response | ||
| // when merging with stored tokens, so a present `refresh_token: undefined` | ||
| // key would clobber the preserved refresh token. It also pins that | ||
| // expires_in: null did not coerce to 0 (an instantly-expired token). | ||
| expect(tokens).toStrictEqual({ | ||
| access_token: 'access123', | ||
| token_type: 'Bearer' | ||
| }); | ||
| }); | ||
|
|
||
| it('exchanges code for tokens with auth', async () => { | ||
| mockFetch.mockResolvedValueOnce({ | ||
| ok: true, | ||
|
|
@@ -2290,6 +2323,26 @@ describe('OAuth Authorization', () => { | |
| expect(tokens).toEqual({ refresh_token: refreshToken, ...validTokens }); | ||
| }); | ||
|
|
||
| it('keeps the existing refresh token when the server returns refresh_token: null', async () => { | ||
| mockFetch.mockResolvedValueOnce({ | ||
| ok: true, | ||
| status: 200, | ||
| json: async () => ({ ...validTokens, refresh_token: null }) | ||
| }); | ||
|
|
||
| const refreshToken = 'refresh123'; | ||
| const tokens = await refreshAuthorization('https://auth.example.com', { | ||
| clientInformation: validClientInfo, | ||
| refreshToken | ||
| }); | ||
|
|
||
| // The null must not clobber the preserved token when the parsed response | ||
| // is merged with the previously-stored tokens (it would then be persisted | ||
| // via saveTokens, silently destroying the stored refresh token). | ||
| expect(tokens.refresh_token).toBe(refreshToken); | ||
| expect(tokens).toStrictEqual({ ...validTokens, refresh_token: refreshToken }); | ||
| }); | ||
|
|
||
| it.each([undefined, ''])('sends no scope parameter when scope is %j', async scope => { | ||
| mockFetch.mockResolvedValueOnce({ ok: true, status: 200, json: async () => validTokens }); | ||
|
|
||
|
|
@@ -3126,7 +3179,7 @@ describe('OAuth Authorization', () => { | |
| expect(body.get('refresh_token')).toBe('refresh123'); | ||
| }); | ||
|
|
||
| // The #2034 tests below differ only in how the token endpoint answers, so the | ||
| // The tests below differ only in how the token endpoint answers, so the | ||
| // discovery fixture is shared. `tokenResponse` is invoked per POST to /token. | ||
| const mockDiscoveryWithTokenEndpoint = (tokenResponse: () => unknown): void => { | ||
| mockFetch.mockImplementation(url => { | ||
|
|
@@ -3161,6 +3214,158 @@ describe('OAuth Authorization', () => { | |
| }); | ||
| }; | ||
|
|
||
| // RFC 6749 §5.1/§6: the SDK sends no `scope` parameter on refresh, so a response | ||
| // without `scope` (or with `scope: null`, stripped by OAuthTokenResponseSchema) | ||
| // asserts the grant is unchanged. The stored scope must survive the refresh — | ||
| // otherwise, after a restart, the insufficient_scope step-up would compute its | ||
| // scope union without the original grant and force interactive re-authorization. | ||
| const mockRefreshFetchWithTokenResponse = (tokenResponse: Record<string, unknown>): void => | ||
| mockDiscoveryWithTokenEndpoint(() => ({ | ||
| ok: true, | ||
| status: 200, | ||
| json: async () => tokenResponse | ||
| })); | ||
|
|
||
| it('keeps the stored scope when the refresh response returns scope: null', async () => { | ||
| mockRefreshFetchWithTokenResponse({ | ||
| access_token: 'new-access123', | ||
| token_type: 'Bearer', | ||
| expires_in: 3600, | ||
| scope: null | ||
| }); | ||
|
|
||
| (mockProvider.clientInformation as Mock).mockResolvedValue({ | ||
| client_id: 'test-client', | ||
| client_secret: 'test-secret' | ||
| }); | ||
| (mockProvider.tokens as Mock).mockResolvedValue({ | ||
| access_token: 'old-access', | ||
| refresh_token: 'refresh123', | ||
| scope: 'read write' | ||
| }); | ||
| (mockProvider.saveTokens as Mock).mockResolvedValue(undefined); | ||
|
|
||
| const result = await auth(mockProvider, { | ||
| serverUrl: 'https://api.example.com/mcp-server' | ||
| }); | ||
|
|
||
| expect(result).toBe('AUTHORIZED'); | ||
| expect(mockProvider.saveTokens).toHaveBeenCalledWith( | ||
| expect.objectContaining({ | ||
| access_token: 'new-access123', | ||
| refresh_token: 'refresh123', | ||
| scope: 'read write' | ||
| }), | ||
| expect.anything() | ||
| ); | ||
| }); | ||
|
|
||
| it('keeps the stored scope when the refresh response omits scope', async () => { | ||
| mockRefreshFetchWithTokenResponse({ | ||
| access_token: 'new-access123', | ||
| token_type: 'Bearer', | ||
| expires_in: 3600 | ||
| }); | ||
|
|
||
| (mockProvider.clientInformation as Mock).mockResolvedValue({ | ||
| client_id: 'test-client', | ||
| client_secret: 'test-secret' | ||
| }); | ||
| (mockProvider.tokens as Mock).mockResolvedValue({ | ||
| access_token: 'old-access', | ||
| refresh_token: 'refresh123', | ||
| scope: 'read write' | ||
| }); | ||
| (mockProvider.saveTokens as Mock).mockResolvedValue(undefined); | ||
|
|
||
| const result = await auth(mockProvider, { | ||
| serverUrl: 'https://api.example.com/mcp-server' | ||
| }); | ||
|
|
||
| expect(result).toBe('AUTHORIZED'); | ||
| expect(mockProvider.saveTokens).toHaveBeenCalledWith( | ||
| expect.objectContaining({ | ||
| access_token: 'new-access123', | ||
| refresh_token: 'refresh123', | ||
| scope: 'read write' | ||
| }), | ||
| expect.anything() | ||
| ); | ||
| }); | ||
|
|
||
| it('stores the scope the refresh response grants when one is present', async () => { | ||
| mockRefreshFetchWithTokenResponse({ | ||
| access_token: 'new-access123', | ||
| token_type: 'Bearer', | ||
| expires_in: 3600, | ||
| scope: 'read' | ||
| }); | ||
|
|
||
| (mockProvider.clientInformation as Mock).mockResolvedValue({ | ||
| client_id: 'test-client', | ||
| client_secret: 'test-secret' | ||
| }); | ||
| (mockProvider.tokens as Mock).mockResolvedValue({ | ||
| access_token: 'old-access', | ||
| refresh_token: 'refresh123', | ||
| scope: 'read write' | ||
| }); | ||
| (mockProvider.saveTokens as Mock).mockResolvedValue(undefined); | ||
|
|
||
| const result = await auth(mockProvider, { | ||
| serverUrl: 'https://api.example.com/mcp-server' | ||
| }); | ||
|
|
||
| expect(result).toBe('AUTHORIZED'); | ||
| // A scope the server does return is authoritative (a refresh may narrow the | ||
| // grant, RFC 6749 §6) — preservation only applies to an absent member. | ||
| expect(mockProvider.saveTokens).toHaveBeenCalledWith( | ||
| expect.objectContaining({ | ||
| access_token: 'new-access123', | ||
| scope: 'read' | ||
| }), | ||
| expect.anything() | ||
| ); | ||
| }); | ||
|
|
||
| it('saves a payload without a scope key when neither the response nor the stored tokens have one', async () => { | ||
| mockRefreshFetchWithTokenResponse({ | ||
| access_token: 'new-access123', | ||
| token_type: 'Bearer', | ||
| expires_in: 3600 | ||
| }); | ||
|
|
||
| (mockProvider.clientInformation as Mock).mockResolvedValue({ | ||
| client_id: 'test-client', | ||
| client_secret: 'test-secret' | ||
| }); | ||
| (mockProvider.tokens as Mock).mockResolvedValue({ | ||
| access_token: 'old-access', | ||
| refresh_token: 'refresh123' | ||
| }); | ||
| (mockProvider.saveTokens as Mock).mockResolvedValue(undefined); | ||
|
|
||
| const result = await auth(mockProvider, { | ||
| serverUrl: 'https://api.example.com/mcp-server' | ||
| }); | ||
|
|
||
| expect(result).toBe('AUTHORIZED'); | ||
| // Scope preservation must not manufacture a present-but-undefined `scope` | ||
| // key — the exact key shape this PR's normalization exists to prevent. | ||
| // toStrictEqual distinguishes an absent key from one set to undefined. | ||
| // The last saveTokens call is the refresh save (the first is the | ||
| // SEP-2352 issuer back-stamp of the legacy unstamped token set). | ||
| const savedTokens = (mockProvider.saveTokens as Mock).mock.lastCall![0]; | ||
| expect('scope' in savedTokens).toBe(false); | ||
| expect(savedTokens).toStrictEqual({ | ||
| access_token: 'new-access123', | ||
| token_type: 'Bearer', | ||
| expires_in: 3600, | ||
| refresh_token: 'refresh123', | ||
| issuer: 'https://auth.example.com' | ||
| }); | ||
| }); | ||
|
Comment on lines
+3229
to
+3367
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 🟡 nit (optional): The behaviours this change gives users are covered only by mocked- Why this was flaggedThe trigger is any later edit to the refresh save at packages/client/src/client/auth.ts:1474-1475 or to the parse site at auth.ts:2317. The tests this diff adds (packages/client/test/client/auth.test.ts:2041, 2326, 3229-3367, and packages/core-internal/test/shared/auth.test.ts) all drive Verification: nit — condition: any later edit to the refresh save or token parse site that regresses these behaviours; nothing fails at runtime today, this is a coverage gap against a written repo principle. Finding ID: |
||
|
|
||
| // A real Response: parseErrorResponse() reads the body via .text(), which a plain | ||
| // object mock cannot satisfy. | ||
| const oauthErrorResponse = (code: OAuthErrorCode, message: string): Response => | ||
|
|
@@ -3188,8 +3393,15 @@ describe('OAuth Authorization', () => { | |
| expect(refreshRequestBody()).toBe( | ||
| 'grant_type=refresh_token&refresh_token=refresh123&resource=https%3A%2F%2Fapi.example.com%2Fmcp-server&client_id=test-client' | ||
| ); | ||
| // The stored scope survives a refresh whose response omits scope (RFC 6749 §5.1: unchanged grant). | ||
| expect(mockProvider.saveTokens).toHaveBeenCalledWith( | ||
| { access_token: 'new-access', token_type: 'Bearer', refresh_token: 'refresh123', issuer: 'https://auth.example.com' }, | ||
| { | ||
| access_token: 'new-access', | ||
| token_type: 'Bearer', | ||
| refresh_token: 'refresh123', | ||
| scope: 'read write', | ||
| issuer: 'https://auth.example.com' | ||
| }, | ||
| expect.anything() | ||
| ); | ||
| }); | ||
|
|
||
Uh oh!
There was an error while loading. Please reload this page.