Skip to content

[NoQA] Tag injected third-party script errors in Sentry with third_party_code - #97223

Open
WojtekBoman wants to merge 13 commits into
Expensify:mainfrom
software-mansion-labs:instrument-opaque-rejection-app-cn8
Open

[NoQA] Tag injected third-party script errors in Sentry with third_party_code#97223
WojtekBoman wants to merge 13 commits into
Expensify:mainfrom
software-mansion-labs:instrument-opaque-rejection-app-cn8

Conversation

@WojtekBoman

@WojtekBoman WojtekBoman commented Jul 28, 2026

Copy link
Copy Markdown
Contributor

Explanation of Change

Errors thrown by injected code (consent tools, tag managers, browser extensions) were indistinguishable from our own in Sentry. This enables Sentry's thirdPartyErrorFilterIntegration on web: @sentry/webpack-plugin stamps every chunk with an application key, and events whose stack holds no stamped frame get tagged third_party_code: true. The key is shared by sentryApplicationKey.ts between bundler config and app source. No-op in development and on native, where no key is stamped.

Fixed Issues

$ #93837
PROPOSAL:

Tests

Test 1: third-party errors get tagged, own errors do not (non-development web build)

  1. Run npm run build-staging (the integration is intentionally off under npm run web, because @sentry/webpack-plugin does not stamp the application key in development builds)
  2. Serve the build with npm run web:dist and open the app in Chrome with DevTools open
  3. Log in and confirm the app renders normally with no errors in the JS console
  4. Throw an error from a stack containing only non-app frames by pasting into the DevTools console:
    const s = document.createElement('script'); s.src = 'data:text/javascript,setTimeout(() => { throw new Error("injected boom"); }, 0)'; document.body.appendChild(s);
  5. Trigger an error from app code (e.g. temporarily patch a component event handler to throw new Error('app boom') and press it)
  6. Open the Sentry app project and find both events
  7. Verify that the injected error carries the tag third_party_code: true
  8. Verify that the app error does NOT carry third_party_code: true

Test 2: development build and native are unaffected

  1. Run npm run web and open the app in Chrome
  2. Log in and navigate around (LHN, open a report, open Settings)
  3. Verify that no errors appear in the JS console and Sentry events are still reported
  4. Verify that no event is tagged third_party_code: true, so nothing is mislabeled while no application key is stamped
  5. Run the app on iOS Native and Android Native, log in, and navigate around
  6. Verify that startup and navigation behave as before, with no errors in the JS console and no third_party_code tag on native events

Offline tests

N/A - no API calls, data fetching, or Onyx operations are added or changed. Sentry keeps its existing offline behavior (events are queued by the SDK and flushed when connectivity returns); this change only adds a tag to events that are already sent.

QA Steps

Same as tests, run against staging instead of a local build:

  1. Open the staging web app in Chrome with DevTools open
  2. Log in and navigate around (LHN, open a report, open Settings)
  3. Verify that the app behaves as before and no errors appear in the JS console
  4. On iOS Native, Android Native, iOS mWeb Safari, and Android mWeb Chrome, log in and navigate around
  5. Verify that there are no new errors, crashes, or startup regressions on any platform
  • Verify that no errors appear in the JS console

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
  • 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 followed proper code patterns (see Reviewing the code)
    • 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 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)
  • 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)
  • 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.
  • 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

@WojtekBoman

Copy link
Copy Markdown
Contributor Author

@codex

@codecov

codecov Bot commented Jul 28, 2026

Copy link
Copy Markdown

Codecov Report

✅ Changes either increased or maintained existing code coverage, great job!

Files with missing lines Coverage Δ
src/libs/telemetry/integrations/index.ts 100.00% <100.00%> (ø)
src/libs/telemetry/sentryApplicationKey.ts 0.00% <0.00%> (ø)
src/setup/telemetry/setupSentry.ts 0.00% <0.00%> (ø)
src/libs/telemetry/integrations/index.web.ts 0.00% <0.00%> (ø)
... and 576 files with indirect coverage changes

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: ba2b5bae8d

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment thread src/libs/telemetry/middlewares/enrichOpaqueRejection.ts Outdated
@WojtekBoman

Copy link
Copy Markdown
Contributor Author

@codex

@WojtekBoman WojtekBoman changed the title Enrich opaque "Cannot call a class as a function" Sentry rejections Enrich opaque Sentry errors with script hostnames to trace injected-script source Jul 28, 2026

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: baff312401

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment thread src/libs/telemetry/middlewares/enrichInjectedScriptError.ts Outdated
@WojtekBoman

Copy link
Copy Markdown
Contributor Author

@codex

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: f3bc8e5c0e

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment thread src/libs/telemetry/middlewares/enrichInjectedScriptError.ts Outdated
@WojtekBoman

Copy link
Copy Markdown
Contributor Author

@codex

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: c984a0fdd6

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment thread src/libs/telemetry/middlewares/enrichInjectedScriptError.ts Outdated
@WojtekBoman
WojtekBoman force-pushed the instrument-opaque-rejection-app-cn8 branch from 26780a3 to e8b59f2 Compare July 30, 2026 14:20
@WojtekBoman WojtekBoman changed the title Enrich opaque Sentry errors with script hostnames to trace injected-script source [NoQA] Tag injected third-party script errors in Sentry with third_party_code Jul 30, 2026

@war-in war-in left a comment

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.

LGTM

Comment thread src/libs/telemetry/integrations/index.web.ts Outdated
Comment thread tests/unit/sentryApplicationKeyTest.ts Outdated
@WojtekBoman
WojtekBoman marked this pull request as ready for review July 30, 2026 15:12
@WojtekBoman
WojtekBoman requested review from a team as code owners July 30, 2026 15:12
@melvin-bot
melvin-bot Bot requested a review from marufsharifi July 30, 2026 15:12
@melvin-bot
melvin-bot Bot removed the request for review from a team July 30, 2026 15:12
@melvin-bot

melvin-bot Bot commented Jul 30, 2026

Copy link
Copy Markdown

@marufsharifi 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 requested review from heyjennahay and removed request for a team July 30, 2026 15:13
@WojtekBoman
WojtekBoman force-pushed the instrument-opaque-rejection-app-cn8 branch from bffd6e4 to 3fbc602 Compare July 30, 2026 15:15
@marufsharifi

marufsharifi commented Jul 30, 2026

Copy link
Copy Markdown
Contributor

Reviewer Checklist

  • I have verified the author checklist is complete (all boxes are checked off).
  • I verified the correct issue is linked in the ### Fixed Issues section above
  • I verified testing steps are clear and they cover the changes made in this PR
    • I verified the steps for local testing are in the Tests section
    • I verified the steps for Staging and/or Production testing are in the QA steps section
    • I verified the steps cover any possible 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 checked that screenshots or videos are included for tests on all platforms
  • I included screenshots or videos for tests on all platforms
  • I verified that the composer does not automatically focus or open the keyboard on mobile unless explicitly intended. This includes checking that returning the app from the background does not unexpectedly open the keyboard.
  • I verified tests pass on all platforms & I tested again on:
    • Android: HybridApp
    • Android: mWeb Chrome
    • iOS: HybridApp
    • iOS: mWeb Safari
    • MacOS: Chrome / Safari
  • If there are any errors in the console that are unrelated to this PR, I either fixed them (preferred) or linked to where I reported them in Slack
  • I verified proper code patterns were followed (see Reviewing the code)
    • 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 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)
  • If a new code pattern is added I verified it was agreed to be used by multiple Expensify engineers
  • I verified that this PR follows the guidelines as stated in the Review Guidelines
  • I verified other components that can be impacted by these changes have been tested, and I retested again (i.e. if the PR modifies a shared library or component like Avatar, I verified the components using Avatar have been tested & I retested again)
  • If a new component is created I verified that:
    • A similar component doesn't exist in the codebase
    • All props are defined accurately
    • The component has a clear name that is non-ambiguous and the purpose of the component can be inferred from the name alone
    • The only data being stored in the state is data necessary for rendering and nothing else
    • The component has the minimum amount of code necessary for its purpose, and it is broken down into smaller components in order to separate concerns and functions
  • 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 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.
  • For any bug fix or new feature in this PR, I verified that sufficient unit tests are included to prevent regressions in this 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.
  • I have checked off every checkbox in the PR reviewer checklist, including those that don't apply to this PR.

Screenshots/Videos

Android: HybridApp
Android: mWeb Chrome
iOS: HybridApp
iOS: mWeb Safari
MacOS: Chrome / Safari

Comment on lines +34 to +39
const thirdPartyErrorFilterIntegration = isDevelopment()
? undefined
: SentryReact.thirdPartyErrorFilterIntegration({
filterKeys: [SENTRY_APPLICATION_KEY],
behaviour: 'apply-tag-if-exclusively-contains-third-party-frames',
});

@dariusz-biela dariusz-biela Jul 30, 2026

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.

NAB:

The current classification has a few edge cases:

  1. Events without stack frames remain unclassified, so truly opaque rejections are still included in third_party_code:false.
  2. Errors thrown by third-party code through Sentry-wrapped browser APIs can contain an own-bundle helpers.js frame and be incorrectly treated as first-party.
  3. If every frame lacks a filename or location, Sentry produces an empty frame-key list. Since [].every() is true, the event is incorrectly tagged as third-party.

The second case was reported in getsentry/sentry-javascript#20687 and fixed by getsentry/sentry-javascript#20802, released in JS SDK 10.54.0. We could upgrade to @sentry/react-native 8.14.2 / @sentry/core 10.57.0 and enable:

ignoreSentryInternalFrames: true,

To catch them all, you could write a custom handler that would categorize them into three groups: stack_origin: first_party | third_party | unknown.

However, I’m not sure if this makes sense, so I’ll leave that up to you to decide. We could also add a comment noting that this solution has these edge cases.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Good catches, all three are real. That said, I think the current change is sufficient for what we're
chasing here: all 313 APP-CN8 events have exactly two frames, both app:/// with line/col, coming
through auto.browser.global_handlers.onunhandledrejection, so there's no missing-frames case, no
sentryWrapped frame to mis-attribute, and nothing getting filtered out.

I agree we should enable ignoreSentryInternalFrames: true, I'll handle it as a followup as it requires upgrading @sentry It would increase the diff in this PR significantly. Thanks for the insightful review 🙇

* plugin only runs for non-development builds, hence the guard: without a key in the bundle every frame
* looks foreign.
*/
const thirdPartyErrorFilterIntegration = isDevelopment()

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.

The "stamp the key" and "enable the integration" guards are decoupled — worth tying them to one fact.

Whether the key is stamped and whether this integration is enabled are decided by two independent conditions:

  • Enable (here, runtime): isDevelopment()Config.ENVIRONMENT === 'dev'
  • Stamp (build time): config/rsbuild/rsbuild.common.ts:320file !== '.env' && file !== '.env.development'

They stay consistent across normal builds (staging/prod/adhoc stamp and run non-dev; the dev server uses .env with ENVIRONMENT=dev), so there's no bug today. But the coupling is implicit.

The dangerous divergence is enabled + not stamped: with no stamped frame in the bundle, every app error looks exclusively third-party and gets mislabeled third_party_code: true — silently hiding real errors and defeating the feature.

const thirdPartyErrorFilterIntegration = isDevelopment()
    ? undefined
    : SentryReact.thirdPartyErrorFilterIntegration({ ... });

Could we derive both guards from the same "is this a stamped build" fact, or at least add a comment cross-referencing rsbuild.common.ts so a future change to one guard doesn't silently desync the other? Not blocking.

filesToDeleteAfterUpload: './dist/**/*.map',
},
// Stamps every chunk so the SDK can tell our frames from injected ones at runtime.
applicationKey: SENTRY_APPLICATION_KEY,

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.

This is the build-time half of the guard pair (see my note on index.web.ts:34). The key is stamped whenever the plugin runs — gated on isDevelopment at line 320 — while the runtime integration is gated separately on isDevelopment().

They agree for all normal builds, but the two conditions are independent. A one-line comment here pointing at the runtime guard (and vice versa) would prevent a future edit to either from silently mislabeling every app error as third_party_code.

@marufsharifi

Copy link
Copy Markdown
Contributor

@MelvinBot Review

@MelvinBot

Copy link
Copy Markdown
Contributor

Review

This looks solid and well-scoped. It swaps the earlier custom beforeSend middleware approach for Sentry's built-in thirdPartyErrorFilterIntegration, which is the right call — less code to maintain and no PII-extraction surface. The net diff is 5 files, and the abandoned middleware/CONST/test artifacts from the earlier commits are fully reverted. API usage is correct: applicationKey is a top-level @sentry/webpack-plugin option, filterKeys/behaviour are the right option names, and apply-tag-if-exclusively-contains-third-party-frames is the most conservative behaviour (tags only when every frame is foreign, so any error touching our bundle is left untagged).

One dependency worth calling out — the correctness of this hinges on the two dev-gates never diverging:

The failure mode to avoid is: bundler doesn't stamp (dev) but runtime thinks it's non-dev → the integration sees every frame as foreign and mislabels all errors third_party_code: true. I checked the standard env files and they stay in sync (.env/.env.development → dev on both sides; staging/prod/adhoc → stamped + active on both), so this is safe today. Just keep the two definitions in lockstep if env handling ever changes.

Other notes (non-blocking)
  • sentryApplicationKey.ts staying import-free (so it's safe to load from the rsbuild config before aliases resolve) is a nice touch, and the shared const is the right way to keep bundler and runtime agreeing by literal string.
  • The @ts-expect-error + relative import in the rsbuild config matches the existing pattern in that file, so it's consistent.
  • No unit tests, but that's reasonable here — the logic now lives in Sentry's integration, and it's gated [NoQA]. The behavior isn't unit-testable without a real stamped bundle anyway.
  • Native parity via the undefined stub in index.ts + the .filter(Boolean) in setupSentry is clean.

I didn't run the platform tests — the Test/QA steps require a non-dev build to actually verify tagging in Sentry, which is a human step. No code issues found.

@WojtekBoman

Copy link
Copy Markdown
Contributor Author

@marufsharifi I've already added a fix that should address your and Melvin comments :)

@marufsharifi marufsharifi left a comment

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.

LGTM

@melvin-bot
melvin-bot Bot requested a review from mountiny August 1, 2026 07:47
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.

5 participants