Browse Source

fix(webhooks): Reset some tags and context for JIRA & GHE (#45368)

This is a follow up to #45139 for JIRA and Github enterprise.

It seems that we're tagging events with information about organizations
even when it's impossible to have any org info.

We have events tagged with the following info even when it is not
possible:

- org slug
- org id
- org context

This issues causes finding errors that are for the wrong organization
when using `organization.slug`, thus, wasting time for engineers and
customer support.

This change only clears the invalid tag values to reduce the impact of
this issue rather than fixing the root issue.

Here's a
[query](https://sentry.sentry.io/discover/results/?end=2023-03-04T04%3A59%3A59&field=transaction&field=count_unique%28organization.slug%29&field=count%28%29&name=Integration.DoesNotExist%3A+Integration+matching+query+does+not+exist.&project=1&query=%21organization.slug%3A%22%22+error.value%3A%22Integration+matching+query+does+not+exist.%22&sort=-transaction&start=2023-03-02T05%3A00%3A00&yAxis=count%28%29)
showing transactions that should not have org values set.

Fixes [WOR-2464](https://getsentry.atlassian.net/browse/WOR-2464)

[WOR-2464]:
https://getsentry.atlassian.net/browse/WOR-2464?atlOrigin=eyJpIjoiNWRkNTljNzYxNjVmNDY3MDlhMDU5Y2ZhYzA5YTRkZjUiLCJwIjoiZ2l0aHViLWNvbS1KU1cifQ
Armen Zambrano G 2 years ago
parent
commit
356bec76bc

+ 1 - 0
mypy.ini

@@ -79,6 +79,7 @@ files = fixtures/mypy-stubs,
         src/sentry/integrations/slack/,
         src/sentry/integrations/message_builder.py,
         src/sentry/integrations/utils/atlassian_connect.py,
+        src/sentry/integrations/utils/cleanup.py,
         src/sentry/integrations/utils/code_mapping.py,
         src/sentry/integrations/utils/codecov.py,
         src/sentry/integrations/vsts/,

+ 2 - 19
src/sentry/integrations/github/webhook.py

@@ -14,10 +14,10 @@ from django.utils.decorators import method_decorator
 from django.views.decorators.csrf import csrf_exempt
 from django.views.generic import View
 from rest_framework.request import Request
-from sentry_sdk import configure_scope
 
 from sentry import options
 from sentry.constants import ObjectStatus
+from sentry.integrations.utils.cleanup import clear_tags_and_context
 from sentry.models import (
     Commit,
     CommitAuthor,
@@ -37,23 +37,6 @@ from .repository import GitHubRepositoryProvider
 logger = logging.getLogger("sentry.webhooks")
 
 
-def clear_tags_and_context_if_already_set() -> None:
-    """Clear org tags and context since it should not be set"""
-    reset_values = False
-    with configure_scope() as scope:
-        for tag in ["organization", "organization.slug"]:
-            if tag in scope._tags:
-                reset_values = True
-                del scope._tags[tag]
-
-        if "organization" in scope._contexts:
-            reset_values = True
-            del scope._contexts["organization"]
-
-        if reset_values:
-            logger.info("We've reset the context and tags.")
-
-
 class Webhook:
     provider = "github"
 
@@ -474,7 +457,7 @@ class GitHubWebhookBase(View):  # type: ignore
         raise NotImplementedError
 
     def handle(self, request: Request) -> HttpResponse:
-        clear_tags_and_context_if_already_set()
+        clear_tags_and_context()
         secret = self.get_secret()
 
         if secret is None:

+ 2 - 0
src/sentry/integrations/github_enterprise/webhook.py

@@ -18,6 +18,7 @@ from sentry.integrations.github.webhook import (
     PullRequestEventWebhook,
     PushEventWebhook,
 )
+from sentry.integrations.utils.cleanup import clear_tags_and_context
 from sentry.models import Integration
 from sentry.utils import json
 from sentry.utils.sdk import configure_scope
@@ -112,6 +113,7 @@ class GitHubEnterpriseWebhookBase(View):
             return None
 
     def handle(self, request: Request) -> Response:
+        clear_tags_and_context()
         with configure_scope() as scope:
             meta = request.META
             try:

+ 2 - 0
src/sentry/integrations/jira_server/webhooks.py

@@ -7,6 +7,7 @@ from rest_framework.response import Response
 
 from sentry.api.base import Endpoint, pending_silo_endpoint
 from sentry.integrations.jira_server.utils import handle_assignee_change, handle_status_change
+from sentry.integrations.utils.cleanup import clear_tags_and_context
 from sentry.models import Integration
 from sentry.shared_integrations.exceptions import ApiError
 from sentry.utils import jwt
@@ -51,6 +52,7 @@ class JiraIssueUpdatedWebhook(Endpoint):
         return super().dispatch(request, *args, **kwargs)
 
     def post(self, request: Request, token, *args, **kwargs) -> Response:
+        clear_tags_and_context()
         extra = {}
         try:
             integration = get_integration_from_token(token)

+ 22 - 0
src/sentry/integrations/utils/cleanup.py

@@ -0,0 +1,22 @@
+import logging
+
+from sentry_sdk import configure_scope
+
+logger = logging.getLogger(__name__)
+
+
+def clear_tags_and_context() -> None:
+    """Clear certain tags and context since it should not be set."""
+    reset_values = False
+    with configure_scope() as scope:
+        for tag in ["organization", "organization.slug"]:
+            if tag in scope._tags:
+                reset_values = True
+                del scope._tags[tag]
+
+        if "organization" in scope._contexts:
+            reset_values = True
+            del scope._contexts["organization"]
+
+        if reset_values:
+            logger.info("We've reset the context and tags.")