|
| 1 | +import { McpOAuthService } from './mcp-oauth.service'; |
| 2 | +import axios from 'axios'; |
| 3 | + |
| 4 | +jest.mock('axios'); |
| 5 | +// assertSafeOutboundUrl performs DNS/SSRF checks — stub it out for unit tests. |
| 6 | +jest.mock('../common/ssrf.util', () => ({ |
| 7 | + assertSafeOutboundUrl: jest.fn().mockResolvedValue(undefined), |
| 8 | +})); |
| 9 | + |
| 10 | +const mockedAxios = axios as jest.Mocked<typeof axios>; |
| 11 | + |
| 12 | +describe('McpOAuthService.exchangeCodeForTokens client authentication', () => { |
| 13 | + let service: McpOAuthService; |
| 14 | + |
| 15 | + beforeEach(() => { |
| 16 | + service = new McpOAuthService(); |
| 17 | + mockedAxios.post.mockReset(); |
| 18 | + mockedAxios.post.mockResolvedValue({ |
| 19 | + data: { access_token: 'at', refresh_token: 'rt', expires_in: 3600 }, |
| 20 | + } as any); |
| 21 | + }); |
| 22 | + |
| 23 | + const baseParams = { |
| 24 | + tokenUrl: 'https://sandbox-api.datev.de/token', |
| 25 | + code: 'authcode', |
| 26 | + redirectUri: 'https://cloud.anythingmcp.com/api/mcp-oauth/callback', |
| 27 | + clientId: 'cid', |
| 28 | + clientSecret: 'secret', |
| 29 | + codeVerifier: 'verifier', |
| 30 | + }; |
| 31 | + |
| 32 | + it('defaults to client_secret_post (credentials in body, no Basic header)', async () => { |
| 33 | + await service.exchangeCodeForTokens({ ...baseParams }); |
| 34 | + |
| 35 | + const [, body, config] = mockedAxios.post.mock.calls[0]; |
| 36 | + expect(String(body)).toContain('client_secret=secret'); |
| 37 | + expect((config as any).headers.Authorization).toBeUndefined(); |
| 38 | + }); |
| 39 | + |
| 40 | + it('uses client_secret_basic when tokenAuthMethod=basic (header, not body)', async () => { |
| 41 | + await service.exchangeCodeForTokens({ |
| 42 | + ...baseParams, |
| 43 | + tokenAuthMethod: 'basic', |
| 44 | + }); |
| 45 | + |
| 46 | + const [, body, config] = mockedAxios.post.mock.calls[0]; |
| 47 | + // Secret must NOT be in the body... |
| 48 | + expect(String(body)).not.toContain('client_secret='); |
| 49 | + // ...but in the Authorization header as base64(client_id:client_secret). |
| 50 | + const expected = |
| 51 | + 'Basic ' + Buffer.from('cid:secret').toString('base64'); |
| 52 | + expect((config as any).headers.Authorization).toBe(expected); |
| 53 | + // client_id still present in the body per RFC 6749. |
| 54 | + expect(String(body)).toContain('client_id=cid'); |
| 55 | + }); |
| 56 | + |
| 57 | + it("treats 'client_secret_basic' as an alias for basic", async () => { |
| 58 | + await service.exchangeCodeForTokens({ |
| 59 | + ...baseParams, |
| 60 | + tokenAuthMethod: 'client_secret_basic', |
| 61 | + }); |
| 62 | + const [, , config] = mockedAxios.post.mock.calls[0]; |
| 63 | + expect((config as any).headers.Authorization).toMatch(/^Basic /); |
| 64 | + }); |
| 65 | +}); |
0 commit comments