tests.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482
  1. import json
  2. import random
  3. from unittest.mock import patch
  4. from django.shortcuts import reverse
  5. from django.test import override_settings
  6. from model_bakery import baker
  7. from rest_framework.test import APITestCase
  8. from environments.models import Environment
  9. from glitchtip import test_utils # pylint: disable=unused-import
  10. from issues.models import EventStatus, Issue
  11. from ..models import Event, LogLevel
  12. from ..test_data.csp import mdn_sample_csp
  13. class EventStoreTestCase(APITestCase):
  14. def setUp(self):
  15. self.project = baker.make("projects.Project")
  16. self.projectkey = self.project.projectkey_set.first()
  17. self.params = f"?sentry_key={self.projectkey.public_key}"
  18. self.url = reverse("event_store", args=[self.project.id]) + self.params
  19. def test_store_api(self):
  20. with open("events/test_data/py_hi_event.json") as json_file:
  21. data = json.load(json_file)
  22. res = self.client.post(self.url, data, format="json")
  23. self.assertEqual(res.status_code, 200)
  24. def test_maintenance_freeze(self):
  25. with open("events/test_data/py_hi_event.json") as json_file:
  26. data = json.load(json_file)
  27. with override_settings(MAINTENANCE_EVENT_FREEZE=True):
  28. res = self.client.post(self.url, data, format="json")
  29. self.assertEqual(res.status_code, 503)
  30. def test_store_duplicate(self):
  31. with open("events/test_data/py_hi_event.json") as json_file:
  32. data = json.load(json_file)
  33. self.client.post(self.url, data, format="json")
  34. res = self.client.post(self.url, data, format="json")
  35. self.assertContains(res, "ID already exist", status_code=403)
  36. def test_store_invalid_key(self):
  37. with open("events/test_data/py_hi_event.json") as json_file:
  38. data = json.load(json_file)
  39. self.client.post(self.url, data, format="json")
  40. res = self.client.post(self.url, data, format="json")
  41. self.assertContains(res, "ID already exist", status_code=403)
  42. def test_store_api_auth_failure(self):
  43. url = "/api/1/store/"
  44. with open("events/test_data/py_hi_event.json") as json_file:
  45. data = json.load(json_file)
  46. params = "?sentry_key=aaa"
  47. url = reverse("event_store", args=[self.project.id]) + params
  48. res = self.client.post(url, data, format="json")
  49. self.assertEqual(res.status_code, 401)
  50. params = "?sentry_key=238df2aac6331578a16c14bcb3db5259"
  51. url = reverse("event_store", args=[self.project.id]) + params
  52. res = self.client.post(url, data, format="json")
  53. self.assertContains(res, "Invalid api key", status_code=401)
  54. url = reverse("event_store", args=[10000]) + self.params
  55. res = self.client.post(url, data, format="json")
  56. self.assertContains(res, "Invalid project_id", status_code=400)
  57. def test_error_event(self):
  58. with open("events/test_data/py_error.json") as json_file:
  59. data = json.load(json_file)
  60. res = self.client.post(self.url, data, format="json")
  61. self.assertEqual(res.status_code, 200)
  62. def test_csp_event(self):
  63. url = reverse("csp_store", args=[self.project.id]) + self.params
  64. data = mdn_sample_csp
  65. res = self.client.post(url, data, format="json")
  66. self.assertEqual(res.status_code, 200)
  67. expected_title = "Blocked 'style' from 'example.com'"
  68. issue = Issue.objects.get(title=expected_title)
  69. event = Event.objects.get()
  70. self.assertEqual(event.data["csp"]["effective_directive"], "style-src")
  71. self.assertTrue(issue)
  72. def test_reopen_resolved_issue(self):
  73. with open("events/test_data/py_hi_event.json") as json_file:
  74. data = json.load(json_file)
  75. self.client.post(self.url, data, format="json")
  76. issue = Issue.objects.all().first()
  77. issue.status = EventStatus.RESOLVED
  78. issue.save()
  79. data["event_id"] = "6600a066e64b4caf8ed7ec5af64ac4ba"
  80. self.client.post(self.url, data, format="json")
  81. issue.refresh_from_db()
  82. self.assertEqual(issue.status, EventStatus.UNRESOLVED)
  83. def test_performance(self):
  84. with open("events/test_data/py_hi_event.json") as json_file:
  85. data = json.load(json_file)
  86. with self.assertNumQueries(15):
  87. res = self.client.post(self.url, data, format="json")
  88. self.assertEqual(res.status_code, 200)
  89. # Second event should have less queries
  90. data["event_id"] = "6600a066e64b4caf8ed7ec5af64ac4bb"
  91. with self.assertNumQueries(8):
  92. res = self.client.post(self.url, data, format="json")
  93. self.assertEqual(res.status_code, 200)
  94. def test_throttle_organization(self):
  95. organization = self.project.organization
  96. organization.is_accepting_events = False
  97. organization.save()
  98. with open("events/test_data/py_hi_event.json") as json_file:
  99. data = json.load(json_file)
  100. res = self.client.post(self.url, data, format="json")
  101. self.assertEqual(res.status_code, 429)
  102. def test_project_first_event(self):
  103. with open("events/test_data/py_error.json") as json_file:
  104. data = json.load(json_file)
  105. self.assertFalse(self.project.first_event)
  106. self.client.post(self.url, data, format="json")
  107. self.project.refresh_from_db()
  108. self.assertTrue(self.project.first_event)
  109. def test_null_character_event(self):
  110. """
  111. Unicode null characters \u0000 are not supported by Postgres JSONB
  112. NUL \x00 characters are not supported by Postgres string types
  113. They should be filtered out
  114. """
  115. with open("events/test_data/py_error.json") as json_file:
  116. data = json.load(json_file)
  117. data["exception"]["values"][0]["stacktrace"]["frames"][0][
  118. "function"
  119. ] = "a\u0000a"
  120. data["exception"]["values"][0]["value"] = "\x00\u0000"
  121. res = self.client.post(self.url, data, format="json")
  122. self.assertEqual(res.status_code, 200)
  123. def test_header_value_array(self):
  124. """
  125. Request Header values are both strings and arrays (sentry-php uses arrays)
  126. """
  127. with open("events/test_data/py_error.json") as json_file:
  128. data = json.load(json_file)
  129. data["request"]["headers"]["Content-Type"] = ["text/plain"]
  130. res = self.client.post(self.url, data, format="json")
  131. self.assertEqual(res.status_code, 200)
  132. event = Event.objects.first()
  133. header = next(
  134. x for x in event.data["request"]["headers"] if x[0] == "Content-Type"
  135. )
  136. self.assertTrue(isinstance(header[1], str))
  137. def test_anonymize_ip(self):
  138. """ip address should get masked because default project settings are to scrub ip address"""
  139. with open("events/test_data/py_hi_event.json") as json_file:
  140. data = json.load(json_file)
  141. test_ip = "123.168.29.14"
  142. res = self.client.post(self.url, data, format="json", REMOTE_ADDR=test_ip)
  143. self.assertEqual(res.status_code, 200)
  144. event = Event.objects.first()
  145. self.assertNotEqual(event.data["user"]["ip_address"], test_ip)
  146. def test_csp_event_anonymize_ip(self):
  147. url = reverse("csp_store", args=[self.project.id]) + self.params
  148. test_ip = "123.168.29.14"
  149. data = mdn_sample_csp
  150. res = self.client.post(url, data, format="json", REMOTE_ADDR=test_ip)
  151. self.assertEqual(res.status_code, 200)
  152. event = Event.objects.first()
  153. self.assertNotEqual(event.data["user"]["ip_address"], test_ip)
  154. def test_store_very_large_data(self):
  155. """
  156. This test is expected to exceed the 1mb limit of a postgres tsvector
  157. """
  158. with open("events/test_data/py_hi_event.json") as json_file:
  159. data = json.load(json_file)
  160. data["platform"] = " ".join([str(random.random()) for _ in range(50000)])
  161. res = self.client.post(self.url, data, format="json")
  162. self.assertEqual(res.status_code, 200)
  163. self.assertEqual(
  164. Issue.objects.first().search_vector,
  165. "",
  166. "No tsvector is expected as it would exceed the Postgres limit",
  167. )
  168. data["event_id"] = "6600a066e64b4caf8ed7ec5af64ac4be"
  169. res = self.client.post(self.url, data, format="json")
  170. self.assertEqual(res.status_code, 200)
  171. @patch("events.views.logger")
  172. def test_invalid_event(self, mock_logger):
  173. with open("events/test_data/py_hi_event.json") as json_file:
  174. data = json.load(json_file)
  175. data["transaction"] = True
  176. res = self.client.post(self.url, data, format="json")
  177. self.assertEqual(res.status_code, 200)
  178. mock_logger.warning.assert_called()
  179. def test_breadcrumbs_object(self):
  180. """Event breadcrumbs may be sent as an array or a object."""
  181. with open("events/test_data/py_hi_event.json") as json_file:
  182. data = json.load(json_file)
  183. data["breadcrumbs"] = {
  184. "values": [
  185. {
  186. "timestamp": "2020-01-20T20:00:00.000Z",
  187. "message": "Something",
  188. "category": "log",
  189. "data": {"foo": "bar"},
  190. },
  191. ]
  192. }
  193. res = self.client.post(self.url, data, format="json")
  194. self.assertEqual(res.status_code, 200)
  195. self.assertTrue(Issue.objects.exists())
  196. def test_event_release(self):
  197. with open("events/test_data/py_hi_event.json") as json_file:
  198. data = json.load(json_file)
  199. self.client.post(self.url, data, format="json")
  200. event = Event.objects.first()
  201. event_json = event.event_json()
  202. self.assertTrue(event.release)
  203. self.assertEqual(event_json.get("release"), event.release.version)
  204. self.assertIn(
  205. event.release.version,
  206. dict(event_json.get("tags")).values(),
  207. )
  208. def test_event_release_blank(self):
  209. """In the SDK, it's possible to set a release to a blank string"""
  210. with open("events/test_data/py_hi_event.json") as json_file:
  211. data = json.load(json_file)
  212. data["release"] = ""
  213. res = self.client.post(self.url, data, format="json")
  214. self.assertEqual(res.status_code, 200)
  215. self.assertTrue(Event.objects.first())
  216. def test_client_tags(self):
  217. with open("events/test_data/py_hi_event.json") as json_file:
  218. data = json.load(json_file)
  219. data["tags"] = {"test_tag": "the value"}
  220. self.client.post(self.url, data, format="json")
  221. event = Event.objects.first()
  222. event_json = event.event_json()
  223. self.assertIn(
  224. "the value",
  225. tuple(event_json.get("tags"))[1],
  226. )
  227. def test_client_tags_invalid(self):
  228. """Invalid tags should not be saved. But should not error."""
  229. with open("events/test_data/py_hi_event.json") as json_file:
  230. data = json.load(json_file)
  231. data["tags"] = {
  232. "value": "valid value",
  233. "my invalid tag key": {"oh": "this is invalid"},
  234. }
  235. res = self.client.post(self.url, data, format="json")
  236. event = Event.objects.first()
  237. self.assertEqual(res.status_code, 200)
  238. self.assertTrue(event)
  239. event_json = event.event_json()
  240. tags = tuple(event_json.get("tags"))
  241. self.assertIn(
  242. "valid value",
  243. tags[0],
  244. )
  245. for tag in tags:
  246. self.assertNotIn("this is invalid", tag)
  247. self.assertEqual(len(event_json.get("errors")), 1)
  248. def test_malformed_exception_value(self):
  249. """Malformed exception values aren't 100% supported, but should stored anyway"""
  250. with open("events/test_data/py_error.json") as json_file:
  251. data = json.load(json_file)
  252. data["exception"]["values"][0]["value"] = {"why is this": "any object?"}
  253. res = self.client.post(self.url, data, format="json")
  254. self.assertEqual(res.status_code, 200)
  255. def test_no_sdk(self):
  256. data = {
  257. "exception": [
  258. {
  259. "type": "Plug.Parsers.ParseError",
  260. "value": "malformed request",
  261. "module": None,
  262. }
  263. ],
  264. "culprit": "Plug.Parsers.JSON.decode",
  265. "extra": {},
  266. "event_id": "11111111111111111111111111111111",
  267. "breadcrumbs": [],
  268. "level": "error",
  269. "modules": {
  270. "cowboy": "2.8.0",
  271. },
  272. "fingerprint": ["{{ default }}"],
  273. "message": "(Plug.Parsers.ParseError) malformed",
  274. }
  275. res = self.client.post(self.url, data, format="json")
  276. self.assertEqual(res.status_code, 200)
  277. self.assertTrue(Event.objects.exists())
  278. def test_invalid_level(self):
  279. data = {
  280. "exception": [
  281. {
  282. "type": "a",
  283. "value": "a",
  284. "module": None,
  285. }
  286. ],
  287. "culprit": "a",
  288. "extra": {},
  289. "event_id": "11111111111111111111111111111111",
  290. "breadcrumbs": [],
  291. "level": "haha",
  292. "message": "a",
  293. }
  294. res = self.client.post(self.url, data, format="json")
  295. self.assertEqual(res.status_code, 200)
  296. self.assertTrue(Event.objects.filter(level=LogLevel.ERROR).exists())
  297. def test_null_release(self):
  298. data = {
  299. "exception": [
  300. {
  301. "type": "a",
  302. "value": "a",
  303. "module": None,
  304. }
  305. ],
  306. "culprit": "a",
  307. "extra": {},
  308. "event_id": "11111111111111111111111111111111",
  309. "breadcrumbs": [],
  310. "level": "haha",
  311. "message": "",
  312. "release": None,
  313. "environment": None,
  314. "request": {"env": {"FOO": None}},
  315. }
  316. res = self.client.post(self.url, data, format="json")
  317. self.assertEqual(res.status_code, 200)
  318. self.assertTrue(Event.objects.filter().exists())
  319. def test_formatted_message(self):
  320. data = {
  321. "exception": [
  322. {
  323. "type": "a",
  324. "value": "a",
  325. "module": None,
  326. }
  327. ],
  328. "event_id": "11111111111111111111111111111111",
  329. "message": {"formatted": "Hello"},
  330. }
  331. res = self.client.post(self.url, data, format="json")
  332. self.assertTrue(Event.objects.filter(data__message="Hello").exists())
  333. def test_invalid_message(self):
  334. # It's actually accepted as is. Considered to be message: ""
  335. data = {
  336. "exception": [
  337. {
  338. "type": "a",
  339. "value": "a",
  340. "module": None,
  341. }
  342. ],
  343. "event_id": "11111111111111111111111111111111",
  344. "message": {},
  345. }
  346. res = self.client.post(self.url, data, format="json")
  347. self.assertTrue(Event.objects.filter(data__message="").exists())
  348. def test_null_message(self):
  349. data = {
  350. "exception": [{}],
  351. "event_id": "11111111111111111111111111111111",
  352. "message": None,
  353. }
  354. res = self.client.post(self.url, data, format="json")
  355. self.assertTrue(Event.objects.filter(data__message=None).exists())
  356. def test_long_environment(self):
  357. data = {
  358. "exception": [
  359. {
  360. "type": "a",
  361. "value": "a",
  362. "module": None,
  363. }
  364. ],
  365. "event_id": "11111111111111111111111111111111",
  366. "environment": "a" * 257,
  367. }
  368. res = self.client.post(self.url, data, format="json")
  369. self.assertTrue(Event.objects.filter().exists())
  370. def test_invalid_environment(self):
  371. data = {
  372. "exception": [
  373. {
  374. "type": "a",
  375. "value": "a",
  376. "module": None,
  377. }
  378. ],
  379. "event_id": "11111111111111111111111111111111",
  380. "environment": "a/a",
  381. }
  382. res = self.client.post(self.url, data, format="json")
  383. self.assertTrue(Event.objects.filter().exists())
  384. self.assertFalse(Environment.objects.exists())
  385. def test_query_string_formats(self):
  386. data = {
  387. "event_id": "11111111111111111111111111111111",
  388. "exception": [
  389. {
  390. "type": "a",
  391. "value": "a",
  392. "module": None,
  393. }
  394. ],
  395. "request": {
  396. "method": "GET",
  397. "query_string": {"search": "foo"},
  398. },
  399. }
  400. self.client.post(self.url, data, format="json")
  401. data = {
  402. "event_id": "11111111111111111111111111111112",
  403. "exception": [
  404. {
  405. "type": "a",
  406. "value": "a",
  407. "module": None,
  408. }
  409. ],
  410. "request": {
  411. "query_string": "search=foo",
  412. },
  413. }
  414. self.client.post(self.url, data, format="json")
  415. data = {
  416. "event_id": "11111111111111111111111111111113",
  417. "exception": [
  418. {
  419. "type": "a",
  420. "value": "a",
  421. "module": None,
  422. }
  423. ],
  424. "request": {"query_string": [["search", "foo"]]},
  425. }
  426. self.client.post(self.url, data, format="json")
  427. self.assertEqual(
  428. Event.objects.filter(
  429. data__request__query_string=[["search", "foo"]]
  430. ).count(),
  431. 3,
  432. )