Skip to content

GitHub OAuth Security Enhancement#4

Open
everettbu wants to merge 1 commit into
oauth-state-vulnerablefrom
oauth-state-secure
Open

GitHub OAuth Security Enhancement#4
everettbu wants to merge 1 commit into
oauth-state-vulnerablefrom
oauth-state-secure

Conversation

@everettbu

@everettbu everettbu commented Jul 26, 2025

Copy link
Copy Markdown

Test 4

Summary by CodeRabbit

  • New Features

    • Added an explicit OAuth login step to the GitHub integration setup flow, enhancing user authentication during app installation.
  • Bug Fixes

    • Improved error handling with clearer messages and consistent failure pages during GitHub integration setup.
    • Enhanced validation to prevent installation if the authenticated GitHub user does not match the app installer.
  • Tests

    • Expanded test coverage for OAuth flows, user mismatch scenarios, and installation error handling in the GitHub integration setup.

…#67876)

We're adding one more step in the GitHub integration installation
pipeline, namely GitHub OAuth2 authorize. This is transparent from the
UX perspective as the data exchange happens without user interaction.

The pipeline will now fail in these cases:
- If there is a mismatch between currently authenticated GitHub user
(derived from OAuth2 authorize step) and the user who installed the
GitHub app (https://github.com/apps/sentry-io)
- If there is a mismatch between `state` parameter supplied by user and
pipeline signature
- If GitHub could not generate correct `access_token` from the `code`
(wrong or attempt of re-use of `code`).

In all those cases, this error is shown:

![image](https://github.com/getsentry/sentry/assets/1127549/18923861-2ead-4cf5-adda-7738aef801d7)
@coderabbitai

coderabbitai Bot commented Jul 26, 2025

Copy link
Copy Markdown

Walkthrough

A new OAuth login step is introduced to the GitHub integration pipeline, adding explicit user authentication and validation. The integration flow is updated with centralized error handling, improved installation checks, and stricter user matching. Related tests are expanded to cover OAuth flows, error cases, and user mismatch scenarios. Minor simplification is made to pipeline advancer logic.

Changes

Cohort / File(s) Change Summary
GitHub Integration Pipeline Logic
src/sentry/integrations/github/integration.py
Adds OAuthLoginView for explicit GitHub OAuth login; updates GitHubInstallation to fetch installation ID from request or pipeline state, centralizes error handling, and enforces user match between OAuth and installation sender; adds error and get_document_origin helpers; updates pipeline view sequence to insert OAuth step before installation.
Pipeline Advancer Logic
src/sentry/web/frontend/pipeline_advancer.py
Removes FORWARD_INSTALL_FOR constant; replaces list membership check with direct string comparison for GitHub; moves explanatory comment inline; logic remains unchanged.
GitHub Integration Tests
tests/sentry/integrations/github/test_integration.py
Expands test suite to cover OAuth login and callback, user mismatch, installation conflicts, and error handling; adds new test for user mismatch; extends stubs for OAuth endpoints; updates assertions to check for new error messages and flow redirects; simulates OAuth callback steps in relevant tests.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant Sentry
    participant GitHub

    User->>Sentry: Start GitHub integration
    Sentry->>User: Redirect to GitHub OAuth authorize
    User->>GitHub: Authorize app
    GitHub->>User: Redirect back with code & state
    User->>Sentry: Callback with code & state
    Sentry->>GitHub: Exchange code for access token
    GitHub->>Sentry: Return access token
    Sentry->>GitHub: Fetch user info
    GitHub->>Sentry: Return user login
    Sentry->>User: Redirect to GitHub App installation
    User->>GitHub: Install app
    GitHub->>Sentry: Send installation event (with sender login)
    Sentry->>Sentry: Validate sender login matches OAuth user
    alt Success
        Sentry->>User: Complete integration
    else Failure
        Sentry->>User: Render error page
    end
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Poem

A bunny hopped through OAuth fields,
With tokens, states, and checks revealed—
Now GitHub’s flow is safe and bright,
User and sender must match just right.
If errors arise, the bunny won’t frown,
It sends a clear message, never a frown!
🐇✨

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch oauth-state-secure

🪧 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.
    • Explain this complex logic.
    • 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 explain this code block.
    • @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 explain its main purpose.
    • @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 generate unit tests to generate unit tests for 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.

@coderabbitai

coderabbitai Bot commented Jul 28, 2025

Copy link
Copy Markdown
✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@everettbu

Copy link
Copy Markdown
Author

@coderabbitai review

@coderabbitai

coderabbitai Bot commented Jul 28, 2025

Copy link
Copy Markdown
✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@coderabbitai coderabbitai 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.

Actionable comments posted: 0

🧹 Nitpick comments (1)
src/sentry/integrations/github/integration.py (1)

493-498: Consider handling inactive integrations.

The query filters for ObjectStatus.ACTIVE integrations, but if an integration exists in a different status, it will raise Integration.DoesNotExist and show a generic error. Consider checking for integrations in any status and providing a more specific error message.

-        try:
-            integration = Integration.objects.get(
-                external_id=installation_id, status=ObjectStatus.ACTIVE
-            )
-        except Integration.DoesNotExist:
-            return error(request, self.active_organization)
+        try:
+            integration = Integration.objects.get(external_id=installation_id)
+            if integration.status != ObjectStatus.ACTIVE:
+                return error(
+                    request,
+                    self.active_organization,
+                    error_short="GitHub integration is not active.",
+                    error_long="The GitHub integration exists but is not in an active state. Please contact support if this issue persists."
+                )
+        except Integration.DoesNotExist:
+            return error(request, self.active_organization)
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between ccd14e4 and 843d7c7.

📒 Files selected for processing (3)
  • src/sentry/integrations/github/integration.py (7 hunks)
  • src/sentry/web/frontend/pipeline_advancer.py (1 hunks)
  • tests/sentry/integrations/github/test_integration.py (9 hunks)
🔇 Additional comments (15)
src/sentry/web/frontend/pipeline_advancer.py (1)

37-41: Good simplification of the GitHub provider check.

The refactoring from list membership check to direct string comparison is appropriate since the list only contained a single element. Moving the comment closer to the relevant code also improves readability.

tests/sentry/integrations/github/test_integration.py (7)

15-15: LGTM!

The import is correctly added to support the new test case for GitHub user mismatch validation.


116-124: Well-structured OAuth endpoint mocking.

The OAuth token exchange and user info endpoints are properly mocked with appropriate test data. The hardcoded values are suitable for test fixtures.


232-250: Comprehensive OAuth flow testing.

The updated assert_setup_flow method properly tests the complete OAuth authorization flow, including URL validation, parameter checking, and callback simulation. The flow correctly follows the OAuth 2.0 authorization code grant pattern.


335-343: Correctly updated to include OAuth flow.

The test properly simulates the OAuth callback as part of the installation flow when testing duplicate installations across organizations.


386-397: Good coverage of error handling in OAuth flow.

The test correctly verifies that installation validation occurs after OAuth authentication, ensuring proper error messages are displayed for invalid installations.


399-455: Excellent security test coverage.

The test_github_user_mismatch method thoroughly validates the critical security check that prevents unauthorized users from completing GitHub app installations. The test properly simulates the attack scenario and verifies the appropriate error response.


701-741: Consistent OAuth flow testing in edge cases.

The pending deletion test properly includes OAuth callback simulations both during the error case and after successful deletion, ensuring comprehensive coverage of the OAuth flow in all scenarios.

src/sentry/integrations/github/integration.py (7)

7-7: LGTM!

The imports are appropriately added to support OAuth functionality and improved error handling.

Also applies to: 10-10, 18-19, 42-42


116-118: Clear and helpful error message.

The error message appropriately informs users about authentication verification failures and provides actionable guidance.


129-153: Well-designed error handling utilities.

The error() function provides a centralized way to render error pages with consistent messaging, while get_document_origin() properly handles the customer domains feature flag. These utilities improve code maintainability and user experience.


344-344: Correct pipeline view ordering.

Adding OAuthLoginView before GitHubInstallation ensures proper OAuth authentication flow.


389-441: Secure and well-implemented OAuth flow.

The OAuthLoginView class properly implements the OAuth 2.0 authorization code flow with:

  • CSRF protection via state parameter validation
  • Secure token exchange
  • Proper error handling at each step
  • User authentication verification

The implementation follows security best practices.


448-455: Good flexibility in installation ID retrieval.

The code properly handles installation ID from both direct requests and pipeline state, supporting different entry points into the integration flow.


500-506: Critical security validation.

Excellent implementation of user verification that ensures the authenticated GitHub user matches the installation sender. This prevents unauthorized users from hijacking GitHub app installations.

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