-
-
Notifications
You must be signed in to change notification settings - Fork 56
feat(oauth): add rotating refresh tokens #408
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
Open
xizhibei
wants to merge
6
commits into
main
Choose a base branch
from
codex/issues-oauth-403-404
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from 2 commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
dcbe92c
feat(oauth): add rotating refresh tokens
xizhibei cace717
fix(oauth): make refresh rotation durable
xizhibei 48014e9
fix(oauth): address refresh rotation review
xizhibei 1c55765
fix(storage): recover failed lock releases
xizhibei d9cea16
test(storage): assert release failure injection
xizhibei 6bd2af4
fix(storage): preserve exclusive lock ownership
xizhibei File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,7 @@ | ||
| # OAuth Refresh Tokens Use Rotating Families | ||
|
|
||
| 1MCP issues refresh tokens only to registered clients that request the `refresh_token` grant. Each approved authorization creates an independent, client-, resource-, and scope-bound Refresh Token Family that persists in its Runtime Scope for a fixed 30 days. Every successful refresh rotates a single-use opaque token; only token digests and family lineage are stored. | ||
|
|
||
| Because public PKCE clients are not sender-constrained, reuse of any consumed family member revokes its family and every access token issued from it. There is no retry grace period: concurrent refreshes permit one success, and later use is replay. A normal refresh may narrow the new access token's scopes and leaves earlier access tokens valid until their own expiry; explicit access-token revocation remains local to that token. | ||
|
|
||
| This chooses RFC 9700 rotation and strong replay containment over retry availability. A lost response or concurrent retry can force reauthorization, but the runtime never permits two valid successors or extends the family beyond its original lifetime. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,330 @@ | ||
| import fs from 'node:fs'; | ||
| import os from 'node:os'; | ||
| import path from 'node:path'; | ||
|
|
||
| import { | ||
| InvalidGrantError, | ||
| InvalidScopeError, | ||
| InvalidTargetError, | ||
| } from '@modelcontextprotocol/sdk/server/auth/errors.js'; | ||
| import type { OAuthClientInformationFull, OAuthTokens } from '@modelcontextprotocol/sdk/shared/auth.js'; | ||
|
|
||
| import { AUTH_CONFIG } from '@src/constants.js'; | ||
| import { AgentConfigManager } from '@src/core/server/agentConfig.js'; | ||
| import logger from '@src/logger/logger.js'; | ||
|
|
||
| import { FileStorageService } from './storage/fileStorageService.js'; | ||
|
|
||
| import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; | ||
|
|
||
| import { SDKOAuthServerProvider } from './sdkOAuthServerProvider.js'; | ||
|
|
||
| const CLIENT: OAuthClientInformationFull = { | ||
| client_id: 'refresh-client', | ||
| redirect_uris: ['http://127.0.0.1:3000/callback'], | ||
| grant_types: ['authorization_code', 'refresh_token'], | ||
| response_types: ['code'], | ||
| token_endpoint_auth_method: 'none', | ||
| }; | ||
| const OTHER_CLIENT: OAuthClientInformationFull = { ...CLIENT, client_id: 'other-client' }; | ||
| const ACCESS_ONLY_CLIENT: OAuthClientInformationFull = { | ||
| ...CLIENT, | ||
| client_id: 'access-only-client', | ||
| grant_types: ['authorization_code'], | ||
| }; | ||
| const RESOURCE = 'https://resource.example/mcp'; | ||
| const SCOPES = ['tag:alpha', 'tag:beta']; | ||
|
|
||
| describe('SDKOAuthServerProvider refresh token families', () => { | ||
| let provider: SDKOAuthServerProvider; | ||
| let tempDir: string; | ||
| let originalAuthEnabled: boolean; | ||
|
|
||
| beforeEach(() => { | ||
| tempDir = fs.mkdtempSync(path.join(os.tmpdir(), '1mcp-refresh-family-')); | ||
| provider = new SDKOAuthServerProvider(tempDir, 'runtime-scope-a'); | ||
| const configManager = AgentConfigManager.getInstance(); | ||
| originalAuthEnabled = configManager.get('features').auth; | ||
| configManager.get('features').auth = true; | ||
| }); | ||
|
|
||
| afterEach(() => { | ||
| provider.shutdown(); | ||
| AgentConfigManager.getInstance().get('features').auth = originalAuthEnabled; | ||
| fs.rmSync(tempDir, { recursive: true, force: true }); | ||
| vi.restoreAllMocks(); | ||
| }); | ||
|
|
||
| it('issues refresh tokens only to opted-in clients and persists only their SHA-256 digest', async () => { | ||
| const renewable = await exchangeAuthorizationCode(provider, CLIENT); | ||
| const accessOnly = await exchangeAuthorizationCode(provider, ACCESS_ONLY_CLIENT); | ||
|
|
||
| expect(renewable.refresh_token).toMatch(/^rt-[A-Za-z0-9_-]{43}$/); | ||
| expect(accessOnly).not.toHaveProperty('refresh_token'); | ||
|
|
||
| const familyFiles = listFamilyFiles(tempDir); | ||
| expect(familyFiles).toHaveLength(1); | ||
| const stored = fs.readFileSync(familyFiles[0], 'utf8'); | ||
| expect(stored).not.toContain(renewable.refresh_token!); | ||
| expect(JSON.parse(stored)).toMatchObject({ | ||
| runtimeScopeId: 'runtime-scope-a', | ||
| clientId: CLIENT.client_id, | ||
| scopeCeiling: SCOPES, | ||
| resource: RESOURCE, | ||
| status: 'active', | ||
| currentTokenDigest: expect.stringMatching(/^[a-f0-9]{64}$/), | ||
| }); | ||
| }); | ||
|
|
||
| it('persists families across provider restarts and rotation does not extend their fixed expiry', async () => { | ||
| const initial = await exchangeAuthorizationCode(provider, CLIENT); | ||
| const before = readOnlyFamily(tempDir); | ||
| provider.shutdown(); | ||
| provider = new SDKOAuthServerProvider(tempDir, 'runtime-scope-a'); | ||
|
|
||
| const rotated = await provider.exchangeRefreshToken(CLIENT, initial.refresh_token!); | ||
| const after = readOnlyFamily(tempDir); | ||
|
|
||
| expect(rotated.refresh_token).toMatch(/^rt-/); | ||
| expect(rotated.refresh_token).not.toBe(initial.refresh_token); | ||
| expect(after.createdAt).toBe(before.createdAt); | ||
| expect(after.expires).toBe(before.expires); | ||
| expect(after.expires - after.createdAt).toBe(AUTH_CONFIG.SERVER.REFRESH_FAMILY.TTL_MS); | ||
| expect(after.consumedTokenDigests).toHaveLength(1); | ||
| }); | ||
|
|
||
| it('fails closed and cleans persisted family state after the fixed expiry', async () => { | ||
| const initial = await exchangeAuthorizationCode(provider, CLIENT); | ||
| for (const filePath of [...listFamilyFiles(tempDir), ...listLookupFiles(tempDir)]) { | ||
| const record = JSON.parse(fs.readFileSync(filePath, 'utf8')) as Record<string, unknown>; | ||
| fs.writeFileSync(filePath, JSON.stringify({ ...record, expires: Date.now() - 1 })); | ||
| } | ||
|
|
||
| await expect(provider.exchangeRefreshToken(CLIENT, initial.refresh_token!)).rejects.toBeInstanceOf( | ||
| InvalidGrantError, | ||
| ); | ||
| await expect(provider.verifyAccessToken(initial.access_token)).rejects.toThrow('Invalid or expired access token'); | ||
| expect(listFamilyFiles(tempDir)).toHaveLength(0); | ||
| expect(listLookupFiles(tempDir)).toHaveLength(0); | ||
| }); | ||
|
|
||
| it('does not consume the current refresh token when access-session persistence fails', async () => { | ||
| const initial = await exchangeAuthorizationCode(provider, CLIENT); | ||
| const createSession = vi | ||
| .spyOn(provider.oauthStorage.sessionRepository, 'createRefreshFamilyAccessSession') | ||
| .mockImplementationOnce(() => { | ||
| throw new Error('session persistence failed'); | ||
| }); | ||
|
|
||
| await expect(provider.exchangeRefreshToken(CLIENT, initial.refresh_token!)).rejects.toThrow( | ||
| 'session persistence failed', | ||
| ); | ||
|
|
||
| createSession.mockRestore(); | ||
| await expect(provider.exchangeRefreshToken(CLIENT, initial.refresh_token!)).resolves.toMatchObject({ | ||
| refresh_token: expect.stringMatching(/^rt-/), | ||
| }); | ||
| }); | ||
|
|
||
| it('does not consume the current refresh token when the family commit fails', async () => { | ||
| const initial = await exchangeAuthorizationCode(provider, CLIENT); | ||
| const originalWriteData = FileStorageService.prototype.writeDataDurable; | ||
| let failedFamilyCommit = false; | ||
| const writeData = vi.spyOn(FileStorageService.prototype, 'writeDataDurable').mockImplementation(function ( | ||
| this: FileStorageService, | ||
| filePrefix: string, | ||
| id: string, | ||
| data: Parameters<FileStorageService['writeDataDurable']>[2], | ||
| ) { | ||
| if (filePrefix === AUTH_CONFIG.SERVER.REFRESH_FAMILY.FILE_PREFIX && !failedFamilyCommit) { | ||
| failedFamilyCommit = true; | ||
| throw new Error('family commit failed'); | ||
| } | ||
| return originalWriteData.call(this, filePrefix, id, data); | ||
| }); | ||
|
|
||
| await expect(provider.exchangeRefreshToken(CLIENT, initial.refresh_token!)).rejects.toThrow('family commit failed'); | ||
| writeData.mockRestore(); | ||
|
|
||
| await expect(provider.exchangeRefreshToken(CLIENT, initial.refresh_token!)).resolves.toMatchObject({ | ||
| refresh_token: expect.stringMatching(/^rt-/), | ||
| }); | ||
| }); | ||
|
|
||
| it('preserves the original scope ceiling and resource while allowing equal or narrower access', async () => { | ||
| const initial = await exchangeAuthorizationCode(provider, CLIENT); | ||
|
|
||
| await expect( | ||
| provider.exchangeRefreshToken(CLIENT, initial.refresh_token!, ['tag:alpha', 'tag:outside']), | ||
| ).rejects.toBeInstanceOf(InvalidScopeError); | ||
| await expect( | ||
| provider.exchangeRefreshToken(CLIENT, initial.refresh_token!, undefined, new URL('https://other.example/mcp')), | ||
| ).rejects.toBeInstanceOf(InvalidTargetError); | ||
|
|
||
| const narrowed = await provider.exchangeRefreshToken( | ||
| CLIENT, | ||
| initial.refresh_token!, | ||
| ['tag:alpha'], | ||
| new URL(RESOURCE), | ||
| ); | ||
| expect(narrowed.scope).toBe('tag:alpha'); | ||
|
|
||
| const restored = await provider.exchangeRefreshToken(CLIENT, narrowed.refresh_token!); | ||
| expect(restored.scope).toBe(SCOPES.join(' ')); | ||
| expect(readOnlyFamily(tempDir).scopeCeiling).toEqual(SCOPES); | ||
| }); | ||
|
|
||
| it('allows exactly one concurrent rotation and replay revokes the family and every associated access token', async () => { | ||
| const initial = await exchangeAuthorizationCode(provider, CLIENT); | ||
| const attempts = await Promise.allSettled([ | ||
| provider.exchangeRefreshToken(CLIENT, initial.refresh_token!), | ||
| provider.exchangeRefreshToken(CLIENT, initial.refresh_token!), | ||
| ]); | ||
|
|
||
| expect(attempts.filter((attempt) => attempt.status === 'fulfilled')).toHaveLength(1); | ||
| const rejection = attempts.find((attempt) => attempt.status === 'rejected') as PromiseRejectedResult; | ||
| expect(rejection.reason).toBeInstanceOf(InvalidGrantError); | ||
| expect(readOnlyFamily(tempDir).status).toBe('revoked'); | ||
|
|
||
| const successful = ( | ||
| attempts.find((attempt) => attempt.status === 'fulfilled') as PromiseFulfilledResult<OAuthTokens> | ||
| ).value; | ||
| await expect(provider.verifyAccessToken(initial.access_token)).rejects.toThrow('Invalid or expired access token'); | ||
| await expect(provider.verifyAccessToken(successful.access_token)).rejects.toThrow( | ||
| 'Invalid or expired access token', | ||
| ); | ||
| await expect(provider.exchangeRefreshToken(CLIENT, successful.refresh_token!)).rejects.toBeInstanceOf( | ||
| InvalidGrantError, | ||
| ); | ||
| }); | ||
|
|
||
| it('keeps family state bounded while older consumed-token lookups retain replay containment', async () => { | ||
| const initial = await exchangeAuthorizationCode(provider, CLIENT); | ||
| const first = await provider.exchangeRefreshToken(CLIENT, initial.refresh_token!); | ||
| const second = await provider.exchangeRefreshToken(CLIENT, first.refresh_token!); | ||
| await provider.exchangeRefreshToken(CLIENT, second.refresh_token!); | ||
|
|
||
| expect(readOnlyFamily(tempDir).consumedTokenDigests).toHaveLength(1); | ||
| await expect(provider.exchangeRefreshToken(CLIENT, initial.refresh_token!)).rejects.toBeInstanceOf( | ||
| InvalidGrantError, | ||
| ); | ||
| expect(readOnlyFamily(tempDir).status).toBe('revoked'); | ||
| }); | ||
|
|
||
| it('isolates refresh families by Runtime Scope even when storage is shared', async () => { | ||
| const initial = await exchangeAuthorizationCode(provider, CLIENT); | ||
| const otherScopeProvider = new SDKOAuthServerProvider(tempDir, 'runtime-scope-b'); | ||
| try { | ||
| await expect( | ||
| otherScopeProvider.exchangeRefreshToken(CLIENT, initial.refresh_token!), | ||
| ).rejects.toBeInstanceOf(InvalidGrantError); | ||
| await expect(provider.exchangeRefreshToken(CLIENT, initial.refresh_token!)).resolves.toMatchObject({ | ||
| refresh_token: expect.stringMatching(/^rt-/), | ||
| }); | ||
| } finally { | ||
| otherScopeProvider.shutdown(); | ||
| } | ||
| }); | ||
|
|
||
| it('propagates replay-cascade deletion failures while revoked family state blocks residual sessions', async () => { | ||
| const initial = await exchangeAuthorizationCode(provider, CLIENT); | ||
| const rotated = await provider.exchangeRefreshToken(CLIENT, initial.refresh_token!); | ||
| const originalUnlinkSync = fs.unlinkSync; | ||
| const unlink = vi.spyOn(fs, 'unlinkSync').mockImplementation((filePath) => { | ||
| if (String(filePath).includes(AUTH_CONFIG.SERVER.SESSION.FILE_PREFIX)) { | ||
| throw new Error('session deletion failed'); | ||
| } | ||
| return originalUnlinkSync(filePath); | ||
| }); | ||
|
|
||
| await expect(provider.exchangeRefreshToken(CLIENT, initial.refresh_token!)).rejects.toThrow( | ||
| 'Failed to revoke access sessions for refresh token family', | ||
| ); | ||
| unlink.mockRestore(); | ||
| await expect(provider.verifyAccessToken(initial.access_token)).rejects.toThrow('Invalid or expired access token'); | ||
| await expect(provider.verifyAccessToken(rotated.access_token)).rejects.toThrow('Invalid or expired access token'); | ||
| }); | ||
|
|
||
| it('does not mutate a rightful family when another client presents its refresh token', async () => { | ||
| const initial = await exchangeAuthorizationCode(provider, CLIENT); | ||
|
|
||
| await expect(provider.exchangeRefreshToken(OTHER_CLIENT, initial.refresh_token!)).rejects.toBeInstanceOf( | ||
| InvalidGrantError, | ||
| ); | ||
| const rightful = await provider.exchangeRefreshToken(CLIENT, initial.refresh_token!); | ||
| expect(rightful.refresh_token).toMatch(/^rt-/); | ||
| }); | ||
|
|
||
| it('keeps earlier access tokens valid on normal rotation and applies token-specific revocation semantics', async () => { | ||
| const initial = await exchangeAuthorizationCode(provider, CLIENT); | ||
| const rotated = await provider.exchangeRefreshToken(CLIENT, initial.refresh_token!); | ||
|
|
||
| await expect(provider.verifyAccessToken(initial.access_token)).resolves.toMatchObject({ | ||
| clientId: CLIENT.client_id, | ||
| }); | ||
| await provider.revokeToken(CLIENT, { token: initial.access_token }); | ||
| await expect(provider.verifyAccessToken(initial.access_token)).rejects.toThrow('Invalid or expired access token'); | ||
| await expect(provider.verifyAccessToken(rotated.access_token)).resolves.toMatchObject({ | ||
| clientId: CLIENT.client_id, | ||
| }); | ||
|
|
||
| const next = await provider.exchangeRefreshToken(CLIENT, rotated.refresh_token!); | ||
| await provider.revokeToken(CLIENT, { token: next.refresh_token! }); | ||
| await expect(provider.verifyAccessToken(rotated.access_token)).rejects.toThrow('Invalid or expired access token'); | ||
| await expect(provider.verifyAccessToken(next.access_token)).rejects.toThrow('Invalid or expired access token'); | ||
| await expect(provider.exchangeRefreshToken(CLIENT, next.refresh_token!)).rejects.toBeInstanceOf(InvalidGrantError); | ||
|
|
||
| await expect(provider.revokeToken(CLIENT, { token: 'unknown-token' })).resolves.toBeUndefined(); | ||
| }); | ||
|
|
||
| it('never passes refresh bearer values to the logger', async () => { | ||
| const debug = vi.spyOn(logger, 'debug'); | ||
| const info = vi.spyOn(logger, 'info'); | ||
| const warn = vi.spyOn(logger, 'warn'); | ||
| const error = vi.spyOn(logger, 'error'); | ||
| const initial = await exchangeAuthorizationCode(provider, CLIENT); | ||
| const rotated = await provider.exchangeRefreshToken(CLIENT, initial.refresh_token!); | ||
| await provider.revokeToken(CLIENT, { token: rotated.refresh_token! }); | ||
|
|
||
| const logged = JSON.stringify([...debug.mock.calls, ...info.mock.calls, ...warn.mock.calls, ...error.mock.calls]); | ||
| expect(logged).not.toContain(initial.refresh_token!); | ||
| expect(logged).not.toContain(rotated.refresh_token!); | ||
| }); | ||
| }); | ||
|
|
||
| async function exchangeAuthorizationCode( | ||
| provider: SDKOAuthServerProvider, | ||
| client: OAuthClientInformationFull, | ||
| ): Promise<OAuthTokens> { | ||
| const code = provider.oauthStorage.authCodeRepository.create( | ||
| client.client_id, | ||
| client.redirect_uris[0], | ||
| RESOURCE, | ||
| SCOPES, | ||
| 60_000, | ||
| 'challenge', | ||
| ); | ||
| return provider.exchangeAuthorizationCode(client, code, undefined, client.redirect_uris[0], new URL(RESOURCE)); | ||
| } | ||
|
|
||
| function listFamilyFiles(tempDir: string): string[] { | ||
| const serverDir = path.join(tempDir, AUTH_CONFIG.SERVER.STORAGE.DIR, AUTH_CONFIG.SERVER.SESSION.SUBDIR); | ||
| return fs | ||
| .readdirSync(serverDir) | ||
| .filter((fileName) => fileName.startsWith(AUTH_CONFIG.SERVER.REFRESH_FAMILY.FILE_PREFIX)) | ||
| .map((fileName) => path.join(serverDir, fileName)); | ||
| } | ||
|
|
||
| function listLookupFiles(tempDir: string): string[] { | ||
| const serverDir = path.join(tempDir, AUTH_CONFIG.SERVER.STORAGE.DIR, AUTH_CONFIG.SERVER.SESSION.SUBDIR); | ||
| return fs | ||
| .readdirSync(serverDir) | ||
| .filter((fileName) => fileName.startsWith(AUTH_CONFIG.SERVER.REFRESH_FAMILY.LOOKUP_FILE_PREFIX)) | ||
| .map((fileName) => path.join(serverDir, fileName)); | ||
| } | ||
|
|
||
| function readOnlyFamily(tempDir: string): Record<string, any> { | ||
| const familyFiles = listFamilyFiles(tempDir); | ||
| expect(familyFiles).toHaveLength(1); | ||
| return JSON.parse(fs.readFileSync(familyFiles[0], 'utf8')); | ||
| } |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.