views.py 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189
  1. import json
  2. import logging
  3. import random
  4. import string
  5. import uuid
  6. from django.conf import settings
  7. from django.core.exceptions import SuspiciousOperation, ValidationError
  8. from django.db.models import Exists, OuterRef
  9. from django.http import HttpResponse
  10. from django.test import RequestFactory
  11. from rest_framework import exceptions, permissions, status
  12. from rest_framework.response import Response
  13. from rest_framework.views import APIView
  14. from sentry_sdk import capture_exception, set_context, set_level
  15. from difs.tasks import difs_run_resolve_stacktrace
  16. from difs.models import DebugInformationFile
  17. from performance.serializers import TransactionEventSerializer
  18. from projects.models import Project
  19. from sentry.utils.auth import parse_auth_header
  20. from .negotiation import IgnoreClientContentNegotiation
  21. from .parsers import EnvelopeParser
  22. from .serializers import (
  23. EnvelopeHeaderSerializer,
  24. StoreCSPReportSerializer,
  25. StoreDefaultSerializer,
  26. StoreErrorSerializer,
  27. )
  28. logger = logging.getLogger(__name__)
  29. def test_event_view(request):
  30. """
  31. This view is used only to test event store performance
  32. It requires DEBUG to be True
  33. """
  34. factory = RequestFactory()
  35. request = request = factory.get(
  36. "/api/6/store/?sentry_key=244703e8083f4b16988c376ea46e9a08"
  37. )
  38. with open("events/test_data/py_hi_event.json") as json_file:
  39. data = json.load(json_file)
  40. data["event_id"] = uuid.uuid4()
  41. data["message"] = "".join(
  42. random.choices(string.ascii_uppercase + string.digits, k=8)
  43. )
  44. request.data = data
  45. EventStoreAPIView().post(request, id=6)
  46. return HttpResponse("<html><body></body></html>")
  47. class BaseEventAPIView(APIView):
  48. permission_classes = [permissions.AllowAny]
  49. authentication_classes = []
  50. content_negotiation_class = IgnoreClientContentNegotiation
  51. http_method_names = ["post"]
  52. @classmethod
  53. def auth_from_request(cls, request):
  54. # Accept both sentry or glitchtip prefix.
  55. # Prefer glitchtip when not using a sentry SDK but support both.
  56. result = {
  57. k: request.GET[k]
  58. for k in request.GET.keys()
  59. if k[:7] == "sentry_" or k[:10] == "glitchtip_"
  60. }
  61. if request.META.get("HTTP_X_SENTRY_AUTH", "")[:7].lower() == "sentry ":
  62. if result:
  63. raise SuspiciousOperation(
  64. "Multiple authentication payloads were detected."
  65. )
  66. result = parse_auth_header(request.META["HTTP_X_SENTRY_AUTH"])
  67. elif request.META.get("HTTP_AUTHORIZATION", "")[:7].lower() == "sentry ":
  68. if result:
  69. raise SuspiciousOperation(
  70. "Multiple authentication payloads were detected."
  71. )
  72. result = parse_auth_header(request.META["HTTP_AUTHORIZATION"])
  73. if not result:
  74. raise exceptions.NotAuthenticated(
  75. "Unable to find authentication information"
  76. )
  77. return result.get("sentry_key", result.get("glitchtip_key"))
  78. def get_project(self, request, project_id):
  79. sentry_key = BaseEventAPIView.auth_from_request(request)
  80. difs_subquery = DebugInformationFile.objects.filter(project_id=OuterRef("pk"))
  81. try:
  82. project = (
  83. Project.objects.filter(id=project_id, projectkey__public_key=sentry_key)
  84. .annotate(has_difs=Exists(difs_subquery))
  85. .select_related("organization")
  86. .only("id", "first_event", "organization__is_accepting_events")
  87. .first()
  88. )
  89. except ValidationError as e:
  90. raise exceptions.AuthenticationFailed({"error": "Invalid api key"})
  91. if not project:
  92. if Project.objects.filter(id=project_id).exists():
  93. raise exceptions.AuthenticationFailed({"error": "Invalid api key"})
  94. raise exceptions.ValidationError("Invalid project_id: %s" % project_id)
  95. if not project.organization.is_accepting_events:
  96. raise exceptions.Throttled(detail="event rejected due to rate limit")
  97. return project
  98. def get_event_serializer_class(self, data=[]):
  99. """Determine event type and return serializer"""
  100. if "exception" in data and data["exception"]:
  101. return StoreErrorSerializer
  102. if "platform" not in data:
  103. return StoreCSPReportSerializer
  104. return StoreDefaultSerializer
  105. def process_event(self, data, request, project):
  106. set_context("incoming event", data)
  107. serializer = self.get_event_serializer_class(data)(
  108. data=data, context={"request": self.request, "project": project}
  109. )
  110. try:
  111. serializer.is_valid(raise_exception=True)
  112. except exceptions.ValidationError as e:
  113. set_level("warning")
  114. capture_exception(e)
  115. logger.warning("Invalid event %s", serializer.errors)
  116. return Response()
  117. event = serializer.save()
  118. if event.data.get("exception") is not None and project.has_difs:
  119. difs_run_resolve_stacktrace(event.event_id)
  120. return Response({"id": event.event_id_hex})
  121. class EventStoreAPIView(BaseEventAPIView):
  122. def post(self, request, *args, **kwargs):
  123. if settings.EVENT_STORE_DEBUG:
  124. print(json.dumps(request.data))
  125. try:
  126. project = self.get_project(request, kwargs.get("id"))
  127. except exceptions.AuthenticationFailed as e:
  128. # Replace 403 status code with 401 to match OSS Sentry
  129. return Response(e.detail, status=401)
  130. return self.process_event(request.data, request, project)
  131. class CSPStoreAPIView(EventStoreAPIView):
  132. pass
  133. class EnvelopeAPIView(BaseEventAPIView):
  134. parser_classes = [EnvelopeParser]
  135. def get_serializer_class(self):
  136. return TransactionEventSerializer
  137. def post(self, request, *args, **kwargs):
  138. if settings.EVENT_STORE_DEBUG:
  139. print(json.dumps(request.data))
  140. project = self.get_project(request, kwargs.get("id"))
  141. data = request.data
  142. if len(data) < 2:
  143. raise ValidationError("Envelope has no headers")
  144. event_header_serializer = EnvelopeHeaderSerializer(data=data.pop(0))
  145. event_header_serializer.is_valid(raise_exception=True)
  146. # Multi part envelopes are not yet supported
  147. message_header = data.pop(0)
  148. if message_header.get("type") == "transaction":
  149. serializer = self.get_serializer_class()(
  150. data=data.pop(0), context={"request": self.request, "project": project}
  151. )
  152. serializer.is_valid(raise_exception=True)
  153. event = serializer.save()
  154. return Response({"id": event.event_id_hex})
  155. elif message_header.get("type") == "event":
  156. event_data = data.pop(0)
  157. return self.process_event(event_data, request, project)
  158. elif message_header.get("type") == "session":
  159. return Response(
  160. {"message": "Session events are not supported at this time."},
  161. status=status.HTTP_501_NOT_IMPLEMENTED,
  162. )
  163. return Response(status=status.HTTP_501_NOT_IMPLEMENTED)