schema.py 13 KB

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