bugsnag / bugsnag-js-performance

Monitor the performance of your JavaScript (web and React Native) and see the results in your BugSnag dashboard.
https://docs.bugsnag.com/performance/integration-guides
MIT License
4 stars 1 forks source link

Generate random bytes natively for ID generation #380

Closed yousif-bugsnag closed 7 months ago

yousif-bugsnag commented 7 months ago

Goal

Some duplicate span IDs were observed in production as Math.random isn't random enough.

This PR updates the id generation to source randomness from cryptographically secure number generators in the native layer.

Design

Two new methods requestEntropy and requestEntropyAsync have been added to the Native Module. These return random bytes as a 2048 character hex string generated using SecureRandom on Android and SecRandomCopyBytes on iOS. These characters are then used by the ID generator to generate span and trace IDs by randomly selecting characters from the string using Math.random().

If the Native Module is not available for any reason, we fall back to generating a random string in JS using Math.random.

When the client is loaded, a synchronous call to requestEntropy is made for an initial set of random values. After 1000 calls, requestEntropyAsync is called to refresh the random values asynchronously.

As part of this work, also fixed a bug in the iOS Native Module that was preventing it from working on the old architecture (it was missing an RCT_EXPORT_ macro on the method), and reinstated the native device attribute e2e tests for old arch on iOS.

Testing

Tested manually, added some more unit tests, and relied on the existing trace validation in e2e tests.

github-actions[bot] commented 7 months ago

Browser bundle size

NPM build

Package
Before 175.95 kB
After 175.95 kB
± No change

CDN build

Unminified Minfied Minified + gzipped
Before 84.94 kB 31.99 kB 9.84 kB
After 84.94 kB 31.99 kB 9.84 kB
± No change No change No change

Code coverage

Ok File (✨=New File) Lines Branches Functions Statements
🔴 /home/runner/work/bugsnag-js-performance/bugsnag-js-performance/packages/platforms/react-native/lib/id-generator.ts 100%
(+0%)
100%
(+0%)
87.5%
(-12.5%)
96.96%
(-3.04%)

Total:

Lines Branches Functions Statements
92.25%(+0.05%) 80.67%(+0.29%) 93.33%(-0.15%) 90.31%(-0.04%)

Generated against 6dae1decad0c6755dad39453c04839cefa7c0533 on 8 December 2023 at 11:43:34 UTC