Skip to content
Merged
Show file tree
Hide file tree
Changes from 16 commits
Commits
Show all changes
18 commits
Select commit Hold shift + click to select a range
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
62 changes: 62 additions & 0 deletions src/server/auth/handlers/token.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import supertest from 'supertest';
import * as pkceChallenge from 'pkce-challenge';
import { InvalidGrantError, InvalidTokenError } from '../errors.js';
import { AuthInfo } from '../types.js';
import { ProxyOAuthServerProvider } from '../providers/proxyProvider.js';

// Mock pkce-challenge
jest.mock('pkce-challenge', () => ({
Expand Down Expand Up @@ -280,6 +281,67 @@ describe('Token Handler', () => {
expect(response.body.expires_in).toBe(3600);
expect(response.body.refresh_token).toBe('mock_refresh_token');
});

it('passes through code verifier when using proxy provider', async () => {
const originalFetch = global.fetch;

try {
global.fetch = jest.fn().mockResolvedValue({
ok: true,
json: () => Promise.resolve({
access_token: 'mock_access_token',
token_type: 'bearer',
expires_in: 3600,
refresh_token: 'mock_refresh_token'
})
});

const proxyProvider = new ProxyOAuthServerProvider({
endpoints: {
authorizationUrl: 'https://example.com/authorize',
tokenUrl: 'https://example.com/token'
},
verifyAccessToken: async (token) => ({
token,
clientId: 'valid-client',
scopes: ['read', 'write'],
expiresAt: Date.now() / 1000 + 3600
}),
getClient: async (clientId) => clientId === 'valid-client' ? validClient : undefined
});

const proxyApp = express();
const options: TokenHandlerOptions = { provider: proxyProvider };
proxyApp.use('/token', tokenHandler(options));

const response = await supertest(proxyApp)
.post('/token')
.type('form')
.send({
client_id: 'valid-client',
client_secret: 'valid-secret',
grant_type: 'authorization_code',
code: 'valid_code',
code_verifier: 'any_verifier'
});

expect(response.status).toBe(200);
expect(response.body.access_token).toBe('mock_access_token');

expect(global.fetch).toHaveBeenCalledWith(
'https://example.com/token',
expect.objectContaining({
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
body: expect.stringContaining('code_verifier=any_verifier')
})
);
} finally {
global.fetch = originalFetch;
}
});
});

describe('Refresh token grant', () => {
Expand Down
16 changes: 11 additions & 5 deletions src/server/auth/handlers/token.ts
Original file line number Diff line number Diff line change
Expand Up @@ -90,13 +90,19 @@ export function tokenHandler({ provider, rateLimit: rateLimitConfig }: TokenHand

const { code, code_verifier } = parseResult.data;

// Verify PKCE challenge
const codeChallenge = await provider.challengeForAuthorizationCode(client, code);
if (!(await verifyChallenge(code_verifier, codeChallenge))) {
throw new InvalidGrantError("code_verifier does not match the challenge");
const skipLocalPkceValidation = provider.skipLocalPkceValidation;

// Perform local PKCE validation unless explicitly skipped
// (e.g. to validate code_verifier in upstream server)
if (!skipLocalPkceValidation) {
const codeChallenge = await provider.challengeForAuthorizationCode(client, code);
if (!(await verifyChallenge(code_verifier, codeChallenge))) {
throw new InvalidGrantError("code_verifier does not match the challenge");
}
}

const tokens = await provider.exchangeAuthorizationCode(client, code);
// Passes the code_verifier to the provider if PKCE validation didn't occur locally
const tokens = await provider.exchangeAuthorizationCode(client, code, skipLocalPkceValidation ? code_verifier : undefined);
res.status(200).json(tokens);
break;
}
Expand Down
11 changes: 10 additions & 1 deletion src/server/auth/provider.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ export interface OAuthServerProvider {
/**
* Exchanges an authorization code for an access token.
*/
exchangeAuthorizationCode(client: OAuthClientInformationFull, authorizationCode: string): Promise<OAuthTokens>;
exchangeAuthorizationCode(client: OAuthClientInformationFull, authorizationCode: string, codeVerifier?: string): Promise<OAuthTokens>;

/**
* Exchanges a refresh token for an access token.
Expand All @@ -54,4 +54,13 @@ export interface OAuthServerProvider {
* If the given token is invalid or already revoked, this method should do nothing.
*/
revokeToken?(client: OAuthClientInformationFull, request: OAuthTokenRevocationRequest): Promise<void>;

/**
* Whether to skip local PKCE validation.
*
* If true, the server will not perform PKCE validation locally and will pass the code_verifier to the upstream server.
*
* NOTE: This should only be true if the upstream server is performing the actual PKCE validation.
*/
skipLocalPkceValidation?: boolean;
}
Loading