test_event_reports.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616
  1. # Copyright 2020 Dirk Klimpel
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. from http import HTTPStatus
  15. from typing import List
  16. from twisted.test.proto_helpers import MemoryReactor
  17. import synapse.rest.admin
  18. from synapse.api.errors import Codes
  19. from synapse.rest.client import login, report_event, room
  20. from synapse.server import HomeServer
  21. from synapse.types import JsonDict
  22. from synapse.util import Clock
  23. from tests import unittest
  24. class EventReportsTestCase(unittest.HomeserverTestCase):
  25. servlets = [
  26. synapse.rest.admin.register_servlets,
  27. login.register_servlets,
  28. room.register_servlets,
  29. report_event.register_servlets,
  30. ]
  31. def prepare(self, reactor: MemoryReactor, clock: Clock, hs: HomeServer) -> None:
  32. self.admin_user = self.register_user("admin", "pass", admin=True)
  33. self.admin_user_tok = self.login("admin", "pass")
  34. self.other_user = self.register_user("user", "pass")
  35. self.other_user_tok = self.login("user", "pass")
  36. self.room_id1 = self.helper.create_room_as(
  37. self.other_user, tok=self.other_user_tok, is_public=True
  38. )
  39. self.helper.join(self.room_id1, user=self.admin_user, tok=self.admin_user_tok)
  40. self.room_id2 = self.helper.create_room_as(
  41. self.other_user, tok=self.other_user_tok, is_public=True
  42. )
  43. self.helper.join(self.room_id2, user=self.admin_user, tok=self.admin_user_tok)
  44. # Two rooms and two users. Every user sends and reports every room event
  45. for _ in range(5):
  46. self._create_event_and_report(
  47. room_id=self.room_id1,
  48. user_tok=self.other_user_tok,
  49. )
  50. for _ in range(5):
  51. self._create_event_and_report(
  52. room_id=self.room_id2,
  53. user_tok=self.other_user_tok,
  54. )
  55. for _ in range(5):
  56. self._create_event_and_report(
  57. room_id=self.room_id1,
  58. user_tok=self.admin_user_tok,
  59. )
  60. for _ in range(5):
  61. self._create_event_and_report_without_parameters(
  62. room_id=self.room_id2,
  63. user_tok=self.admin_user_tok,
  64. )
  65. self.url = "/_synapse/admin/v1/event_reports"
  66. def test_no_auth(self) -> None:
  67. """
  68. Try to get an event report without authentication.
  69. """
  70. channel = self.make_request("GET", self.url, b"{}")
  71. self.assertEqual(
  72. HTTPStatus.UNAUTHORIZED,
  73. channel.code,
  74. msg=channel.json_body,
  75. )
  76. self.assertEqual(Codes.MISSING_TOKEN, channel.json_body["errcode"])
  77. def test_requester_is_no_admin(self) -> None:
  78. """
  79. If the user is not a server admin, an error HTTPStatus.FORBIDDEN is returned.
  80. """
  81. channel = self.make_request(
  82. "GET",
  83. self.url,
  84. access_token=self.other_user_tok,
  85. )
  86. self.assertEqual(
  87. HTTPStatus.FORBIDDEN,
  88. channel.code,
  89. msg=channel.json_body,
  90. )
  91. self.assertEqual(Codes.FORBIDDEN, channel.json_body["errcode"])
  92. def test_default_success(self) -> None:
  93. """
  94. Testing list of reported events
  95. """
  96. channel = self.make_request(
  97. "GET",
  98. self.url,
  99. access_token=self.admin_user_tok,
  100. )
  101. self.assertEqual(HTTPStatus.OK, channel.code, msg=channel.json_body)
  102. self.assertEqual(channel.json_body["total"], 20)
  103. self.assertEqual(len(channel.json_body["event_reports"]), 20)
  104. self.assertNotIn("next_token", channel.json_body)
  105. self._check_fields(channel.json_body["event_reports"])
  106. def test_limit(self) -> None:
  107. """
  108. Testing list of reported events with limit
  109. """
  110. channel = self.make_request(
  111. "GET",
  112. self.url + "?limit=5",
  113. access_token=self.admin_user_tok,
  114. )
  115. self.assertEqual(HTTPStatus.OK, channel.code, msg=channel.json_body)
  116. self.assertEqual(channel.json_body["total"], 20)
  117. self.assertEqual(len(channel.json_body["event_reports"]), 5)
  118. self.assertEqual(channel.json_body["next_token"], 5)
  119. self._check_fields(channel.json_body["event_reports"])
  120. def test_from(self) -> None:
  121. """
  122. Testing list of reported events with a defined starting point (from)
  123. """
  124. channel = self.make_request(
  125. "GET",
  126. self.url + "?from=5",
  127. access_token=self.admin_user_tok,
  128. )
  129. self.assertEqual(HTTPStatus.OK, channel.code, msg=channel.json_body)
  130. self.assertEqual(channel.json_body["total"], 20)
  131. self.assertEqual(len(channel.json_body["event_reports"]), 15)
  132. self.assertNotIn("next_token", channel.json_body)
  133. self._check_fields(channel.json_body["event_reports"])
  134. def test_limit_and_from(self) -> None:
  135. """
  136. Testing list of reported events with a defined starting point and limit
  137. """
  138. channel = self.make_request(
  139. "GET",
  140. self.url + "?from=5&limit=10",
  141. access_token=self.admin_user_tok,
  142. )
  143. self.assertEqual(HTTPStatus.OK, channel.code, msg=channel.json_body)
  144. self.assertEqual(channel.json_body["total"], 20)
  145. self.assertEqual(channel.json_body["next_token"], 15)
  146. self.assertEqual(len(channel.json_body["event_reports"]), 10)
  147. self._check_fields(channel.json_body["event_reports"])
  148. def test_filter_room(self) -> None:
  149. """
  150. Testing list of reported events with a filter of room
  151. """
  152. channel = self.make_request(
  153. "GET",
  154. self.url + "?room_id=%s" % self.room_id1,
  155. access_token=self.admin_user_tok,
  156. )
  157. self.assertEqual(HTTPStatus.OK, channel.code, msg=channel.json_body)
  158. self.assertEqual(channel.json_body["total"], 10)
  159. self.assertEqual(len(channel.json_body["event_reports"]), 10)
  160. self.assertNotIn("next_token", channel.json_body)
  161. self._check_fields(channel.json_body["event_reports"])
  162. for report in channel.json_body["event_reports"]:
  163. self.assertEqual(report["room_id"], self.room_id1)
  164. def test_filter_user(self) -> None:
  165. """
  166. Testing list of reported events with a filter of user
  167. """
  168. channel = self.make_request(
  169. "GET",
  170. self.url + "?user_id=%s" % self.other_user,
  171. access_token=self.admin_user_tok,
  172. )
  173. self.assertEqual(HTTPStatus.OK, channel.code, msg=channel.json_body)
  174. self.assertEqual(channel.json_body["total"], 10)
  175. self.assertEqual(len(channel.json_body["event_reports"]), 10)
  176. self.assertNotIn("next_token", channel.json_body)
  177. self._check_fields(channel.json_body["event_reports"])
  178. for report in channel.json_body["event_reports"]:
  179. self.assertEqual(report["user_id"], self.other_user)
  180. def test_filter_user_and_room(self) -> None:
  181. """
  182. Testing list of reported events with a filter of user and room
  183. """
  184. channel = self.make_request(
  185. "GET",
  186. self.url + "?user_id=%s&room_id=%s" % (self.other_user, self.room_id1),
  187. access_token=self.admin_user_tok,
  188. )
  189. self.assertEqual(HTTPStatus.OK, channel.code, msg=channel.json_body)
  190. self.assertEqual(channel.json_body["total"], 5)
  191. self.assertEqual(len(channel.json_body["event_reports"]), 5)
  192. self.assertNotIn("next_token", channel.json_body)
  193. self._check_fields(channel.json_body["event_reports"])
  194. for report in channel.json_body["event_reports"]:
  195. self.assertEqual(report["user_id"], self.other_user)
  196. self.assertEqual(report["room_id"], self.room_id1)
  197. def test_valid_search_order(self) -> None:
  198. """
  199. Testing search order. Order by timestamps.
  200. """
  201. # fetch the most recent first, largest timestamp
  202. channel = self.make_request(
  203. "GET",
  204. self.url + "?dir=b",
  205. access_token=self.admin_user_tok,
  206. )
  207. self.assertEqual(HTTPStatus.OK, channel.code, msg=channel.json_body)
  208. self.assertEqual(channel.json_body["total"], 20)
  209. self.assertEqual(len(channel.json_body["event_reports"]), 20)
  210. report = 1
  211. while report < len(channel.json_body["event_reports"]):
  212. self.assertGreaterEqual(
  213. channel.json_body["event_reports"][report - 1]["received_ts"],
  214. channel.json_body["event_reports"][report]["received_ts"],
  215. )
  216. report += 1
  217. # fetch the oldest first, smallest timestamp
  218. channel = self.make_request(
  219. "GET",
  220. self.url + "?dir=f",
  221. access_token=self.admin_user_tok,
  222. )
  223. self.assertEqual(HTTPStatus.OK, channel.code, msg=channel.json_body)
  224. self.assertEqual(channel.json_body["total"], 20)
  225. self.assertEqual(len(channel.json_body["event_reports"]), 20)
  226. report = 1
  227. while report < len(channel.json_body["event_reports"]):
  228. self.assertLessEqual(
  229. channel.json_body["event_reports"][report - 1]["received_ts"],
  230. channel.json_body["event_reports"][report]["received_ts"],
  231. )
  232. report += 1
  233. def test_invalid_search_order(self) -> None:
  234. """
  235. Testing that a invalid search order returns a HTTPStatus.BAD_REQUEST
  236. """
  237. channel = self.make_request(
  238. "GET",
  239. self.url + "?dir=bar",
  240. access_token=self.admin_user_tok,
  241. )
  242. self.assertEqual(
  243. HTTPStatus.BAD_REQUEST,
  244. channel.code,
  245. msg=channel.json_body,
  246. )
  247. self.assertEqual(Codes.INVALID_PARAM, channel.json_body["errcode"])
  248. self.assertEqual("Unknown direction: bar", channel.json_body["error"])
  249. def test_limit_is_negative(self) -> None:
  250. """
  251. Testing that a negative limit parameter returns a HTTPStatus.BAD_REQUEST
  252. """
  253. channel = self.make_request(
  254. "GET",
  255. self.url + "?limit=-5",
  256. access_token=self.admin_user_tok,
  257. )
  258. self.assertEqual(
  259. HTTPStatus.BAD_REQUEST,
  260. channel.code,
  261. msg=channel.json_body,
  262. )
  263. self.assertEqual(Codes.INVALID_PARAM, channel.json_body["errcode"])
  264. def test_from_is_negative(self) -> None:
  265. """
  266. Testing that a negative from parameter returns a HTTPStatus.BAD_REQUEST
  267. """
  268. channel = self.make_request(
  269. "GET",
  270. self.url + "?from=-5",
  271. access_token=self.admin_user_tok,
  272. )
  273. self.assertEqual(
  274. HTTPStatus.BAD_REQUEST,
  275. channel.code,
  276. msg=channel.json_body,
  277. )
  278. self.assertEqual(Codes.INVALID_PARAM, channel.json_body["errcode"])
  279. def test_next_token(self) -> None:
  280. """
  281. Testing that `next_token` appears at the right place
  282. """
  283. # `next_token` does not appear
  284. # Number of results is the number of entries
  285. channel = self.make_request(
  286. "GET",
  287. self.url + "?limit=20",
  288. access_token=self.admin_user_tok,
  289. )
  290. self.assertEqual(HTTPStatus.OK, channel.code, msg=channel.json_body)
  291. self.assertEqual(channel.json_body["total"], 20)
  292. self.assertEqual(len(channel.json_body["event_reports"]), 20)
  293. self.assertNotIn("next_token", channel.json_body)
  294. # `next_token` does not appear
  295. # Number of max results is larger than the number of entries
  296. channel = self.make_request(
  297. "GET",
  298. self.url + "?limit=21",
  299. access_token=self.admin_user_tok,
  300. )
  301. self.assertEqual(HTTPStatus.OK, channel.code, msg=channel.json_body)
  302. self.assertEqual(channel.json_body["total"], 20)
  303. self.assertEqual(len(channel.json_body["event_reports"]), 20)
  304. self.assertNotIn("next_token", channel.json_body)
  305. # `next_token` does appear
  306. # Number of max results is smaller than the number of entries
  307. channel = self.make_request(
  308. "GET",
  309. self.url + "?limit=19",
  310. access_token=self.admin_user_tok,
  311. )
  312. self.assertEqual(HTTPStatus.OK, channel.code, msg=channel.json_body)
  313. self.assertEqual(channel.json_body["total"], 20)
  314. self.assertEqual(len(channel.json_body["event_reports"]), 19)
  315. self.assertEqual(channel.json_body["next_token"], 19)
  316. # Check
  317. # Set `from` to value of `next_token` for request remaining entries
  318. # `next_token` does not appear
  319. channel = self.make_request(
  320. "GET",
  321. self.url + "?from=19",
  322. access_token=self.admin_user_tok,
  323. )
  324. self.assertEqual(HTTPStatus.OK, channel.code, msg=channel.json_body)
  325. self.assertEqual(channel.json_body["total"], 20)
  326. self.assertEqual(len(channel.json_body["event_reports"]), 1)
  327. self.assertNotIn("next_token", channel.json_body)
  328. def _create_event_and_report(self, room_id: str, user_tok: str) -> None:
  329. """Create and report events"""
  330. resp = self.helper.send(room_id, tok=user_tok)
  331. event_id = resp["event_id"]
  332. channel = self.make_request(
  333. "POST",
  334. "rooms/%s/report/%s" % (room_id, event_id),
  335. {"score": -100, "reason": "this makes me sad"},
  336. access_token=user_tok,
  337. )
  338. self.assertEqual(HTTPStatus.OK, channel.code, msg=channel.json_body)
  339. def _create_event_and_report_without_parameters(
  340. self, room_id: str, user_tok: str
  341. ) -> None:
  342. """Create and report an event, but omit reason and score"""
  343. resp = self.helper.send(room_id, tok=user_tok)
  344. event_id = resp["event_id"]
  345. channel = self.make_request(
  346. "POST",
  347. "rooms/%s/report/%s" % (room_id, event_id),
  348. {},
  349. access_token=user_tok,
  350. )
  351. self.assertEqual(HTTPStatus.OK, channel.code, msg=channel.json_body)
  352. def _check_fields(self, content: List[JsonDict]) -> None:
  353. """Checks that all attributes are present in an event report"""
  354. for c in content:
  355. self.assertIn("id", c)
  356. self.assertIn("received_ts", c)
  357. self.assertIn("room_id", c)
  358. self.assertIn("event_id", c)
  359. self.assertIn("user_id", c)
  360. self.assertIn("sender", c)
  361. self.assertIn("canonical_alias", c)
  362. self.assertIn("name", c)
  363. self.assertIn("score", c)
  364. self.assertIn("reason", c)
  365. class EventReportDetailTestCase(unittest.HomeserverTestCase):
  366. servlets = [
  367. synapse.rest.admin.register_servlets,
  368. login.register_servlets,
  369. room.register_servlets,
  370. report_event.register_servlets,
  371. ]
  372. def prepare(self, reactor: MemoryReactor, clock: Clock, hs: HomeServer) -> None:
  373. self.admin_user = self.register_user("admin", "pass", admin=True)
  374. self.admin_user_tok = self.login("admin", "pass")
  375. self.other_user = self.register_user("user", "pass")
  376. self.other_user_tok = self.login("user", "pass")
  377. self.room_id1 = self.helper.create_room_as(
  378. self.other_user, tok=self.other_user_tok, is_public=True
  379. )
  380. self.helper.join(self.room_id1, user=self.admin_user, tok=self.admin_user_tok)
  381. self._create_event_and_report(
  382. room_id=self.room_id1,
  383. user_tok=self.other_user_tok,
  384. )
  385. # first created event report gets `id`=2
  386. self.url = "/_synapse/admin/v1/event_reports/2"
  387. def test_no_auth(self) -> None:
  388. """
  389. Try to get event report without authentication.
  390. """
  391. channel = self.make_request("GET", self.url, b"{}")
  392. self.assertEqual(
  393. HTTPStatus.UNAUTHORIZED,
  394. channel.code,
  395. msg=channel.json_body,
  396. )
  397. self.assertEqual(Codes.MISSING_TOKEN, channel.json_body["errcode"])
  398. def test_requester_is_no_admin(self) -> None:
  399. """
  400. If the user is not a server admin, an error HTTPStatus.FORBIDDEN is returned.
  401. """
  402. channel = self.make_request(
  403. "GET",
  404. self.url,
  405. access_token=self.other_user_tok,
  406. )
  407. self.assertEqual(
  408. HTTPStatus.FORBIDDEN,
  409. channel.code,
  410. msg=channel.json_body,
  411. )
  412. self.assertEqual(Codes.FORBIDDEN, channel.json_body["errcode"])
  413. def test_default_success(self) -> None:
  414. """
  415. Testing get a reported event
  416. """
  417. channel = self.make_request(
  418. "GET",
  419. self.url,
  420. access_token=self.admin_user_tok,
  421. )
  422. self.assertEqual(HTTPStatus.OK, channel.code, msg=channel.json_body)
  423. self._check_fields(channel.json_body)
  424. def test_invalid_report_id(self) -> None:
  425. """
  426. Testing that an invalid `report_id` returns a HTTPStatus.BAD_REQUEST.
  427. """
  428. # `report_id` is negative
  429. channel = self.make_request(
  430. "GET",
  431. "/_synapse/admin/v1/event_reports/-123",
  432. access_token=self.admin_user_tok,
  433. )
  434. self.assertEqual(
  435. HTTPStatus.BAD_REQUEST,
  436. channel.code,
  437. msg=channel.json_body,
  438. )
  439. self.assertEqual(Codes.INVALID_PARAM, channel.json_body["errcode"])
  440. self.assertEqual(
  441. "The report_id parameter must be a string representing a positive integer.",
  442. channel.json_body["error"],
  443. )
  444. # `report_id` is a non-numerical string
  445. channel = self.make_request(
  446. "GET",
  447. "/_synapse/admin/v1/event_reports/abcdef",
  448. access_token=self.admin_user_tok,
  449. )
  450. self.assertEqual(
  451. HTTPStatus.BAD_REQUEST,
  452. channel.code,
  453. msg=channel.json_body,
  454. )
  455. self.assertEqual(Codes.INVALID_PARAM, channel.json_body["errcode"])
  456. self.assertEqual(
  457. "The report_id parameter must be a string representing a positive integer.",
  458. channel.json_body["error"],
  459. )
  460. # `report_id` is undefined
  461. channel = self.make_request(
  462. "GET",
  463. "/_synapse/admin/v1/event_reports/",
  464. access_token=self.admin_user_tok,
  465. )
  466. self.assertEqual(
  467. HTTPStatus.BAD_REQUEST,
  468. channel.code,
  469. msg=channel.json_body,
  470. )
  471. self.assertEqual(Codes.INVALID_PARAM, channel.json_body["errcode"])
  472. self.assertEqual(
  473. "The report_id parameter must be a string representing a positive integer.",
  474. channel.json_body["error"],
  475. )
  476. def test_report_id_not_found(self) -> None:
  477. """
  478. Testing that a not existing `report_id` returns a HTTPStatus.NOT_FOUND.
  479. """
  480. channel = self.make_request(
  481. "GET",
  482. "/_synapse/admin/v1/event_reports/123",
  483. access_token=self.admin_user_tok,
  484. )
  485. self.assertEqual(
  486. HTTPStatus.NOT_FOUND,
  487. channel.code,
  488. msg=channel.json_body,
  489. )
  490. self.assertEqual(Codes.NOT_FOUND, channel.json_body["errcode"])
  491. self.assertEqual("Event report not found", channel.json_body["error"])
  492. def _create_event_and_report(self, room_id: str, user_tok: str) -> None:
  493. """Create and report events"""
  494. resp = self.helper.send(room_id, tok=user_tok)
  495. event_id = resp["event_id"]
  496. channel = self.make_request(
  497. "POST",
  498. "rooms/%s/report/%s" % (room_id, event_id),
  499. {"score": -100, "reason": "this makes me sad"},
  500. access_token=user_tok,
  501. )
  502. self.assertEqual(HTTPStatus.OK, channel.code, msg=channel.json_body)
  503. def _check_fields(self, content: JsonDict) -> None:
  504. """Checks that all attributes are present in a event report"""
  505. self.assertIn("id", content)
  506. self.assertIn("received_ts", content)
  507. self.assertIn("room_id", content)
  508. self.assertIn("event_id", content)
  509. self.assertIn("user_id", content)
  510. self.assertIn("sender", content)
  511. self.assertIn("canonical_alias", content)
  512. self.assertIn("name", content)
  513. self.assertIn("event_json", content)
  514. self.assertIn("score", content)
  515. self.assertIn("reason", content)
  516. self.assertIn("auth_events", content["event_json"])
  517. self.assertIn("type", content["event_json"])
  518. self.assertIn("room_id", content["event_json"])
  519. self.assertIn("sender", content["event_json"])
  520. self.assertIn("content", content["event_json"])