crbench//

← all cases

GitHub OAuth Security Enhancement

Tier 2 medium python · local · real merged PR from getsentry/sentry #67876

Ground-truth defects

d2 · security · medium
OAuth state uses pipeline.signature (static) instead of a per-request random value
d3 · other · medium
The code attempts to access integration.metadata[sender][login] without checking for the existence of the sender key. This causes a KeyError for integrations where the sender metadata was not set during creation

The change under review

diff
diff --git a/src/sentry/integrations/github/integration.py b/src/sentry/integrations/github/integration.py
index 2e157a08961..fa535e4bd4a 100644
--- a/src/sentry/integrations/github/integration.py
+++ b/src/sentry/integrations/github/integration.py
@@ -4,8 +4,10 @@ import logging
 import re
 from collections.abc import Collection, Mapping, Sequence
 from typing import Any
+from urllib.parse import parse_qsl
 
 from django.http import HttpResponse
+from django.urls import reverse
 from django.utils.text import slugify
 from django.utils.translation import gettext_lazy as _
 from rest_framework.request import Request
@@ -13,6 +15,8 @@ from rest_framework.request import Request
 from sentry import features, options
 from sentry.api.utils import generate_organization_url
 from sentry.constants import ObjectStatus
+from sentry.http import safe_urlopen, safe_urlread
+from sentry.identity.github import GitHubIdentityProvider, get_user_info
 from sentry.integrations import (
     FeatureDescription,
     IntegrationFeatures,
@@ -35,6 +39,7 @@ from sentry.tasks.integrations import migrate_repo
 from sentry.tasks.integrations.github.constants import RATE_LIMITED_MESSAGE
 from sentry.tasks.integrations.link_all_repos import link_all_repos
 from sentry.utils import metrics
+from sentry.utils.http import absolute_uri
 from sentry.web.helpers import render_to_response
 
 from .client import GitHubAppsClient, GitHubClientMixin
@@ -108,6 +113,9 @@ API_ERRORS = {
 ERR_INTEGRATION_EXISTS_ON_ANOTHER_ORG = _(
     "It seems that your GitHub account has been installed on another Sentry organization. Please uninstall and try again."
 )
+ERR_INTEGRATION_INVALID_INSTALLATION_REQUEST = _(
+    "We could not verify the authenticity of the installation request. We recommend restarting the installation process."
+)
 ERR_INTEGRATION_PENDING_DELETION = _(
     "It seems that your Sentry organization has an installation pending deletion. Please wait ~15min for the uninstall to complete and try again."
 )
@@ -118,6 +126,32 @@ def build_repository_query(metadata: Mapping[str, Any], name: str, query: str) -
     return f"{account_type}:{name} {query}".encode()
 
 
+def error(
+    request,
+    org,
+    error_short="Invalid installation request.",
+    error_long=ERR_INTEGRATION_INVALID_INSTALLATION_REQUEST,
+):
+    return render_to_response(
+        "sentry/integrations/github-integration-failed.html",
+        context={
+            "error": error_long,
+            "payload": {
+                "success": False,
+                "data": {"error": _(error_short)},
+            },
+            "document_origin": get_document_origin(org),
+        },
+        request=request,
+    )
+
+
+def get_document_origin(org) -> str:
+    if org and features.has("organizations:customer-domains", org.organization):
+        return f'"{generate_organization_url(org.organization.slug)}"'
+    return "document.origin"
+
+
 # Github App docs and list of available endpoints
 # https://docs.github.com/en/rest/apps/installations
 # https://docs.github.com/en/rest/overview/endpoints-available-for-github-apps
@@ -307,7 +341,7 @@ class GitHubIntegrationProvider(IntegrationProvider):
         )
 
     def get_pipeline_views(self) -> Sequence[PipelineView]:
-        return [GitHubInstallation()]
+        return [OAuthLoginView(), GitHubInstallation()]
 
     def get_installation_info(self, installation_id: str) -> Mapping[str, Any]:
         client = self.get_client()
@@ -352,15 +386,72 @@ class GitHubIntegrationProvider(IntegrationProvider):
         )
 
 
+class OAuthLoginView(PipelineView):
+    def dispatch(self, request: Request, pipeline) -> HttpResponse:
+        self.determine_active_organization(request)
+
+        ghip = GitHubIdentityProvider()
+        github_client_id = ghip.get_oauth_client_id()
+        github_client_secret = ghip.get_oauth_client_secret()
+
+        installation_id = request.GET.get("installation_id")
+        if installation_id:
+            pipeline.bind_state("installation_id", installation_id)
+
+        if not request.GET.get("state"):
+            state = pipeline.signature
+
+            redirect_uri = absolute_uri(
+                reverse("sentry-extension-setup", kwargs={"provider_id": "github"})
+            )
+            return self.redirect(
+                f"{ghip.get_oauth_authorize_url()}?client_id={github_client_id}&state={state}&redirect_uri={redirect_uri}"
+            )
+
+        # At this point, we are past the GitHub "authorize" step
+        if request.GET.get("state") != pipeline.signature:
+            return error(request, self.active_organization)
+
+        # similar to OAuth2CallbackView.get_token_params
+        data = {
+            "code": request.GET.get("code"),
+            "client_id": github_client_id,
+            "client_secret": github_client_secret,
+        }
+
+        # similar to OAuth2CallbackView.exchange_token
+        req = safe_urlopen(url=ghip.get_oauth_access_token_url(), data=data)
+
+        try:
+            body = safe_urlread(req).decode("utf-8")
+            payload = dict(parse_qsl(body))
+        except Exception:
+            payload = {}
+
+        if "access_token" not in payload:
+            return error(request, self.active_organization)
+
+        authenticated_user_info = get_user_info(payload["access_token"])
+        if "login" not in authenticated_user_info:
+            return error(request, self.active_organization)
+
+        pipeline.bind_state("github_authenticated_user", authenticated_user_info["login"])
+        return pipeline.next_step()
+
+
 class GitHubInstallation(PipelineView):
     def get_app_url(self) -> str:
         name = options.get("github-app.name")
         return f"https://github.com/apps/{slugify(name)}"
 
     def dispatch(self, request: Request, pipeline: Pipeline) -> HttpResponse:
-        if "installation_id" not in request.GET:
+        installation_id = request.GET.get(
+            "installation_id", pipeline.fetch_state("installation_id")
+        )
+        if installation_id is None:
             return self.redirect(self.get_app_url())
 
+        pipeline.bind_state("installation_id", installation_id)
         self.determine_active_organization(request)
 
         integration_pending_deletion_exists = False
@@ -374,57 +465,43 @@ class GitHubInstallation(PipelineView):
             ).exists()
 
         if integration_pending_deletion_exists:
-            document_origin = "document.origin"
-            if self.active_organization and features.has(
-                "organizations:customer-domains", self.active_organization.organization
-            ):
-                document_origin = (
-                    f'"{generate_organization_url(self.active_organization.organization.slug)}"'
-                )
-            return render_to_response(
-                "sentry/integrations/github-integration-failed.html",
-                context={
-                    "error": ERR_INTEGRATION_PENDING_DELETION,
-                    "payload": {
-                        "success": False,
-                        "data": {"error": _("GitHub installation pending deletion.")},
-                    },
-                    "document_origin": document_origin,
-                },
-                request=request,
+            return error(
+                request,
+                self.active_organization,
+                error_short="GitHub installation pending deletion.",
+                error_long=ERR_INTEGRATION_PENDING_DELETION,
             )
 
         try:
             # We want to limit GitHub integrations to 1 organization
             installations_exist = OrganizationIntegration.objects.filter(
-                integration=Integration.objects.get(external_id=request.GET["installation_id"])
+                integration=Integration.objects.get(external_id=installation_id)
             ).exists()
 
         except Integration.DoesNotExist:
-            pipeline.bind_state("installation_id", request.GET["installation_id"])
             return pipeline.next_step()
 
         if installations_exist:
-            document_origin = "document.origin"
-            if self.active_organization and features.has(
-                "organizations:customer-domains", self.active_organization.organization
-            ):
-                document_origin = (
-                    f'"{generate_organization_url(self.active_organization.organization.slug)}"'
-                )
-            return render_to_response(
-                "sentry/integrations/github-integration-failed.html",
-                context={
-                    "error": ERR_INTEGRATION_EXISTS_ON_ANOTHER_ORG,
-                    "payload": {
-                        "success": False,
-                        "data": {"error": _("Github installed on another Sentry organization.")},
-                    },
-                    "document_origin": document_origin,
-                },
-                request=request,
+            return error(
+                request,
+                self.active_organization,
+                error_short="Github installed on another Sentry organization.",
+                error_long=ERR_INTEGRATION_EXISTS_ON_ANOTHER_ORG,
             )
 
         # OrganizationIntegration does not exist, but Integration does exist.
-        pipeline.bind_state("installation_id", request.GET["installation_id"])
+        try:
+            integration = Integration.objects.get(
+                external_id=installation_id, status=ObjectStatus.ACTIVE
+            )
+        except Integration.DoesNotExist:
+            return error(request, self.active_organization)
+
+        # Check that the authenticated GitHub user is the same as who installed the app.
+        if (
+            pipeline.fetch_state("github_authenticated_user")
+            != integration.metadata["sender"]["login"]
+        ):
+            return error(request, self.active_organization)
+
         return pipeline.next_step()
diff --git a/src/sentry/web/frontend/pipeline_advancer.py b/src/sentry/web/frontend/pipeline_advancer.py
index 63183a4d271..cfe97929605 100644
--- a/src/sentry/web/frontend/pipeline_advancer.py
+++ b/src/sentry/web/frontend/pipeline_advancer.py
@@ -16,12 +16,6 @@ from sentry.web.frontend.base import BaseView
 PIPELINE_CLASSES = [IntegrationPipeline, IdentityProviderPipeline]
 
 
-# GitHub apps may be installed directly from GitHub, in which case
-# they will redirect here *without* being in the pipeline. If that happens
-# redirect to the integration install org picker.
-FORWARD_INSTALL_FOR = ["github"]
-
-
 from rest_framework.request import Request
 
 
@@ -40,8 +34,11 @@ class PipelineAdvancerView(BaseView):
             if pipeline:
                 break
 
+        # GitHub apps may be installed directly from GitHub, in which case
+        # they will redirect here *without* being in the pipeline. If that happens
+        # redirect to the integration install org picker.
         if (
-            provider_id in FORWARD_INSTALL_FOR
+            provider_id == "github"
             and request.GET.get("setup_action") == "install"
             and pipeline is None
         ):
diff --git a/tests/sentry/integrations/github/test_integration.py b/tests/sentry/integrations/github/test_integration.py
index c6417da8ab9..895219d1706 100644
--- a/tests/sentry/integrations/github/test_integration.py
+++ b/tests/sentry/integrations/github/test_integration.py
@@ -12,6 +12,7 @@ import responses
 from django.urls import reverse
 
 import sentry
+from fixtures.github import INSTALLATION_EVENT_EXAMPLE
 from sentry.api.utils import generate_organization_url
 from sentry.constants import ObjectStatus
 from sentry.integrations.github import (
@@ -32,6 +33,7 @@ from sentry.shared_integrations.exceptions import ApiError
 from sentry.silo.base import SiloMode
 from sentry.testutils.cases import IntegrationTestCase
 from sentry.testutils.silo import assume_test_silo_mode, control_silo_test
+from sentry.utils import json
 from sentry.utils.cache import cache
 
 TREE_RESPONSES = {
@@ -111,6 +113,15 @@ class GitHubIntegrationTest(IntegrationTestCase):
         self.gh_org = "Test-Organization"
         pp = 1
 
+        access_token = "xxxxx-xxxxxxxxx-xxxxxxxxxx-xxxxxxxxxxxx"
+        responses.add(
+            responses.POST,
+            "https://github.com/login/oauth/access_token",
+            body=f"access_token={access_token}",
+        )
+
+        responses.add(responses.GET, self.base_url + "/user", json={"login": "octocat"})
+
         responses.add(
             responses.POST,
             self.base_url + f"/app/installations/{self.installation_id}/access_tokens",
@@ -218,6 +229,24 @@ class GitHubIntegrationTest(IntegrationTestCase):
         redirect = urlparse(resp["Location"])
         assert redirect.scheme == "https"
         assert redirect.netloc == "github.com"
+        assert redirect.path == "/login/oauth/authorize"
+        assert (
+            redirect.query
+            == "client_id=github-client-id&state=9cae5e88803f35ed7970fc131e6e65d3&redirect_uri=http://testserver/extensions/github/setup/"
+        )
+
+        resp = self.client.get(
+            "{}?{}".format(
+                self.setup_path,
+                urlencode(
+                    {"code": "12345678901234567890", "state": "9cae5e88803f35ed7970fc131e6e65d3"}
+                ),
+            )
+        )
+        assert resp.status_code == 302
+        redirect = urlparse(resp["Location"])
+        assert redirect.scheme == "https"
+        assert redirect.netloc == "github.com"
         assert redirect.path == "/apps/sentry-test-app"
 
         # App installation ID is provided
@@ -225,7 +254,7 @@ class GitHubIntegrationTest(IntegrationTestCase):
             "{}?{}".format(self.setup_path, urlencode({"installation_id": self.installation_id}))
         )
 
-        auth_header = responses.calls[0].request.headers["Authorization"]
+        auth_header = responses.calls[2].request.headers["Authorization"]
         assert auth_header == "Bearer jwt_token_1"
 
         self.assertDialogSuccess(resp)
@@ -303,8 +332,15 @@ class GitHubIntegrationTest(IntegrationTestCase):
             ),
             urlencode({"installation_id": self.installation_id}),
         )
+        self.setup_path_2 = "{}?{}".format(
+            self.setup_path,
+            urlencode(
+                {"code": "12345678901234567890", "state": "9cae5e88803f35ed7970fc131e6e65d3"}
+            ),
+        )
         with self.feature({"organizations:customer-domains": [self.organization_2.slug]}):
             resp = self.client.get(self.init_path_2)
+            resp = self.client.get(self.setup_path_2)
             self.assertTemplateUsed(resp, "sentry/integrations/github-integration-failed.html")
             assert (
                 b'{"success":false,"data":{"error":"Github installed on another Sentry organization."}}'
@@ -330,6 +366,8 @@ class GitHubIntegrationTest(IntegrationTestCase):
 
         # Try again and should be successful
         resp = self.client.get(self.init_path_2)
+        resp = self.client.get(self.setup_path_2)
+
         self.assertDialogSuccess(resp)
         integration = Integration.objects.get(external_id=self.installation_id)
         assert integration.provider == "github"
@@ -347,7 +385,73 @@ class GitHubIntegrationTest(IntegrationTestCase):
         resp = self.client.get(
             "{}?{}".format(self.setup_path, urlencode({"installation_id": self.installation_id}))
         )
-        assert b"The GitHub installation could not be found." in resp.content
+        resp = self.client.get(
+            "{}?{}".format(
+                self.setup_path,
+                urlencode(
+                    {"code": "12345678901234567890", "state": "ddd023d87a913d5226e2a882c4c4cc05"}
+                ),
+            )
+        )
+        assert b"Invalid installation request." in resp.content
+
+    @responses.activate
+    def test_github_user_mismatch(self):
+        self._stub_github()
+
+        # Emulate GitHub installation
+        init_path_1 = "{}?{}".format(
+            reverse(
+                "sentry-organization-integrations-setup",
+                kwargs={
+                    "organization_slug": self.organization.slug,
+                    "provider_id": self.provider.key,
+                },
+            ),
+            urlencode({"installation_id": self.installation_id}),
+        )
+        self.client.get(init_path_1)
+
+        webhook_event = json.loads(INSTALLATION_EVENT_EXAMPLE)
+        webhook_event["installation"]["id"] = self.installation_id
+        webhook_event["sender"]["login"] = "attacker"
+        resp = self.client.post(
+            path="/extensions/github/webhook/",
+            data=json.dumps(webhook_event),
+            content_type="application/json",
+            HTTP_X_GITHUB_EVENT="installation",
+            HTTP_X_HUB_SIGNATURE="sha1=d184e6717f8bfbcc291ebc8c0756ee446c6c9486",
+            HTTP_X_GITHUB_DELIVERY="00000000-0000-4000-8000-1234567890ab",
+        )
+        assert resp.status_code == 204
+
+        # Validate the installation user
+        user_2 = self.create_user("foo@example.com")
+        org_2 = self.create_organization(name="Rowdy Tiger", owner=user_2)
+        self.login_as(user_2)
+        init_path_2 = "{}?{}".format(
+            reverse(
+                "sentry-organization-integrations-setup",
+                kwargs={
+                    "organization_slug": org_2.slug,
+                    "provider_id": self.provider.key,
+                },
+            ),
+            urlencode({"installation_id": self.installation_id}),
+        )
+        setup_path_2 = "{}?{}".format(
+            self.setup_path,
+            urlencode(
+                {"code": "12345678901234567890", "state": "9cae5e88803f35ed7970fc131e6e65d3"}
+            ),
+        )
+        with self.feature({"organizations:customer-domains": [org_2.slug]}):
+            resp = self.client.get(init_path_2)
+            resp = self.client.get(setup_path_2)
+            self.assertTemplateUsed(resp, "sentry/integrations/github-integration-failed.html")
+            assert resp.status_code == 200
+            assert b'window.opener.postMessage({"success":false' in resp.content
+            assert b"Invalid installation request." in resp.content
 
     @responses.activate
     def test_disable_plugin_when_fully_migrated(self):
@@ -594,6 +698,17 @@ class GitHubIntegrationTest(IntegrationTestCase):
             resp = self.client.get(
                 "{}?{}".format(self.init_path, urlencode({"installation_id": self.installation_id}))
             )
+            resp = self.client.get(
+                "{}?{}".format(
+                    self.setup_path,
+                    urlencode(
+                        {
+                            "code": "12345678901234567890",
+                            "state": "9cae5e88803f35ed7970fc131e6e65d3",
+                        }
+                    ),
+                )
+            )
 
         assert resp.status_code == 200
         self.assertTemplateUsed(resp, "sentry/integrations/github-integration-failed.html")
@@ -615,6 +730,14 @@ class GitHubIntegrationTest(IntegrationTestCase):
         resp = self.client.get(
             "{}?{}".format(self.init_path, urlencode({"installation_id": self.installation_id}))
         )
+        resp = self.client.get(
+            "{}?{}".format(
+                self.setup_path,
+                urlencode(
+                    {"code": "12345678901234567890", "state": "9cae5e88803f35ed7970fc131e6e65d3"}
+                ),
+            )
+        )
         self.assertDialogSuccess(resp)
         integration = Integration.objects.get(external_id=self.installation_id)
         assert integration.provider == "github"

Leaderboard for this case

medium · 4 of 9 bots fully caught it (44% solve rate) · 67% avg coverage.

#BotResultCaughtCoverageFindingsFalse alarms
1 cursor solved 2/2 100.0% 2 0
2 Drape (Deep Review) solved 2/2 100.0% 7 0
3 Drape (Review) solved 2/2 100.0% 4 0
4 qodo solved 2/2 100.0% 4 0
5 greptile partial 1/2 50.0% 3 0
6 Mjolnir (Opus 5.5) partial 1/2 50.0% 2 0
7 Mjolnir (Sonnet 5.5) partial 1/2 50.0% 2 0
8 Claude Code (Opus 5.5) partial 1/2 50.0% 4 1
9 Cubic miss 0/2 0.0% 3 0

Bot results

Claude Code (Opus 5.5) · cross-file engine perris 0.11.1+proven.tiered0.25.call.read.subclass.type
DefectSeverityFoundGrade
d2 medium ✗ —
d3 medium ✓ off by one
valid · matches d3 · impact medium
valid · impact medium
The new installer-match check only runs when the Integration row exists. In the DoesNotExist branch the code calls next_step() without checking github_authenticated_user, so the security fix is incomplete. Exploiting it means winning a race against the webhook. [grounded: tree src/sentry/integrations/github/integration.py] [consensus 3/3: valid=3]
valid · impact low
The new authorize URL is built with an f-string and nothing is URL-encoded. In practice the values are a hex signature, an alphanumeric client id and a plain path, so a malformed URL is unlikely, but the claim about the code is accurate. [grounded: diff] [consensus 3/3: valid=3]
invalid
The pipeline is tied to the user's own session, and GitHubInstallation reads installation_id from request.GET anyway. Overwriting the stored value in OAuthLoginView gives the requester no extra capability, and the state check and sender match still apply. [invalid: contradiction] [consensus 3/3: invalid=3]
raw comments (4)
src/sentry/integrations/github/integration.py:503
`integration.metadata["sender"]["login"]` assumes every existing Integration has `sender` in its metadata. It is only set when the install webhook arrives (webhook.py), and `build_integration` only adds it when `state.get("sender")` is set. Integrations created before that, or whose webhook never arrived, will raise a KeyError here, so reinstalling an orphaned integration (one with no OrganizationIntegration) fails with a 500 instead of a handled error page. Use `.get()` and treat a missing sender as a failed check.
src/sentry/integrations/github/integration.py:482
The check that the OAuth-authenticated GitHub user matches the installer only runs when an Integration row already exists. If the Integration doesn't exist yet (for example, the installation webhook hasn't arrived), the code goes straight to `pipeline.next_step()` without comparing `github_authenticated_user` to anyone. A user who knows or guesses a fresh installation_id can race the webhook and link someone else's GitHub installation to their own Sentry org, which is the attack this change is meant to stop.
src/sentry/integrations/github/integration.py:409
The OAuth authorize URL is built with an f-string, and `redirect_uri`, `client_id` and `state` are not URL-encoded. If the absolute URI contains query characters or the configured values contain `&` or `#`, the URL will be malformed. Build it with `urlencode`.
src/sentry/integrations/github/integration.py:399
`installation_id` from the query string is bound into pipeline state on every OAuthLoginView request, including the OAuth callback, before the `state` parameter is checked. Any request carrying `installation_id` can overwrite the stored installation for the in-progress pipeline. Only bind it on the initial request, before the redirect to GitHub.
Cubic · cross-file engine perris 0.11.1+proven.tiered0.25.call.read.subclass.type
DefectSeverityFoundGrade
d2 medium ✗ —
d3 medium ✗ —
valid · impact medium
The new authenticated-user check only runs when the Integration already exists. In the DoesNotExist branch the code advances straight to next_step, build_integration gets no sender, and the OAuth login is never compared against the installation. The fix is incomplete across the two branches; exploiting it needs a race with the webhook. [grounded: tree src/sentry/integrations/github/integration.py] [consensus 5/5: valid=5]
valid · impact low
get_user_info calls resp.raise_for_status() (src/sentry/identity/github/provider.py) and the new OAuthLoginView never catches the error. A non-2xx response from GitHub therefore surfaces as an unhandled exception (a 500) instead of the error page. [grounded: diff] [consensus 5/5: valid=5]
valid · impact low
With OAuthLoginView now the first step, the first request redirects to OAuth and the second fails the state check, so the error comes from the state mismatch. The 404 installation stub is never reached, and the not-found path is no longer tested. [grounded: diff] [consensus 5/5: valid=5]
raw comments (4)
src/sentry/integrations/github/integration.py:501
<!-- cubic:v=6cba4da9-3a70-491e-a223-166b0cee12af --> <!-- cubic:review-run=33334f34-9236-5f34-833b-8e62ed98b93a --> <!-- metadata:{"confidence":8} --> P1: When the installation webhook has not created the `Integration` yet, this new identity check is skipped and the newly built integration has no trusted installer identity. Validate the authenticated user against the installation before advancing through the new-integration path, or reject installations lacking trusted sender data. <details> <summary>Prompt for AI agents</summary> ```text Check if this issue is valid — if so, understand the root cause and fix it. At src/sentry/integrations/github/integration.py, line 501: <comment>When the installation webhook has not created the `Integration` yet, this new identity check is skipped and the newly built integration has no trusted installer identity. Validate the authenticated user against the installation before advancing through the new-integration path, or reject installations lacking trusted sender data.</comment> <file context> @@ -374,57 +465,43 @@ def dispatch(self, request: Request, pipeline: Pipeline) -> HttpResponse: + return error(request, self.active_organization) + + # Check that the authenticated GitHub user is the same as who installed the app. + if ( + pipeline.fetch_state("github_authenticated_user") + != integration.metadata["sender"]["login"] </file context> ``` </details>
src/sentry/integrations/github/integration.py:434
<!-- cubic:v=402ccd3e-b209-412a-ab9e-079f7e2a5781 --> <!-- cubic:review-run=33334f34-9236-5f34-833b-8e62ed98b93a --> <!-- metadata:{"confidence":9} --> P2: When GitHub's user lookup fails or returns a non-2xx response, `get_user_info` raises and the OAuth callback returns an unhandled 500. Catch the provider/request error and render the existing installation error response instead. <details> <summary>Prompt for AI agents</summary> ```text Check if this issue is valid — if so, understand the root cause and fix it. At src/sentry/integrations/github/integration.py, line 434: <comment>When GitHub's user lookup fails or returns a non-2xx response, `get_user_info` raises and the OAuth callback returns an unhandled 500. Catch the provider/request error and render the existing installation error response instead.</comment> <file context> @@ -352,15 +386,72 @@ def setup(self) -> None: + if "access_token" not in payload: + return error(request, self.active_organization) + + authenticated_user_info = get_user_info(payload["access_token"]) + if "login" not in authenticated_user_info: + return error(request, self.active_organization) </file context> ``` </details>
tests/sentry/integrations/github/test_integration.py:396
<!-- cubic:v=f895496e-f2c8-4eff-9d49-062a754420ef --> <!-- cubic:review-run=33334f34-9236-5f34-833b-8e62ed98b93a --> <!-- metadata:{"confidence":8} --> P2: test_installation_not_found no longer tests the installation-not-found path. With the new flow the GET setup_path?installation_id returns a 302 to the OAuth authorize URL (no state), so the responses.replace(... status=404) stub is never hit, and 'Invalid installation request.' is produced by the mismatched state (ddd023… ≠ signature 9cae5e…), not by a 404. The 404 behavior ('The GitHub installation could not be found.') is now untested and the dead stub should be removed or the test updated to hit the 404 through the new flow. <details> <summary>Prompt for AI agents</summary> ```text Check if this issue is valid — if so, understand the root cause and fix it. At tests/sentry/integrations/github/test_integration.py, line 396: <comment>test_installation_not_found no longer tests the installation-not-found path. With the new flow the GET setup_path?installation_id returns a 302 to the OAuth authorize URL (no state), so the responses.replace(... status=404) stub is never hit, and 'Invalid installation request.' is produced by the mismatched state (ddd023… ≠ signature 9cae5e…), not by a 404. The 404 behavior ('The GitHub installation could not be found.') is now untested and the dead stub should be removed or the test updated to hit the 404 through the new flow.</comment> <file context> @@ -347,7 +385,73 @@ def test_installation_not_found(self): + ), + ) + ) + assert b"Invalid installation request." in resp.content + + @responses.activate </file context> ``` </details>
PR-level
<!-- cubic:review-summary:start --> **3 issues found** across 3 files <!-- cubic:review-summary:end --> <details> <summary>Prompt for AI agents (unresolved issues)</summary> ```text Check if these issues are valid — if so, understand the root cause of each and fix them. If appropriate, use sub-agents to investigate and fix each issue separately. <file name="src/sentry/integrations/github/integration.py"> <violation number="1" location="src/sentry/integrations/github/integration.py:434"> P2: When GitHub's user lookup fails or returns a non-2xx response, `get_user_info` raises and the OAuth callback returns an unhandled 500. Catch the provider/request error and render the existing installation error response instead.</violation> <violation number="2" location="src/sentry/integrations/github/integration.py:501"> P1: When the installation webhook has not created the `Integration` yet, this new identity check is skipped and the newly built integration has no trusted installer identity. Validate the authenticated user against the installation before advancing through the new-integration path, or reject installations lacking trusted sender data.</violation> </file> <file name="tests/sentry/integrations/github/test_integration.py"> <violation number="1" location="tests/sentry/integrations/github/test_integration.py:396"> P2: test_installation_not_found no longer tests the installation-not-found path. With the new flow the GET setup_path?installation_id returns a 302 to the OAuth authorize URL (no state), so the responses.replace(... status=404) stub is never hit, and 'Invalid installation request.' is produced by the mismatched state (ddd023… ≠ signature 9cae5e…), not by a 404. The 404 behavior ('The GitHub installation could not be found.') is now untested and the dead stub should be removed or the test updated to hit the 404 through the new flow.</violation> </file> ``` </details> <sub>Reply with feedback, questions, or to request a fix.<br /><br />[Re-trigger cubic](https://www.cubic.dev/action/re-review/pr/drape-io/crbench-cubic-2026-09/73/ai_pr_review_github_delivery_971a8ee83f62f22dc2c2417d84d8fefe0a84a03414cfdec7be93171894c3acb1?returnTo=https%3A%2F%2Fgithub.com%2Fdrape-io%2Fcrbench-cubic-2026-09%2Fpull%2F73)</sub> <!-- cubic:review-post:ai_pr_review_github_delivery_971a8ee83f62f22dc2c2417d84d8fefe0a84a03414cfdec7be93171894c3acb1:7ee3658779259f597b7886551f380a5342145ddf:33334f34-9236-5f34-833b-8e62ed98b93a -->
cursor · cross-file engine perris 0.11.1+proven.tiered0.25.call.read.subclass.type
DefectSeverityFoundGrade
d2 medium ✓ exact
d3 medium ✓ exact
valid · matches d2 · impact medium
valid · matches d3 · impact medium
raw comments (3)
src/sentry/integrations/github/integration.py:412
### OAuth state is predictable **Medium Severity** <!-- DESCRIPTION START --> `OAuthLoginView` uses `pipeline.signature` as the OAuth `state` value. That signature is an MD5 of the pipeline view class names, so it is the same for every GitHub install. The existing `OAuth2LoginView` generates a per-session `secrets.token_hex()` instead. A static `state` lets an attacker reuse a known value on the callback while a victim has an active pipeline, which can bind the attacker’s GitHub identity and `installation_id` to the victim’s org. <!-- DESCRIPTION END --> <!-- BUGBOT_BUG_ID: c6a77857-26c5-4348-87f3-8917e76b0f6c --> <!-- LOCATIONS START src/sentry/integrations/github/integration.py#L400-L412 LOCATIONS END --> <div><a href="https://cursor.com/open?link=eyJ2ZXJzaW9uIjoxLCJ0eXBlIjoiQlVHQk9UX0ZJWF9JTl9DVVJTT1IiLCJkYXRhIjp7InJlZGlzS2V5IjoiYnVnYm90OjZhYzlkNWNhLWQ0OTEtNDI5OC1hYjQ3LTZjZGNjZjEyNTUzNCIsImVuY3J5cHRpb25LZXkiOiI1QWJQS3FLLVVLYm5qLXd1Y3RiVHpoc3h3aDFqM3JlN2RkRXlERkJYU3lrIiwiYnJhbmNoIjoidDItc2VudHJ5LTY3ODc2IiwicmVwb093bmVyIjoiZHJhcGUtaW8iLCJyZXBvTmFtZSI6ImNyYmVuY2gtY3Vyc29yLTIwMjYtMDkiLCJwcm92aWRlciI6ImdpdGh1YiJ9fQ" target="_blank" rel="noopener noreferrer"><picture><source media="(prefers-color-scheme: dark)" srcset="https://cursor.com/assets/images/fix-in-cursor-dark.png"><source media="(prefers-color-scheme: light)" srcset="https://cursor.com/assets/images/fix-in-cursor-light.png"><img alt="Fix in Cursor" width="115" height="28" src="https://cursor.com/assets/images/fix-in-cursor-dark.png"></picture></a>&nbsp;<a href="https://cursor.com/agents?link=eyJ2ZXJzaW9uIjoxLCJ0eXBlIjoiQlVHQk9UX0ZJWF9JTl9XRUIiLCJkYXRhIjp7InJlZGlzS2V5IjoiYnVnYm90OjZhYzlkNWNhLWQ0OTEtNDI5OC1hYjQ3LTZjZGNjZjEyNTUzNCIsImVuY3J5cHRpb25LZXkiOiI1QWJQS3FLLVVLYm5qLXd1Y3RiVHpoc3h3aDFqM3JlN2RkRXlERkJYU3lrIiwiYnJhbmNoIjoidDItc2VudHJ5LTY3ODc2IiwicmVwb093bmVyIjoiZHJhcGUtaW8iLCJyZXBvTmFtZSI6ImNyYmVuY2gtY3Vyc29yLTIwMjYtMDkiLCJwck51bWJlciI6NzUsImNvbW1pdFNoYSI6ImZiZDFhZmYxZjQ4NTVlMWUwMTUxMDdlNjJkNWZiZDAyNmY1ZWJhZDAiLCJwcm92aWRlciI6ImdpdGh1YiJ9fQ" target="_blank" rel="noopener noreferrer"><picture><source media="(prefers-color-scheme: dark)" srcset="https://cursor.com/assets/images/fix-in-web-dark.png"><source media="(prefers-color-scheme: light)" srcset="https://cursor.com/assets/images/fix-in-web-light.png"><img alt="Fix in Web" width="99" height="28" src="https://cursor.com/assets/images/fix-in-web-dark.png"></picture></a></div> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit fbd1aff1f4855e1e015107e62d5fbd026f5ebad0. Configure [here](https://www.cursor.com/dashboard/bugbot).</sup>
src/sentry/integrations/github/integration.py:504
### Sender metadata lookup can crash **Medium Severity** <!-- DESCRIPTION START --> The new installer check reads `integration.metadata["sender"]["login"]` without guarding a missing `sender`. `build_integration` only copies `sender` when it is present in pipeline state, and `GitHubIntegrationsInstallationEndpoint` already treats missing `sender` as a valid case. Integrations created or updated without that key will raise `KeyError` instead of the installation error page. <!-- DESCRIPTION END --> <!-- BUGBOT_BUG_ID: 1b17115b-36e0-4952-935f-549da6ba9ed5 --> <!-- LOCATIONS START src/sentry/integrations/github/integration.py#L500-L504 LOCATIONS END --> <div><a href="https://cursor.com/open?link=eyJ2ZXJzaW9uIjoxLCJ0eXBlIjoiQlVHQk9UX0ZJWF9JTl9DVVJTT1IiLCJkYXRhIjp7InJlZGlzS2V5IjoiYnVnYm90Ojc2NTBiMTgyLWZkMGYtNGQ3YS04NDE1LTc3NjA0MjI1MGFmYSIsImVuY3J5cHRpb25LZXkiOiIxOGlhWWluaWUwekUxdlB4WjJrYTQzLXJtU25DLTFzV2VMMUcyTGpTc0ZRIiwiYnJhbmNoIjoidDItc2VudHJ5LTY3ODc2IiwicmVwb093bmVyIjoiZHJhcGUtaW8iLCJyZXBvTmFtZSI6ImNyYmVuY2gtY3Vyc29yLTIwMjYtMDkiLCJwcm92aWRlciI6ImdpdGh1YiJ9fQ" target="_blank" rel="noopener noreferrer"><picture><source media="(prefers-color-scheme: dark)" srcset="https://cursor.com/assets/images/fix-in-cursor-dark.png"><source media="(prefers-color-scheme: light)" srcset="https://cursor.com/assets/images/fix-in-cursor-light.png"><img alt="Fix in Cursor" width="115" height="28" src="https://cursor.com/assets/images/fix-in-cursor-dark.png"></picture></a>&nbsp;<a href="https://cursor.com/agents?link=eyJ2ZXJzaW9uIjoxLCJ0eXBlIjoiQlVHQk9UX0ZJWF9JTl9XRUIiLCJkYXRhIjp7InJlZGlzS2V5IjoiYnVnYm90Ojc2NTBiMTgyLWZkMGYtNGQ3YS04NDE1LTc3NjA0MjI1MGFmYSIsImVuY3J5cHRpb25LZXkiOiIxOGlhWWluaWUwekUxdlB4WjJrYTQzLXJtU25DLTFzV2VMMUcyTGpTc0ZRIiwiYnJhbmNoIjoidDItc2VudHJ5LTY3ODc2IiwicmVwb093bmVyIjoiZHJhcGUtaW8iLCJyZXBvTmFtZSI6ImNyYmVuY2gtY3Vyc29yLTIwMjYtMDkiLCJwck51bWJlciI6NzUsImNvbW1pdFNoYSI6ImZiZDFhZmYxZjQ4NTVlMWUwMTUxMDdlNjJkNWZiZDAyNmY1ZWJhZDAiLCJwcm92aWRlciI6ImdpdGh1YiJ9fQ" target="_blank" rel="noopener noreferrer"><picture><source media="(prefers-color-scheme: dark)" srcset="https://cursor.com/assets/images/fix-in-web-dark.png"><source media="(prefers-color-scheme: light)" srcset="https://cursor.com/assets/images/fix-in-web-light.png"><img alt="Fix in Web" width="99" height="28" src="https://cursor.com/assets/images/fix-in-web-dark.png"></picture></a></div> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit fbd1aff1f4855e1e015107e62d5fbd026f5ebad0. Configure [here](https://www.cursor.com/dashboard/bugbot).</sup>
PR-level
<!-- BUGBOT_REVIEW --> Cursor Bugbot has reviewed your changes using high effort and found 2 potential issues. <!-- BUGBOT_FIX_ALL --> <a href="https://cursor.com/open?link=eyJ2ZXJzaW9uIjoxLCJ0eXBlIjoiQlVHQk9UX0ZJWF9BTExfSU5fQ1VSU09SIiwiZGF0YSI6eyJyZWRpc0tleSI6ImJ1Z2JvdC1tdWx0aTo0MjMxOTQ3Yy01NGY4LTRiYzMtOTQ3OS0yYjM0ZGI4Mjc1MWYiLCJlbmNyeXB0aW9uS2V5IjoiZEJzR2N0ZnVLZ195bFFFQTVuYUFpRnJoMms1a0kwSWl6U3FTNkxZLUNxayIsImJyYW5jaCI6InQyLXNlbnRyeS02Nzg3NiIsInJlcG9Pd25lciI6ImRyYXBlLWlvIiwicmVwb05hbWUiOiJjcmJlbmNoLWN1cnNvci0yMDI2LTA5IiwicHJvdmlkZXIiOiJnaXRodWIifX0" target="_blank" rel="noopener noreferrer"><picture><source media="(prefers-color-scheme: dark)" srcset="https://cursor.com/assets/images/fix-in-cursor-dark.png"><source media="(prefers-color-scheme: light)" srcset="https://cursor.com/assets/images/fix-in-cursor-light.png"><img alt="Fix All in Cursor" width="115" height="28" src="https://cursor.com/assets/images/fix-in-cursor-dark.png"></picture></a> <!-- /BUGBOT_FIX_ALL --> <!-- BUGBOT_AUTOFIX_REVIEW_FOOTNOTE_BEGIN --> <sup>❌ Bugbot Autofix is OFF. To automatically fix reported issues with cloud agents, enable autofix in the [Cursor dashboard](https://www.cursor.com/dashboard/bugbot).</sup> <!-- BUGBOT_AUTOFIX_REVIEW_FOOTNOTE_END --> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit fbd1aff1f4855e1e015107e62d5fbd026f5ebad0. Configure [here](https://www.cursor.com/dashboard/bugbot).</sup>
Drape (Deep Review) · cross-file engine perris 0.11.1+proven.tiered0.25.call.read.subclass.type
DefectSeverityFoundGrade
d2 medium ✓ exact
d3 medium ✓ off by one
valid · matches d3 · impact medium
valid · impact low
The new OAuthLoginView calls safe_urlopen outside the try block. Connection or SSL errors therefore propagate as unhandled exceptions, while OAuth2CallbackView catches them. [grounded: diff] [consensus 3/3: valid=3]
valid · impact low
get_user_info calls resp.raise_for_status(), and the new view never catches it. A 401 or 5xx from GitHub crashes the request instead of reaching the error() branch. [grounded: diff] [consensus 3/3: valid=3]
valid · matches d2 · impact medium
valid · impact low
The new installer check compares the mutable login string, although the stable sender id is stored in metadata. If the installer renames their account, someone else could register the old username and pass the check. [grounded: diff] [consensus 3/3: valid=3]
valid · impact low
The query is built by f-string interpolation with no URL-encoding. In practice the redirect_uri is a fixed reversed path (the test shows http://testserver/extensions/github/setup/), so corruption is unlikely, but the construction is fragile. [grounded: diff] [consensus 3/5: valid=3, invalid=2]
valid · impact medium
The change adds installer verification only in the branch where the Integration already exists. When it does not exist, the pipeline still proceeds with an installation_id the user supplied and never checks github_authenticated_user. That makes the security fix incomplete. [grounded: diff] [consensus 3/3: valid=3]
raw comments (7)
src/sentry/integrations/github/integration.py:503
**Reinstall crashes for integrations without stored sender** Integrations created through the Sentry setup flow (not the installation webhook) never get `metadata["sender"]`, so re-adding such an installation to an org after removal raises KeyError and returns a 500. Use `integration.metadata.get("sender", {}).get("login")` and return `error()` when it is missing. ``` src/sentry/integrations/github/integration.py:498 return error(request, self.active_organization) src/sentry/integrations/github/integration.py:500 # Check that the authenticated GitHub user is the same as who installed the app. src/sentry/integrations/github/integration.py:501 if ( src/sentry/integrations/github/integration.py:502 pipeline.fetch_state("github_authenticated_user") src/sentry/integrations/github/integration.py:376 if state.get("sender"): src/sentry/integrations/github/integration.py:377 integration["metadata"]["sender"] = state["sender"] src/sentry/integrations/github/webhook.py:201 if event["action"] == "created": src/sentry/integrations/github/webhook.py:202 state = { src/sentry/integrations/github/webhook.py:203 "installation_id": event["installation"]["id"], src/sentry/integrations/github/webhook.py:204 "sender": { ```
src/sentry/integrations/github/integration.py:425
**Token-exchange network errors cause a 500** The `safe_urlopen` call sits outside the try block. A connection or SSL error while reaching GitHub's token endpoint therefore escapes as an unhandled exception, whereas OAuth2CallbackView.exchange_token catches these errors. Move `safe_urlopen` inside the try and return `error(...)` on failure. ``` src/sentry/integrations/github/integration.py:425 try: src/sentry/integrations/github/integration.py:426 body = safe_urlread(req).decode("utf-8") src/sentry/integrations/github/integration.py:427 payload = dict(parse_qsl(body)) src/sentry/integrations/github/integration.py:428 except Exception: src/sentry/identity/oauth2.py:286 try: src/sentry/identity/oauth2.py:287 req = safe_urlopen(self.access_token_url, data=data, verify_ssl=verify_ssl) src/sentry/identity/oauth2.py:288 body = safe_urlread(req) src/sentry/identity/oauth2.py:289 if req.headers.get("Content-Type", "").startswith("application/x-www-form-urlencoded"): src/sentry/identity/oauth2.py:290 return dict(parse_qsl(body)) src/sentry/identity/oauth2.py:291 return json.loads(body) ```
src/sentry/integrations/github/integration.py:436
**Rejected GitHub token crashes setup with 500** `get_user_info` calls `raise_for_status()`. A 401 or 5xx from api.github.com/user raises an HTTPError that this view does not catch, so the request fails instead of reaching the existing `"login" not in ...` error branch. Wrap `get_user_info` in try/except and return `error(...)`. ``` src/sentry/integrations/github/integration.py:436 return error(request, self.active_organization) src/sentry/integrations/github/integration.py:438 pipeline.bind_state("github_authenticated_user", authenticated_user_info["login"]) src/sentry/identity/github/provider.py:7 def get_user_info(access_token): src/sentry/identity/github/provider.py:8 with http.build_session() as session: src/sentry/identity/github/provider.py:9 resp = session.get( src/sentry/identity/github/provider.py:10 "https://api.github.com/user", src/sentry/identity/github/provider.py:11 headers={ src/sentry/identity/github/provider.py:12 "Accept": "application/vnd.github.machine-man-preview+json", src/sentry/identity/github/provider.py:13 "Authorization": f"token {access_token}", src/sentry/identity/github/provider.py:14 }, ```
src/sentry/integrations/github/integration.py:403
**OAuth state is a fixed, guessable value** `state` is `pipeline.signature`, an md5 of view class names that is identical for every user, so it gives no CSRF protection: a victim's browser can be made to finish OAuth with an attacker's `code`. Bind a random `secrets.token_hex()` state and compare against it. ``` src/sentry/integrations/github/integration.py:402 state = pipeline.signature src/sentry/integrations/github/integration.py:404 redirect_uri = absolute_uri( src/sentry/integrations/github/integration.py:405 reverse("sentry-extension-setup", kwargs={"provider_id": "github"}) src/sentry/integrations/github/integration.py:406 ) src/sentry/pipeline/base.py:132 pipe_ids = [f"{type(v).__module__}.{type(v).__name__}" for v in self.pipeline_views] src/sentry/pipeline/base.py:133 self.signature = md5_text(*pipe_ids).hexdigest() src/sentry/identity/oauth2.py:245 state = secrets.token_hex() src/sentry/identity/oauth2.py:247 params = self.get_authorize_params( src/sentry/identity/oauth2.py:248 state=state, redirect_uri=absolute_uri(pipeline.redirect_url()) src/sentry/identity/oauth2.py:249 ) ```
src/sentry/integrations/github/integration.py:502
**Installer check compares mutable login, not id** The check compares GitHub usernames, which can be changed and re-registered; the stored `sender["id"]` should be compared instead so a renamed installer's old username can't be claimed to pass verification. Bind the GitHub user id and compare it to `metadata["sender"]["id"]`. ``` src/sentry/integrations/github/integration.py:449 "installation_id", pipeline.fetch_state("installation_id") src/sentry/integrations/github/integration.py:500 # Check that the authenticated GitHub user is the same as who installed the app. src/sentry/integrations/github/integration.py:501 if ( src/sentry/integrations/github/integration.py:502 pipeline.fetch_state("github_authenticated_user") src/sentry/integrations/github/webhook.py:204 "sender": { src/sentry/integrations/github/webhook.py:205 "id": event["sender"]["id"], src/sentry/integrations/github/webhook.py:206 "login": event["sender"]["login"], src/sentry/integrations/github/webhook.py:207 }, ```
src/sentry/integrations/github/integration.py:408
**Authorize URL query params not URL-encoded** The authorize URL is built with an f-string, so `redirect_uri` (and client id) are inserted raw; any `&`, `?` or `#` in the absolute URI would corrupt the query. Build the query with `urlencode({...})`. ``` src/sentry/integrations/github/integration.py:404 redirect_uri = absolute_uri( src/sentry/integrations/github/integration.py:405 reverse("sentry-extension-setup", kwargs={"provider_id": "github"}) src/sentry/integrations/github/integration.py:406 ) src/sentry/integrations/github/integration.py:407 return self.redirect( src/sentry/integrations/github/integration.py:408 f"{ghip.get_oauth_authorize_url()}?client_id={github_client_id}&state={state}&redirect_uri={redirect_uri}" src/sentry/integrations/github/integration.py:409 ) ```
src/sentry/integrations/github/integration.py:482
**Installer check skipped when integration not yet created** If no Integration row exists yet (webhook delayed or lost), this goes straight to `next_step()` without checking `github_authenticated_user`, so anyone supplying another account's installation_id can link it. Verify the authenticated user against the installation owner before proceeding here too. ``` src/sentry/integrations/github/integration.py:481 except Integration.DoesNotExist: src/sentry/integrations/github/integration.py:482 return pipeline.next_step() src/sentry/integrations/github/integration.py:449 "installation_id", pipeline.fetch_state("installation_id") src/sentry/integrations/github/integration.py:450 ) src/sentry/integrations/github/integration.py:351 def build_integration(self, state: Mapping[str, str]) -> Mapping[str, Any]: src/sentry/integrations/github/integration.py:352 try: src/sentry/integrations/github/integration.py:353 installation = self.get_installation_info(state["installation_id"]) src/sentry/integrations/github/integration.py:354 except ApiError as api_error: src/sentry/integrations/github/integration.py:355 if api_error.code == 404: src/sentry/integrations/github/integration.py:356 raise IntegrationError("The GitHub installation could not be found.") ```
Drape (Review) · cross-file engine perris 0.11.1+proven.tiered0.25.call.read.subclass.type
DefectSeverityFoundGrade
d2 medium ✓ exact
d3 medium ✓ exact
valid · impact low
The new OAuthLoginView calls safe_urlopen outside the try block. It also calls get_user_info, which runs resp.raise_for_status() (sentry/identity/github/provider.py). A network error or a non-2xx response from GitHub therefore raises an unhandled exception instead of showing the error() page. [grounded: diff] [consensus 3/3: valid=3]
valid · matches d3 · impact medium
valid · matches d2 · impact medium
valid · impact medium
The new sender-login check runs only when an Integration already exists. In the DoesNotExist branch the pipeline advances with no comparison to the authenticated user, so the new authenticity check is incomplete and can be bypassed if the webhook has not arrived yet. [grounded: diff] [consensus 3/4: valid=3, uncertain=1]
raw comments (4)
src/sentry/integrations/github/integration.py:432
**OAuth token exchange errors cause a 500** `safe_urlopen` and `get_user_info` sit outside any try/except. A network error, or a non-2xx response from GitHub's `/user` (`raise_for_status`), raises an unhandled exception instead of showing the installation error page. Wrap the token exchange and `get_user_info` in try/except and return `error(...)`. ``` src/sentry/integrations/github/integration.py:420 } src/sentry/integrations/github/integration.py:422 # similar to OAuth2CallbackView.exchange_token src/sentry/integrations/github/integration.py:423 req = safe_urlopen(url=ghip.get_oauth_access_token_url(), data=data) src/sentry/integrations/github/integration.py:425 try: ```
src/sentry/integrations/github/integration.py:501
**KeyError when integration has no sender metadata** The check reads `integration.metadata["sender"]["login"]` directly. `sender` is only stored when the webhook or pipeline state supplied it (`build_integration` is conditional on `state.get("sender")`), so older or differently created integrations lack it. Use `.get("sender", {}).get("login")` and return the error page when it is missing. ``` src/sentry/integrations/github/integration.py:500 # Check that the authenticated GitHub user is the same as who installed the app. src/sentry/integrations/github/integration.py:501 if ( src/sentry/integrations/github/integration.py:502 pipeline.fetch_state("github_authenticated_user") src/sentry/integrations/github/integration.py:503 != integration.metadata["sender"]["login"] ```
src/sentry/integrations/github/integration.py:412
**OAuth `state` is a constant, not a nonce** `pipeline.signature` is an md5 of the view class names, identical for every user and session. Comparing it to `state` gives no CSRF protection; anyone can craft a callback with the known state and their own `code`. Store a random per-session nonce in pipeline state and compare against it. ``` src/sentry/integrations/github/integration.py:398 if installation_id: src/sentry/integrations/github/integration.py:399 pipeline.bind_state("installation_id", installation_id) src/sentry/integrations/github/integration.py:401 if not request.GET.get("state"): src/sentry/integrations/github/integration.py:402 state = pipeline.signature src/sentry/pipeline/base.py:132 pipe_ids = [f"{type(v).__module__}.{type(v).__name__}" for v in self.pipeline_views] src/sentry/pipeline/base.py:133 self.signature = md5_text(*pipe_ids).hexdigest() ```
src/sentry/integrations/github/integration.py:481
**User check skipped when Integration is missing** When no `Integration` exists for the installation_id, the code calls `next_step()` without comparing the authenticated user to anyone. If the webhook hasn't arrived yet, any user with the installation_id completes the install. Verify the installer another way, e.g. ask GitHub, instead of skipping the check. ``` src/sentry/integrations/github/integration.py:476 # We want to limit GitHub integrations to 1 organization src/sentry/integrations/github/integration.py:477 installations_exist = OrganizationIntegration.objects.filter( src/sentry/integrations/github/integration.py:478 integration=Integration.objects.get(external_id=installation_id) src/sentry/integrations/github/integration.py:479 ).exists() ```
greptile · cross-file engine perris 0.11.1+proven.tiered0.25.call.read.subclass.type
DefectSeverityFoundGrade
d2 medium ✗ —
d3 medium ✓ off by one
valid · impact medium
The change adds a GitHub-user ownership check only on the branch where an Integration already exists; the DoesNotExist branch still advances to build_integration with a browser-supplied installation_id and no OAuth-user comparison. That leaves the new security fix incomplete. The gap is narrow, though, because the installation webhook normally creates the Integration. [grounded: diff] [consensus 3/5: valid=3, invalid=2]
valid · matches d3 · impact medium
valid · impact low
get_user_info calls resp.raise_for_status() and resp.json(), and neither call is wrapped. safe_urlopen also runs outside the try block. A network error or a non-2xx response from GitHub therefore escapes OAuthLoginView.dispatch as an uncaught exception instead of rendering the error page. [grounded: diff] [consensus 3/3: valid=3]
raw comments (4)
src/sentry/integrations/github/integration.py:482
<a href="#"><img alt="P1" src="https://greptile-static-assets.s3.amazonaws.com/badges/p1.svg?v=9" align="top"></a> <a href="#"><img alt="security" src="https://greptile-static-assets.s3.amazonaws.com/badges/Security.svg?v=2" align="top"></a> **Ownership Check Is Skipped** When the supplied installation ID has no existing `Integration` record, this branch advances without applying the new ownership check. Because the installation ID comes from a browser-controlled query parameter, a user can supply another valid installation ID; the pipeline then fetches it with the GitHub App's credentials and links its repositories to the selected Sentry organization without confirming that the OAuth user owns it. **How this was verified:** The browser-supplied installation ID reaches integration creation and organization linking through an app-authenticated GitHub request without an OAuth-user ownership comparison.
src/sentry/integrations/github/integration.py:504
<a href="#"><img alt="P1" src="https://greptile-static-assets.s3.amazonaws.com/badges/p1.svg?v=9" align="top"></a> **Optional Metadata Causes Crash** This comparison assumes every active GitHub integration has `metadata["sender"]["login"]`, but integrations created through the regular pipeline can have no `sender` metadata. If one of those integrations exists without an organization link, this lookup raises `KeyError` instead of returning the invalid-installation response, causing setup to fail with a server error.
src/sentry/integrations/github/integration.py:434
<a href="#"><img alt="P1" src="https://greptile-static-assets.s3.amazonaws.com/badges/p1.svg?v=9" align="top"></a> **OAuth Failures Escape Handling** The new OAuth calls leave common failures outside the integration error path. `safe_urlopen` can raise before the parsing handler, and `get_user_info` can raise on connection failures, non-2xx responses, or invalid JSON. In those cases the exception escapes the pipeline and produces an internal server error rather than the GitHub installation failure page.
PR-level
<h3>Greptile Summary</h3> This PR adds a GitHub OAuth identity step before installation setup, persists installation IDs across callbacks, and compares the authenticated GitHub user with webhook sender metadata before reusing an existing installation. - Adds OAuth authorization, token exchange, and GitHub user lookup. - Adds an installation-user authenticity check for existing active integrations. - Refactors GitHub installation error rendering and updates integration tests. - The ownership check does not cover integrations absent from Sentry, and some existing metadata shapes can crash the new comparison. <h3>Confidence Score: 1/5</h3> This PR is not safe to merge because the intended GitHub installation ownership validation remains bypassable and two common setup paths can fail with internal server errors. A browser-provided installation ID can still be attached without validating its owner when no Integration record exists; existing sender-less records can crash the new metadata lookup, and GitHub OAuth request failures escape the pipeline error handling. **Files Needing Attention:** src/sentry/integrations/github/integration.py <details open><summary><h3>Security Review</h3></summary> The new ownership validation remains bypassable when the supplied GitHub installation does not yet have an Integration record. That path trusts a browser-provided installation ID and uses app-level GitHub credentials to create and attach the installation without proving that the OAuth user owns it. </details> <details><summary><h3>Important Files Changed</h3></summary> | Filename | Overview | |----------|----------| | src/sentry/integrations/github/integration.py | Adds GitHub OAuth and installer validation, but skips ownership verification for absent integrations, assumes optional sender metadata exists, and leaves external-call failures unhandled. | | src/sentry/web/frontend/pipeline_advancer.py | Replaces a single-item provider allowlist with an equivalent direct GitHub comparison while preserving direct-install forwarding. | | tests/sentry/integrations/github/test_integration.py | Updates integration tests for the OAuth step and user mismatch, but does not cover the absent-Integration ownership bypass, sender-less metadata, or OAuth request failures. | </details> <details open><summary><h3>Sequence Diagram</h3></summary> ```mermaid sequenceDiagram actor User participant Browser participant OAuth as GitHub OAuth participant Pipeline as Sentry setup pipeline participant AppAPI as GitHub App API participant DB as Sentry integrations Browser->>Pipeline: Start setup with installation_id Pipeline->>OAuth: Authorize with signed pipeline state OAuth-->>Pipeline: code + state Pipeline->>OAuth: Exchange code and fetch user login Pipeline->>DB: Look up Integration by installation_id alt Existing active Integration DB-->>Pipeline: Integration with sender metadata Pipeline->>Pipeline: Compare OAuth login to sender login else Integration absent DB-->>Pipeline: Not found Pipeline->>AppAPI: Fetch installation using app JWT AppAPI-->>Pipeline: Installation metadata Pipeline->>DB: Create Integration and attach organization Note over Pipeline,DB: Ownership comparison is skipped end ``` </details> <!-- greptile_other_comments_section --> <sub>Reviews (1): Last reviewed commit: ["Update src/sentry/integrations/github/in..."](https://github.com/drape-io/crbench-greptile-2026-09/commit/7a642186abce1854597919aec14fbcad3f1fb658) | [Re-trigger Greptile](https://app.greptile.com/api/retrigger?id=64284812)</sub>
Mjolnir (Opus 5.5) · cross-file engine perris 0.11.1+proven.tiered0.25.call.read.subclass.type
DefectSeverityFoundGrade
d2 medium ✗ —
d3 medium ✓ exact
valid · impact medium
build_integration only sets metadata['sender'] when the state includes a sender, and only the webhook path supplies one. The pipeline path does not, so an active Integration created through the pipeline, or an older one, has no 'sender' key. In that case the new check raises KeyError, which surfaces as a 500, when an existing Integration is reinstalled with no OrganizationIntegration. installation.py:44 already guards against this same missing key. [grounded: diff] [consensus 3/3: valid=3]
valid · matches d3 · impact medium
raw comments (2)
src/sentry/integrations/github/integration.py:499
[P2] KeyError when an existing Integration has no `sender` in its metadata The new check reads `integration.metadata["sender"]["login"]` directly, but `sender` isn't always there. `build_integration` only adds it when `state.get("sender")` is set, and only the installation webhook path (`webhook.py:204`) supplies it. So an Integration created through the setup pipeline, or one that existed before this metadata was added, has no `sender` key. If a user later reinstalls into an org (the OrganizationIntegration is gone but the Integration row still exists and is active), `dispatch` raises KeyError and returns a 500 instead of the "Invalid installation request" page. `installation.py:44` already guards this case with `if "sender" not in integration.metadata`. Using `.get("sender", {}).get("login")` here, or returning `error(...)` when the key is missing, would avoid the crash.
src/sentry/integrations/github/integration.py:499
[P2] Sender check raises KeyError when integration metadata has no `sender` The new check indexes `integration.metadata["sender"]["login"]` directly, but `sender` is only stored when the integration is created from the installation webhook. `build_integration` only sets it when `state.get("sender")` is present, and the pipeline state never contains it. `ensure_integration` also overwrites `metadata` with `update(**defaults)` when the pipeline finishes, so the `sender` key is lost even for webhook-created integrations. This code path is reached when an `Integration` exists but has no `OrganizationIntegration`, for example after a user uninstalls GitHub on the Sentry side and installs again. For those integrations, and for older ones, the lookup raises `KeyError`. The user gets a 500 error instead of the "invalid installation request" page or a successful reinstall. `installation.py` already handles this case with `if "sender" not in integration.metadata`.
Mjolnir (Sonnet 5.5) · cross-file engine perris 0.11.1+proven.tiered0.25.call.read.subclass.type
DefectSeverityFoundGrade
d2 medium ✗ —
d3 medium ✓ exact
valid · impact medium
`build_integration` sets `sender` only when `state.get("sender")` is present, and an integration created through the normal pipeline has no sender (test_basic_flow's metadata shows this). If such an active Integration has no OrganizationIntegration, the new unguarded lookup raises KeyError. installation.py:44 already treats `sender` as optional. [grounded: diff] [consensus 3/3: valid=3]
valid · matches d3 · impact medium
raw comments (2)
src/sentry/integrations/github/integration.py:500
[P2] Missing `sender` metadata raises KeyError during reinstall The new ownership check reads `integration.metadata["sender"]["login"]` unconditionally, but `sender` is only written when the integration was created from the `installation` "created" webhook (webhook.py:204, integration.py:376-377). Other code already treats it as optional (`installation.py:44`, `if "sender" not in integration.metadata`). An existing active Integration without `sender` metadata that has no OrganizationIntegration, for example an older install or one whose webhook state lacked a sender, raises KeyError when the user installs it into a new org. The install flow then returns a 500 instead of the intended error page. Reading it with `.get` and failing closed through `error(...)` would avoid the crash
src/sentry/integrations/github/integration.py:500
[P2] Unguarded `metadata["sender"]["login"]` can raise KeyError and return a 500 When an Integration row exists with no OrganizationIntegration, the new check reads `integration.metadata["sender"]["login"]` directly. `sender` is only written to metadata when the build state contains it (integration.py:376-377). That happens for webhook-created integrations but not for ones created through the normal pipeline or older rows. `installation.py:44` already guards with `"sender" not in integration.metadata`. For such an integration, for example one whose org link was removed, re-installing hits a KeyError and a 500. It should fail with the `error(...)` response instead. This only affects integrations that have no `sender` metadata
qodo · cross-file engine perris 0.11.1+proven.tiered0.25.call.read.subclass.type
DefectSeverityFoundGrade
d2 medium ✓ off by one
d3 medium ✓ exact
valid · impact medium
The new installer check only runs when an Integration row already exists. If none exists yet (webhook not processed), dispatch calls next_step and setup finishes with no installer verification. That makes this security fix incomplete for the race it is meant to close. [grounded: tree src/sentry/integrations/github/integration.py] [consensus 3/3: valid=3]
valid · matches d2 · impact medium
valid · matches d3 · impact medium
valid · impact low
safe_urlopen sits outside the try block and raises on connection errors. get_user_info calls raise_for_status() and resp.json() with no handling around the call. A GitHub outage therefore causes an unhandled exception (a 500) in the new view instead of the error page. [grounded: diff] [consensus 3/3: valid=3]
raw comments (6)
src/sentry/integrations/github/integration.py:503
<img src="https://img.shields.io/badge/High-634FD1?style=flat-square" height="20px" alt="Action required"> 1\. Installer checks can be skipped <code>🐞 Bug</code> <code>⛨ Security</code> <pre> <b><i>GitHubInstallation.dispatch</i></b> advances immediately when no <b><i>Integration</i></b> row exists, so the newly added sender comparison runs only when webhook processing wins the race. If the OAuth callback arrives first, <b><i>finish_pipeline</i></b> creates and links an active integration without <b><i>sender</i></b> metadata, as the basic-flow test&#x27;s persisted metadata demonstrates. </pre> <details> <summary><strong>Agent Prompt</strong></summary> ``` ## Issue description The installer comparison is skipped whenever setup reaches the pipeline before the installation webhook creates its integration row, allowing setup to complete without verifying the installer. ## Fix Focus Areas - src/sentry/integrations/github/integration.py[475-505] - src/sentry/integrations/github/integration.py[351-379] - src/sentry/integrations/github/webhook.py[201-210] - src/sentry/integrations/pipeline.py[126-132] ## Recommended Fix Do not advance from the missing-integration branch until an active webhook-created integration containing verified sender metadata exists. Return a retryable installation error when the webhook has not arrived, then compare the authenticated user's stable GitHub identifier against the stored sender identifier before advancing. ``` <code>ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools</code> </details>
src/sentry/integrations/github/integration.py:412
<img src="https://img.shields.io/badge/High-634FD1?style=flat-square" height="20px" alt="Action required"> 2\. Forged callbacks can connect attacker repositories <code>🐞 Bug</code> <code>⛨ Security</code> <pre> <b><i>OAuthLoginView.dispatch</i></b> sends and validates the deterministic <b><i>pipeline.signature</i></b>, which is shared by pipelines with the same configured view classes, instead of a random nonce stored for the individual authorization attempt. When an attacker supplies an authorization code for their GitHub account to an organization member’s active setup pipeline using that known state, the subsequent sender comparison accepts the attacker-owned installation and associates it with the member’s organization. </pre> <details> <summary><strong>Agent Prompt</strong></summary> ``` ## Issue description The GitHub OAuth flow uses the deterministic pipeline signature as callback state, so it does not prove that a callback belongs to the browser’s authorization attempt and permits an authorization code to be submitted to another user’s active pipeline. ## Fix Focus Areas - src/sentry/integrations/github/integration.py[401-413] - src/sentry/identity/oauth2.py[245-253] - src/sentry/identity/oauth2.py[316-335] ## Recommended Fix Generate a cryptographically random OAuth state value before redirecting to GitHub, store it with `pipeline.bind_state`, and validate the callback’s `state` against `pipeline.fetch_state("state")`. Reject absent, mismatched, or already-consumed state before exchanging the authorization code, and construct the authorization query with the standard URL encoder, following the established OAuth2 flow. ``` <code>ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools</code> </details>
src/sentry/integrations/github/integration.py:505
<img src="https://img.shields.io/badge/Medium-634FD1?style=flat-square" height="20px" alt="Remediation recommended"> 3\. Some github setup retries now crash <code>🐞 Bug</code> <code>☼ Reliability</code> <pre> <b><i>GitHubInstallation.dispatch</i></b> unconditionally indexes <b><i>integration.metadata[&quot;sender&quot;][&quot;login&quot;]</i></b> after finding an active unassociated integration, although integrations created through the ordinary <b><i>ensure_integration</i></b> setup path may have no <b><i>sender</i></b> metadata. A concurrent, interrupted, or later repeated setup can reach this branch before organization association completes or while such an integration is retained, raising <b><i>KeyError</i></b> instead of rendering the controlled installation error response. </pre> <details> <summary><strong>Agent Prompt</strong></summary> ``` ## Issue description The authenticated-user comparison assumes every active unassociated integration contains webhook sender metadata, although integrations created through the normal setup flow can omit that field. Concurrent, interrupted, or repeated setup can therefore reach the comparison with absent or malformed sender data. ## Fix Focus Areas - src/sentry/integrations/github/integration.py[493-505] - src/sentry/integrations/github/integration.py[351-379] - src/sentry/integrations/github/installation.py[32-45] - src/sentry/integrations/pipeline.py[126-132] - tests/sentry/integrations/github/test_integration.py[294-313] ## Recommended Fix Read sender metadata defensively before comparing the authenticated user, and treat absent or malformed sender data as an unverified installation rather than indexing it directly. Return the existing controlled invalid-installation response or implement a supported verification path, and prevent setup-created integrations from entering this branch without webhook verification. ``` <code>ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools</code> </details>
src/sentry/integrations/github/integration.py:434
<img src="https://img.shields.io/badge/Medium-634FD1?style=flat-square" height="20px" alt="Remediation recommended"> 4\. Github outages turn setup into server errors <code>🐞 Bug</code> <code>☼ Reliability</code> <pre> <b><i>OAuthLoginView.dispatch</i></b> calls <b><i>safe_urlopen</i></b> and <b><i>get_user_info</i></b> without handling their transport, HTTP-status, decoding, or malformed user-response failures. A token-endpoint connection failure or a non-success or malformed response from GitHub’s user endpoint escapes the integration pipeline instead of reaching the existing installation failure page. </pre> <details> <summary><strong>Agent Prompt</strong></summary> ``` ## Issue description External GitHub token and user-information requests, including response parsing, can raise exceptions that are not converted into the existing setup failure response and instead propagate out of the integration pipeline. ## Fix Focus Areas - src/sentry/integrations/github/integration.py[422-436] - src/sentry/identity/oauth2.py[282-315] - src/sentry/identity/github/provider.py[7-17] ## Recommended Fix Wrap both external requests and their response parsing in targeted exception handling for transport or connection failures, HTTP-response errors, decoding failures, and malformed payloads. Log each failure with exception context but without recording credentials or token contents, then return `error(request, self.active_organization)` so the existing invalid-installation response is shown instead of allowing the exception to produce a 500 response. ``` <code>ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools</code> </details>
PR-level
<h3>PR Summary by Qodo</h3> Verify GitHub App installers through OAuth identity matching <code>🐞 Bug fix</code> <code>🧪 Tests</code> <code>✨ Enhancement</code> <code>🕐 20-40 Minutes</code> <img src="https://www.qodo.ai/wp-content/uploads/2025/11/light-grey-line.svg" height="10%" alt="Grey Divider"> <details> <summary>AI Description</summary> <dl> <dd> <br/> ><pre> >• Authenticate GitHub App installers through OAuth before continuing installation. >• Reject invalid callbacks and installers differing from the webhook-recorded GitHub sender. >• Preserve installation state and cover OAuth success and failure paths. ></pre> </dd> </dl> </details> <details> <summary>Diagram</summary> <dl> <dd> <br/> ```mermaid sequenceDiagram actor User participant Pipeline as Setup Pipeline participant OAuth as OAuth Login participant GitHub as GitHub OAuth participant Install as Install Check participant DB as Integration Store User->>Pipeline: Start installation Pipeline->>OAuth: Run identity check OAuth-->>User: Redirect for consent User->>GitHub: Authorize Sentry GitHub-->>OAuth: Return code and state OAuth->>OAuth: Validate state OAuth->>GitHub: Exchange code GitHub-->>OAuth: Return token and login OAuth->>Pipeline: Bind GitHub login Pipeline->>Install: Continue with installation ID Install->>DB: Load active installation DB-->>Install: Return sender metadata Install->>Install: Compare GitHub users alt Users match Install->>Pipeline: Continue setup else Users differ Install-->>User: Render verification failure end ``` </dd> </dl> </details> <details> <summary>High-Level Assessment</summary> <dl> <dd> <br/> >The following are alternative approaches to this PR: <details> <summary><b>1. Reuse a shared OAuth callback abstraction</b></summary> <dl> <dd> - ➕ Centralizes state validation and token exchange behavior. - ➕ Reduces duplicated OAuth security-sensitive code. - ➕ Could standardize error handling across integration providers. - ➖ Existing identity pipelines may not preserve GitHub installation state correctly. - ➖ Adapting generic callbacks could broaden this security fix considerably. - ➖ GitHub-specific sender matching would still require custom installation logic. </dd> </dl> </details> <details> <summary><b>2. Validate a signed installation nonce</b></summary> <dl> <dd> - ➕ Avoids exchanging a user OAuth token during installation. - ➕ Provides strong callback correlation for Sentry-initiated installs. - ➖ Does not support installations initiated directly from GitHub without prior Sentry state. - ➖ Does not independently prove the requester matches GitHub’s installation sender. - ➖ Requires additional nonce storage and lifecycle handling. </dd> </dl> </details> >**Recommendation:** Use the pipeline-integrated OAuth verification for this targeted fix because it supports both Sentry- and GitHub-initiated installations while proving the requester’s GitHub identity. A follow-up could extract the duplicated OAuth exchange and state-validation logic into a shared helper without changing this installation flow. </dd> </dl> </details> <details> <summary> Files changed (3) <code> +247 / -50 </code> </summary> <dl> <dd> <br/> <details> <summary>Bug fix (1) <code> +118 / -41 </code></summary> <dl> <dd> <details> <summary>integration.py<code>Authenticate and verify GitHub App installers</code> <code>+118/-41</code></summary> <br/> >Authenticate and verify GitHub App installers > ><pre> >• Adds an OAuth login step that validates callback state, retrieves the authenticated GitHub login, and preserves the installation ID in pipeline state. Installation validation now requires an active integration whose webhook sender matches that authenticated user, with shared rendering for invalid, duplicate, and pending-deletion failures. ></pre> > ><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/69/files#diff-b517da9f8145142071b7180613fc7d96383b7213f6be500fd29baa261e81cdb4'>src/sentry/integrations/github/integration.py</a> </details> </dd> </dl> </details> <details> <summary>Refactor (1) <code> +4 / -7 </code></summary> <dl> <dd> <details> <summary>pipeline_advancer.py<code>Inline GitHub direct-install forwarding condition</code> <code>+4/-7</code></summary> <br/> >Inline GitHub direct-install forwarding condition > ><pre> >• Replaces the single-entry provider allowlist with an explicit GitHub check while retaining direct GitHub installation forwarding when no pipeline exists. ></pre> > ><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/69/files#diff-409cef61423dd29f87267469d57a201b100e0c643d95d45c8205054a5103bf67'>src/sentry/web/frontend/pipeline_advancer.py</a> </details> </dd> </dl> </details> <details> <summary>Tests (1) <code> +125 / -2 </code></summary> <dl> <dd> <details> <summary>test_integration.py<code>Cover OAuth verification across GitHub installation flows</code> <code>+125/-2</code></summary> <br/> >Cover OAuth verification across GitHub installation flows > ><pre> >• Extends GitHub stubs and setup assertions for OAuth authorization, token exchange, and user lookup. Updates duplicate, missing, and pending-deletion scenarios to traverse OAuth, and adds coverage rejecting a user who differs from the webhook-recorded installer. ></pre> > ><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/69/files#diff-588695fc16c1f31777ee392ba45f0f9cb5c1f470d9b78078442425af96ca85d7'>tests/sentry/integrations/github/test_integration.py</a> </details> </dd> </dl> </details> </dd> </dl> </details>
PR-level
<h3>Code Review by Qodo</h3> <code>🐞 Bugs (4)</code> <code>📘 Rule violations (0)</code> <code>📜 Skill insights (0)</code> <img src="https://www.qodo.ai/wp-content/uploads/2025/11/light-grey-line.svg" height="10%" alt="Grey Divider"> <br/> <img src="https://img.shields.io/badge/High-634FD1?style=flat-square" height="20px" alt="Action required"> <details> <summary> 1. Installer checks can be skipped <code>🐞 Bug</code> <code>⛨ Security</code></summary> <br/> > <details open> ><summary>Description</summary> ><br/> > ><pre> ><b><i>GitHubInstallation.dispatch</i></b> advances immediately when no <b><i>Integration</i></b> row exists, so the newly >added sender comparison runs only when webhook processing wins the race. If the OAuth callback >arrives first, <b><i>finish_pipeline</i></b> creates and links an active integration without <b><i>sender</i></b> metadata, >as the basic-flow test&#x27;s persisted metadata demonstrates. ></pre> ></details> > <details> ><summary>Code</summary> ><br/> > ><code>[src/sentry/integrations/github/integration.py[R500-503]](https://github.com/drape-io/crbench-qodo-2026-09/pull/69/files#diff-b517da9f8145142071b7180613fc7d96383b7213f6be500fd29baa261e81cdb4R500-R503)</code> > >```diff >+ # Check that the authenticated GitHub user is the same as who installed the app. >+ if ( >+ pipeline.fetch_state("github_authenticated_user") >+ != integration.metadata["sender"]["login"] >``` ></details> > <details> ><summary>Evidence</summary> ><br/> > ><pre> >A missing integration returns directly to the next pipeline step before the new comparison. Pipeline >completion then calls <b><i>build_integration</i></b> and <b><i>ensure_integration</i></b>; without webhook state, ><b><i>build_integration</i></b> omits <b><i>sender</i></b>, and the basic setup test confirms that this sender-free metadata >is persisted successfully, while only the installation webhook supplies sender data. ></pre> > > <code>[src/sentry/integrations/github/integration.py[475-505]](https://github.com/drape-io/crbench-qodo-2026-09/blob/4dac495122950c3b48d618b43491b869c98cc43e/src/sentry/integrations/github/integration.py/#L475-L505)</code> > <code>[src/sentry/integrations/github/integration.py[351-379]](https://github.com/drape-io/crbench-qodo-2026-09/blob/4dac495122950c3b48d618b43491b869c98cc43e/src/sentry/integrations/github/integration.py/#L351-L379)</code> > <code>[src/sentry/integrations/github/webhook.py[201-210]](https://github.com/drape-io/crbench-qodo-2026-09/blob/4dac495122950c3b48d618b43491b869c98cc43e/src/sentry/integrations/github/webhook.py/#L201-L210)</code> > <code>[src/sentry/integrations/pipeline.py[91-132]](https://github.com/drape-io/crbench-qodo-2026-09/blob/4dac495122950c3b48d618b43491b869c98cc43e/src/sentry/integrations/pipeline.py/#L91-L132)</code> > <code>[tests/sentry/integrations/github/test_integration.py[294-313]](https://github.com/drape-io/crbench-qodo-2026-09/blob/4dac495122950c3b48d618b43491b869c98cc43e/tests/sentry/integrations/github/test_integration.py/#L294-L313)</code> ></details> > <details> ><summary>Agent prompt</summary> ><br/> > >``` >The issue below was found during a code review. Follow the provided context and guidance below and implement a solution > >## Issue description >The installer comparison is skipped whenever setup reaches the pipeline before the installation webhook creates its integration row, allowing setup to complete without verifying the installer. > >## Fix Focus Areas >- src/sentry/integrations/github/integration.py[475-505] >- src/sentry/integrations/github/integration.py[351-379] >- src/sentry/integrations/github/webhook.py[201-210] >- src/sentry/integrations/pipeline.py[126-132] > >## Recommended Fix >Do not advance from the missing-integration branch until an active webhook-created integration containing verified sender metadata exists. Return a retryable installation error when the webhook has not arrived, then compare the authenticated user's stable GitHub identifier against the stored sender identifier before advancing. >``` > <code>ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools</code> ></details> <hr/> </details> <details> <summary> 2. Forged callbacks can connect attacker repositories <code>🐞 Bug</code> <code>⛨ Security</code></summary> <br/> > <details open> ><summary>Description</summary> ><br/> > ><pre> ><b><i>OAuthLoginView.dispatch</i></b> sends and validates the deterministic <b><i>pipeline.signature</i></b>, which is >shared by pipelines with the same configured view classes, instead of a random nonce stored for the >individual authorization attempt. When an attacker supplies an authorization code for their GitHub >account to an organization member’s active setup pipeline using that known state, the subsequent >sender comparison accepts the attacker-owned installation and associates it with the member’s >organization. ></pre> ></details> > <details> ><summary>Code</summary> ><br/> > ><code>[src/sentry/integrations/github/integration.py[R401-412]](https://github.com/drape-io/crbench-qodo-2026-09/pull/69/files#diff-b517da9f8145142071b7180613fc7d96383b7213f6be500fd29baa261e81cdb4R401-R412)</code> > >```diff >+ if not request.GET.get("state"): >+ state = pipeline.signature >+ >+ redirect_uri = absolute_uri( >+ reverse("sentry-extension-setup", kwargs={"provider_id": "github"}) >+ ) >+ return self.redirect( >+ f"{ghip.get_oauth_authorize_url()}?client_id={github_client_id}&state={state}&redirect_uri={redirect_uri}" >+ ) >+ >+ # At this point, we are past the GitHub "authorize" step >+ if request.GET.get("state") != pipeline.signature: >``` ></details> > <details> ><summary>Evidence</summary> ><br/> > ><pre> >The changed view uses <b><i>pipeline.signature</i></b> both when sending the OAuth request and when validating >the callback, while that signature is derived solely from the fixed list of configured view class >names and is therefore not unique to an authorization attempt. The repository’s standard OAuth >implementation instead generates a fresh random token, stores it in pipeline state, and validates >the callback against that stored value; because the organization setup endpoint accepts GET requests >without CSRF protection and initializes a pipeline for a member with the integrations scope, OAuth >state is the relevant binding between the callback and that specific setup attempt. ></pre> > > <code>[src/sentry/integrations/github/integration.py[401-412]](https://github.com/drape-io/crbench-qodo-2026-09/blob/4dac495122950c3b48d618b43491b869c98cc43e/src/sentry/integrations/github/integration.py/#L401-L412)</code> > <code>[src/sentry/pipeline/base.py[127-133]](https://github.com/drape-io/crbench-qodo-2026-09/blob/4dac495122950c3b48d618b43491b869c98cc43e/src/sentry/pipeline/base.py/#L127-L133)</code> > <code>[src/sentry/identity/oauth2.py[239-252]](https://github.com/drape-io/crbench-qodo-2026-09/blob/4dac495122950c3b48d618b43491b869c98cc43e/src/sentry/identity/oauth2.py/#L239-L252)</code> > <code>[src/sentry/identity/oauth2.py[316-335]](https://github.com/drape-io/crbench-qodo-2026-09/blob/4dac495122950c3b48d618b43491b869c98cc43e/src/sentry/identity/oauth2.py/#L316-L335)</code> > <code>[src/sentry/web/frontend/organization_integration_setup.py[18-28]](https://github.com/drape-io/crbench-qodo-2026-09/blob/4dac495122950c3b48d618b43491b869c98cc43e/src/sentry/web/frontend/organization_integration_setup.py/#L18-L28)</code> > <code>[src/sentry/integrations/github/integration.py[401-413]](https://github.com/drape-io/crbench-qodo-2026-09/blob/4dac495122950c3b48d618b43491b869c98cc43e/src/sentry/integrations/github/integration.py/#L401-L413)</code> > <code>[src/sentry/identity/oauth2.py[245-253]](https://github.com/drape-io/crbench-qodo-2026-09/blob/4dac495122950c3b48d618b43491b869c98cc43e/src/sentry/identity/oauth2.py/#L245-L253)</code> ></details> > <details> ><summary>Agent prompt</summary> ><br/> > >``` >The issue below was found during a code review. Follow the provided context and guidance below and implement a solution > >## Issue description >The GitHub OAuth flow uses the deterministic pipeline signature as callback state, so it does not prove that a callback belongs to the browser’s authorization attempt and permits an authorization code to be submitted to another user’s active pipeline. > >## Fix Focus Areas >- src/sentry/integrations/github/integration.py[401-413] >- src/sentry/identity/oauth2.py[245-253] >- src/sentry/identity/oauth2.py[316-335] > >## Recommended Fix >Generate a cryptographically random OAuth state value before redirecting to GitHub, store it with `pipeline.bind_state`, and validate the callback’s `state` against `pipeline.fetch_state("state")`. Reject absent, mismatched, or already-consumed state before exchanging the authorization code, and construct the authorization query with the standard URL encoder, following the established OAuth2 flow. >``` > <code>ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools</code> ></details> <hr/> </details> <br/> <img src="https://img.shields.io/badge/Medium-634FD1?style=flat-square" height="20px" alt="Remediation recommended"> <details> <summary> 3. Some GitHub setup retries now crash <code>🐞 Bug</code> <code>☼ Reliability</code></summary> <br/> > <details open> ><summary>Description</summary> ><br/> > ><pre> ><b><i>GitHubInstallation.dispatch</i></b> unconditionally indexes <b><i>integration.metadata[&quot;sender&quot;][&quot;login&quot;]</i></b> >after finding an active unassociated integration, although integrations created through the ordinary ><b><i>ensure_integration</i></b> setup path may have no <b><i>sender</i></b> metadata. A concurrent, interrupted, or later >repeated setup can reach this branch before organization association completes or while such an >integration is retained, raising <b><i>KeyError</i></b> instead of rendering the controlled installation error >response. ></pre> ></details> > <details> ><summary>Code</summary> ><br/> > ><code>[src/sentry/integrations/github/integration.py[R501-505]](https://github.com/drape-io/crbench-qodo-2026-09/pull/69/files#diff-b517da9f8145142071b7180613fc7d96383b7213f6be500fd29baa261e81cdb4R501-R505)</code> > >```diff >+ if ( >+ pipeline.fetch_state("github_authenticated_user") >+ != integration.metadata["sender"]["login"] >+ ): >+ return error(request, self.active_organization) >``` ></details> > <details> ><summary>Evidence</summary> ><br/> > ><pre> ><b><i>build_integration</i></b> includes <b><i>sender</i></b> only when pipeline state supplies it, while pipeline >completion creates the integration before adding its organization association, and the basic >setup-flow test confirms that setup-created GitHub integration metadata lacks this field. The >external installation endpoint explicitly treats an otherwise active integration without sender >metadata as a possible state, so the direct nested lookup is unsafe when association is incomplete >or interrupted. ></pre> > > <code>[src/sentry/integrations/github/integration.py[493-505]](https://github.com/drape-io/crbench-qodo-2026-09/blob/4dac495122950c3b48d618b43491b869c98cc43e/src/sentry/integrations/github/integration.py/#L493-L505)</code> > <code>[src/sentry/integrations/github/integration.py[351-379]](https://github.com/drape-io/crbench-qodo-2026-09/blob/4dac495122950c3b48d618b43491b869c98cc43e/src/sentry/integrations/github/integration.py/#L351-L379)</code> > <code>[tests/sentry/integrations/github/test_integration.py[295-310]](https://github.com/drape-io/crbench-qodo-2026-09/blob/4dac495122950c3b48d618b43491b869c98cc43e/tests/sentry/integrations/github/test_integration.py/#L295-L310)</code> > <code>[src/sentry/integrations/github/installation.py[32-45]](https://github.com/drape-io/crbench-qodo-2026-09/blob/4dac495122950c3b48d618b43491b869c98cc43e/src/sentry/integrations/github/installation.py/#L32-L45)</code> > <code>[src/sentry/integrations/pipeline.py[126-132]](https://github.com/drape-io/crbench-qodo-2026-09/blob/4dac495122950c3b48d618b43491b869c98cc43e/src/sentry/integrations/pipeline.py/#L126-L132)</code> > <code>[src/sentry/integrations/pipeline.py[225-227]](https://github.com/drape-io/crbench-qodo-2026-09/blob/4dac495122950c3b48d618b43491b869c98cc43e/src/sentry/integrations/pipeline.py/#L225-L227)</code> > <code>[tests/sentry/integrations/github/test_integration.py[294-313]](https://github.com/drape-io/crbench-qodo-2026-09/blob/4dac495122950c3b48d618b43491b869c98cc43e/tests/sentry/integrations/github/test_integration.py/#L294-L313)</code> ></details> > <details> ><summary>Agent prompt</summary> ><br/> > >``` >The issue below was found during a code review. Follow the provided context and guidance below and implement a solution > >## Issue description >The authenticated-user comparison assumes every active unassociated integration contains webhook sender metadata, although integrations created through the normal setup flow can omit that field. Concurrent, interrupted, or repeated setup can therefore reach the comparison with absent or malformed sender data. > >## Fix Focus Areas >- src/sentry/integrations/github/integration.py[493-505] >- src/sentry/integrations/github/integration.py[351-379] >- src/sentry/integrations/github/installation.py[32-45] >- src/sentry/integrations/pipeline.py[126-132] >- tests/sentry/integrations/github/test_integration.py[294-313] > >## Recommended Fix >Read sender metadata defensively before comparing the authenticated user, and treat absent or malformed sender data as an unverified installation rather than indexing it directly. Return the existing controlled invalid-installation response or implement a supported verification path, and prevent setup-created integrations from entering this branch without webhook verification. >``` > <code>ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools</code> ></details> <hr/> </details> <details> <summary> 4. GitHub outages turn setup into server errors <code>🐞 Bug</code> <code>☼ Reliability</code></summary> <br/> > <details open> ><summary>Description</summary> ><br/> > ><pre> ><b><i>OAuthLoginView.dispatch</i></b> calls <b><i>safe_urlopen</i></b> and <b><i>get_user_info</i></b> without handling their transport, >HTTP-status, decoding, or malformed user-response failures. A token-endpoint connection failure or a >non-success or malformed response from GitHub’s user endpoint escapes the integration pipeline >instead of reaching the existing installation failure page. ></pre> ></details> > <details> ><summary>Code</summary> ><br/> > ><code>[src/sentry/integrations/github/integration.py[R423-434]](https://github.com/drape-io/crbench-qodo-2026-09/pull/69/files#diff-b517da9f8145142071b7180613fc7d96383b7213f6be500fd29baa261e81cdb4R423-R434)</code> > >```diff >+ req = safe_urlopen(url=ghip.get_oauth_access_token_url(), data=data) >+ >+ try: >+ body = safe_urlread(req).decode("utf-8") >+ payload = dict(parse_qsl(body)) >+ except Exception: >+ payload = {} >+ >+ if "access_token" not in payload: >+ return error(request, self.active_organization) >+ >+ authenticated_user_info = get_user_info(payload["access_token"]) >``` ></details> > <details> ><summary>Evidence</summary> ><br/> > ><pre> >Both external calls are made outside a covering exception handler: the parsing-only <b><i>try</i></b> begins >after <b><i>safe_urlopen</i></b>, and <b><i>get_user_info</i></b> is also invoked outside it. <b><i>safe_urlopen</i></b> delegates >directly to the HTTP session request, while <b><i>get_user_info</i></b> calls <b><i>raise_for_status()</i></b> and parses >JSON directly; by comparison, the shared OAuth callback explicitly converts connection, >TLS/certificate, and decoding failures into user-visible pipeline errors. ></pre> > > <code>[src/sentry/integrations/github/integration.py[423-434]](https://github.com/drape-io/crbench-qodo-2026-09/blob/4dac495122950c3b48d618b43491b869c98cc43e/src/sentry/integrations/github/integration.py/#L423-L434)</code> > <code>[src/sentry/http.py[85-116]](https://github.com/drape-io/crbench-qodo-2026-09/blob/4dac495122950c3b48d618b43491b869c98cc43e/src/sentry/http.py/#L85-L116)</code> > <code>[src/sentry/identity/github/provider.py[7-17]](https://github.com/drape-io/crbench-qodo-2026-09/blob/4dac495122950c3b48d618b43491b869c98cc43e/src/sentry/identity/github/provider.py/#L7-L17)</code> > <code>[src/sentry/identity/oauth2.py[282-315]](https://github.com/drape-io/crbench-qodo-2026-09/blob/4dac495122950c3b48d618b43491b869c98cc43e/src/sentry/identity/oauth2.py/#L282-L315)</code> > <code>[src/sentry/integrations/github/integration.py[422-436]](https://github.com/drape-io/crbench-qodo-2026-09/blob/4dac495122950c3b48d618b43491b869c98cc43e/src/sentry/integrations/github/integration.py/#L422-L436)</code> > <code>[src/sentry/http.py[85-120]](https://github.com/drape-io/crbench-qodo-2026-09/blob/4dac495122950c3b48d618b43491b869c98cc43e/src/sentry/http.py/#L85-L120)</code> ></details> > <details> ><summary>Agent prompt</summary> ><br/> > >``` >The issue below was found during a code review. Follow the provided context and guidance below and implement a solution > >## Issue description >External GitHub token and user-information requests, including response parsing, can raise exceptions that are not converted into the existing setup failure response and instead propagate out of the integration pipeline. > >## Fix Focus Areas >- src/sentry/integrations/github/integration.py[422-436] >- src/sentry/identity/oauth2.py[282-315] >- src/sentry/identity/github/provider.py[7-17] > >## Recommended Fix >Wrap both external requests and their response parsing in targeted exception handling for transport or connection failures, HTTP-response errors, decoding failures, and malformed payloads. Log each failure with exception context but without recording credentials or token contents, then return `error(request, self.active_organization)` so the existing invalid-installation response is shown instead of allowing the exception to produce a 500 response. >``` > <code>ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools</code> ></details> <hr/> </details> <img src="https://www.qodo.ai/wp-content/uploads/2025/11/light-grey-line.svg" height="10%" alt="Grey Divider"> <!-- qodo-context:start --> <details><summary><strong>Context sources</strong></summary> <div>Review mode: <code>🧠 Deep</code>: This security-sensitive GitHub OAuth and installation-flow change adds substantial new logic across multiple independent paths, with many opportunities for subtle authentication, state-validation, and integration regressions.</div> <!-- qodo-context:end --> </details> <img src="https://www.qodo.ai/wp-content/uploads/2025/11/light-grey-line.svg" height="10%" alt="Grey Divider"> <!-- qodo-daily-tip:start --> <details> <summary><strong>Tip of the day</strong></summary> <br/> <pre>💡 Did you know, you can reply &#x27;qodo&#x27; on any finding to push back, ask questions, or dig deeper</pre> <a href="https://docs.qodo.ai/tips-and-tricks">More tips ↗</a> | <a href="https://app.qodo.ai/configurations?tab=display-preferences">Customize Qodo ↗</a> | <a href="https://docs.qodo.ai">Qodo docs ↗</a> </details> <img src="https://www.qodo.ai/wp-content/uploads/2025/11/light-grey-line.svg" height="10%" alt="Grey Divider"> <!-- qodo-daily-tip:end --> <!-- https://github.com/drape-io/crbench-qodo-2026-09/commit/4dac495122950c3b48d618b43491b869c98cc43e --> <a href="https://www.qodo.ai"><img src="https://www.qodo.ai/wp-content/uploads/2025/03/qodo-logo.svg" width="80" alt="Qodo Logo"></a>