Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
110 changes: 58 additions & 52 deletions packages/fxa-auth-server/lib/routes/linked-accounts.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,21 +22,6 @@ jest.mock('google-auth-library', () => {
};
});

// Mock axios with a getter so per-test overrides work.
// Default returns the real axios so transitive deps (googleapis, google-maps) work at init time.
// eslint-disable-next-line no-var
var axiosDefaultOverride: any = null;
jest.mock('axios', () => {
const actual = jest.requireActual('axios');
return {
...actual,
__esModule: true,
get default() {
return axiosDefaultOverride || actual;
},
};
});

jest.mock('./utils/third-party-events', () => {
const actual = jest.requireActual('./utils/third-party-events');
return new Proxy(actual, {
Expand Down Expand Up @@ -81,16 +66,9 @@ const makeRoutes = function (options: any = {}, requireMocks?: any) {
if (requireMocks['google-auth-library']) {
mockOAuth2ClientClass = requireMocks['google-auth-library'].OAuth2Client;
}
if (requireMocks['axios']) {
axiosDefaultOverride = requireMocks['axios'];
} else {
axiosDefaultOverride = null;
}
if (requireMocks['./utils/third-party-events']) {
mockThirdPartyEventsModule = requireMocks['./utils/third-party-events'];
}
} else {
axiosDefaultOverride = null;
}

// Reset FxaMailer mocks
Expand Down Expand Up @@ -119,11 +97,19 @@ describe('/linked_account', () => {
mockFxaMailer: any,
mockRequest: any,
route: any,
axiosMock: any,
statsd: any;
let originalFetch: typeof global.fetch;

const UID = 'fxauid';

beforeEach(() => {
originalFetch = global.fetch;
});

afterEach(() => {
global.fetch = originalFetch;
});

describe('/linked_account/login', () => {
describe('google auth', () => {
const mockGoogleUser = {
Expand Down Expand Up @@ -163,12 +149,10 @@ describe('/linked_account', () => {
}
};

const mockGoogleAuthResponse = {
data: { id_token: 'somedata' },
};
axiosMock = {
post: jest.fn(() => mockGoogleAuthResponse),
};
global.fetch = jest.fn().mockResolvedValue({
ok: true,
json: async () => ({ id_token: 'somedata' }),
} as unknown as Response);

route = getRoute(
makeRoutes(
Expand All @@ -183,7 +167,6 @@ describe('/linked_account', () => {
'google-auth-library': {
OAuth2Client: OAuth2ClientMock,
},
axios: axiosMock,
}
),
'/linked_account/login'
Expand Down Expand Up @@ -221,8 +204,11 @@ describe('/linked_account', () => {
mockRequest.payload.code = 'oauth code';
const result: any = await runTest(route, mockRequest);

expect(axiosMock.post).toHaveBeenCalledTimes(1);
expect(axiosMock.post.mock.calls[0][1]).toEqual(
expect(global.fetch).toHaveBeenCalledTimes(1);
const requestBody = JSON.parse(
(global.fetch as jest.Mock).mock.calls[0][1].body
);
expect(requestBody).toEqual(
expect.objectContaining({ code: 'oauth code' })
);

Expand All @@ -243,6 +229,17 @@ describe('/linked_account', () => {
expect(result.sessionToken).toBeTruthy();
});

it('throws thirdPartyAccountError when the Google token endpoint responds non-ok', async () => {
global.fetch = jest
.fn()
.mockResolvedValue({ ok: false, status: 400 } as unknown as Response);
mockRequest.payload.code = 'oauth code';

await expect(runTest(route, mockRequest)).rejects.toMatchObject({
errno: error.ERRNO.THIRD_PARTY_ACCOUNT_ERROR,
});
});

it('should create new fxa account from new google account, return session, emit Glean events', async () => {
mockDB.accountRecord = jest.fn(() =>
Promise.reject(error.unknownAccount(mockGoogleUser.email))
Expand Down Expand Up @@ -447,30 +444,23 @@ describe('/linked_account', () => {
},
});

const mockAppleAuthResponse = {
data: {
global.fetch = jest.fn().mockResolvedValue({
ok: true,
json: async () => ({
id_token:
'eyJhbGciOiJFUzI1NiIsInR5cCI6IkpXVCIsImtpZCI6IkFCQzEyM0RFRkcifQ.eyJpc3MiOiJERUYxMjNHSElKIiwic3ViIjoiT29vT29vIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWUsImlhdCI6MTUxNjIzOTAyMiwiZXhwIjoxNTcyMzU4MDg2LCJhdWQiOiJodHRwczovL2FwcGxlaWQuYXBwbGUuY29tIiwiZW1haWwiOiJibG9vcEBtb3ppbGxhLmNvbSIsInRlYW1JZCI6Ik15IGNvb2wgdGVhbSB5byJ9.owz0xkgzDr9rLwXhd3TWV2QSRfH2YSnLt7LkS_TS42oGq_cbp1pyqhBtOBNTyvpZT6YKlxAxdmDkAr9x_KI7-A',
email: 'bloop@mozilla.com',
user: 'OooOoo',
},
};
axiosMock = {
post: jest.fn(() => mockAppleAuthResponse),
};
}),
} as unknown as Response);

route = getRoute(
makeRoutes(
{
config: mockConfig,
db: mockDB,
log: mockLog,
mailer: mockMailer,
},
{
axios: axiosMock,
}
),
makeRoutes({
config: mockConfig,
db: mockDB,
log: mockLog,
mailer: mockMailer,
}),
'/linked_account/login'
);
glean.registration.complete.mockClear();
Expand Down Expand Up @@ -506,9 +496,14 @@ describe('/linked_account', () => {
mockRequest.payload.code = 'oauth code';
const result: any = await runTest(route, mockRequest);

expect(axiosMock.post).toHaveBeenCalledTimes(1);
expect(global.fetch).toHaveBeenCalledTimes(1);
// The body is a pre-encoded form string, so the request must set this
// Content-Type explicitly — fetch won't infer it from a string body.
expect((global.fetch as jest.Mock).mock.calls[0][1].headers).toEqual({
'Content-Type': 'application/x-www-form-urlencoded',
});
const urlSearchParams = new URLSearchParams(
axiosMock.post.mock.calls[0][1]
(global.fetch as jest.Mock).mock.calls[0][1].body
);
const params = Object.fromEntries(urlSearchParams.entries());

Expand All @@ -531,6 +526,17 @@ describe('/linked_account', () => {
expect(result.sessionToken).toBeTruthy();
});

it('throws thirdPartyAccountError when the Apple token endpoint responds non-ok', async () => {
global.fetch = jest
.fn()
.mockResolvedValue({ ok: false, status: 400 } as unknown as Response);
mockRequest.payload.code = 'oauth code';

await expect(runTest(route, mockRequest)).rejects.toMatchObject({
errno: error.ERRNO.THIRD_PARTY_ACCOUNT_ERROR,
});
});

it('should create new fxa account from new apple account, return session, emit Glean events', async () => {
mockDB.accountRecord = jest.fn(() =>
Promise.reject(error.unknownAccount(mockAppleUser.email))
Expand Down
36 changes: 27 additions & 9 deletions packages/fxa-auth-server/lib/routes/linked-accounts.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@
import { AuthLogger, AuthRequest } from '../types';
import { ConfigType } from '../../config';
import { OAuth2Client } from 'google-auth-library';
import axios from 'axios';
import * as uuid from 'uuid';
import * as random from '../crypto/random';
import * as jose from 'jose';
Expand Down Expand Up @@ -279,16 +278,26 @@ export class LinkedAccountHandler {
};

try {
const res = await axios.post(
const res = await fetch(
this.config.googleAuthConfig.tokenEndpoint,
data
{
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(data),

@toufali toufali Jun 10, 2026

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Keeping the request identical to what axios previously sent: turn the plain object into a JSON body with application/json header.

}
);
if (!res.ok) {
throw new Error(
`Google token endpoint responded with ${res.status}`
);
}
const tokenResponse = await res.json();
// We currently only use the `id_token` after completing the
// authorization code exchange. In the future we could store a
// refresh token to do other things like revoking sessions.
//
// See https://developers.google.com/identity/protocols/oauth2/openid-connect#exchangecode
rawIdToken = res.data['id_token'];
rawIdToken = tokenResponse['id_token'];

const verifiedToken = await this.googleAuthClient.verifyIdToken({
idToken: rawIdToken,
Expand Down Expand Up @@ -328,11 +337,20 @@ export class LinkedAccountHandler {
};

try {
const res = await axios.post(
this.config.appleAuthConfig.tokenEndpoint,
new URLSearchParams(data).toString()
);
rawIdToken = res.data['id_token'];
const res = await fetch(this.config.appleAuthConfig.tokenEndpoint, {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',

@toufali toufali Jun 10, 2026

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Keeping the request identical to what axios previously sent for Apple: form-encoded instead of JSON (application/x-www-form-urlencoded).

Note: this header added to the call is mandatory - fetch won't add automatically. Test added so we can catch it if it ever gets dropped.

},
body: new URLSearchParams(data).toString(),
});
if (!res.ok) {
throw new Error(
`Apple token endpoint responded with ${res.status}`
);
}
const tokenResponse = await res.json();
rawIdToken = tokenResponse['id_token'];
idToken = jose.decodeJwt(rawIdToken);
} catch (err) {
this.log.error('linked_account.code_exchange_error', err);
Expand Down
118 changes: 118 additions & 0 deletions packages/fxa-auth-server/lib/routes/utils/third-party-events.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,118 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */

import jwt from 'jsonwebtoken';
import { getApplePublicKey, getGooglePublicKey } from './third-party-events';

jest.mock('jsonwebtoken', () => ({
decode: jest.fn(),
verify: jest.fn(),
}));

jest.mock('@fxa/shared/pem-jwk', () => ({
jwk2pem: jest.fn(() => 'fake-pem'),
}));

describe('third-party-events public key fetching', () => {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for adding!

let statsd: any;
let originalFetch: typeof global.fetch;

beforeEach(() => {
statsd = { increment: jest.fn() };
originalFetch = global.fetch;
});

afterEach(() => {
global.fetch = originalFetch;
});

describe('getApplePublicKey', () => {
it('returns the pem for the key matching the token kid', async () => {
(jwt.decode as jest.Mock).mockReturnValue({
header: { kid: 'apple-kid' },
});
global.fetch = jest.fn().mockResolvedValue({
ok: true,
json: async () => ({ keys: [{ kid: 'apple-kid', n: 'x', e: 'AQAB' }] }),
} as unknown as Response);

const result = await getApplePublicKey('token', statsd);

expect(result).toEqual({ pem: 'fake-pem' });
});

it('throws and increments statsd when the key endpoint responds non-ok', async () => {
global.fetch = jest
.fn()
.mockResolvedValue({ ok: false, status: 503 } as unknown as Response);

await expect(getApplePublicKey('token', statsd)).rejects.toThrow(
'Failed to get Apple public key'
);
expect(statsd.increment).toHaveBeenCalledWith('getApplePublicKey.error');
});
});

describe('getGooglePublicKey', () => {
it('returns the pem and issuer for the key matching the token kid', async () => {
(jwt.decode as jest.Mock).mockReturnValue({
header: { kid: 'google-kid' },
});
global.fetch = jest
.fn()
.mockResolvedValueOnce({
ok: true,
json: async () => ({
jwks_uri: 'https://example.com/jwks',
issuer: 'https://accounts.google.com',
}),
} as unknown as Response)
.mockResolvedValueOnce({
ok: true,
json: async () => ({
keys: [{ kid: 'google-kid', n: 'x', e: 'AQAB' }],
}),
} as unknown as Response);

const result = await getGooglePublicKey('token', statsd);

expect(result).toEqual({
pem: 'fake-pem',
issuer: 'https://accounts.google.com',
});
});

it('throws and increments statsd when the RISC config endpoint responds non-ok', async () => {
global.fetch = jest
.fn()
.mockResolvedValue({ ok: false, status: 500 } as unknown as Response);

await expect(getGooglePublicKey('token', statsd)).rejects.toThrow(
'Failed to get Google public key'
);
expect(statsd.increment).toHaveBeenCalledWith('getGooglePublicKey.error');
});

it('throws when the jwks endpoint responds non-ok', async () => {
global.fetch = jest
.fn()
.mockResolvedValueOnce({
ok: true,
json: async () => ({
jwks_uri: 'https://example.com/jwks',
issuer: 'https://accounts.google.com',
}),
} as unknown as Response)
.mockResolvedValueOnce({
ok: false,
status: 502,
} as unknown as Response);

await expect(getGooglePublicKey('token', statsd)).rejects.toThrow(
'Failed to get Google public key'
);
expect(statsd.increment).toHaveBeenCalledWith('getGooglePublicKey.error');
});
});
});
Loading