authentication.py 3.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. from typing import Literal
  2. from uuid import UUID
  3. from django.conf import settings
  4. from django.core.cache import cache
  5. from django.http import HttpRequest
  6. from ninja.errors import AuthenticationError, HttpError, ValidationError
  7. from glitchtip.api.exceptions import ThrottleException
  8. from projects.models import Project
  9. from sentry.utils.auth import parse_auth_header
  10. from .constants import EVENT_BLOCK_CACHE_KEY
  11. def auth_from_request(request: HttpRequest):
  12. """
  13. Get DSN (sentry_key) from request header
  14. Accept both sentry or glitchtip prefix
  15. Do not read request body when possible. This may result in uncompression which is slow.
  16. """
  17. for k in request.GET.keys():
  18. if k in ["sentry_key", "glitchtip_key"]:
  19. return request.GET[k]
  20. if auth_header := request.META.get(
  21. "HTTP_X_SENTRY_AUTH", request.META.get("HTTP_AUTHORIZATION")
  22. ):
  23. result = parse_auth_header(auth_header)
  24. return result.get("sentry_key", result.get("glitchtip_key"))
  25. raise AuthenticationError("Unable to find authentication information")
  26. # One letter codes to save cache memory and map to various event rejection type exceptions
  27. REJECTION_MAP: dict[Literal["v", "t"], Exception] = {
  28. "v": AuthenticationError([{"message": "Invalid DSN"}]),
  29. "t": ThrottleException(),
  30. }
  31. REJECTION_WAIT = 30
  32. async def get_project(request: HttpRequest):
  33. """
  34. Return the valid and accepting events project based on a request.
  35. Throttle unwanted requests using cache to mitigate repeat attempts
  36. """
  37. if not request.resolver_match:
  38. raise ValidationError([{"message": "Invalid project ID"}])
  39. project_id: int = request.resolver_match.captured_kwargs.get("project_id")
  40. try:
  41. sentry_key = UUID(auth_from_request(request))
  42. except ValueError as err:
  43. raise ValidationError(
  44. [{"message": "dsn key badly formed hexadecimal UUID string"}]
  45. ) from err
  46. # block cache check should be right before database call
  47. block_cache_key = EVENT_BLOCK_CACHE_KEY + str(project_id)
  48. if block_value := cache.get(block_cache_key):
  49. # Repeat the original message until cache expires
  50. raise REJECTION_MAP[block_value]
  51. project = (
  52. await Project.objects.filter(
  53. id=project_id,
  54. projectkey__public_key=sentry_key,
  55. )
  56. .select_related("organization")
  57. .only(
  58. "id",
  59. "organization__is_accepting_events",
  60. )
  61. .afirst()
  62. )
  63. if not project:
  64. cache.set(block_cache_key, "v", REJECTION_WAIT)
  65. raise REJECTION_MAP["v"]
  66. if not project.organization.is_accepting_events:
  67. cache.set(block_cache_key, "t", REJECTION_WAIT)
  68. raise REJECTION_MAP["t"]
  69. return project
  70. async def event_auth(request: HttpRequest):
  71. """
  72. Event Ingest authentication means validating the DSN (sentry_key).
  73. Throttling is also handled here.
  74. It does not include user authentication.
  75. """
  76. if settings.MAINTENANCE_EVENT_FREEZE:
  77. raise HttpError(
  78. 503, "Events are not currently being accepted due to maintenance."
  79. )
  80. return await get_project(request)