Skip to content

[No QA] Send current policy ID to Sentry#73848

Closed
sosek108 wants to merge 7 commits intoExpensify:mainfrom
callstack-internal:feat/sentry-policyid
Closed

[No QA] Send current policy ID to Sentry#73848
sosek108 wants to merge 7 commits intoExpensify:mainfrom
callstack-internal:feat/sentry-policyid

Conversation

@sosek108
Copy link
Contributor

@sosek108 sosek108 commented Oct 30, 2025

Explanation of Change

Sent active policyId to Sentry.

This is follow up to another PR #73843.

Fixed Issues

$ #73324
PROPOSAL:

Tests

  1. Run application
  2. Perform some actions
  3. Go to Sentry dashboard and find traces associated with your account
  4. Set up filtering and check if you can filter by active_policy_id tag
  5. Go to details of any action and verify if there is policies context inside of Span and it consist proper policy ids

Offline tests

N/A

QA Steps

// TODO: These must be filled out, or the issue title must include "[No QA]."

N/A

PR Author Checklist

  • I linked the correct issue in the ### Fixed Issues section above
  • I wrote clear testing steps that cover the changes made in this PR
    • I added steps for local testing in the Tests section
    • I added steps for the expected offline behavior in the Offline steps section
    • I added steps for Staging and/or Production testing in the QA steps section
    • I added steps to cover failure scenarios (i.e. verify an input displays the correct error message if the entered data is not correct)
    • I turned off my network connection and tested it while offline to ensure it matches the expected behavior (i.e. verify the default avatar icon is displayed if app is offline)
    • I tested this PR with a High Traffic account against the staging or production API to ensure there are no regressions (e.g. long loading states that impact usability).
  • I included screenshots or videos for tests on all platforms
  • I ran the tests on all platforms & verified they passed on:
    • Android: Native
    • Android: mWeb Chrome
    • iOS: Native
    • iOS: mWeb Safari
    • MacOS: Chrome / Safari
    • MacOS: Desktop
  • I verified there are no console errors (if there's a console error not related to the PR, report it or open an issue for it to be fixed)
  • I verified there are no new alerts related to the canBeMissing param for useOnyx
  • I followed proper code patterns (see Reviewing the code)
    • I verified that any callback methods that were added or modified are named for what the method does and never what callback they handle (i.e. toggleReport and not onIconClick)
    • I verified that comments were added to code that is not self explanatory
    • I verified that any new or modified comments were clear, correct English, and explained "why" the code was doing something instead of only explaining "what" the code was doing.
    • I verified any copy / text shown in the product is localized by adding it to src/languages/* files and using the translation method
      • If any non-english text was added/modified, I used JaimeGPT to get English > Spanish translation. I then posted it in #expensify-open-source and it was approved by an internal Expensify engineer. Link to Slack message:
    • I verified all numbers, amounts, dates and phone numbers shown in the product are using the localization methods
    • I verified any copy / text that was added to the app is grammatically correct in English. It adheres to proper capitalization guidelines (note: only the first word of header/labels should be capitalized), and is either coming verbatim from figma or has been approved by marketing (in order to get marketing approval, ask the Bug Zero team member to add the Waiting for copy label to the issue)
    • I verified proper file naming conventions were followed for any new files or renamed files. All non-platform specific files are named after what they export and are not named "index.js". All platform-specific files are named for the platform the code supports as outlined in the README.
    • I verified the JSDocs style guidelines (in STYLE.md) were followed
  • If a new code pattern is added I verified it was agreed to be used by multiple Expensify engineers
  • I followed the guidelines as stated in the Review Guidelines
  • I tested other components that can be impacted by my changes (i.e. if the PR modifies a shared library or component like Avatar, I verified the components using Avatar are working as expected)
  • I verified all code is DRY (the PR doesn't include any logic written more than once, with the exception of tests)
  • I verified any variables that can be defined as constants (ie. in CONST.ts or at the top of the file that uses the constant) are defined as such
  • I verified that if a function's arguments changed that all usages have also been updated correctly
  • If any new file was added I verified that:
    • The file has a description of what it does and/or why is needed at the top of the file if the code is not self explanatory
  • If a new CSS style is added I verified that:
    • A similar style doesn't already exist
    • The style can't be created with an existing StyleUtils function (i.e. StyleUtils.getBackgroundAndBorderStyle(theme.componentBG))
  • If new assets were added or existing ones were modified, I verified that:
    • The assets are optimized and compressed (for SVG files, run npm run compress-svg)
    • The assets load correctly across all supported platforms.
  • If the PR modifies code that runs when editing or sending messages, I tested and verified there is no unexpected behavior for all supported markdown - URLs, single line code, code blocks, quotes, headings, bold, strikethrough, and italic.
  • If the PR modifies a generic component, I tested and verified that those changes do not break usages of that component in the rest of the App (i.e. if a shared library or component like Avatar is modified, I verified that Avatar is working as expected in all cases)
  • If the PR modifies a component related to any of the existing Storybook stories, I tested and verified all stories for that component are still working as expected.
  • If the PR modifies a component or page that can be accessed by a direct deeplink, I verified that the code functions as expected when the deeplink is used - from a logged in and logged out account.
  • If the PR modifies the UI (e.g. new buttons, new UI components, changing the padding/spacing/sizing, moving components, etc) or modifies the form input styles:
    • I verified that all the inputs inside a form are aligned with each other.
    • I added Design label and/or tagged @Expensify/design so the design team can review the changes.
  • If a new page is added, I verified it's using the ScrollView component to make it scrollable when more elements are added to the page.
  • I added unit tests for any new feature or bug fix in this PR to help automatically prevent regressions in this user flow.
  • If the main branch was merged into this PR after a review, I tested again and verified the outcome was still expected according to the Test steps.

Screenshots/Videos

Android: Native
Android: mWeb Chrome
iOS: Native
iOS: mWeb Safari
MacOS: Chrome / Safari
MacOS: Desktop

@codecov
Copy link

codecov bot commented Oct 31, 2025

Codecov Report

❌ Patch coverage is 75.00000% with 6 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
src/libs/TelemetrySynchronizer.ts 75.00% 6 Missing ⚠️
Files with missing lines Coverage Δ
src/CONST/index.ts 85.71% <ø> (ø)
src/libs/TelemetrySynchronizer.ts 75.86% <75.00%> (-4.14%) ⬇️

... and 8 files with indirect coverage changes

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@github-actions
Copy link
Contributor

🚧 @mountiny has triggered a test Expensify/App build. You can view the workflow run here.

@github-actions
Copy link
Contributor

🧪🧪 Use the links below to test this adhoc build on Android, iOS, Desktop, and Web. Happy testing! 🧪🧪
Built from App PR #73848.

Android 🤖 iOS 🍎
https://ad-hoc-expensify-cash.s3.amazonaws.com/android/73848/index.html https://ad-hoc-expensify-cash.s3.amazonaws.com/ios/73848/index.html
Android iOS
Desktop 💻 Web 🕸️
https://ad-hoc-expensify-cash.s3.amazonaws.com/desktop/73848/NewExpensify.dmg https://73848.pr-testing.expensify.com
Desktop Web

👀 View the workflow run that generated this build 👀

@sosek108 sosek108 marked this pull request as ready for review October 31, 2025 15:45
@sosek108 sosek108 requested a review from a team as a code owner October 31, 2025 15:45
@melvin-bot melvin-bot bot requested a review from rojiphil October 31, 2025 15:45
@melvin-bot
Copy link

melvin-bot bot commented Oct 31, 2025

@rojiphil Please copy/paste the Reviewer Checklist from here into a new comment on this PR and complete it. If you have the K2 extension, you can simply click: [this button]

@melvin-bot melvin-bot bot removed the request for review from a team October 31, 2025 15:45
@sosek108
Copy link
Contributor Author

Context Policies is present in Sentry and we can filter by policyID

image image

Onyx.connectWithoutView({
key: ONYXKEYS.SESSION,
callback: (value) => {
if (!value?.email) {
Copy link
Contributor

Choose a reason for hiding this comment

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

Security Concern: Potential PII Exposure

The sendPoliciesContext() function sends an array of all policy IDs the user is a member of to Sentry. This could potentially expose sensitive information about the user's workspace memberships.

Considerations:

  • Policy IDs can be considered sensitive data as they reveal which workspaces a user belongs to
  • The array activePolicies could become quite large for users with many workspace memberships
  • This data will be attached to every error reported to Sentry for this session

Recommendation:
Consider whether sending all policy IDs is necessary, or if just sending the count would suffice:

const activePoliciesCount = getActivePolicies(policies, session.email).length;
Sentry.setTag(CONST.TELEMETRY.TAG_ACTIVE_POLICY, activePolicyID);
Sentry.setContext(CONST.TELEMETRY.CONTEXT_POLICIES, {activePolicyID, activePoliciesCount});

If the full list is needed for debugging, ensure this is documented and approved by the security/privacy team.


Onyx.connectWithoutView({
key: ONYXKEYS.SESSION,
callback: (value) => {
Copy link
Contributor

Choose a reason for hiding this comment

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

Performance: Race Condition and Multiple Unnecessary Calls

The current implementation has a race condition where sendPoliciesContext() may be called multiple times unnecessarily:

  1. When activePolicyID updates → calls sendPoliciesContext()
  2. When session updates → calls sendPoliciesContext()
  3. When policies updates → calls sendPoliciesContext()

Issues:

  • If all three Onyx connections update simultaneously (e.g., during app initialization), sendPoliciesContext() could be called 3 times
  • Each call processes the entire policies collection with getActivePolicies() and .map(), which can be expensive with many policies
  • Repeated calls to Sentry.setTag() and Sentry.setContext() with the same data

Recommendation:
Debounce the sendPoliciesContext() calls or use a flag to prevent redundant updates:

let hasInitialized = false;

function sendPoliciesContext() {
    if (!policies || !session?.email || !activePolicyID) {
        return;
    }
    
    const activePolicies = getActivePolicies(policies, session.email).map((policy) => policy.id);
    const newContext = {activePolicyID, activePolicies};
    
    // Only update if data has changed
    if (!hasInitialized || previousActivePolicyID !== activePolicyID) {
        Sentry.setTag(CONST.TELEMETRY.TAG_ACTIVE_POLICY, activePolicyID);
        Sentry.setContext(CONST.TELEMETRY.CONTEXT_POLICIES, newContext);
        hasInitialized = true;
    }
}

if (!value?.email) {
return;
}
session = value;
Copy link
Contributor

Choose a reason for hiding this comment

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

Performance: Inefficient Array Transformation

The code performs two array operations on potentially large collections:

  1. getActivePolicies(policies, session.email) - filters all policies
  2. .map((policy) => policy.id) - transforms the filtered array

Issue:
For users with many policies, this creates unnecessary intermediate arrays and can impact performance, especially since this runs on every policy/session/activePolicyID change.

Recommendation:
Combine the operations for better performance:

const activePolicies = Object.values(policies ?? {})
    .filter<Policy>(
        (policy): policy is Policy =>
            !!policy && 
            policy.pendingAction !== CONST.RED_BRICK_ROAD_PENDING_ACTION.DELETE && 
            !!policy.name && 
            !!policy.id && 
            !!getPolicyRole(policy, session.email)
    )
    .map((policy) => policy.id);

Or even better, directly extract IDs without creating intermediate Policy objects:

const activePolicies = Object.values(policies ?? {})
    .reduce<string[]>((ids, policy) => {
        if (policy && 
            policy.pendingAction !== CONST.RED_BRICK_ROAD_PENDING_ACTION.DELETE && 
            policy.name && 
            policy.id && 
            getPolicyRole(policy, session.email)) {
            ids.push(policy.id);
        }
        return ids;
    }, []);

let activePolicyID: OnyxEntry<string>;
let policies: OnyxCollection<Policy>;

Onyx.connectWithoutView({
Copy link
Contributor

Choose a reason for hiding this comment

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

Missing Import Statement

The code uses getPolicyRole() function from PolicyUtils in line 50, but there's no import statement for it.

Current imports:

import * as Sentry from '@sentry/react-native';
import type {OnyxCollection, OnyxEntry} from 'react-native-onyx';
import Onyx from 'react-native-onyx';
import CONST from '@src/CONST';
import ONYXKEYS from '@src/ONYXKEYS';
import type {Policy, Session} from '@src/types/onyx';
import FS from './Fullstory';
import {getActivePolicies} from './PolicyUtils';

Issue:
The function getPolicyRole is used inside getActivePolicies but if you're calling getActivePolicies, the function internally uses getPolicyRole, so this should work. However, if the recommendation from my previous comment is followed (inlining the logic), you'll need to import getPolicyRole.

Required addition if inlining the logic:

import {getActivePolicies, getPolicyRole} from './PolicyUtils';

Or import from CONST:

// getPolicyRole uses CONST.RED_BRICK_ROAD_PENDING_ACTION internally

This is a note for maintainability - the current code works because getActivePolicies is properly imported.

import type {Policy, Session} from '@src/types/onyx';
import FS from './Fullstory';
import {getActivePolicies} from './PolicyUtils';

Copy link
Contributor

Choose a reason for hiding this comment

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

TypeScript: Missing Type Safety for Onyx Callbacks

The Onyx callback functions lack explicit type annotations, which reduces type safety.

Current:

Onyx.connectWithoutView({
    key: ONYXKEYS.NVP_ACTIVE_POLICY_ID,
    callback: (value) => {
        // ...
    },
});

Issue:

  • The value parameter is implicitly typed
  • No type checking ensures the correct data structure is being handled
  • Harder to catch type errors during development

Recommendation:
Add explicit types to all callback parameters:

Onyx.connectWithoutView({
    key: ONYXKEYS.NVP_ACTIVE_POLICY_ID,
    callback: (value: OnyxEntry<string>) => {
        if (!value) {
            return;
        }
        activePolicyID = value;
        sendPoliciesContext();
    },
});

Onyx.connectWithoutView({
    key: ONYXKEYS.SESSION,
    callback: (value: OnyxEntry<Session>) => {
        if (!value?.email) {
            return;
        }
        session = value;
        sendPoliciesContext();
    },
});

Onyx.connectWithoutView({
    key: ONYXKEYS.COLLECTION.POLICY,
    waitForCollectionCallback: true,
    callback: (value: OnyxCollection<Policy>) => {
        if (!value) {
            return;
        }
        policies = value;
        sendPoliciesContext();
    },
});


/**
* Connect to Onyx to retrieve information about user's active policies.
*/
Copy link
Contributor

Choose a reason for hiding this comment

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

Error Handling: Missing Error Boundaries

The code lacks error handling for potential failures in the Sentry integration or the getActivePolicies function.

Potential failure points:

  1. getActivePolicies() could throw if policies data is corrupted
  2. Sentry.setTag() or Sentry.setContext() could fail if Sentry isn't initialized
  3. Accessing policy.id could fail if the policy object is malformed

Issue:
If any error occurs in sendPoliciesContext(), it could:

  • Break the telemetry synchronization silently
  • Prevent other Onyx callbacks from executing properly
  • Leave the app in an inconsistent state

Recommendation:
Wrap the logic in try-catch blocks:

function sendPoliciesContext() {
    try {
        if (!policies || !session?.email || !activePolicyID) {
            return;
        }
        
        const activePolicies = getActivePolicies(policies, session.email).map((policy) => policy.id);
        Sentry.setTag(CONST.TELEMETRY.TAG_ACTIVE_POLICY, activePolicyID);
        Sentry.setContext(CONST.TELEMETRY.CONTEXT_POLICIES, {activePolicyID, activePolicies});
    } catch (error) {
        // Log error but don't throw - telemetry failures shouldn't break the app
        console.error('[TelemetrySynchronizer] Failed to send policies context:', error);
    }
}

Also consider wrapping individual Onyx callbacks:

Onyx.connectWithoutView({
    key: ONYXKEYS.NVP_ACTIVE_POLICY_ID,
    callback: (value: OnyxEntry<string>) => {
        try {
            if (!value) {
                return;
            }
            activePolicyID = value;
            sendPoliciesContext();
        } catch (error) {
            console.error('[TelemetrySynchronizer] Error in activePolicyID callback:', error);
        }
    },
});

let policies: OnyxCollection<Policy>;

Onyx.connectWithoutView({
key: ONYXKEYS.NVP_ACTIVE_POLICY_ID,
Copy link
Contributor

Choose a reason for hiding this comment

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

Onyx Pattern: Consider Using initWithStoredValues: false

For the ONYXKEYS.COLLECTION.POLICY connection, you may want to set initWithStoredValues: false to prevent unnecessary initial processing.

Current behavior:

  • When the app starts, Onyx will immediately call the callback with all stored policies
  • This triggers sendPoliciesContext() even before the user's session is fully loaded
  • Could result in unnecessary processing of potentially stale data

Issue:
The callback will fire with cached policy data from storage, which might be outdated or irrelevant if the user isn't logged in yet.

Recommendation:

Onyx.connectWithoutView({
    key: ONYXKEYS.COLLECTION.POLICY,
    waitForCollectionCallback: true,
    initWithStoredValues: false, // Only react to fresh updates, not cached data
    callback: (value: OnyxCollection<Policy>) => {
        if (!value) {
            return;
        }
        policies = value;
        sendPoliciesContext();
    },
});

Alternatively, if you do want to use cached values, ensure the guard in sendPoliciesContext() properly handles stale data by checking if the session is valid and active.

* This file contains the logic for sending additional data to Sentry.
*
* It uses Onyx.connectWithoutView as nothing here is related to the UI. We only send data to external provider and want to keep this outside of the render loop.
* It uses Onyx.connectWithoutView as nothing here is related to the UI. We only send data to the external provider and want to keep this outside of the render loop.
Copy link
Contributor

Choose a reason for hiding this comment

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

Documentation: Update File Comment

The file-level comment should be updated to reflect the new functionality.

Current comment:

/**
 * This file contains the logic for sending additional data to Sentry.
 *
 * It uses Onyx.connectWithoutView as nothing here is related to the UI. We only send data to external provider and want to keep this outside of the render loop.
 */

Recommendation:
Update to describe what data is being sent:

/**
 * This file contains the logic for sending additional data to Sentry.
 * 
 * Currently synchronizes:
 * - FullStory session ID for cross-platform debugging
 * - Active policy ID and user's policy memberships for workspace context
 *
 * It uses Onyx.connectWithoutView as nothing here is related to the UI. 
 * We only send data to the external provider and want to keep this outside of the render loop.
 */

This helps future developers understand what telemetry data is being collected and sent to Sentry.

@@ -1614,6 +1614,8 @@ const CONST = {
},
TELEMETRY: {
CONTEXT_FULLSTORY: 'Fullstory',
Copy link
Contributor

Choose a reason for hiding this comment

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

Code Organization: Consider Grouping Related Constants

The new telemetry constants are well-named, but consider adding a comment to document their purpose:

TELEMETRY: {
    // FullStory integration
    CONTEXT_FULLSTORY: 'Fullstory',
    
    // Policy/Workspace tracking
    TAG_ACTIVE_POLICY: 'active_policy_id',
    CONTEXT_POLICIES: 'Policies',
},

This makes it clearer which constants are related and makes it easier to find relevant constants when working on telemetry features.

Minor style note: Consider consistent casing - CONTEXT_FULLSTORY uses 'Fullstory' (Pascal case) while CONTEXT_POLICIES uses 'Policies'. Should these both be uppercase for consistency?

CONTEXT_FULLSTORY: 'FullStory',  // or 'fullstory'
CONTEXT_POLICIES: 'Policies',     // matches


Onyx.connectWithoutView({
key: ONYXKEYS.SESSION,
callback: (value) => {
Copy link
Contributor

Choose a reason for hiding this comment

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

Logic Issue: No Cleanup When User Logs Out

The current implementation doesn't clear Sentry context when a user logs out or when the session becomes invalid.

Issue:
If a user logs out:

  1. session.email becomes undefined or the session object is cleared
  2. The guard if (!session?.email) prevents updating Sentry
  3. However, the previous user's policy data remains in Sentry's context
  4. This stale data will be attached to error reports even after logout

Security/Privacy Concern:
After logout, errors should not include the previous user's policy information.

Recommendation:
Clear Sentry context when session is invalidated:

Onyx.connectWithoutView({
    key: ONYXKEYS.SESSION,
    callback: (value: OnyxEntry<Session>) => {
        // Clear context if session is cleared/invalid
        if (!value?.email) {
            Sentry.setTag(CONST.TELEMETRY.TAG_ACTIVE_POLICY, null);
            Sentry.setContext(CONST.TELEMETRY.CONTEXT_POLICIES, null);
            session = null;
            return;
        }
        session = value;
        sendPoliciesContext();
    },
});

Similarly, consider clearing when activePolicyID is cleared:

Onyx.connectWithoutView({
    key: ONYXKEYS.NVP_ACTIVE_POLICY_ID,
    callback: (value: OnyxEntry<string>) => {
        if (!value) {
            // Clear the active policy tag when it's unset
            Sentry.setTag(CONST.TELEMETRY.TAG_ACTIVE_POLICY, null);
            activePolicyID = null;
            return;
        }
        activePolicyID = value;
        sendPoliciesContext();
    },
});

/**
* Connect to Onyx to retrieve information about user's active policies.
*/
let session: OnyxEntry<Session>;
Copy link
Contributor

Choose a reason for hiding this comment

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

Code Style: Inconsistent Variable Initialization

The module-level variables are declared but not initialized:

let session: OnyxEntry<Session>;
let activePolicyID: OnyxEntry<string>;
let policies: OnyxCollection<Policy>;

Issue:

  • These variables are declared but not initialized
  • TypeScript allows accessing them before Onyx populates them
  • Could lead to undefined behavior if sendPoliciesContext() is called before all connections are established

Recommendation:
Initialize with explicit null for clarity:

let session: OnyxEntry<Session> = null;
let activePolicyID: OnyxEntry<string> = null;
let policies: OnyxCollection<Policy> = null;

This makes it explicit that these values start as null. Note: This follows some patterns in the codebase, though PolicyUtils.ts also doesn't initialize its allPolicies variable, so either pattern is acceptable for consistency.

@github-actions
Copy link
Contributor

Code Review Summary

I've reviewed PR #73848 and identified several areas for improvement:

Critical Issues

  1. Security/Privacy: Sending all policy IDs to Sentry may expose sensitive workspace membership information
  2. Logout Cleanup: Sentry context is not cleared when users log out, leaving stale data attached to error reports

Performance Concerns

  1. Race Conditions: sendPoliciesContext() can be called multiple times unnecessarily during initialization
  2. Array Operations: The policy filtering and mapping creates unnecessary intermediate arrays

Code Quality

  1. Error Handling: Missing try-catch blocks could cause silent failures
  2. Type Safety: Onyx callback parameters lack explicit type annotations
  3. Documentation: File comment should describe what data is being sent

Minor Issues

  1. Onyx Pattern: Consider using initWithStoredValues: false for the policies connection
  2. Code Style: Variables could be explicitly initialized for clarity
  3. Constants: CONST values could use consistent casing

All issues have been documented with inline comments containing specific recommendations and code examples.

The implementation is functional but would benefit from addressing the security/privacy and cleanup concerns before merging.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant