schema.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477
  1. import logging
  2. import typing
  3. import uuid
  4. from datetime import datetime
  5. from typing import Annotated, Any, Literal, Union
  6. from urllib.parse import parse_qs, urlparse
  7. from django.utils.timezone import now
  8. from ninja import Field
  9. from pydantic import (
  10. AliasChoices,
  11. BaseModel,
  12. BeforeValidator,
  13. JsonValue,
  14. RootModel,
  15. ValidationError,
  16. WrapValidator,
  17. field_validator,
  18. model_validator,
  19. )
  20. from apps.issue_events.constants import IssueEventType
  21. from ..shared.schema.base import LaxIngestSchema
  22. from ..shared.schema.contexts import Contexts
  23. from ..shared.schema.event import (
  24. BaseIssueEvent,
  25. BaseRequest,
  26. EventBreadcrumb,
  27. ListKeyValue,
  28. )
  29. from ..shared.schema.user import EventUser
  30. from ..shared.schema.utils import invalid_to_none
  31. logger = logging.getLogger(__name__)
  32. CoercedStr = Annotated[
  33. str, BeforeValidator(lambda v: str(v) if isinstance(v, (bool, list)) else v)
  34. ]
  35. """
  36. Coerced Str that will coerce bool/list to str when found
  37. """
  38. def coerce_list(v: Any) -> Any:
  39. """Wrap non-list dict into list: {"a": 1} to [{"a": 1}]"""
  40. return v if not isinstance(v, dict) else [v]
  41. class Signal(LaxIngestSchema):
  42. number: int
  43. code: int | None
  44. name: str | None
  45. code_name: str | None
  46. class MachException(LaxIngestSchema):
  47. number: int
  48. code: int
  49. subcode: int
  50. name: str | None
  51. class NSError(LaxIngestSchema):
  52. code: int
  53. domain: str
  54. class Errno(LaxIngestSchema):
  55. number: int
  56. name: str | None
  57. class MechanismMeta(LaxIngestSchema):
  58. signal: Signal | None = None
  59. match_exception: MachException | None = None
  60. ns_error: NSError | None = None
  61. errno: Errno | None = None
  62. class ExceptionMechanism(LaxIngestSchema):
  63. type: str
  64. description: str | None = None
  65. help_link: str | None = None
  66. handled: bool | None = None
  67. synthetic: bool | None = None
  68. meta: dict | None = None
  69. data: dict | None = None
  70. class StackTraceFrame(LaxIngestSchema):
  71. filename: str | None = None
  72. function: str | None = None
  73. raw_function: str | None = None
  74. module: str | None = None
  75. lineno: int | None = None
  76. colno: int | None = None
  77. abs_path: str | None = None
  78. context_line: str | None = None
  79. pre_context: list[str | None] | None = None
  80. post_context: list[str | None] | None = None
  81. source_link: str | None = None
  82. in_app: bool | None = None
  83. stack_start: bool | None = None
  84. vars: dict[str, Union[str, dict, list]] | None = None
  85. instruction_addr: str | None = None
  86. addr_mode: str | None = None
  87. symbol_addr: str | None = None
  88. image_addr: str | None = None
  89. package: str | None = None
  90. platform: str | None = None
  91. def is_url(self, filename: str) -> bool:
  92. return filename.startswith(("file:", "http:", "https:", "applewebdata:"))
  93. @model_validator(mode="after")
  94. def normalize_files(self):
  95. if not self.abs_path and self.filename:
  96. self.abs_path = self.filename
  97. if self.filename and self.is_url(self.filename):
  98. self.filename = urlparse(self.filename).path
  99. return self
  100. @field_validator("pre_context", "post_context")
  101. @classmethod
  102. def replace_null(cls, context: list[str | None]) -> list[str | None] | None:
  103. if context:
  104. return [line if line else "" for line in context]
  105. return None
  106. class StackTrace(LaxIngestSchema):
  107. frames: list[StackTraceFrame]
  108. registers: dict[str, str] | None = None
  109. class EventException(LaxIngestSchema):
  110. type: str | None = None
  111. value: Annotated[str | None, WrapValidator(invalid_to_none)] = None
  112. module: str | None = None
  113. thread_id: str | None = None
  114. mechanism: Annotated[ExceptionMechanism | None, WrapValidator(invalid_to_none)] = (
  115. None
  116. )
  117. stacktrace: Annotated[StackTrace | None, WrapValidator(invalid_to_none)] = None
  118. @model_validator(mode="after")
  119. def check_type_value(self):
  120. if self.type is None and self.value is None:
  121. return None
  122. return self
  123. class ValueEventException(LaxIngestSchema):
  124. values: list[EventException]
  125. @field_validator("values")
  126. @classmethod
  127. def strip_null(cls, v: list[EventException]) -> list[EventException]:
  128. return [e for e in v if e is not None]
  129. class EventMessage(LaxIngestSchema):
  130. formatted: str = Field(max_length=8192, default="")
  131. message: str | None = None
  132. params: list[CoercedStr] | dict[str, str] | None = None
  133. @model_validator(mode="after")
  134. def set_formatted(self) -> "EventMessage":
  135. """
  136. When the EventMessage formatted string is not set,
  137. attempt to set it based on message and params interpolation
  138. """
  139. if not self.formatted and self.message:
  140. params = self.params
  141. if isinstance(params, list) and params:
  142. self.formatted = self.message % tuple(params)
  143. elif isinstance(params, dict):
  144. self.formatted = self.message.format(**params)
  145. return self
  146. class EventTemplate(LaxIngestSchema):
  147. lineno: int
  148. abs_path: str | None = None
  149. filename: str
  150. context_line: str
  151. pre_context: list[str] | None = None
  152. post_context: list[str] | None = None
  153. # Important, for some reason using Schema will cause the DebugImage union not to work
  154. class SourceMapImage(BaseModel):
  155. type: Literal["sourcemap"]
  156. code_file: str
  157. debug_id: uuid.UUID
  158. # Important, for some reason using Schema will cause the DebugImage union not to work
  159. class OtherDebugImage(BaseModel):
  160. type: str
  161. DebugImage = Annotated[SourceMapImage, Field(discriminator="type")] | OtherDebugImage
  162. class DebugMeta(LaxIngestSchema):
  163. images: list[DebugImage]
  164. class ValueEventBreadcrumb(LaxIngestSchema):
  165. values: list[EventBreadcrumb]
  166. class ClientSDKPackage(LaxIngestSchema):
  167. name: str | None = None
  168. version: str | None = None
  169. class ClientSDKInfo(LaxIngestSchema):
  170. integrations: list[str | None] | None = None
  171. name: str | None
  172. packages: list[ClientSDKPackage] | None = None
  173. version: str | None
  174. @field_validator("packages", mode="before")
  175. def name_must_contain_space(cls, v: Any) -> Any:
  176. return coerce_list(v)
  177. class RequestHeaders(LaxIngestSchema):
  178. content_type: str | None
  179. class RequestEnv(LaxIngestSchema):
  180. remote_addr: str | None
  181. QueryString = str | ListKeyValue | dict[str, str | dict[str, Any] | None]
  182. """Raw URL querystring, list, or dict"""
  183. KeyValueFormat = Union[list[list[str | None]], dict[str, CoercedStr | None]]
  184. """
  185. key-values in list or dict format. Example {browser: firefox} or [[browser, firefox]]
  186. """
  187. class IngestRequest(BaseRequest):
  188. headers: KeyValueFormat | None = None
  189. query_string: QueryString | None = None
  190. @field_validator("headers", mode="before")
  191. @classmethod
  192. def fix_non_standard_headers(cls, v):
  193. """
  194. Fix non-documented format used by PHP Sentry Client
  195. Convert {"Foo": ["bar"]} into {"Foo: "bar"}
  196. """
  197. if isinstance(v, dict):
  198. return {
  199. key: value[0] if isinstance(value, list) else value
  200. for key, value in v.items()
  201. }
  202. return v
  203. @field_validator("query_string", "headers")
  204. @classmethod
  205. def prefer_list_key_value(
  206. cls, v: Union[QueryString, KeyValueFormat] | None
  207. ) -> ListKeyValue | None:
  208. """Store all querystring, header formats in a list format"""
  209. result: ListKeyValue | None = None
  210. if isinstance(v, str) and v: # It must be a raw querystring, parse it
  211. qs = parse_qs(v)
  212. result = [[key, value] for key, values in qs.items() for value in values]
  213. elif isinstance(v, dict): # Convert dict to list
  214. result = [[key, value] for key, value in v.items()]
  215. elif isinstance(v, list): # Normalize list (throw out any weird data)
  216. result = [item[:2] for item in v if len(item) >= 2]
  217. if result:
  218. # Remove empty and any key called "Cookie" which could be sensitive data
  219. entry_to_remove = ["Cookie", ""]
  220. return sorted(
  221. [entry for entry in result if entry != entry_to_remove],
  222. key=lambda x: (x[0], x[1]),
  223. )
  224. return result
  225. class IngestIssueEvent(BaseIssueEvent):
  226. timestamp: datetime = Field(default_factory=now)
  227. level: str | None = "error"
  228. logentry: EventMessage | None = None
  229. logger: str | None = None
  230. transaction: str | None = Field(
  231. validation_alias=AliasChoices("transaction", "culprit"), default=None
  232. )
  233. server_name: str | None = None
  234. release: str | None = None
  235. dist: str | None = None
  236. tags: KeyValueFormat | None = None
  237. environment: str | None = None
  238. modules: dict[str, str | None] | None = None
  239. extra: dict[str, Any] | None = None
  240. fingerprint: list[Union[str, None]] | None = None
  241. errors: list[Any] | None = None
  242. exception: Union[list[EventException], ValueEventException] | None = None
  243. message: Union[str, EventMessage] | None = None
  244. template: EventTemplate | None = None
  245. breadcrumbs: Union[list[EventBreadcrumb], ValueEventBreadcrumb] | None = None
  246. sdk: ClientSDKInfo | None = None
  247. request: IngestRequest | None = None
  248. contexts: Contexts | None = None
  249. user: EventUser | None = None
  250. debug_meta: DebugMeta | None = None
  251. @field_validator("tags")
  252. @classmethod
  253. def prefer_dict(cls, v: KeyValueFormat | None) -> dict[str, str | None] | None:
  254. if isinstance(v, list):
  255. return {key: value for key, value in v if key is not None}
  256. return v
  257. class EventIngestSchema(IngestIssueEvent):
  258. event_id: uuid.UUID
  259. class TransactionEventSchema(LaxIngestSchema):
  260. type: Literal["transaction"] = "transaction"
  261. contexts: JsonValue
  262. measurements: JsonValue | None = None
  263. start_timestamp: datetime
  264. timestamp: datetime
  265. transaction: str
  266. # # SentrySDKEventSerializer
  267. breadcrumbs: JsonValue | None = None
  268. fingerprint: list[str] | None = None
  269. tags: KeyValueFormat | None = None
  270. event_id: uuid.UUID = Field(default_factory=uuid.uuid4)
  271. extra: JsonValue | None = None
  272. request: IngestRequest | None = None
  273. server_name: str | None = None
  274. sdk: ClientSDKInfo | None = None
  275. platform: str | None
  276. release: str | None = None
  277. environment: str | None = None
  278. _meta: JsonValue | None
  279. class EnvelopeHeaderSchema(LaxIngestSchema):
  280. event_id: uuid.UUID | None = None
  281. dsn: str | None = None
  282. sdk: ClientSDKInfo | None = None
  283. sent_at: datetime = Field(default_factory=now)
  284. SupportedItemType = Literal["transaction", "event"]
  285. IgnoredItemType = Literal[
  286. "session", "sessions", "client_report", "attachment", "user_report", "check_in"
  287. ]
  288. SUPPORTED_ITEMS = typing.get_args(SupportedItemType)
  289. class ItemHeaderSchema(LaxIngestSchema):
  290. content_type: str | None = None
  291. type: Union[SupportedItemType, IgnoredItemType]
  292. length: int | None = None
  293. class EnvelopeSchema(RootModel[list[dict[str, Any]]]):
  294. root: list[dict[str, Any]]
  295. _header: EnvelopeHeaderSchema
  296. _items: list[
  297. tuple[ItemHeaderSchema, IngestIssueEvent | TransactionEventSchema]
  298. ] = []
  299. @model_validator(mode="after")
  300. def validate_envelope(self) -> "EnvelopeSchema":
  301. data = self.root
  302. try:
  303. header = data.pop(0)
  304. except IndexError:
  305. raise ValidationError([{"message": "Envelope is empty"}])
  306. self._header = EnvelopeHeaderSchema(**header)
  307. while len(data) >= 2:
  308. item_header_data = data.pop(0)
  309. if item_header_data.get("type", None) not in SUPPORTED_ITEMS:
  310. continue
  311. item_header = ItemHeaderSchema(**item_header_data)
  312. if item_header.type == "event":
  313. try:
  314. item = IngestIssueEvent(**data.pop(0))
  315. except ValidationError as err:
  316. logger.warning("Envelope Event item invalid", exc_info=True)
  317. raise err
  318. self._items.append((item_header, item))
  319. elif item_header.type == "transaction":
  320. item = TransactionEventSchema(**data.pop(0))
  321. self._items.append((item_header, item))
  322. return self
  323. class CSPReportSchema(LaxIngestSchema):
  324. """
  325. https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy-Report-Only#violation_report_syntax
  326. """
  327. blocked_uri: str = Field(alias="blocked-uri")
  328. disposition: Literal["enforce", "report"] = Field(alias="disposition")
  329. document_uri: str = Field(alias="document-uri")
  330. effective_directive: str = Field(alias="effective-directive")
  331. original_policy: str | None = Field(alias="original-policy")
  332. script_sample: str | None = Field(alias="script-sample", default=None)
  333. status_code: int | None = Field(alias="status-code")
  334. line_number: int | None = None
  335. column_number: int | None = None
  336. class SecuritySchema(LaxIngestSchema):
  337. csp_report: CSPReportSchema = Field(alias="csp-report")
  338. ## Normalized Interchange Issue Events
  339. class IssueEventSchema(IngestIssueEvent):
  340. """
  341. Event storage and interchange format
  342. Used in json view and celery interchange
  343. Don't use this for api intake
  344. """
  345. type: Literal[IssueEventType.DEFAULT] = IssueEventType.DEFAULT
  346. class ErrorIssueEventSchema(IngestIssueEvent):
  347. type: Literal[IssueEventType.ERROR] = IssueEventType.ERROR
  348. class CSPIssueEventSchema(IngestIssueEvent):
  349. type: Literal[IssueEventType.CSP] = IssueEventType.CSP
  350. csp: CSPReportSchema
  351. class InterchangeEvent(LaxIngestSchema):
  352. """Normalized wrapper around issue event. Event should not contain repeat information."""
  353. event_id: uuid.UUID = Field(default_factory=uuid.uuid4)
  354. project_id: int
  355. organization_id: int
  356. received: datetime = Field(default_factory=now)
  357. payload: (
  358. IssueEventSchema
  359. | ErrorIssueEventSchema
  360. | CSPIssueEventSchema
  361. | TransactionEventSchema
  362. ) = Field(discriminator="type")
  363. class InterchangeIssueEvent(InterchangeEvent):
  364. payload: (
  365. IssueEventSchema
  366. | ErrorIssueEventSchema
  367. | CSPIssueEventSchema
  368. | TransactionEventSchema
  369. ) = Field(discriminator="type")
  370. class InterchangeTransactionEvent(InterchangeEvent):
  371. payload: TransactionEventSchema