import type { AuthenticationResult, ConfidentialClientApplication } from '@azure/msal-node'; import { PRE_AUTH_COOKIE_TTL_MS } from './auth.cookie'; import { AuthCodeFlowException } from './auth.errors'; import { AuthService, type PreAuthPayload } from './auth.service'; import type { EntraConfig } from './entra-config.token'; const ENTRA: EntraConfig = { instanceUrl: 'https://login.microsoftonline.com/', tenantId: 'aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee', clientId: '11111111-2222-3333-4444-555555555555', clientSecret: 's3cret', redirectUri: 'http://localhost:3000/api/auth/callback', postLogoutRedirectUri: 'http://localhost:4200/', authority: 'https://login.microsoftonline.com/aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee', }; interface ServiceFixture { service: AuthService; getAuthCodeUrl: jest.Mock; acquireTokenByCode: jest.Mock; } function makeService(overrides?: { acquireTokenByCode?: jest.Mock }): ServiceFixture { const getAuthCodeUrl = jest.fn().mockResolvedValue('https://entra.example/authorize?…'); const acquireTokenByCode = overrides?.acquireTokenByCode ?? jest.fn().mockResolvedValue(makeAuthResult({ amr: ['pwd', 'mfa'] })); const msalStub = { getAuthCodeUrl, acquireTokenByCode, } as unknown as ConfidentialClientApplication; return { service: new AuthService(msalStub, ENTRA), getAuthCodeUrl, acquireTokenByCode }; } function makeAuthResult( claims: Partial<{ amr: string[]; oid: string; tid: string; name: string; preferred_username: string; }>, ): AuthenticationResult { return { idTokenClaims: { oid: claims.oid ?? 'user-oid', tid: claims.tid ?? ENTRA.tenantId, name: claims.name ?? 'Jane Doe', preferred_username: claims.preferred_username ?? 'jane.doe@apf.example', amr: claims.amr ?? ['pwd', 'mfa'], }, account: { username: 'jane.doe@apf.example', name: 'Jane Doe' }, } as unknown as AuthenticationResult; } const PRE_AUTH_OK: PreAuthPayload = { state: 'state-nonce', codeVerifier: 'verifier-secret', createdAt: 1_000_000, }; describe('AuthService.beginAuthCodeFlow', () => { it('builds the auth URL with the configured redirect, OIDC scopes, S256 challenge', async () => { const { service, getAuthCodeUrl } = makeService(); await service.beginAuthCodeFlow(); expect(getAuthCodeUrl).toHaveBeenCalledTimes(1); const arg = getAuthCodeUrl.mock.calls[0]?.[0] as Record; expect(arg['redirectUri']).toBe(ENTRA.redirectUri); expect(arg['scopes']).toEqual(['openid', 'profile', 'email']); expect(arg['codeChallengeMethod']).toBe('S256'); expect(typeof arg['codeChallenge']).toBe('string'); expect(typeof arg['state']).toBe('string'); }); it('returns the pre-auth payload with state + codeVerifier matching what MSAL was called with', async () => { const { service, getAuthCodeUrl } = makeService(); const { preAuthPayload } = await service.beginAuthCodeFlow(); const arg = getAuthCodeUrl.mock.calls[0]?.[0] as Record; expect(preAuthPayload.state).toBe(arg['state']); expect(preAuthPayload.codeVerifier).not.toBe(arg['codeChallenge']); expect(preAuthPayload.createdAt).toBeLessThanOrEqual(Date.now()); }); it('generates a fresh state + verifier on every call', async () => { const { service } = makeService(); const a = await service.beginAuthCodeFlow(); const b = await service.beginAuthCodeFlow(); expect(a.preAuthPayload.state).not.toBe(b.preAuthPayload.state); expect(a.preAuthPayload.codeVerifier).not.toBe(b.preAuthPayload.codeVerifier); }); }); describe('AuthService.completeAuthCodeFlow', () => { it('returns the authenticated user on the happy path', async () => { const { service, acquireTokenByCode } = makeService(); const user = await service.completeAuthCodeFlow( 'auth-code', PRE_AUTH_OK.state, PRE_AUTH_OK, PRE_AUTH_OK.createdAt + 1_000, ); expect(acquireTokenByCode).toHaveBeenCalledWith({ code: 'auth-code', codeVerifier: PRE_AUTH_OK.codeVerifier, redirectUri: ENTRA.redirectUri, scopes: ['openid', 'profile', 'email'], }); expect(user).toEqual({ oid: 'user-oid', tid: ENTRA.tenantId, username: 'jane.doe@apf.example', displayName: 'Jane Doe', amr: ['pwd', 'mfa'], }); }); it('throws state-mismatch when the query state differs from the cookie state', async () => { const { service } = makeService(); await expect( service.completeAuthCodeFlow('code', 'other-state', PRE_AUTH_OK, PRE_AUTH_OK.createdAt), ).rejects.toMatchObject({ failure: { kind: 'state-mismatch' } }); }); it('throws flow-expired when the cookie is older than the TTL', async () => { const { service } = makeService(); const now = PRE_AUTH_OK.createdAt + PRE_AUTH_COOKIE_TTL_MS + 1; await expect( service.completeAuthCodeFlow('code', PRE_AUTH_OK.state, PRE_AUTH_OK, now), ).rejects.toMatchObject({ failure: { kind: 'flow-expired' } }); }); it('throws amr-missing when the ID token has no amr claim', async () => { const acquireTokenByCode = jest.fn().mockResolvedValue(makeAuthResult({ amr: [] })); const { service } = makeService({ acquireTokenByCode }); await expect( service.completeAuthCodeFlow('code', PRE_AUTH_OK.state, PRE_AUTH_OK, PRE_AUTH_OK.createdAt), ).rejects.toMatchObject({ failure: { kind: 'amr-missing' } }); }); it('throws token-exchange-failed when MSAL throws', async () => { const acquireTokenByCode = jest.fn().mockRejectedValue(new Error('AADSTS70008')); const { service } = makeService({ acquireTokenByCode }); await expect( service.completeAuthCodeFlow('code', PRE_AUTH_OK.state, PRE_AUTH_OK, PRE_AUTH_OK.createdAt), ).rejects.toMatchObject({ failure: { kind: 'token-exchange-failed', cause: 'AADSTS70008' }, }); }); it('throws token-exchange-failed when MSAL returns null', async () => { const acquireTokenByCode = jest.fn().mockResolvedValue(null); const { service } = makeService({ acquireTokenByCode }); await expect( service.completeAuthCodeFlow('code', PRE_AUTH_OK.state, PRE_AUTH_OK, PRE_AUTH_OK.createdAt), ).rejects.toBeInstanceOf(AuthCodeFlowException); }); it('throws token-exchange-failed when oid claim is missing', async () => { const acquireTokenByCode = jest.fn().mockResolvedValue({ idTokenClaims: { tid: ENTRA.tenantId, amr: ['mfa'] }, account: { username: '', name: '' }, } as unknown as AuthenticationResult); const { service } = makeService({ acquireTokenByCode }); await expect( service.completeAuthCodeFlow('code', PRE_AUTH_OK.state, PRE_AUTH_OK, PRE_AUTH_OK.createdAt), ).rejects.toMatchObject({ failure: { kind: 'token-exchange-failed', cause: /oid/ }, }); }); });