1
0

test_redactions.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468
  1. # Copyright 2019 The Matrix.org Foundation C.I.C.
  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 typing import List, Optional
  15. from twisted.test.proto_helpers import MemoryReactor
  16. from synapse.api.constants import EventTypes, RelationTypes
  17. from synapse.rest import admin
  18. from synapse.rest.client import login, room, sync
  19. from synapse.server import HomeServer
  20. from synapse.types import JsonDict
  21. from synapse.util import Clock
  22. from tests.unittest import HomeserverTestCase, override_config
  23. class RedactionsTestCase(HomeserverTestCase):
  24. """Tests that various redaction events are handled correctly"""
  25. servlets = [
  26. admin.register_servlets,
  27. room.register_servlets,
  28. login.register_servlets,
  29. sync.register_servlets,
  30. ]
  31. def make_homeserver(self, reactor: MemoryReactor, clock: Clock) -> HomeServer:
  32. config = self.default_config()
  33. config["rc_message"] = {"per_second": 0.2, "burst_count": 10}
  34. config["rc_admin_redaction"] = {"per_second": 1, "burst_count": 100}
  35. return self.setup_test_homeserver(config=config)
  36. def prepare(self, reactor: MemoryReactor, clock: Clock, hs: HomeServer) -> None:
  37. # register a couple of users
  38. self.mod_user_id = self.register_user("user1", "pass")
  39. self.mod_access_token = self.login("user1", "pass")
  40. self.other_user_id = self.register_user("otheruser", "pass")
  41. self.other_access_token = self.login("otheruser", "pass")
  42. # Create a room
  43. self.room_id = self.helper.create_room_as(
  44. self.mod_user_id, tok=self.mod_access_token
  45. )
  46. # Invite the other user
  47. self.helper.invite(
  48. room=self.room_id,
  49. src=self.mod_user_id,
  50. tok=self.mod_access_token,
  51. targ=self.other_user_id,
  52. )
  53. # The other user joins
  54. self.helper.join(
  55. room=self.room_id, user=self.other_user_id, tok=self.other_access_token
  56. )
  57. def _redact_event(
  58. self,
  59. access_token: str,
  60. room_id: str,
  61. event_id: str,
  62. expect_code: int = 200,
  63. with_relations: Optional[List[str]] = None,
  64. ) -> JsonDict:
  65. """Helper function to send a redaction event.
  66. Returns the json body.
  67. """
  68. path = "/_matrix/client/r0/rooms/%s/redact/%s" % (room_id, event_id)
  69. request_content = {}
  70. if with_relations:
  71. request_content["org.matrix.msc3912.with_relations"] = with_relations
  72. channel = self.make_request(
  73. "POST", path, request_content, access_token=access_token
  74. )
  75. self.assertEqual(channel.code, expect_code)
  76. return channel.json_body
  77. def _sync_room_timeline(self, access_token: str, room_id: str) -> List[JsonDict]:
  78. channel = self.make_request("GET", "sync", access_token=self.mod_access_token)
  79. self.assertEqual(channel.code, 200)
  80. room_sync = channel.json_body["rooms"]["join"][room_id]
  81. return room_sync["timeline"]["events"]
  82. def test_redact_event_as_moderator(self) -> None:
  83. # as a regular user, send a message to redact
  84. b = self.helper.send(room_id=self.room_id, tok=self.other_access_token)
  85. msg_id = b["event_id"]
  86. # as the moderator, send a redaction
  87. b = self._redact_event(self.mod_access_token, self.room_id, msg_id)
  88. redaction_id = b["event_id"]
  89. # now sync
  90. timeline = self._sync_room_timeline(self.mod_access_token, self.room_id)
  91. # the last event should be the redaction
  92. self.assertEqual(timeline[-1]["event_id"], redaction_id)
  93. self.assertEqual(timeline[-1]["redacts"], msg_id)
  94. # and the penultimate should be the redacted original
  95. self.assertEqual(timeline[-2]["event_id"], msg_id)
  96. self.assertEqual(timeline[-2]["unsigned"]["redacted_by"], redaction_id)
  97. self.assertEqual(timeline[-2]["content"], {})
  98. def test_redact_event_as_normal(self) -> None:
  99. # as a regular user, send a message to redact
  100. b = self.helper.send(room_id=self.room_id, tok=self.other_access_token)
  101. normal_msg_id = b["event_id"]
  102. # also send one as the admin
  103. b = self.helper.send(room_id=self.room_id, tok=self.mod_access_token)
  104. admin_msg_id = b["event_id"]
  105. # as a normal, try to redact the admin's event
  106. self._redact_event(
  107. self.other_access_token, self.room_id, admin_msg_id, expect_code=403
  108. )
  109. # now try to redact our own event
  110. b = self._redact_event(self.other_access_token, self.room_id, normal_msg_id)
  111. redaction_id = b["event_id"]
  112. # now sync
  113. timeline = self._sync_room_timeline(self.other_access_token, self.room_id)
  114. # the last event should be the redaction of the normal event
  115. self.assertEqual(timeline[-1]["event_id"], redaction_id)
  116. self.assertEqual(timeline[-1]["redacts"], normal_msg_id)
  117. # the penultimate should be the unredacted one from the admin
  118. self.assertEqual(timeline[-2]["event_id"], admin_msg_id)
  119. self.assertNotIn("redacted_by", timeline[-2]["unsigned"])
  120. self.assertTrue(timeline[-2]["content"]["body"], {})
  121. # and the antepenultimate should be the redacted normal
  122. self.assertEqual(timeline[-3]["event_id"], normal_msg_id)
  123. self.assertEqual(timeline[-3]["unsigned"]["redacted_by"], redaction_id)
  124. self.assertEqual(timeline[-3]["content"], {})
  125. def test_redact_nonexistent_event(self) -> None:
  126. # control case: an existing event
  127. b = self.helper.send(room_id=self.room_id, tok=self.other_access_token)
  128. msg_id = b["event_id"]
  129. b = self._redact_event(self.other_access_token, self.room_id, msg_id)
  130. redaction_id = b["event_id"]
  131. # room moderators can send redactions for non-existent events
  132. self._redact_event(self.mod_access_token, self.room_id, "$zzz")
  133. # ... but normals cannot
  134. self._redact_event(
  135. self.other_access_token, self.room_id, "$zzz", expect_code=404
  136. )
  137. # when we sync, we should see only the valid redaction
  138. timeline = self._sync_room_timeline(self.other_access_token, self.room_id)
  139. self.assertEqual(timeline[-1]["event_id"], redaction_id)
  140. self.assertEqual(timeline[-1]["redacts"], msg_id)
  141. # and the penultimate should be the redacted original
  142. self.assertEqual(timeline[-2]["event_id"], msg_id)
  143. self.assertEqual(timeline[-2]["unsigned"]["redacted_by"], redaction_id)
  144. self.assertEqual(timeline[-2]["content"], {})
  145. def test_redact_create_event(self) -> None:
  146. # control case: an existing event
  147. b = self.helper.send(room_id=self.room_id, tok=self.mod_access_token)
  148. msg_id = b["event_id"]
  149. self._redact_event(self.mod_access_token, self.room_id, msg_id)
  150. # sync the room, to get the id of the create event
  151. timeline = self._sync_room_timeline(self.other_access_token, self.room_id)
  152. create_event_id = timeline[0]["event_id"]
  153. # room moderators cannot send redactions for create events
  154. self._redact_event(
  155. self.mod_access_token, self.room_id, create_event_id, expect_code=403
  156. )
  157. # and nor can normals
  158. self._redact_event(
  159. self.other_access_token, self.room_id, create_event_id, expect_code=403
  160. )
  161. def test_redact_event_as_moderator_ratelimit(self) -> None:
  162. """Tests that the correct ratelimiting is applied to redactions"""
  163. message_ids = []
  164. # as a regular user, send messages to redact
  165. for _ in range(20):
  166. b = self.helper.send(room_id=self.room_id, tok=self.other_access_token)
  167. message_ids.append(b["event_id"])
  168. self.reactor.advance(10) # To get around ratelimits
  169. # as the moderator, send a bunch of redactions
  170. for msg_id in message_ids:
  171. # These should all succeed, even though this would be denied by
  172. # the standard message ratelimiter
  173. self._redact_event(self.mod_access_token, self.room_id, msg_id)
  174. @override_config({"experimental_features": {"msc3912_enabled": True}})
  175. def test_redact_relations(self) -> None:
  176. """Tests that we can redact the relations of an event at the same time as the
  177. event itself.
  178. """
  179. # Send a root event.
  180. res = self.helper.send_event(
  181. room_id=self.room_id,
  182. type=EventTypes.Message,
  183. content={"msgtype": "m.text", "body": "hello"},
  184. tok=self.mod_access_token,
  185. )
  186. root_event_id = res["event_id"]
  187. # Send an edit to this root event.
  188. res = self.helper.send_event(
  189. room_id=self.room_id,
  190. type=EventTypes.Message,
  191. content={
  192. "body": " * hello world",
  193. "m.new_content": {
  194. "body": "hello world",
  195. "msgtype": "m.text",
  196. },
  197. "m.relates_to": {
  198. "event_id": root_event_id,
  199. "rel_type": RelationTypes.REPLACE,
  200. },
  201. "msgtype": "m.text",
  202. },
  203. tok=self.mod_access_token,
  204. )
  205. edit_event_id = res["event_id"]
  206. # Also send a threaded message whose root is the same as the edit's.
  207. res = self.helper.send_event(
  208. room_id=self.room_id,
  209. type=EventTypes.Message,
  210. content={
  211. "msgtype": "m.text",
  212. "body": "message 1",
  213. "m.relates_to": {
  214. "event_id": root_event_id,
  215. "rel_type": RelationTypes.THREAD,
  216. },
  217. },
  218. tok=self.mod_access_token,
  219. )
  220. threaded_event_id = res["event_id"]
  221. # Also send a reaction, again with the same root.
  222. res = self.helper.send_event(
  223. room_id=self.room_id,
  224. type=EventTypes.Reaction,
  225. content={
  226. "m.relates_to": {
  227. "rel_type": RelationTypes.ANNOTATION,
  228. "event_id": root_event_id,
  229. "key": "👍",
  230. }
  231. },
  232. tok=self.mod_access_token,
  233. )
  234. reaction_event_id = res["event_id"]
  235. # Redact the root event, specifying that we also want to delete events that
  236. # relate to it with m.replace.
  237. self._redact_event(
  238. self.mod_access_token,
  239. self.room_id,
  240. root_event_id,
  241. with_relations=[
  242. RelationTypes.REPLACE,
  243. RelationTypes.THREAD,
  244. ],
  245. )
  246. # Check that the root event got redacted.
  247. event_dict = self.helper.get_event(
  248. self.room_id, root_event_id, self.mod_access_token
  249. )
  250. self.assertIn("redacted_because", event_dict, event_dict)
  251. # Check that the edit got redacted.
  252. event_dict = self.helper.get_event(
  253. self.room_id, edit_event_id, self.mod_access_token
  254. )
  255. self.assertIn("redacted_because", event_dict, event_dict)
  256. # Check that the threaded message got redacted.
  257. event_dict = self.helper.get_event(
  258. self.room_id, threaded_event_id, self.mod_access_token
  259. )
  260. self.assertIn("redacted_because", event_dict, event_dict)
  261. # Check that the reaction did not get redacted.
  262. event_dict = self.helper.get_event(
  263. self.room_id, reaction_event_id, self.mod_access_token
  264. )
  265. self.assertNotIn("redacted_because", event_dict, event_dict)
  266. @override_config({"experimental_features": {"msc3912_enabled": True}})
  267. def test_redact_relations_no_perms(self) -> None:
  268. """Tests that, when redacting a message along with its relations, if not all
  269. the related messages can be redacted because of insufficient permissions, the
  270. server still redacts all the ones that can be.
  271. """
  272. # Send a root event.
  273. res = self.helper.send_event(
  274. room_id=self.room_id,
  275. type=EventTypes.Message,
  276. content={
  277. "msgtype": "m.text",
  278. "body": "root",
  279. },
  280. tok=self.other_access_token,
  281. )
  282. root_event_id = res["event_id"]
  283. # Send a first threaded message, this one from the moderator. We do this for the
  284. # first message with the m.thread relation (and not the last one) to ensure
  285. # that, when the server fails to redact it, it doesn't stop there, and it
  286. # instead goes on to redact the other one.
  287. res = self.helper.send_event(
  288. room_id=self.room_id,
  289. type=EventTypes.Message,
  290. content={
  291. "msgtype": "m.text",
  292. "body": "message 1",
  293. "m.relates_to": {
  294. "event_id": root_event_id,
  295. "rel_type": RelationTypes.THREAD,
  296. },
  297. },
  298. tok=self.mod_access_token,
  299. )
  300. first_threaded_event_id = res["event_id"]
  301. # Send a second threaded message, this time from the user who'll perform the
  302. # redaction.
  303. res = self.helper.send_event(
  304. room_id=self.room_id,
  305. type=EventTypes.Message,
  306. content={
  307. "msgtype": "m.text",
  308. "body": "message 2",
  309. "m.relates_to": {
  310. "event_id": root_event_id,
  311. "rel_type": RelationTypes.THREAD,
  312. },
  313. },
  314. tok=self.other_access_token,
  315. )
  316. second_threaded_event_id = res["event_id"]
  317. # Redact the thread's root, and request that all threaded messages are also
  318. # redacted. Send that request from the non-mod user, so that the first threaded
  319. # event cannot be redacted.
  320. self._redact_event(
  321. self.other_access_token,
  322. self.room_id,
  323. root_event_id,
  324. with_relations=[RelationTypes.THREAD],
  325. )
  326. # Check that the thread root got redacted.
  327. event_dict = self.helper.get_event(
  328. self.room_id, root_event_id, self.other_access_token
  329. )
  330. self.assertIn("redacted_because", event_dict, event_dict)
  331. # Check that the last message in the thread got redacted, despite failing to
  332. # redact the one before it.
  333. event_dict = self.helper.get_event(
  334. self.room_id, second_threaded_event_id, self.other_access_token
  335. )
  336. self.assertIn("redacted_because", event_dict, event_dict)
  337. # Check that the message that was sent into the tread by the mod user is not
  338. # redacted.
  339. event_dict = self.helper.get_event(
  340. self.room_id, first_threaded_event_id, self.other_access_token
  341. )
  342. self.assertIn("body", event_dict["content"], event_dict)
  343. self.assertEqual("message 1", event_dict["content"]["body"])
  344. @override_config({"experimental_features": {"msc3912_enabled": True}})
  345. def test_redact_relations_txn_id_reuse(self) -> None:
  346. """Tests that redacting a message using a transaction ID, then reusing the same
  347. transaction ID but providing an additional list of relations to redact, is
  348. effectively a no-op.
  349. """
  350. # Send a root event.
  351. res = self.helper.send_event(
  352. room_id=self.room_id,
  353. type=EventTypes.Message,
  354. content={
  355. "msgtype": "m.text",
  356. "body": "root",
  357. },
  358. tok=self.mod_access_token,
  359. )
  360. root_event_id = res["event_id"]
  361. # Send a first threaded message.
  362. res = self.helper.send_event(
  363. room_id=self.room_id,
  364. type=EventTypes.Message,
  365. content={
  366. "msgtype": "m.text",
  367. "body": "I'm in a thread!",
  368. "m.relates_to": {
  369. "event_id": root_event_id,
  370. "rel_type": RelationTypes.THREAD,
  371. },
  372. },
  373. tok=self.mod_access_token,
  374. )
  375. threaded_event_id = res["event_id"]
  376. # Send a first redaction request which redacts only the root event.
  377. channel = self.make_request(
  378. method="PUT",
  379. path=f"/rooms/{self.room_id}/redact/{root_event_id}/foo",
  380. content={},
  381. access_token=self.mod_access_token,
  382. )
  383. self.assertEqual(channel.code, 200)
  384. # Send a second redaction request which redacts the root event as well as
  385. # threaded messages.
  386. channel = self.make_request(
  387. method="PUT",
  388. path=f"/rooms/{self.room_id}/redact/{root_event_id}/foo",
  389. content={"org.matrix.msc3912.with_relations": [RelationTypes.THREAD]},
  390. access_token=self.mod_access_token,
  391. )
  392. self.assertEqual(channel.code, 200)
  393. # Check that the root event got redacted.
  394. event_dict = self.helper.get_event(
  395. self.room_id, root_event_id, self.mod_access_token
  396. )
  397. self.assertIn("redacted_because", event_dict)
  398. # Check that the threaded message didn't get redacted (since that wasn't part of
  399. # the original redaction).
  400. event_dict = self.helper.get_event(
  401. self.room_id, threaded_event_id, self.mod_access_token
  402. )
  403. self.assertIn("body", event_dict["content"], event_dict)
  404. self.assertEqual("I'm in a thread!", event_dict["content"]["body"])