Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: braze anonymousId tracking with alias details #1994

Conversation

utsabc
Copy link
Member

@utsabc utsabc commented Jan 7, 2025

PR Description

Anonymous User Identification

  • Added automatic alias creation by setting the RudderStack anonymous_id as an alias_id in Braze when the SDK initializes
  • Aligned device mode behavior with cloud mode implementation for consistent user tracking
  • Fixed incorrect usage of Braze's change_user API for anonymous user tracking

Profile Management

  • Implemented proper linking between device_id and anonymous_id to maintain a single user profile
  • Removed redundant user_id assignments that were causing profile duplication
  • Streamlined page tracking implementation to maintain consistent user identification

We achieve the above by making the following Key Changes

  • We are setting the anonymous_id as braze alias label in the isReady call back
  • We are calling changeUser only in case of identify change user api doc

Linear Ticket

Cross Browser Tests

Please confirm you have tested for the following browsers:

  • Chrome
  • Firefox
  • IE11

Sanity Suite

  • All sanity suite test cases pass locally

Security

  • The code changed/added as part of this pull request won't create any security issues with how the software is being used.

Summary by CodeRabbit

Summary by CodeRabbit

  • New Features

    • Enhanced Braze integration with improved event tracking mechanisms.
  • Bug Fixes

    • Streamlined event logging process for more reliable tracking.
  • Refactor

    • Simplified tracking and page view methods to improve code clarity and performance.
    • Updated handlePurchase function to operate without user ID, focusing on logging purchases.
    • Introduced a mock for the addAlias method in the test suite to enhance testing coverage.

@utsabc utsabc requested a review from a team as a code owner January 7, 2025 07:02
Copy link
Contributor

coderabbitai bot commented Jan 7, 2025

Important

Review skipped

Auto reviews are disabled on base/target branches other than the default branch.

🗂️ Base branches to auto review (2)
  • main
  • develop

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

📝 Walkthrough

Walkthrough

The pull request introduces modifications to the Braze integration in the analytics JavaScript library. The changes enhance the logic for user identification and event tracking in the isReady, track, and page methods. The isReady method now includes a more complex return structure for user aliasing, while the track and page methods have been simplified by removing user ID checks. Additionally, the test suite has been updated to reflect these changes, including the mocking of new methods and adjustments to assertions.

Changes

File Change Summary
packages/analytics-js-integrations/src/integrations/Braze/browser.js - Modified isReady method to add user alias when loaded
- Simplified track method by removing user ID checks
- Streamlined page method to directly process event names
packages/analytics-js-integrations/__tests__/integrations/Braze/browser.test.js - Mocked addAlias method in mockBrazeSDK
- Added test for addAlias in isReady method
- Updated assertions for track and page methods to remove changeUser checks and updated URL format
packages/analytics-js-integrations/src/integrations/Braze/utils.js - Updated handlePurchase method signature to remove userId parameter and related logic

Possibly related PRs

Suggested labels

Stale

Suggested reviewers

  • sandeepdsvs
  • sanpj2292
  • shrouti1507
  • ItsSudip

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR. (Beta)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🔭 Outside diff range comments (1)
packages/analytics-js-integrations/src/integrations/Braze/browser.js (1)

Implement PII protection mechanisms for error logging and data handling

The code has multiple security vulnerabilities that need to be addressed:

  1. Error Logging:

    • Replace stringifyWithoutCircularV1(error, true) with a sanitized error logging that excludes PII
    • Add a dedicated error sanitizer utility to redact sensitive data before logging
  2. Data Handling:

    • Add input validation for all user traits before processing
    • Implement PII filtering for sensitive fields like email, phone, address
    • Create a dedicated sanitization layer for user data
  3. Storage:

    • Review and validate encryption implementation for stored user data
    • Add data minimization to only store required PII fields
🔗 Analysis chain

Line range hint 1-290: Verify security considerations for user data handling

Please ensure the following security aspects are addressed:

  1. PII Handling:

    • Verify that sensitive user attributes are not logged in debug/error messages
    • Consider implementing a PII filter in handleReservedProperties
  2. Input Sanitization:

    • Add validation for event names and property values before sending to Braze
    • Consider implementing maximum length limits for custom attributes

Run this script to check for potential PII logging:

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for logging statements that might expose PII
rg -n "logger\.(debug|error|info|warn).*(\{|user|email|phone|address)" .

# Check for direct access to sensitive user properties
ast-grep --pattern 'context?.traits?.email' .
ast-grep --pattern 'context?.traits?.phone' .

Length of output: 80017


Script:

#!/bin/bash
# Search for stringifyWithoutCircularV1 usage in logging
rg -n "stringifyWithoutCircularV1.*logger" .

# Look for input validation/sanitization functions
ast-grep --pattern 'function $name($_) {
  $$$
  sanitize
  $$$
}'

# Check for other potential PII logging
rg -n "logger\.(error|debug|info).*(\{.*traits|\{.*user|\{.*email|\{.*phone)" .

Length of output: 65734


Script:

#!/bin/bash
# Search for input validation/sanitization functions
ast-grep --pattern 'function $name($param) {
  $$$
  validate
  $$$
}'

# Look for other potential PII exposures in error handling
rg -n "error.*(\{.*user|\{.*email|\{.*phone|\{.*traits)" .

# Check for sanitization functions
rg -n "(sanitize|redact|mask|filter).*(\{.*user|\{.*email|\{.*phone)" .

Length of output: 65743

🧹 Nitpick comments (2)
packages/analytics-js-integrations/src/integrations/Braze/browser.js (2)

Line range hint 266-273: Add defensive programming to event handling

While the simplified logic is cleaner, consider adding some safeguards:

    if (eventName) {
+     // Normalize event name to handle null/undefined properties
+     const normalizedEventName = String(eventName).trim();
+     if (!normalizedEventName) {
+       logger.debug('Skipping track call - empty event name');
+       return;
+     }
-     if (eventName.toLowerCase() === 'order completed') {
+     if (normalizedEventName.toLowerCase() === 'order completed') {
        handlePurchase(properties, userId);
      } else {
+       // Ensure properties is an object
+       properties = properties && typeof properties === 'object' ? properties : {};
        properties = handleReservedProperties(properties);
-       window.braze.logCustomEvent(eventName, properties);
+       window.braze.logCustomEvent(normalizedEventName, properties);
      }
    }

Line range hint 279-290: Align page tracking with track method improvements

For consistency and robustness, apply similar defensive programming patterns:

    if (this.isHybridModeEnabled) {
      return;
    }
    const eventName = rudderElement.message.name;
    let { properties } = rudderElement.message;
+   // Ensure properties is an object
+   properties = properties && typeof properties === 'object' ? properties : {};
    properties = handleReservedProperties(properties);
+   // Normalize event name
+   const normalizedEventName = eventName ? String(eventName).trim() : '';
-   if (eventName) {
+   if (normalizedEventName) {
-     window.braze.logCustomEvent(eventName, properties);
+     window.braze.logCustomEvent(normalizedEventName, properties);
    } else {
      window.braze.logCustomEvent('Page View', properties);
    }
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 0dfb893 and e85e1a1.

📒 Files selected for processing (1)
  • packages/analytics-js-integrations/src/integrations/Braze/browser.js (2 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (4)
  • GitHub Check: Security and code quality checks
  • GitHub Check: Bundle size checks
  • GitHub Check: Unit Tests and Lint
  • GitHub Check: Analyze (javascript-typescript)

Copy link

github-actions bot commented Jan 7, 2025

size-limit report 📦

Name Size (Base) Size (Current) Size Limit Status
Cookies Utils - Legacy - NPM (ESM) 1.54 KB 1.54 KB (0%) 2 KB
Cookies Utils - Legacy - NPM (CJS) 1.75 KB 1.75 KB (0%) 2 KB
Cookies Utils - Legacy - NPM (UMD) 1.54 KB 1.54 KB (0%) 2 KB
Cookies Utils - Modern - NPM (ESM) 1.17 KB 1.17 KB (0%) 1.5 KB
Cookies Utils - Modern - NPM (CJS) 1.4 KB 1.4 KB (0%) 1.5 KB
Cookies Utils - Modern - NPM (UMD) 1.16 KB 1.16 KB (0%) 1.5 KB
Plugins Module Federation Mapping - Legacy - CDN 332 B 332 B (0%) 512 B
Plugins - Legacy - CDN 15.75 KB 15.75 KB (0%) 16 KB
Plugins Module Federation Mapping - Modern - CDN 331 B 331 B (0%) 512 B
Plugins - Modern - CDN 7.2 KB 7.2 KB (0%) 7.5 KB
Common - No bundling 17.8 KB 17.8 KB (0%) 18.4 KB
Load Snippet 762 B 762 B (0%) 1 KB
Core (v1.1) - NPM (ESM) 30.25 KB 30.25 KB (0%) 32 KB
Core (v1.1) - NPM (CJS) 30.47 KB 30.47 KB (0%) 32 KB
Core (v1.1) - NPM (UMD) 30.29 KB 30.29 KB (0%) 32 KB
Core (Content Script - v1.1) - NPM (ESM) 29.81 KB 29.81 KB (0%) 30.5 KB
Core (Content Script - v1.1) - NPM (CJS) 29.97 KB 29.97 KB (0%) 30.5 KB
Core (Content Script - v1.1) - NPM (UMD) 29.81 KB 29.81 KB (0%) 30 KB
Core - Legacy - CDN 48.99 KB 48.99 KB (0%) 49 KB
Core - Modern - CDN 24.98 KB 24.98 KB (0%) 25.5 KB
Service Worker - Legacy - NPM (ESM) 30.62 KB 30.62 KB (0%) 31 KB
Service Worker - Legacy - NPM (CJS) 30.85 KB 30.85 KB (0%) 31 KB
Service Worker - Legacy - NPM (UMD) 30.58 KB 30.58 KB (0%) 31 KB
Service Worker - Modern - NPM (ESM) 25.71 KB 25.71 KB (0%) 26 KB
Service Worker - Modern - NPM (CJS) 26 KB 26 KB (0%) 26.5 KB
Service Worker - Modern - NPM (UMD) 25.75 KB 25.75 KB (0%) 26 KB
Core - Legacy - NPM (ESM) 48.79 KB 48.79 KB (0%) 49 KB
Core - Legacy - NPM (CJS) 49.05 KB 49.05 KB (0%) 49.1 KB
Core - Legacy - NPM (UMD) 48.84 KB 48.84 KB (0%) 49 KB
Core - Modern - NPM (ESM) 24.76 KB 24.76 KB (0%) 25 KB
Core - Modern - NPM (CJS) 24.96 KB 24.96 KB (0%) 25.5 KB
Core - Modern - NPM (UMD) 24.75 KB 24.75 KB (0%) 25 KB
Core (Bundled) - Legacy - NPM (ESM) 48.79 KB 48.79 KB (0%) 49 KB
Core (Bundled) - Legacy - NPM (CJS) 49.11 KB 49.11 KB (0%) 49.2 KB
Core (Bundled) - Legacy - NPM (UMD) 48.84 KB 48.84 KB (0%) 49 KB
Core (Bundled) - Modern - NPM (ESM) 39.77 KB 39.77 KB (0%) 40 KB
Core (Bundled) - Modern - NPM (CJS) 39.98 KB 39.98 KB (0%) 40.5 KB
Core (Bundled) - Modern - NPM (UMD) 39.82 KB 39.82 KB (0%) 40 KB
Core (Content Script) - Legacy - NPM (ESM) 48.29 KB 48.29 KB (0%) 48.5 KB
Core (Content Script) - Legacy - NPM (CJS) 48.52 KB 48.52 KB (0%) 48.6 KB
Core (Content Script) - Legacy - NPM (UMD) 48.25 KB 48.25 KB (0%) 48.5 KB
Core (Content Script) - Modern - NPM (ESM) 39.27 KB 39.27 KB (0%) 39.5 KB
Core (Content Script) - Modern - NPM (CJS) 39.5 KB 39.5 KB (0%) 40 KB
Core (Content Script) - Modern - NPM (UMD) 39.22 KB 39.22 KB (0%) 39.5 KB
All Integrations - Legacy - CDN 94.74 KB 94.93 KB (+0.2% ▲) 95.3 KB
All Integrations - Modern - CDN 90.16 KB 90.38 KB (+0.25% ▲) 91 KB

coderabbitai[bot]
coderabbitai bot previously approved these changes Jan 17, 2025
coderabbitai[bot]
coderabbitai bot previously approved these changes Jan 17, 2025
Copy link

codecov bot commented Jan 17, 2025

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 61.30%. Comparing base (959b84c) to head (5e59f74).
Report is 5 commits behind head on hotfix/integrations-braze-indentity-issue-fix.

Additional details and impacted files
@@                                Coverage Diff                                @@
##           hotfix/integrations-braze-indentity-issue-fix    #1994      +/-   ##
=================================================================================
+ Coverage                                          61.27%   61.30%   +0.02%     
=================================================================================
  Files                                                484      484              
  Lines                                              16616    16626      +10     
  Branches                                            3340     3356      +16     
=================================================================================
+ Hits                                               10182    10192      +10     
+ Misses                                              5213     5167      -46     
- Partials                                            1221     1267      +46     

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

@utsabc utsabc changed the base branch from develop to hotfix/integrations-braze-indentity-issue-fix January 21, 2025 06:57
@utsabc utsabc merged commit 7215304 into hotfix/integrations-braze-indentity-issue-fix Jan 21, 2025
10 checks passed
@utsabc utsabc deleted the fix.braze-anonymous-tracking branch January 21, 2025 11:55
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.

3 participants