Skip to content

Conversation

@shubham1g5
Copy link
Contributor

@shubham1g5 shubham1g5 commented May 5, 2025

Product Description

https://dimagi.atlassian.net/browse/CCCT-1147

Safety Assurance

Safety story

Automated test coverage

Good coverage around changed areas.

QA Plan

No speicifc QA other than release test plan

Labels and Review

  • Do we need to enhance the manual QA test coverage ? If yes, the "QA Note" label is set correctly
  • Does the PR introduce any major changes worth communicating ? If yes, the "Release Note" label is set and a "Release Note" is specified in PR description.
  • Risk label is set correctly
  • The set of people pinged as reviewers is appropriate for the level of risk of the change

@coderabbitai
Copy link

coderabbitai bot commented May 5, 2025

📝 Walkthrough

Walkthrough

This set of changes introduces support for token-based authentication and enhanced analytics tracking, along with minor UI and resource updates. Several classes now use a unified authentication object (AuthInfo) in network requests, supporting both traditional credentials and new bearer token authentication. Error handling is expanded to recognize and process token-specific exceptions, with new enum values, notification messages, and analytics events for token unavailability and denial. Analytics coverage is extended with new event and parameter constants, as well as additional reporting methods for user actions and navigation. A new vector drawable resource (ic_marker.xml) is added and integrated into the UI. Developer preferences now include a toggle for enabling Connect ID, with corresponding analytics reporting. The codebase also receives minor formatting, import cleanup, and variable naming improvements, but no core logic or control flow is otherwise altered outside of the authentication and analytics enhancements.

Sequence Diagram(s)

sequenceDiagram
    participant UI
    participant NetworkLayer
    participant AuthManager
    participant Analytics
    participant NotificationFactory

    UI->>NetworkLayer: Initiate network request
    NetworkLayer->>AuthManager: buildAuth()
    AuthManager-->>NetworkLayer: AuthInfo (TokenAuth or ProvidedAuth)
    NetworkLayer->>NetworkLayer: Execute request with AuthInfo
    alt TokenAuth used and response is 401
        NetworkLayer->>AuthManager: checkForTokenError()
        AuthManager-->>NetworkLayer: Invalidate token
        NetworkLayer->>NotificationFactory: Show TokenUnavailable/TokenRequestDenied
        NetworkLayer->>Analytics: Report token error event
    else Success or other error
        NetworkLayer->>Analytics: Report event as needed
    end
Loading

Possibly related PRs

  • Graceful error handling for SSO token retrieval #2996: Introduces new notification enum constants for token-related errors and updates error handling to include these token error cases, directly relating to the current PR’s enhancements for managing token error states and notifications.

Suggested labels

Release Note, QA Note

Suggested reviewers

  • avazirna
  • pm-dimagi
✨ Finishing Touches
  • 📝 Generate Docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ 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.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

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.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @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

@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: 6

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 5667bce and fb0a93e.

📒 Files selected for processing (21)
  • app/res/drawable-anydpi/ic_marker.xml (1 hunks)
  • app/src/org/commcare/activities/CommCareVerificationActivity.java (4 hunks)
  • app/src/org/commcare/activities/EntitySelectActivity.java (2 hunks)
  • app/src/org/commcare/activities/HomeScreenBaseActivity.java (1 hunks)
  • app/src/org/commcare/activities/LoginActivity.java (8 hunks)
  • app/src/org/commcare/activities/LoginActivityUIController.java (6 hunks)
  • app/src/org/commcare/activities/SyncCapableCommCareActivity.java (8 hunks)
  • app/src/org/commcare/connect/network/ConnectNetworkHelper.java (1 hunks)
  • app/src/org/commcare/connect/network/IApiCallback.java (0 hunks)
  • app/src/org/commcare/google/services/analytics/AnalyticsParamValue.java (2 hunks)
  • app/src/org/commcare/google/services/analytics/CCAnalyticsEvent.java (2 hunks)
  • app/src/org/commcare/google/services/analytics/CCAnalyticsParam.java (2 hunks)
  • app/src/org/commcare/google/services/analytics/FirebaseAnalyticsUtil.java (6 hunks)
  • app/src/org/commcare/network/CommcareRequestGenerator.java (5 hunks)
  • app/src/org/commcare/network/HttpCalloutTask.java (4 hunks)
  • app/src/org/commcare/network/HttpUtils.java (2 hunks)
  • app/src/org/commcare/preferences/AppManagerDeveloperPreferences.java (4 hunks)
  • app/src/org/commcare/services/CommCareSessionService.java (1 hunks)
  • app/src/org/commcare/services/FCMMessageData.java (1 hunks)
  • app/src/org/commcare/tasks/ManageKeyRecordTask.java (3 hunks)
  • app/src/org/commcare/views/notifications/NotificationMessageFactory.java (1 hunks)
💤 Files with no reviewable changes (1)
  • app/src/org/commcare/connect/network/IApiCallback.java
🧰 Additional context used
🧬 Code Graph Analysis (1)
app/src/org/commcare/activities/LoginActivity.java (5)
app/src/org/commcare/CommCareApplication.java (1)
  • CommCareApplication (154-1260)
app/src/org/commcare/connect/ConnectConstants.java (1)
  • ConnectConstants (8-84)
app/src/org/commcare/views/notifications/NotificationMessageFactory.java (1)
  • NotificationMessageFactory (20-260)
app/src/org/commcare/connect/network/TokenRequestDeniedException.kt (1)
  • message (14-17)
app/src/org/commcare/connect/network/TokenUnavailableException.kt (1)
  • message (12-15)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: Lint Code Base
🔇 Additional comments (50)
app/src/org/commcare/services/FCMMessageData.java (1)

31-31: The added blank line is purely formatting and has no functional impact. No review necessary.

app/res/drawable-anydpi/ic_marker.xml (1)

1-11: Approve new custom marker icon

The vector drawable is well-defined with appropriate viewport, tint, and path data, and aligns well with the UI requirements for map-related actions.

app/src/org/commcare/services/CommCareSessionService.java (1)

20-22: Import grouping for AndroidX

The androidx.core.app.NotificationCompat and androidx.preference.PreferenceManager imports are correctly placed immediately after the Android framework imports, maintaining a clear separation between platform and support libraries.

app/src/org/commcare/google/services/analytics/CCAnalyticsEvent.java (2)

33-33: New analytics event constant added

The LOGIN_CLICK constant follows existing naming conventions and pairs with the newly introduced reportLoginClicks() method.


52-52: New analytics event constant added

The CCC_REKEYED_DB constant aligns with other CCC_* events and integrates with reportRekeyedDatabase().

app/src/org/commcare/google/services/analytics/AnalyticsParamValue.java (2)

111-111: Added analytics parameter for ConnectID feature.

This new constant adds support for tracking ConnectID enablement in analytics, consistent with other feature flag parameters in this section.


160-163: Minor formatting improvement.

The whitespace changes improve code readability by providing consistent spacing around related constants.

app/src/org/commcare/activities/HomeScreenBaseActivity.java (1)

583-585: Fixed result intent passing for Connect opportunity flow.

You've properly updated the setResult() call to include the created intent, ensuring that the REDIRECT_TO_CONNECT_OPPORTUNITY_INFO flag is correctly passed back to the calling activity.

app/src/org/commcare/activities/EntitySelectActivity.java (1)

723-723: UI improvement: Map icon now shows in action bar.

Good change to use the custom ic_marker drawable and display it in the action bar when there's room, making the map feature more discoverable.

app/src/org/commcare/activities/LoginActivityUIController.java (3)

29-30: Import organization improvement.

Better organization of imports improves code readability.

Also applies to: 50-51


72-74: UI element grouping for better code structure.

Moving the connectLoginButton declaration to group it with other UI elements improves code organization and maintainability.


101-102: Consistent spacing for improved readability.

Adding consistent blank lines between logical sections of code improves readability and follows good coding practices.

Also applies to: 228-229, 462-463

app/src/org/commcare/activities/CommCareVerificationActivity.java (4)

46-47: Added new constant for Connect ID integration.

The new constant KEY_LAUNCH_FROM_CONNECT follows the existing naming pattern and helps identify when the activity is launched from Connect.


73-73: Added flag to track Connect ID origin.

The new fromConnect field appropriately complements the existing fromManager and fromSettings fields.


92-93: Initialized fromConnect flag from intent extras.

The initialization follows the existing pattern used for other origin flags.


137-137: Updated visibility logic to consider Connect ID launch.

The condition correctly includes the new fromConnect flag in the activity visibility check.

app/src/org/commcare/google/services/analytics/CCAnalyticsParam.java (3)

9-9: Added analytics parameter for build number.

This constant follows the established naming pattern for analytics parameters.


15-15: Added analytics parameter for Connect ID enablement.

This parameter will be useful for tracking Connect ID feature usage in analytics.


29-29: Added analytics parameter for notification type.

This constant allows tracking different notification types in analytics reporting.

app/src/org/commcare/tasks/ManageKeyRecordTask.java (3)

12-13: Added imports for token authentication exceptions.

These imports support the new token-based authentication error handling.


220-227: Added error handling for token authentication failures.

The new cases appropriately handle token-specific error conditions following the established pattern in the switch statement.


355-355: Updated method signature to declare token exceptions.

The method now properly declares that it can throw the new token-related exceptions.

app/src/org/commcare/activities/SyncCapableCommCareActivity.java (3)

17-17: Added import for ConnectIDManager.

This import is necessary for the new Connect ID integration logic.


108-114: Added error logging for Connect ID authentication failures.

This change enhances diagnostics by logging specific error information when token authentication fails for Connect ID-managed apps.


458-459: Improved variable declaration formatting.

Split the variable declarations for better readability without changing functionality.

app/src/org/commcare/network/HttpUtils.java (2)

32-33: Proper addition of token authentication support.

The change correctly adds token authentication support by handling the AuthInfo.TokenAuth type in the getCredential method.


78-84: Well-implemented bearer token formatting.

This helper method correctly formats the bearer token authorization header according to the OAuth 2.0 standard.

app/src/org/commcare/network/CommcareRequestGenerator.java (5)

151-203: Well-designed authentication centralization.

You've created a comprehensive method that centralizes authentication logic, making code more maintainable and consistent. The logic handles multiple authentication scenarios properly:

  1. Uses Connect ID tokens when available
  2. Detects when token auth should be available but isn't and logs appropriately
  3. Falls back to current session auth when possible
  4. Uses provided credentials as a final fallback

204-210: Good token invalidation logic.

This method correctly identifies token failures (401 responses) and invalidates the tokens to prevent repeated failures.


222-234: Consistent request update pattern.

The update from direct auth instantiation to using the centralized buildAuth() method is implemented consistently, including proper error handling with checkForTokenError.


276-292: Consistent request update pattern.

This change follows the same pattern as the other methods, maintaining consistency across the codebase.


304-315: Consistent request update pattern.

The simple GET method is properly updated to use centralized auth handling and token error checking.

app/src/org/commcare/preferences/AppManagerDeveloperPreferences.java (3)

25-25: Consistent preference key and title definition.

The new ConnectID preference key and title mapping follow the established pattern.

Also applies to: 32-32


62-69: Well-implemented preference click listener.

The click listener correctly reports analytics and calls the toggle method.


100-100: Default value changed from false to true.

The default value for ConnectID is changed from false to true. This may affect app behavior for new installations. Make sure this is intentional.

app/src/org/commcare/network/HttpCalloutTask.java (4)

5-6: Added imports for new token-related exceptions.

Correctly added imports for token-related exceptions that will be handled.


49-51: New enum values for token-related outcomes.

Added appropriate enum values to represent token authentication failures.


105-111: Comprehensive token exception handling.

The exception handlers for token-related exceptions follow the same pattern as other exception handlers, maintaining consistency.


149-149: Updated method signature to include new exceptions.

The doHttpRequest method signature correctly declares the new token-related exceptions.

app/src/org/commcare/activities/LoginActivity.java (2)

95-97: Consistent ordering of modifiers

The code now consistently uses public static final ordering for constants, which follows Java standard conventions.

Also applies to: 100-103


275-276: Improved code readability with better line breaks

Long method chains and parameter lists have been broken into multiple lines for improved readability, making the code easier to maintain and review.

Also applies to: 589-590, 617-618, 733-734, 767-769

app/src/org/commcare/google/services/analytics/FirebaseAnalyticsUtil.java (9)

45-47: Helpful utility method for simpler event logging

Added a convenient overload for reportEvent() that accepts just an event name without parameters, reducing boilerplate when logging simple events.


93-96: Fixed build profile property setting

The code now correctly checks if the build profile ID is non-empty before setting it as a user property, preventing potential null reference issues.


108-109: Added ConnectID login state tracking

New user property CCC_ENABLED tracks whether the user is logged in with ConnectID, providing valuable analytics data for feature usage.


487-489: New method to track ConnectID sign-out

Added analytics tracking for when users sign out of ConnectID, completing the lifecycle tracking of the feature.


491-493: New method to track login clicks

Added a method to report login clicks, which helps measure user engagement with the authentication features.


495-508: Added screen navigation tracking capability

This navigation listener implementation elegantly captures screen transitions in the app, providing valuable user journey analytics. The implementation correctly handles fragment navigation destinations and extracts relevant information for analytics reporting.


510-514: Added ConnectID tab change tracking

New method to track user navigation between tabs in the Connect interface, providing insights into feature usage patterns.


516-519: Added notification type tracking

New method to report the types of notifications displayed to users, which helps understand the frequency of different system messages.


521-523: Added database rekeying event tracking

New method to report when a database is rekeyed, which helps monitor potential security-related operations.

@shubham1g5 shubham1g5 force-pushed the cccToMasterLoginHome branch from fb0a93e to cd5fe4c Compare May 5, 2025 17:19
Comment on lines 110 to 113
if(ConnectIDManager.getInstance().isSeatedAppLinkedToConnectId(username)) {
Logger.exception("Token auth error for connect managed app",
new Throwable("Token Auth failed during sync for a ConnectID managed app"));
}
Copy link
Contributor Author

Choose a reason for hiding this comment

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

@OrangeAndGreen wondering if it's fine to remove this now as we can land here in a genuine scenario due to token request failing ?

Copy link
Contributor

@OrangeAndGreen OrangeAndGreen May 6, 2025

Choose a reason for hiding this comment

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

I agree that we can get rid of the non-fatal exception since now it is always logged from a better place (in buildAuth), making this a duplicate. However, the sync.fail.auth.loggedin message should probably be changed in this if-case, so it indicates a possibly-temporary network issue rather than a changed password.

Copy link
Contributor

Choose a reason for hiding this comment

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

Another option would be to add PullTaskResult cases for token unavailable and rejected, similar to the new HttpCalloutOutcomes. Currently these exceptions are handled as generic IOExceptions.


this.fromSettings = this.getIntent().
getBooleanExtra(KEY_LAUNCH_FROM_SETTINGS, false);
this.fromConnect = this.getIntent().
Copy link
Contributor

Choose a reason for hiding this comment

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

we have removed this flag

Copy link
Contributor Author

Choose a reason for hiding this comment

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

that is not true anymore after #3072

Comment on lines 110 to 113
if(ConnectIDManager.getInstance().isSeatedAppLinkedToConnectId(username)) {
Logger.exception("Token auth error for connect managed app",
new Throwable("Token Auth failed during sync for a ConnectID managed app"));
}
Copy link
Contributor

@OrangeAndGreen OrangeAndGreen May 6, 2025

Choose a reason for hiding this comment

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

I agree that we can get rid of the non-fatal exception since now it is always logged from a better place (in buildAuth), making this a duplicate. However, the sync.fail.auth.loggedin message should probably be changed in this if-case, so it indicates a possibly-temporary network issue rather than a changed password.

Comment on lines 110 to 113
if(ConnectIDManager.getInstance().isSeatedAppLinkedToConnectId(username)) {
Logger.exception("Token auth error for connect managed app",
new Throwable("Token Auth failed during sync for a ConnectID managed app"));
}
Copy link
Contributor

Choose a reason for hiding this comment

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

Another option would be to add PullTaskResult cases for token unavailable and rejected, similar to the new HttpCalloutOutcomes. Currently these exceptions are handled as generic IOExceptions.

@shubham1g5 shubham1g5 force-pushed the cccToMasterLoginHome branch from 5a561f3 to e0847bf Compare May 7, 2025 19:14
@shubham1g5 shubham1g5 marked this pull request as ready for review May 7, 2025 19:17
@shubham1g5 shubham1g5 added the skip-integration-tests Skip android tests. label May 8, 2025
@shubham1g5
Copy link
Contributor Author

Had one network related failure on integration test which I verified locally and hence running build without integration test now.
@damagatchi retest this please

@shubham1g5
Copy link
Contributor Author

@damagatchi retest this please

@shubham1g5 shubham1g5 merged commit ba1b305 into master May 8, 2025
4 of 10 checks passed
@shubham1g5 shubham1g5 deleted the cccToMasterLoginHome branch May 8, 2025 06:08
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

skip-integration-tests Skip android tests.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants