Skip to content
Open
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
11 changes: 10 additions & 1 deletion packages/fxa-auth-server/lib/account-events.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,12 @@ type EmailEvent = BaseEvent & {
template: string;
};

export type SecurityEventLoginMethod =
| 'password'
| 'passwordless.otp'
| 'passwordless.thirdParty'
| 'passkey';

interface SecurityEventAdditionalInfo {
userAgent?: string;
location?: {
Expand All @@ -39,6 +45,9 @@ interface SecurityEventAdditionalInfo {
};
client_id?: string;
service?: string;
// How the user authenticated. Rows written before this field existed have no
// method; read those as unknown, not as a password login.
method?: SecurityEventLoginMethod;
waf?: {
clientJa4?: string;
clientJa3?: string;
Expand Down Expand Up @@ -138,7 +147,7 @@ export class AccountEventsManager {

await this.usersDbRef?.doc(uid).collection('events').add(emailEvent);
this.statsd.increment('accountEvents.recordEmailEvent.write', {
template: message.template
template: message.template,
});
} catch (err) {
// Failing to write to events shouldn't break anything
Expand Down
30 changes: 30 additions & 0 deletions packages/fxa-auth-server/lib/routes/linked-accounts.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,8 +48,13 @@ jest.mock('fxa-shared/db/models/auth', () => ({
},
}));

jest.mock('./utils/security-event', () => ({
recordSecurityEvent: jest.fn(),
}));

const mocks = require('../../test/mocks');
const { getRoute } = require('../../test/routes_helpers');
const { recordSecurityEvent } = require('./utils/security-event');
const { AppError: error } = require('@fxa/accounts/errors');

// Install a typed mock FxaMailer in the Container before loading linked-accounts
Expand Down Expand Up @@ -243,6 +248,31 @@ describe('/linked_account', () => {
expect(result.sessionToken).toBeTruthy();
});

it('records an account.login security event tagged as third party', async () => {
// The stored proc derives `verified` from the token id, so the new
// session token id has to reach the event. Without it a TOTP-gated
// sign-in is recorded as a verified login.
const SESSION_TOKEN_ID = 'sessiontokenid';
mockDB.createSessionToken = jest.fn(() =>
Promise.resolve({
id: SESSION_TOKEN_ID,
uid: UID,
data: 'sessiontoken123',
})
);

await runTest(route, mockRequest);

expect(recordSecurityEvent).toHaveBeenCalledWith(
'account.login',
expect.objectContaining({
account: { uid: UID },
tokenId: SESSION_TOKEN_ID,
method: 'passwordless.thirdParty',
})
);
});

it('does not create a new account when the domain is blocklisted', async () => {
const { DomainBlocklist } = require('fxa-shared/db/models/auth');
mockDB.accountRecord = jest.fn(() =>
Expand Down
9 changes: 9 additions & 0 deletions packages/fxa-auth-server/lib/routes/linked-accounts.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ import {
notifyAttachedServicesForAccountSession,
} from './utils/account';
import { normalizeEmail } from 'fxa-shared/email/helpers';
import { recordSecurityEvent } from './utils/security-event';
import {
getGooglePublicKey,
getApplePublicKey,
Expand Down Expand Up @@ -630,6 +631,14 @@ export class LinkedAccountHandler {

const sessionToken = await this.db.createSessionToken(sessionTokenOptions);

await recordSecurityEvent('account.login', {
db: this.db,
request,
account: { uid: accountRecord.uid },
tokenId: sessionToken.id,
method: 'passwordless.thirdParty',
});
Comment on lines +634 to +640

// Mirror the SNS notifications that AccountHandler.createAccount
// fires. Placed after createSessionToken so db.sessions already
// includes the new session. A new third-party link on an existing
Expand Down
5 changes: 4 additions & 1 deletion packages/fxa-auth-server/lib/routes/passkeys.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1628,7 +1628,10 @@ describe('passkeys routes', () => {

expect(recordSecurityEvent).toHaveBeenCalledWith(
'account.login',
expect.objectContaining({ account: { uid: UID } })
expect.objectContaining({
account: { uid: UID },
method: 'passkey',
})
);
});

Expand Down
1 change: 1 addition & 0 deletions packages/fxa-auth-server/lib/routes/passkeys.ts
Original file line number Diff line number Diff line change
Expand Up @@ -594,6 +594,7 @@ export class PasskeyHandler {
db: this.db,
request,
account: { uid: account.uid },
method: 'passkey',
});
}
} catch (err) {
Expand Down
62 changes: 59 additions & 3 deletions packages/fxa-auth-server/lib/routes/passwordless.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1300,10 +1300,10 @@ describe('passwordless security events', () => {
route = getRoute(routes, '/account/passwordless/confirm_code', 'POST');

return runTest(route, mockRequest, () => {
// Should record three events: account.create (so the generic
// Should record four events: account.create (so the generic
// account-creation metric fires for OTP signups too), then
// registration_complete and otp_verified.
expect(mockRecordSecurityEvent).toHaveBeenCalledTimes(3);
// registration_complete, otp_verified and account.login.
expect(mockRecordSecurityEvent).toHaveBeenCalledTimes(4);
expect(mockRecordSecurityEvent).toHaveBeenNthCalledWith(
1,
'account.create',
Expand All @@ -1319,6 +1319,61 @@ describe('passwordless security events', () => {
'account.passwordless_login_otp_verified',
expect.objectContaining({ account: { uid } })
);
expect(mockRecordSecurityEvent).toHaveBeenNthCalledWith(
4,
'account.login',
expect.objectContaining({
account: { uid },
method: 'passwordless.otp',
})
);
});
});

it('should pass the new session token id on the account.login event', () => {
// The stored proc derives `verified` from the token id, so the new session
// token id has to reach the event. Without it a TOTP-gated sign-in is
// recorded as a verified login.
const SESSION_TOKEN_ID = 'sessiontokenid';
mockDB.createSessionToken = jest.fn(() =>
Promise.resolve({
id: SESSION_TOKEN_ID,
data: 'sessiontoken123',
emailVerified: true,
tokenVerified: false,
lastAuthAt: () => 1234567890,
})
);

mockRequest.payload.code = '123456';

routes = makeRoutes({
log: mockLog,
db: mockDB,
customs: mockCustoms,
recordSecurityEvent: mockRecordSecurityEvent,
config: {
passwordlessOtp: {
enabled: true,
ttl: 300,
digits: 6,
allowedClientServices: {
'test-client-id': { allowedServices: ['*'] },
},
},
},
});
route = getRoute(routes, '/account/passwordless/confirm_code', 'POST');

return runTest(route, mockRequest, () => {
expect(mockRecordSecurityEvent).toHaveBeenCalledWith(
'account.login',
expect.objectContaining({
account: { uid },
tokenId: SESSION_TOKEN_ID,
method: 'passwordless.otp',
})
);
});
});

Expand Down Expand Up @@ -1362,6 +1417,7 @@ describe('passwordless security events', () => {
expect(recordedEvents).not.toContain('account.create');
expect(recordedEvents).toEqual([
'account.passwordless_login_otp_verified',
'account.login',
]);
});
});
Expand Down
12 changes: 9 additions & 3 deletions packages/fxa-auth-server/lib/routes/passwordless.ts
Original file line number Diff line number Diff line change
Expand Up @@ -213,9 +213,7 @@ class PasswordlessHandler {
await this.customs.check(
request,
email,
isNewAccount
? PASSWORDLESS_SEND_OTP_SIGNUP
: PASSWORDLESS_SEND_OTP_SIGNIN
isNewAccount ? PASSWORDLESS_SEND_OTP_SIGNUP : PASSWORDLESS_SEND_OTP_SIGNIN
);
}

Expand Down Expand Up @@ -348,6 +346,14 @@ class PasswordlessHandler {
account: { uid: account.uid },
});

await recordSecurityEvent('account.login', {
db: this.db,
request,
account: { uid: account.uid },
tokenId: sessionToken.id,
method: 'passwordless.otp',
});
Comment on lines +349 to +355

// Mirror the SNS notifications that AccountHandler.createAccount
// fires, since passwordless bypasses that path. This runs after
// createSessionToken so db.sessions already includes the new session.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -364,4 +364,21 @@ describe('recordSecurityEvent', () => {
sigsciTags: 'TRAVERSAL',
});
});

it('includes the method in additionalInfo when given', async () => {
await recordSecurityEvent('account.login', {
...makeOpts(),
method: 'passkey',
});

const [, message] = mockMgrRecordSecurityEvent.mock.calls[0];
expect(message.additionalInfo.method).toBe('passkey');
});

it('omits the method from additionalInfo when not given', async () => {
await recordSecurityEvent('account.login', makeOpts());

const [, message] = mockMgrRecordSecurityEvent.mock.calls[0];
expect(message.additionalInfo).not.toHaveProperty('method');
});
});
22 changes: 19 additions & 3 deletions packages/fxa-auth-server/lib/routes/utils/security-event.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,25 @@
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */

import { SecurityEventNames } from 'fxa-shared/db/models/auth/security-event';
import { AccountEventsManager } from '../../account-events';
import {
AccountEventsManager,
SecurityEventLoginMethod,
} from '../../account-events';
import { Container } from 'typedi';

export async function recordSecurityEvent(name: SecurityEventNames, opts: any) {
type RecordSecurityEventOpts = {
method?: SecurityEventLoginMethod;
// Routes that create a session while unauthenticated must pass the new
// session token id. Without it the stored proc cannot find the pending
// tokenVerificationId and marks the row verified.
tokenId?: string;
[key: string]: any;
};

export async function recordSecurityEvent(
name: SecurityEventNames,
opts: RecordSecurityEventOpts
) {
const mgr = Container.get(AccountEventsManager);
if (mgr == null || typeof mgr.recordSecurityEvent !== 'function') {
return;
Expand All @@ -28,12 +43,13 @@ export async function recordSecurityEvent(name: SecurityEventNames, opts: any) {
name,
uid: opts?.account?.uid || opts?.request?.auth?.credentials?.uid,
ipAddr: opts?.request?.app?.clientAddress,
tokenId: opts?.request?.auth?.credentials?.id,
tokenId: opts?.tokenId ?? opts?.request?.auth?.credentials?.id,
additionalInfo: {
userAgent: opts?.request.headers['user-agent'],
location: opts?.request.app.geo.location,
...(clientId && { client_id: clientId }),
...(service && { service }),
...(opts?.method && { method: opts.method }),
waf: Object.values(waf).some(Boolean) ? waf : undefined,
},
});
Expand Down
1 change: 1 addition & 0 deletions packages/fxa-auth-server/lib/routes/utils/signin.js
Original file line number Diff line number Diff line change
Expand Up @@ -682,6 +682,7 @@ module.exports = (
location: request.app.geo.location,
...(clientId && { client_id: clientId }),
...(service && { service }),
method: 'password',
},
});
}
Expand Down
1 change: 1 addition & 0 deletions packages/fxa-auth-server/lib/routes/utils/signin.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -836,6 +836,7 @@ describe('sendSigninNotifications', () => {
state: 'California',
stateCode: 'CA',
},
method: 'password',
},
});
});
Expand Down