api.py 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170
  1. from typing import Optional
  2. from anonymizeip import anonymize_ip
  3. from django.conf import settings
  4. from django.http import HttpResponse
  5. from ipware import get_client_ip
  6. from ninja import Router, Schema
  7. from ninja.errors import ValidationError
  8. from glitchtip.utils import async_call_celery_task
  9. from .authentication import EventAuthHttpRequest, event_auth
  10. from .schema import (
  11. CSPIssueEventSchema,
  12. EnvelopeSchema,
  13. ErrorIssueEventSchema,
  14. EventIngestSchema,
  15. EventUser,
  16. IngestIssueEvent,
  17. InterchangeIssueEvent,
  18. IssueEventSchema,
  19. SecuritySchema,
  20. TransactionEventSchema,
  21. )
  22. from .tasks import ingest_event, ingest_transaction
  23. from .utils import cache_set_nx
  24. router = Router(auth=event_auth)
  25. class EventIngestOut(Schema):
  26. event_id: str
  27. task_id: Optional[str] = None # For debug purposes only
  28. class EnvelopeIngestOut(Schema):
  29. id: Optional[str] = None
  30. def get_issue_event_class(event: IngestIssueEvent):
  31. return ErrorIssueEventSchema if event.exception else IssueEventSchema
  32. def get_ip_address(request: EventAuthHttpRequest) -> Optional[str]:
  33. """
  34. Get IP address from request. Anonymize it based on project settings.
  35. Keep this logic in the api view, we aim to anonymize data before storing
  36. on redis/postgres.
  37. """
  38. project = request.auth
  39. client_ip, is_routable = get_client_ip(request)
  40. if is_routable:
  41. if project.should_scrub_ip_addresses:
  42. client_ip = anonymize_ip(client_ip)
  43. return client_ip
  44. return None
  45. @router.post("/{project_id}/store/", response=EventIngestOut)
  46. async def event_store(
  47. request: EventAuthHttpRequest,
  48. payload: EventIngestSchema,
  49. project_id: int,
  50. ):
  51. """
  52. Event store is the original event ingest API from OSS Sentry but is used less often
  53. Unlike Envelope, it accepts only one Issue event.
  54. """
  55. if cache_set_nx("uuid" + payload.event_id.hex, True) is False:
  56. raise ValidationError([{"message": "Duplicate event id"}])
  57. if client_ip := get_ip_address(request):
  58. if payload.user:
  59. payload.user.ip_address = client_ip
  60. else:
  61. payload.user = EventUser(ip_address=client_ip)
  62. issue_event_class = get_issue_event_class(payload)
  63. issue_event = InterchangeIssueEvent(
  64. event_id=payload.event_id,
  65. project_id=project_id,
  66. organization_id=request.auth.organization_id,
  67. payload=issue_event_class(**payload.dict()),
  68. )
  69. task_result = await async_call_celery_task(ingest_event, issue_event.dict())
  70. result = {"event_id": payload.event_id.hex}
  71. if settings.IS_LOAD_TEST:
  72. result["task_id"] = task_result.task_id
  73. return result
  74. @router.post("/{project_id}/envelope/", response=EnvelopeIngestOut)
  75. async def event_envelope(
  76. request: EventAuthHttpRequest,
  77. payload: EnvelopeSchema,
  78. project_id: int,
  79. ):
  80. """
  81. Envelopes can contain various types of data.
  82. GlitchTip supports issue events and transaction events.
  83. Ignore other data types.
  84. Do support multiple valid events
  85. Make as few io calls as possible. Some language SDKs (PHP) cannot run async code
  86. and will block while waiting for GlitchTip to respond.
  87. """
  88. client_ip = get_ip_address(request)
  89. header = payload._header
  90. for item_header, item in payload._items:
  91. if item_header.type == "event" and isinstance(item, IngestIssueEvent):
  92. if item.user:
  93. item.user.ip_address = client_ip
  94. else:
  95. item.user = EventUser(ip_address=client_ip)
  96. issue_event_class = get_issue_event_class(item)
  97. interchange_event_kwargs = {
  98. "project_id": project_id,
  99. "organization_id": request.auth.organization_id,
  100. "payload": issue_event_class(**item.dict()),
  101. }
  102. if header.event_id:
  103. interchange_event_kwargs["event_id"] = header.event_id
  104. interchange_event = InterchangeIssueEvent(**interchange_event_kwargs)
  105. # Faux unique uuid as GlitchTip can accept duplicate UUIDs
  106. # The primary key of an event is uuid, received
  107. if cache_set_nx("uuid" + interchange_event.event_id.hex, True) is True:
  108. await async_call_celery_task(ingest_event, interchange_event.dict())
  109. elif item_header.type == "transaction" and isinstance(
  110. item, TransactionEventSchema
  111. ):
  112. interchange_event_kwargs = {
  113. "project_id": project_id,
  114. "organization_id": request.auth.organization_id,
  115. "payload": TransactionEventSchema(**item.dict()),
  116. }
  117. interchange_event = InterchangeIssueEvent(**interchange_event_kwargs)
  118. if cache_set_nx("uuid" + interchange_event.event_id.hex, True) is True:
  119. await async_call_celery_task(
  120. ingest_transaction, interchange_event.dict()
  121. )
  122. if header.event_id:
  123. return {"id": header.event_id.hex}
  124. return {}
  125. @router.post("/{project_id}/security/")
  126. async def event_security(
  127. request: EventAuthHttpRequest,
  128. payload: SecuritySchema,
  129. project_id: int,
  130. ):
  131. """
  132. Accept Security (and someday other) issue events.
  133. Reformats event to make CSP browser format match more standard
  134. event format.
  135. """
  136. event = CSPIssueEventSchema(csp=payload.csp_report.dict(by_alias=True))
  137. if client_ip := get_ip_address(request):
  138. if event.user:
  139. event.user.ip_address = client_ip
  140. else:
  141. event.user = EventUser(ip_address=client_ip)
  142. issue_event = InterchangeIssueEvent(
  143. project_id=project_id,
  144. organization_id=request.auth.organization_id,
  145. payload=event.dict(by_alias=True),
  146. )
  147. await async_call_celery_task(ingest_event, issue_event.dict(by_alias=True))
  148. return HttpResponse(status=201)