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

Update component exported attribute #2930

Open
wants to merge 2 commits into
base: commcare_2.55
Choose a base branch
from

Conversation

avazirna
Copy link
Contributor

@avazirna avazirna commented Dec 20, 2024

Summary

Android 14 brought new restrictions around implicit intents and CC app callouts are based on implicit intents, this PR reviews the exported attribute of activities targeted by predefined app callout options.
Ticket: https://dimagi.atlassian.net/browse/QA-7356

PR Checklist

  • If I think the PR is high risk, "High Risk" label is set
  • I have confidence that this PR will not introduce a regression for the reasons below
  • Do we need to enhance manual QA test coverage ? If yes, "QA Note" label is set correctly
  • Does the PR introduce any major changes worth communicating ? If yes, "Release Note" label is set and a "Release Note" is specified in PR description.

@avazirna avazirna changed the base branch from master to commcare_2.55 December 20, 2024 21:46
@avazirna avazirna marked this pull request as ready for review December 20, 2024 21:46
Copy link

coderabbitai bot commented Dec 20, 2024

📝 Walkthrough

Walkthrough

This pull request involves modifications to the Android application's manifest file and a layout resource. In the AndroidManifest.xml, several components have had their android:exported attribute changed from false to true, which increases the accessibility of specific activities and a receiver. The affected components include:

  • DrawingBoundaryActivity
  • NfcWriteActivity
  • NfcReadActivity
  • RefreshToLatestBuildReceiver
  • TemplatePrinterActivity

These changes essentially allow these components to be accessed or invoked by external applications, potentially enhancing the app's interoperability with other system or third-party applications.

Additionally, the progress_dialog_cancel_button.xml layout file has been updated to change the visibility of a MaterialButton from visible to gone, which means the button will no longer be displayed in the user interface.

Sequence Diagram

sequenceDiagram
    participant ExternalApp
    participant CommCareApp
    
    ExternalApp->>CommCareApp: Invoke NfcWriteActivity
    ExternalApp->>CommCareApp: Invoke NfcReadActivity
    ExternalApp->>CommCareApp: Invoke DrawingBoundaryActivity
    ExternalApp->>CommCareApp: Invoke TemplatePrinterActivity
Loading

Possibly related PRs

Suggested reviewers

  • pm-dimagi

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

@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 (3)
app/AndroidManifest.xml (3)

Input Validation Present but Documentation Needed for Template Format

Based on the verification results:

  1. Input validation exists in TemplatePrinterTask.java through the validateString() method which checks for well-formed {{ }} and < > pairs.
  2. Security measures are implemented with encryption for file operations in TemplatePrinterUtils.java.
  3. However, there's no user-facing documentation about the expected template format and intent structure.

Required actions:

  • Add documentation in the codebase (e.g., README.md) describing:
    • The expected intent format for org.commcare.dalvik.action.PRINT
    • Template format requirements (e.g., {{ }} for variables, < > for sections)
    • Supported template styles (TEMPLATE_HTML, TEMPLATE_ZPL)

The existing validation and security measures appear sufficient, so rate limiting isn't necessary for this use case.

🔗 Analysis chain

Line range hint 506-512: Document Printer Integration Requirements

Since TemplatePrinterActivity is now exposed, please:

  1. Document the expected intent format
  2. Add input validation for template data
  3. Consider rate limiting if necessary
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check for existing documentation
fd README.md | xargs rg -l "TemplatePrinter|Print.*Activity"

# Check for input validation
ast-grep --pattern 'validateTemplate($_)' -l java

Length of output: 114


Script:

#!/bin/bash
# Search for the TemplatePrinterActivity class implementation
ast-grep --pattern 'class TemplatePrinterActivity' -l

# Look for any input handling in printer-related activities
rg -l "getIntent|getExtra.*" --type java | xargs rg "class.*Print.*Activity" -A 5

# Search for any existing validation or security checks in printer activities
rg -l "Print.*Activity" --type java | xargs rg "validate|check|security" -A 3

# Look for any documentation in comments
rg -l "Print.*Activity" --type java | xargs rg "/\*\*|//.*print" -B 1 -A 3

Length of output: 20133


Based on the evidence gathered from the codebase, I can now generate the final response:

Security concerns confirmed for RefreshToLatestBuildReceiver

The exposed broadcast receiver lacks proper security controls:

  • No custom permission requirement in the manifest unlike other receivers (e.g., CommCareLogoutReceiver uses org.commcare.dalvik.permission.COMMCARE_LOGOUT)
  • No source validation or build verification in the implementation
  • Only basic checks for app existence and developer preferences
  • Directly launches update activity with FLAG_ACTIVITY_NEW_TASK without user confirmation

Recommendations:

  • Add a custom permission requirement in AndroidManifest.xml
  • Implement source package validation in onReceive()
  • Add build signature verification before proceeding with the update
  • Consider requiring user confirmation before initiating the update process
🔗 Analysis chain

Line range hint 441-447: Verify Build Refresh Security

The RefreshToLatestBuildReceiver being exposed could potentially be used to force app updates. Ensure:

  1. Proper verification of the source application
  2. Validation of the build being installed
  3. User consent mechanisms

Let's search for the receiver implementation and related security measures to verify how the build refresh functionality is secured.


From the initial results, we can see the receiver implementation, but we need to understand the security controls around it, particularly through developer preferences and permissions.


From the previous results, we see the receiver launches RefreshToLatestBuildActivity and uses developer preferences. Let's check the activity implementation and any security validations in the update process.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check for build verification
rg -A 10 "verifyBuild|validateBuild"

# Check for user consent implementation
rg -A 5 "showUpdatePrompt|confirmUpdate"

Length of output: 81


Script:

#!/bin/bash
# Search for the RefreshToLatestBuildReceiver implementation
rg -A 20 "class.*RefreshToLatestBuildReceiver"

# Search for build-related security checks
rg -A 10 "checkPermission|validateSource|validateIntent"

# Look for update-related code
rg -A 10 "updateTo|installBuild|processBuild"

# Search for the action constant usage
rg "org.commcare.dalvik.api.action.RefreshToLatestBuildAction"

Length of output: 10222


Script:

#!/bin/bash
# Let's check for any security-related code in the RefreshToLatestBuildReceiver
rg -A 30 "DeveloperPreferences|MainConfigurablePreferences" app/src/org/commcare/provider/RefreshToLatestBuildReceiver.java

# Check for any permission declarations related to this receiver
rg -B 5 -A 5 "org.commcare.dalvik.permission" app/AndroidManifest.xml

# Look for any security-related preferences
rg -A 5 "DeveloperPreferences.*enable|UPDATE_TARGET" app/src/org/commcare/

Length of output: 13832


Script:

#!/bin/bash
# Check for the RefreshToLatestBuildActivity implementation
rg -A 20 "class.*RefreshToLatestBuildActivity"

# Look for any update validation or security checks in the update process
rg -A 10 "validateUpdate|verifyUpdate|checkUpdate" app/src/org/commcare/

# Check for any developer mode or privilege checks
rg -A 5 "isDeveloperModeEnabled|requiresDeveloperPrivilege" app/src/org/commcare/

Length of output: 12142


Based on the gathered information, I can now provide a final response:

Additional NFC Security Controls Required

The NFC implementation shows basic structure but lacks comprehensive security controls:

  • The base NfcActivity class has encryption key support (NFC_ENCRYPTION_KEY_ARG) but implementation details are not visible
  • Error handling exists but appears minimal (finishWithErrorToast)
  • No clear data validation mechanisms are present in the NFC read/write activities

Required security improvements:

  • Implement robust input validation in NfcWriteActivity before writing NDEF messages
  • Add data sanitization in NfcReadActivity.onNewIntent for incoming NFC data
  • Enhance error handling beyond basic toast messages
  • Document the encryption implementation if present, or add if missing
🔗 Analysis chain

Line range hint 402-408: Verify NFC Security Implementation

The NFC activities being exposed need additional security considerations:

  1. Ensure proper validation of NFC data
  2. Consider encryption for sensitive data
  3. Implement proper error handling for malformed inputs

Also applies to: 411-417


Let me gather more specific information about the NFC implementation.


Let me check one more aspect of the NFC implementation to see how the data is handled.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check for NFC security implementations
echo "Checking for NFC data validation..."
rg -A 5 "getNfcAdapter|createNdefMessage"

# Look for encryption usage
rg -l "encrypt.*NFC|decrypt.*NFC"

Length of output: 276


Script:

#!/bin/bash
# Check NFC activity implementations
echo "Checking NFC activity implementations..."
rg -A 10 "class.*NfcWriteActivity|class.*NfcReadActivity"

# Check for data validation and error handling in NFC related files
echo "Checking NFC data validation and error handling..."
fd -e java -e kt --exec rg -l "try.*catch.*NFC|validate.*NFC|isValid|checkNfc" {} \;

# Look for specific NFC security measures
echo "Checking NFC security implementations..."
ast-grep --pattern 'try {
  $$$
  getNfcAdapter()
  $$$
} catch ($$$) {
  $$$
}'

Length of output: 2873


Script:

#!/bin/bash
# Check NFC base class and data handling
echo "Checking NFC base class implementation..."
rg -A 15 "class NfcActivity" 

# Check for NDEF message handling and validation
echo "Checking NDEF message handling..."
rg -A 10 "handleNdefMessage|onNewIntent|createNdefMessage"

# Look for error handling in NFC activities
echo "Checking error handling..."
rg -A 5 "catch.*Exception.*NFC|onNfcError|handleError" app/src/org/commcare/android/nfc/

Length of output: 3907

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 4238469 and 76b6695.

📒 Files selected for processing (2)
  • app/AndroidManifest.xml (5 hunks)
  • app/res/layout/progress_dialog_cancel_button.xml (1 hunks)
🔇 Additional comments (2)
app/res/layout/progress_dialog_cancel_button.xml (1)

17-17: Verify the UX impact of hiding the cancel button

Changing the button's visibility to "gone" removes the ability for users to cancel operations. Please ensure this won't negatively impact user experience, especially in scenarios where operations might take longer than expected.

app/AndroidManifest.xml (1)

Line range hint 349-355: Verify Drawing Boundary Integration

For DrawingBoundaryActivity:

  1. Ensure proper validation of boundary data
  2. Implement size limits for boundary data
  3. Add proper error handling for invalid inputs
✅ Verification successful

Let's search for the actual implementation and boundary-related code to better understand the validation mechanisms in place.


Let's examine the actual implementation of DrawingBoundaryActivity to understand the current validation and error handling mechanisms.


Boundary validation and limits are partially implemented

The code review reveals that DrawingBoundaryActivity already implements several validation mechanisms:

  1. Location accuracy validation:

    • Enforces minimum accuracy between 10-50 meters (LOCATION_MIN_MIN_ACCURACY and LOCATION_MIN_MAX_ACCURACY)
    • Validates location accuracy against locationMinAccuracy threshold
  2. Boundary data validation:

    • Validates coordinates parsing with error handling
    • Implements distance and time interval checks for tracking points
    • Includes error handling for invalid boundary coordinates
  3. Size/Area handling:

    • Calculates and validates area using AreaCalculator
    • Provides perimeter calculations
    • Includes proper error handling for geometry calculations

However, there's no explicit maximum size limit for the boundary area, which could be a potential improvement.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check for boundary validation
rg -A 5 "validateBoundary|checkBounds"

# Look for size limit implementations
ast-grep --pattern 'getMaxSize|getLimitSize' -l java

Length of output: 95


Script:

#!/bin/bash
# Search for DrawingBoundaryActivity implementation
rg -A 10 "class DrawingBoundaryActivity"

# Search for boundary-related methods in the codebase
rg -A 5 "boundary|Boundary" --type java

# Look for input validation patterns
ast-grep --pattern 'if ($boundary $_) {
  $$$
}'

Length of output: 1759


Script:

#!/bin/bash
# Search for content of DrawingBoundaryActivity.kt
cat app/src/org/commcare/gis/DrawingBoundaryActivity.kt

# Look for any validation or error handling patterns in the GIS module
rg -A 5 "throw|error|exception|validate" app/src/org/commcare/gis/

Length of output: 14625

@@ -346,7 +346,7 @@

<activity
android:name="org.commcare.gis.DrawingBoundaryActivity"
android:exported="false">
android:exported="true">
Copy link

Choose a reason for hiding this comment

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

💡 Codebase verification

⚠️ Potential issue

Based on the gathered information, I can now provide the final response:

Security Review Completed: Additional Protection Required

The exposed components require additional security measures:

  • NFC activities (NfcReadActivity, NfcWriteActivity) handle sensitive data but lack custom permission protection. Add a custom permission requirement similar to CommCareLogoutReceiver.
  • DrawingBoundaryActivity and TemplatePrinterActivity are exposed without permission checks. Implement custom permissions or checkCallingOrSelfPermission().
  • RefreshToLatestBuildReceiver lacks security validation before processing broadcasts. Add signature/system permission protection.

Required changes:

  1. Add custom permission declarations in AndroidManifest.xml for each component
  2. Add android:permission attribute to each component's manifest entry
  3. Implement runtime permission validation in RefreshToLatestBuildReceiver's onReceive()
🔗 Analysis chain

Security Review Required: Components exposed to external applications

Multiple components are being made accessible to external applications. This change requires careful security review:

  1. Ensure each component has proper permission checks
  2. Validate input from external applications
  3. Consider adding custom permissions if needed
  4. Document the security implications for future maintenance

Also applies to: 402-402, 411-411, 441-441, 506-506


Let me gather more information about security checks in these components.


Let me gather one final piece of information about the base NFC activity class since both NFC activities inherit from it.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check for permission checks in these components
echo "Checking DrawingBoundaryActivity for permission checks..."
ast-grep --pattern 'checkCallingOrSelfPermission($_)' -l java

echo "Checking for input validation in NFC activities..."
ast-grep --pattern 'getIntent()' -l java

echo "Checking RefreshToLatestBuildReceiver for security checks..."
rg -A 10 "class RefreshToLatestBuildReceiver"

Length of output: 15095


Script:

#!/bin/bash
# Check for permission declarations in manifest
echo "Checking permission declarations in AndroidManifest.xml..."
rg -A 2 "permission" app/AndroidManifest.xml

# Check for security checks in the activities
echo "Checking NfcWriteActivity for security measures..."
rg -A 10 "class NfcWriteActivity" app/src/org/commcare/android/nfc/

echo "Checking NfcReadActivity for security measures..."
rg -A 10 "class NfcReadActivity" app/src/org/commcare/android/nfc/

echo "Checking DrawingBoundaryActivity for security measures..."
rg -A 10 "class DrawingBoundaryActivity"

echo "Checking TemplatePrinterActivity for security measures..."
rg -A 10 "class TemplatePrinterActivity"

# Check for intent filters
echo "Checking intent filters for these components..."
rg -A 5 "<intent-filter" app/AndroidManifest.xml

Length of output: 15036


Script:

#!/bin/bash
# Check NfcActivity base class for security measures
echo "Checking NfcActivity base class security..."
rg -A 20 "class NfcActivity" app/src/org/commcare/android/nfc/

# Check for custom permissions usage
echo "Checking for custom permission usage..."
rg -B 2 -A 2 "android:permission=" app/AndroidManifest.xml

Length of output: 2656

@avazirna avazirna changed the title Update components exported attribute Update component exported attribute Dec 20, 2024
@avazirna avazirna requested a review from shubham1g5 December 24, 2024 07:33
@shubham1g5
Copy link
Contributor

@avazirna can you link the Android docs reg. restriction you are talking about in PR description.

@avazirna
Copy link
Contributor Author

@avazirna can you link the Android docs reg. restriction you are talking about in PR description.

done @shubham1g5, we might need to consider having an option to allow app callout questions to use explicit intents.

@shubham1g5
Copy link
Contributor

@avazirna I think we need to implement a permission at the very least for these exported components as we don't really want to allow other apps to have access to these.

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.

2 participants