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
174 changes: 129 additions & 45 deletions src/libs/ExportOnyxState/common.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,14 +49,12 @@ const ONYX_KEY_EXPORT_RULES: Record<string, ExportRule> = {
'statusNum',
'isOwnPolicyExpenseChat',
'participantAccountIDs',
'total',
'currency',
'created',
],
maskList: ['reportName', 'description', 'ownerAccountID', 'managerID'],
},
[ONYXKEYS.COLLECTION.TRANSACTION]: {
allowList: ['transactionID', 'reportID', 'amount', 'currency', 'created', 'category', 'tag', 'billable'],
allowList: ['transactionID', 'reportID', 'created', 'category', 'tag', 'billable'],
Comment thread
MarioExpensify marked this conversation as resolved.
Resolved
maskList: ['merchant', 'description', 'comment'],
},
[ONYXKEYS.COLLECTION.POLICY]: {
Expand Down Expand Up @@ -97,6 +95,7 @@ const keysToMask = [
'bank',
'cardName',
'cardNumber',
'childReportName',
'city',
'comment',
'description',
Expand Down Expand Up @@ -125,14 +124,17 @@ const keysToMask = [
'source',
'state',
'street',
'title',
'validateCode',
'zip',
'zipCode',
];

const emailRegex = /[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/;
const amountKeysToRandomize = ['amount', 'modifiedAmount', 'originalAmount', 'total', 'unheldTotal', 'unheldNonReimbursableTotal', 'nonReimbursableTotal'];
Comment thread
MarioExpensify marked this conversation as resolved.
Resolved

const nodesToFullyMask = ['reservationList'];

const emailMap = new Map<string, string>();
const emailRegex = /[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/;

const getRandomLetter = () => String.fromCharCode(97 + Math.floor(Math.random() * 26));

Expand All @@ -152,6 +154,14 @@ function maskValuePreservingLength(value: unknown) {
return getRandomString(value.length);
}

function randomizeAmount(amount: number): number {
if (!Number.isFinite(amount)) {
return 0;
}
Comment thread
MarioExpensify marked this conversation as resolved.
Resolved
const randomizedValue = Math.floor(Math.random() * 999999) + 1;
Comment thread
MarioExpensify marked this conversation as resolved.
Resolved
Comment thread
MarioExpensify marked this conversation as resolved.
Resolved
return amount < 0 ? -randomizedValue : randomizedValue;
}

function stringContainsEmail(text: string) {
return emailRegex.test(text);
}
Expand All @@ -176,6 +186,22 @@ function replaceEmailInString(text: string, emailReplacement: string) {
return text.replace(emailRegex, emailReplacement);
}

const isDateValue = (value: unknown): boolean => {
if (typeof value !== 'string') {
return false;
}

const datePatterns = [
/^\d{4}-\d{2}-\d{2}/, // ISO date
Comment thread
MarioExpensify marked this conversation as resolved.
Resolved
/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}/, // ISO datetime
];
return datePatterns.some((pattern) => pattern.test(value));
};

const getCurrentDate = (): string => {
return new Date().toISOString();
};

const processOnyxKeyWithRule = (key: string, data: unknown, rule: ExportRule): unknown => {
if (data === null || data === undefined) {
return data;
Expand All @@ -195,7 +221,17 @@ const processOnyxKeyWithRule = (key: string, data: unknown, rule: ExportRule): u
processedData[fieldKey] = maskValuePreservingLength(fieldValue);
} else if (rule.allowList.includes(fieldKey)) {
processedData[fieldKey] = fieldValue;
} else if (typeof fieldValue === 'object' && fieldValue !== null) {
Comment thread
MarioExpensify marked this conversation as resolved.
Resolved
// If it's an object and not in allowList/maskList, recursively process it
processedData[fieldKey] = processOnyxKeyWithRule(key, fieldValue, rule);
} else if (typeof fieldValue === 'number') {
processedData[fieldKey] = randomizeAmount(fieldValue);
} else if (typeof fieldValue === 'string' && isDateValue(fieldValue)) {
processedData[fieldKey] = getCurrentDate();
} else if (typeof fieldValue === 'string') {
processedData[fieldKey] = maskValuePreservingLength(fieldValue);
} else {
// Default: redact to '***' for anything else
processedData[fieldKey] = MASKING_PATTERN;
}
});
Expand All @@ -206,7 +242,7 @@ const processOnyxKeyWithRule = (key: string, data: unknown, rule: ExportRule): u
return data;
};

const maskEmail = (email: string) => {
const maskEmail = (email: string, emailMap: Map<string, string>) => {
let maskedEmail = '';
if (!emailMap.has(email)) {
maskedEmail = randomizeEmail(email);
Expand All @@ -218,53 +254,82 @@ const maskEmail = (email: string) => {
return maskedEmail;
};

const maskFragileData = (data: OnyxState | unknown[] | null, parentKey?: string): OnyxState | unknown[] | null => {
const maskFragileData = (data: OnyxState | unknown[] | null, emailMap: Map<string, string>, parentKey?: string): OnyxState | unknown[] | null => {
if (data === null) {
return data;
}

if (Array.isArray(data)) {
return data.map((item): unknown => {
if (typeof item === 'string' && Str.isValidEmail(item)) {
return maskEmail(item);
return maskEmail(item, emailMap);
}
return typeof item === 'object' ? maskFragileData(item as OnyxState, parentKey) : item;
return typeof item === 'object' ? maskFragileData(item as OnyxState, emailMap, parentKey) : item;
});
}

const maskedData: OnyxState = {};

Object.keys(data).forEach((key) => {
if (!Object.prototype.hasOwnProperty.call(data, key)) {
Object.keys(data).forEach((sourceKey) => {
if (!Object.prototype.hasOwnProperty.call(data, sourceKey)) {
return;
}

// loginList is an object that contains emails as keys, the keys should be masked as well
let propertyName = '';
if (Str.isValidEmail(key)) {
propertyName = maskEmail(key);
} else {
propertyName = key;
}
// Read value from source using the original key
const value = (data as Record<string, unknown>)[sourceKey];

// Determine the destination key - mask it if it's an email
// (e.g., in loginList where email addresses are used as object keys)
const destinationKey = Str.isValidEmail(sourceKey) ? maskEmail(sourceKey, emailMap) : sourceKey;

const value = data[propertyName];
// Skip values that are already masked as MASKING_PATTERN
if (value === MASKING_PATTERN) {
maskedData[destinationKey] = value;
return;
}

if (keysToMask.includes(key)) {
// Handle collection nodes (reportActions, reports, transactions)
Comment thread
MarioExpensify marked this conversation as resolved.
Resolved
if (sourceKey.startsWith(ONYXKEYS.COLLECTION.REPORT_ACTIONS) && typeof value === 'object') {
maskedData[destinationKey] = maskFragileData(value as OnyxState, emailMap, sourceKey);
} else if (sourceKey.startsWith(ONYXKEYS.COLLECTION.REPORT) && typeof value === 'object') {
maskedData[destinationKey] = maskFragileData(value as OnyxState, emailMap, sourceKey);
} else if (sourceKey.startsWith(ONYXKEYS.COLLECTION.TRANSACTION) && typeof value === 'object') {
maskedData[destinationKey] = maskFragileData(value as OnyxState, emailMap, sourceKey);
} else if (amountKeysToRandomize.includes(sourceKey) && typeof value === 'number') {
maskedData[destinationKey] = randomizeAmount(value);
// Handle expensify_text_title masking
} else if (parentKey === 'expensify_text_title' && sourceKey === 'value' && typeof value === 'string') {
maskedData[destinationKey] = maskValuePreservingLength(value);
} else if (sourceKey === 'expensify_text_title' && typeof value === 'object') {
maskedData[destinationKey] = maskFragileData(value as OnyxState, emailMap, 'expensify_text_title');
// Handle nodes that need full masking
} else if (nodesToFullyMask.includes(sourceKey) && typeof value === 'object') {
maskedData[destinationKey] = maskFragileData(value as OnyxState, emailMap, sourceKey);
} else if (parentKey && nodesToFullyMask.includes(parentKey) && typeof value === 'string' && isDateValue(value)) {
maskedData[destinationKey] = getCurrentDate();
} else if (parentKey && nodesToFullyMask.includes(parentKey) && typeof value === 'string') {
maskedData[destinationKey] = maskValuePreservingLength(value);
} else if (parentKey && nodesToFullyMask.includes(parentKey) && typeof value === 'object') {
maskedData[destinationKey] = maskFragileData(value as OnyxState, emailMap, parentKey);
} else if (keysToMask.includes(sourceKey)) {
if (Array.isArray(value)) {
maskedData[key] = value.map(() => MASKING_PATTERN);
maskedData[destinationKey] = value.map(() => MASKING_PATTERN);
} else if (typeof value === 'object') {
// If the value is an object, don't mask it as a string - recursively process it
maskedData[destinationKey] = maskFragileData(value as OnyxState, emailMap, sourceKey);
} else {
maskedData[key] = maskValuePreservingLength(value);
maskedData[destinationKey] = maskValuePreservingLength(value);
}
} else if (typeof value === 'string' && Str.isValidEmail(value)) {
maskedData[propertyName] = maskEmail(value);
maskedData[destinationKey] = maskEmail(value, emailMap);
} else if (typeof value === 'string' && stringContainsEmail(value)) {
maskedData[propertyName] = replaceEmailInString(value, maskEmail(extractEmail(value) ?? ''));
} else if (parentKey && parentKey.includes(ONYXKEYS.COLLECTION.REPORT_ACTIONS) && (propertyName === 'text' || propertyName === 'html')) {
maskedData[key] = MASKING_PATTERN;
maskedData[destinationKey] = replaceEmailInString(value, maskEmail(extractEmail(value) ?? '', emailMap));
} else if (parentKey && parentKey.includes(ONYXKEYS.COLLECTION.REPORT_ACTIONS) && (destinationKey === 'text' || destinationKey === 'html')) {
maskedData[destinationKey] = MASKING_PATTERN;
} else if (typeof value === 'object') {
maskedData[propertyName] = maskFragileData(value as OnyxState, propertyName.includes(ONYXKEYS.COLLECTION.REPORT_ACTIONS) ? propertyName : parentKey);
maskedData[destinationKey] = maskFragileData(value as OnyxState, emailMap, destinationKey.includes(ONYXKEYS.COLLECTION.REPORT_ACTIONS) ? destinationKey : parentKey);
} else {
maskedData[propertyName] = value;
maskedData[destinationKey] = value;
}
});

Expand All @@ -285,30 +350,49 @@ const removePrivateOnyxKeys = (onyxState: OnyxState): OnyxState => {
};

const maskOnyxState: MaskOnyxState = (data, isMaskingFragileDataEnabled) => {
let onyxState = {...data};
const emailMap = new Map<string, string>();

onyxState = removePrivateOnyxKeys(onyxState);
try {
let onyxState = {...data};

Object.keys(onyxState).forEach((key) => {
let ruleKey = key;
const collectionKey = Object.values(ONYXKEYS.COLLECTION).find((cKey) => key.startsWith(cKey));
if (collectionKey) {
ruleKey = collectionKey;
}
onyxState = removePrivateOnyxKeys(onyxState);

const keysWithRules = new Set<string>();

const rule = ONYX_KEY_EXPORT_RULES[ruleKey];
Object.keys(onyxState).forEach((key) => {
let ruleKey = key;
const collectionKey = Object.values(ONYXKEYS.COLLECTION).find((cKey) => key.startsWith(cKey));
if (collectionKey) {
ruleKey = collectionKey;
}

const rule = ONYX_KEY_EXPORT_RULES[ruleKey];

if (rule) {
onyxState[key] = processOnyxKeyWithRule(key, onyxState[key], rule);
if (rule) {
onyxState[key] = processOnyxKeyWithRule(key, onyxState[key], rule);
keysWithRules.add(key);
}
});

if (isMaskingFragileDataEnabled) {
// Only apply maskFragileData to keys that don't have export rules
const maskedState: OnyxState = {};
Object.keys(onyxState).forEach((key) => {
if (keysWithRules.has(key)) {
maskedState[key] = onyxState[key];
} else {
const masked = maskFragileData({[key]: onyxState[key]}, emailMap) as OnyxState;
maskedState[key] = masked[key];
}
});
onyxState = maskedState;
}
});

if (isMaskingFragileDataEnabled) {
onyxState = maskFragileData(onyxState) as OnyxState;
return onyxState;
} finally {
// Always clear the email map, even if an error occurred
emailMap.clear();
}

emailMap.clear();
return onyxState;
};

export {maskOnyxState, emailRegex};
39 changes: 25 additions & 14 deletions tests/unit/ExportOnyxStateTest.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,9 +28,11 @@ describe('maskOnyxState', () => {
expect(result.session.loading).toBe(false);
expect(result.session.creationDate).toBe('2024-01-01');

// Non-whitelisted fields should be redacted
expect(result.session.authToken).toBe('***');
expect(result.session.encryptedAuthToken).toBe('***');
// Non-whitelisted fields should be intelligently redacted
expect(result.session.authToken).not.toBe('sensitive-auth-token');
Comment thread
MarioExpensify marked this conversation as resolved.
Resolved
expect(result.session.authToken).toHaveLength('sensitive-auth-token'.length);
expect(result.session.encryptedAuthToken).not.toBe('sensitive-encrypted-token');
expect(result.session.encryptedAuthToken).toHaveLength('sensitive-encrypted-token'.length);
});

it('should mask fields in maskList while preserving structure', () => {
Expand Down Expand Up @@ -72,9 +74,11 @@ describe('maskOnyxState', () => {
expect(result.session.email).toBe('user@example.com');
expect(result.session.accountID).toBe(12345);

// Non-whitelisted fields should be redacted
expect(result.session.customField).toBe('***');
expect(result.session.anotherField).toBe('***');
// Non-whitelisted fields should be intelligently redacted
expect(result.session.customField).not.toBe('should-be-redacted');
expect(result.session.customField).toHaveLength('should-be-redacted'.length);
expect(result.session.anotherField).not.toBe('also-redacted');
expect(result.session.anotherField).toHaveLength('also-redacted'.length);
});

it('should handle collection keys correctly', () => {
Expand Down Expand Up @@ -109,8 +113,9 @@ describe('maskOnyxState', () => {
expect(processedReport.reportName).toHaveLength('Test Report'.length);
expect(processedReport.description).not.toBe('Test Description');

// Non-whitelisted, non-masked fields should be redacted
expect(processedReport.customField).toBe('***');
// Non-whitelisted, non-masked fields should be intelligently redacted
expect(processedReport.customField).not.toBe('should-be-redacted');
expect(processedReport.customField).toHaveLength('should-be-redacted'.length);
});

it('should remove sensitive keys from export', () => {
Expand Down Expand Up @@ -155,8 +160,10 @@ describe('maskOnyxState', () => {
const input = {session: mockSession};
const result = maskOnyxState(input) as ExampleOnyxState;

expect(result.session.authToken).toBe('***');
expect(result.session.encryptedAuthToken).toBe('***');
expect(result.session.authToken).not.toBe('sensitive-auth-token');
expect(result.session.authToken).toHaveLength('sensitive-auth-token'.length);
expect(result.session.encryptedAuthToken).not.toBe('sensitive-encrypted-token');
expect(result.session.encryptedAuthToken).toHaveLength('sensitive-encrypted-token'.length);
});

it('should not mask fragile data when isMaskingFragileDataEnabled is false', () => {
Expand All @@ -165,8 +172,10 @@ describe('maskOnyxState', () => {
};
const result = maskOnyxState(input) as ExampleOnyxState;

expect(result.session.authToken).toBe('***');
expect(result.session.encryptedAuthToken).toBe('***');
expect(result.session.authToken).not.toBe('sensitive-auth-token');
expect(result.session.authToken).toHaveLength('sensitive-auth-token'.length);
expect(result.session.encryptedAuthToken).not.toBe('sensitive-encrypted-token');
expect(result.session.encryptedAuthToken).toHaveLength('sensitive-encrypted-token'.length);
expect(result.session.email).toBe('user@example.com');
});

Expand All @@ -176,8 +185,10 @@ describe('maskOnyxState', () => {
};
const result = maskOnyxState(input, true) as ExampleOnyxState;

expect(result.session.authToken).toBe('***');
expect(result.session.encryptedAuthToken).toBe('***');
expect(result.session.authToken).not.toBe('sensitive-auth-token');
expect(result.session.authToken).toHaveLength('sensitive-auth-token'.length);
expect(result.session.encryptedAuthToken).not.toBe('sensitive-encrypted-token');
expect(result.session.encryptedAuthToken).toHaveLength('sensitive-encrypted-token'.length);
});

it('should mask emails as a string value in property with a random email', () => {
Expand Down