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
72 changes: 55 additions & 17 deletions src/libs/FraudProtection/index.ts
Original file line number Diff line number Diff line change
@@ -1,31 +1,69 @@
import {Str} from 'expensify-common';
import Onyx from 'react-native-onyx';
import type {OnyxEntry} from 'react-native-onyx';
import ONYXKEYS from '@src/ONYXKEYS';
import type {Account, Session} from '@src/types/onyx';
import {init, sendEvent, setAttribute, setAuthenticationData} from './GroupIBSdkBridge';

let sessionID: string;
let identity: string | undefined;
// We use `connectWithoutView` here since this connection only sends the new session data to the Fraud Protection backend, and doesn't need to trigger component re-renders.
let sessionID = Str.guid();
let lastSentIdentity: string | undefined;
let cachedAccount: OnyxEntry<Account>;
let cachedSession: OnyxEntry<Session>;

function sendAccountAttributes() {
setAttribute('email', cachedAccount?.primaryLogin ?? '', false, true);
setAttribute('mfa', cachedAccount?.requiresTwoFactorAuth ? '2fa_enabled' : '2fa_disabled', false, true);
setAttribute('is_validated', cachedAccount?.validated ? 'true' : 'false', false, true);
}

function trySendToFraudProtection() {
const isAuthenticated = !!(cachedSession?.authToken ?? null);
const identity = isAuthenticated ? (cachedSession?.accountID?.toString() ?? '') : '';

// Only send when the user is authenticated with a valid identity and we have account data.
if (!isAuthenticated || !identity || !cachedAccount?.primaryLogin) {
return;
}

// Always forward the latest account attributes, but only re-send identity when it changes.
if (identity === lastSentIdentity) {
sendAccountAttributes();
return;
Comment thread
cristipaval marked this conversation as resolved.
Resolved
}

lastSentIdentity = identity;

setAuthenticationData(identity, sessionID);
sendAccountAttributes();
}

// Cache account data and attempt to send.
Onyx.connectWithoutView({
key: ONYXKEYS.ACCOUNT,
callback: (account) => {
cachedAccount = account;
trySendToFraudProtection();
},
});

// Cache session data and attempt to send. On logout, generate a new sessionID for the next session.
Onyx.connectWithoutView({
key: ONYXKEYS.SESSION,
callback: (session) => {
const wasAuthenticated = !!(cachedSession?.authToken ?? null);
cachedSession = session;
const isAuthenticated = !!(session?.authToken ?? null);
const newIdentity = isAuthenticated ? (session?.accountID?.toString() ?? '') : '';
if (newIdentity !== identity) {
identity = newIdentity;
sessionID = typeof identity === 'string' && identity.length > 0 ? Str.guid() : '';
setAuthenticationData(identity, sessionID);

if (wasAuthenticated && !isAuthenticated) {
sessionID = Str.guid();
lastSentIdentity = undefined;
cachedAccount = undefined;
setAuthenticationData('', sessionID);
sendAccountAttributes();
return;
Comment thread
cristipaval marked this conversation as resolved.
Resolved
}
},
});

// We use `connectWithoutView` here since this connection only sends the new email and mfa data to the Fraud Protection backend, and doesn't need to trigger component re-renders.
Onyx.connectWithoutView({
key: ONYXKEYS.ACCOUNT,
callback: (account) => {
setAttribute('email', account?.primaryLogin ?? '', false, true);
setAttribute('mfa', account?.requiresTwoFactorAuth ? '2fa_enabled' : '2fa_disabled', false, true);
setAttribute('is_validated', account?.validated ? 'true' : 'false', false, true);
trySendToFraudProtection();
},
});

Expand Down
174 changes: 174 additions & 0 deletions tests/unit/FraudProtectionTest.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,174 @@
import Onyx from 'react-native-onyx';
import ONYXKEYS from '@src/ONYXKEYS';
import waitForBatchedUpdates from '../utils/waitForBatchedUpdates';

const mockSetAuthenticationData = jest.fn();
const mockSetAttribute = jest.fn();

jest.mock('@libs/FraudProtection/GroupIBSdkBridge', () => ({
init: jest.fn(),
sendEvent: jest.fn(),
setAttribute: mockSetAttribute,
setAuthenticationData: mockSetAuthenticationData,
}));

// Load the module once. Onyx connections are registered at module scope.
// eslint-disable-next-line @typescript-eslint/no-require-imports
require('@libs/FraudProtection');

beforeAll(() =>
Onyx.init({
keys: ONYXKEYS,
}),
);

beforeEach(async () => {
await Onyx.clear();
await waitForBatchedUpdates();

// Clear mocks AFTER Onyx.clear() finishes, because the clear triggers callbacks.
jest.clearAllMocks();
});

/** Returns the sessionID argument from the Nth call to setAuthenticationData. */
function getSessionIDFromCall(callIndex: number): string {
const call = mockSetAuthenticationData.mock.calls.at(callIndex) as unknown[];
return call.at(1) as string;
}

describe('FraudProtection', () => {
it('should not send auth data when only account data arrives without a session', async () => {
await Onyx.merge(ONYXKEYS.ACCOUNT, {primaryLogin: 'user@expensify.com', requiresTwoFactorAuth: false, validated: true});
await waitForBatchedUpdates();

expect(mockSetAuthenticationData).not.toHaveBeenCalled();
});

it('should not send auth data when session arrives without account data', async () => {
await Onyx.merge(ONYXKEYS.SESSION, {authToken: 'token123', accountID: 12345});
await waitForBatchedUpdates();

expect(mockSetAuthenticationData).not.toHaveBeenCalled();
});

it('should send auth data once both account and session are available', async () => {
await Onyx.merge(ONYXKEYS.ACCOUNT, {primaryLogin: 'user@expensify.com', requiresTwoFactorAuth: true, validated: true});
await Onyx.merge(ONYXKEYS.SESSION, {authToken: 'token123', accountID: 12345});
await waitForBatchedUpdates();

expect(mockSetAuthenticationData).toHaveBeenCalledTimes(1);
expect(mockSetAuthenticationData).toHaveBeenCalledWith('12345', expect.any(String));
expect(mockSetAttribute).toHaveBeenCalledWith('email', 'user@expensify.com', false, true);
expect(mockSetAttribute).toHaveBeenCalledWith('mfa', '2fa_enabled', false, true);
expect(mockSetAttribute).toHaveBeenCalledWith('is_validated', 'true', false, true);
});

it('should send auth data when session arrives after account (multi-step sign-in)', async () => {
// Step 1: BeginSignIn returns account data (no session yet)
await Onyx.merge(ONYXKEYS.ACCOUNT, {primaryLogin: 'user@expensify.com', requiresTwoFactorAuth: false, validated: true});
await waitForBatchedUpdates();

expect(mockSetAuthenticationData).not.toHaveBeenCalled();

// Step 2: Magic code verified, session is created
await Onyx.merge(ONYXKEYS.SESSION, {authToken: 'token123', accountID: 12345});
await waitForBatchedUpdates();

expect(mockSetAuthenticationData).toHaveBeenCalledTimes(1);
expect(mockSetAuthenticationData).toHaveBeenCalledWith('12345', expect.any(String));
});

it('should not re-send identity when session updates but identity has not changed, but should re-send attributes', async () => {
await Onyx.merge(ONYXKEYS.ACCOUNT, {primaryLogin: 'user@expensify.com', requiresTwoFactorAuth: false, validated: false});
await Onyx.merge(ONYXKEYS.SESSION, {authToken: 'token123', accountID: 12345});
await waitForBatchedUpdates();

expect(mockSetAuthenticationData).toHaveBeenCalledTimes(1);
jest.clearAllMocks();

// Session token refreshes but accountID stays the same
await Onyx.merge(ONYXKEYS.SESSION, {authToken: 'token456', accountID: 12345});
await waitForBatchedUpdates();

expect(mockSetAuthenticationData).not.toHaveBeenCalled();
expect(mockSetAttribute).toHaveBeenCalledWith('email', 'user@expensify.com', false, true);
});

it('should forward updated account attributes for the same identity', async () => {
await Onyx.merge(ONYXKEYS.ACCOUNT, {primaryLogin: 'user@expensify.com', requiresTwoFactorAuth: false, validated: false});
await Onyx.merge(ONYXKEYS.SESSION, {authToken: 'token123', accountID: 12345});
await waitForBatchedUpdates();
jest.clearAllMocks();

// User enables 2FA while already logged in
await Onyx.merge(ONYXKEYS.ACCOUNT, {requiresTwoFactorAuth: true});
await waitForBatchedUpdates();

expect(mockSetAuthenticationData).not.toHaveBeenCalled();
expect(mockSetAttribute).toHaveBeenCalledWith('mfa', '2fa_enabled', false, true);
});

it('should send new session with empty identity on logout', async () => {
// Login
await Onyx.merge(ONYXKEYS.ACCOUNT, {primaryLogin: 'user@expensify.com', requiresTwoFactorAuth: false, validated: true});
await Onyx.merge(ONYXKEYS.SESSION, {authToken: 'token123', accountID: 12345});
await waitForBatchedUpdates();

const firstSessionID = getSessionIDFromCall(0);
jest.clearAllMocks();

// Logout: clear the session (Onyx.merge strips undefined, so use set with null)
await Onyx.set(ONYXKEYS.SESSION, null);
await waitForBatchedUpdates();

expect(mockSetAuthenticationData).toHaveBeenCalledTimes(1);
expect(mockSetAuthenticationData).toHaveBeenCalledWith('', expect.any(String));

// The new sessionID should differ from the one used during auth
const logoutSessionID = getSessionIDFromCall(0);
expect(logoutSessionID).not.toBe(firstSessionID);

// Previous user's attributes should be cleared on logout
expect(mockSetAttribute).toHaveBeenCalledWith('email', '', false, true);
expect(mockSetAttribute).toHaveBeenCalledWith('mfa', '2fa_disabled', false, true);
expect(mockSetAttribute).toHaveBeenCalledWith('is_validated', 'false', false, true);
});

it('should use a new sessionID after logout and re-login', async () => {
// First login
await Onyx.merge(ONYXKEYS.ACCOUNT, {primaryLogin: 'user@expensify.com', requiresTwoFactorAuth: false, validated: true});
await Onyx.merge(ONYXKEYS.SESSION, {authToken: 'token123', accountID: 12345});
await waitForBatchedUpdates();

const firstSessionID = getSessionIDFromCall(0);

// Logout
await Onyx.set(ONYXKEYS.SESSION, null);
await waitForBatchedUpdates();
jest.clearAllMocks();

// Second login with a different account
await Onyx.merge(ONYXKEYS.ACCOUNT, {primaryLogin: 'other@expensify.com', requiresTwoFactorAuth: true, validated: false});
await Onyx.merge(ONYXKEYS.SESSION, {authToken: 'token999', accountID: 67890});
await waitForBatchedUpdates();

expect(mockSetAuthenticationData).toHaveBeenCalledTimes(1);
expect(mockSetAuthenticationData).toHaveBeenCalledWith('67890', expect.any(String));
expect(mockSetAttribute).toHaveBeenCalledWith('email', 'other@expensify.com', false, true);
expect(mockSetAttribute).toHaveBeenCalledWith('mfa', '2fa_enabled', false, true);
expect(mockSetAttribute).toHaveBeenCalledWith('is_validated', 'false', false, true);

// Should use a different sessionID than the first login
const secondSessionID = getSessionIDFromCall(0);
expect(secondSessionID).not.toBe(firstSessionID);
});

it('should set 2FA attribute correctly based on account data', async () => {
// Without 2FA
await Onyx.merge(ONYXKEYS.ACCOUNT, {primaryLogin: 'user@expensify.com', requiresTwoFactorAuth: false, validated: true});
await Onyx.merge(ONYXKEYS.SESSION, {authToken: 'token123', accountID: 11111});
await waitForBatchedUpdates();

expect(mockSetAttribute).toHaveBeenCalledWith('mfa', '2fa_disabled', false, true);
});
});
Loading