views.py 9.5 KB

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