You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

652 lines
24 KiB

  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 parameterized import parameterized
  16. from twisted.test.proto_helpers import MemoryReactor
  17. from synapse.api.constants import EventTypes, RelationTypes
  18. from synapse.api.room_versions import RoomVersion, RoomVersions
  19. from synapse.rest import admin
  20. from synapse.rest.client import login, room, sync
  21. from synapse.server import HomeServer
  22. from synapse.storage._base import db_to_json
  23. from synapse.storage.database import LoggingTransaction
  24. from synapse.types import JsonDict
  25. from synapse.util import Clock
  26. from tests.unittest import HomeserverTestCase, override_config
  27. class RedactionsTestCase(HomeserverTestCase):
  28. """Tests that various redaction events are handled correctly"""
  29. servlets = [
  30. admin.register_servlets,
  31. room.register_servlets,
  32. login.register_servlets,
  33. sync.register_servlets,
  34. ]
  35. def make_homeserver(self, reactor: MemoryReactor, clock: Clock) -> HomeServer:
  36. config = self.default_config()
  37. config["rc_message"] = {"per_second": 0.2, "burst_count": 10}
  38. config["rc_admin_redaction"] = {"per_second": 1, "burst_count": 100}
  39. return self.setup_test_homeserver(config=config)
  40. def prepare(self, reactor: MemoryReactor, clock: Clock, hs: HomeServer) -> None:
  41. # register a couple of users
  42. self.mod_user_id = self.register_user("user1", "pass")
  43. self.mod_access_token = self.login("user1", "pass")
  44. self.other_user_id = self.register_user("otheruser", "pass")
  45. self.other_access_token = self.login("otheruser", "pass")
  46. # Create a room
  47. self.room_id = self.helper.create_room_as(
  48. self.mod_user_id, tok=self.mod_access_token
  49. )
  50. # Invite the other user
  51. self.helper.invite(
  52. room=self.room_id,
  53. src=self.mod_user_id,
  54. tok=self.mod_access_token,
  55. targ=self.other_user_id,
  56. )
  57. # The other user joins
  58. self.helper.join(
  59. room=self.room_id, user=self.other_user_id, tok=self.other_access_token
  60. )
  61. def _redact_event(
  62. self,
  63. access_token: str,
  64. room_id: str,
  65. event_id: str,
  66. expect_code: int = 200,
  67. with_relations: Optional[List[str]] = None,
  68. content: Optional[JsonDict] = None,
  69. ) -> JsonDict:
  70. """Helper function to send a redaction event.
  71. Returns the json body.
  72. """
  73. path = "/_matrix/client/r0/rooms/%s/redact/%s" % (room_id, event_id)
  74. request_content = content or {}
  75. if with_relations:
  76. request_content["org.matrix.msc3912.with_relations"] = with_relations
  77. channel = self.make_request(
  78. "POST", path, request_content, access_token=access_token
  79. )
  80. self.assertEqual(channel.code, expect_code)
  81. return channel.json_body
  82. def _sync_room_timeline(self, access_token: str, room_id: str) -> List[JsonDict]:
  83. channel = self.make_request("GET", "sync", access_token=access_token)
  84. self.assertEqual(channel.code, 200)
  85. room_sync = channel.json_body["rooms"]["join"][room_id]
  86. return room_sync["timeline"]["events"]
  87. def test_redact_event_as_moderator(self) -> None:
  88. # as a regular user, send a message to redact
  89. b = self.helper.send(room_id=self.room_id, tok=self.other_access_token)
  90. msg_id = b["event_id"]
  91. # as the moderator, send a redaction
  92. b = self._redact_event(self.mod_access_token, self.room_id, msg_id)
  93. redaction_id = b["event_id"]
  94. # now sync
  95. timeline = self._sync_room_timeline(self.mod_access_token, self.room_id)
  96. # the last event should be the redaction
  97. self.assertEqual(timeline[-1]["event_id"], redaction_id)
  98. self.assertEqual(timeline[-1]["redacts"], msg_id)
  99. # and the penultimate should be the redacted original
  100. self.assertEqual(timeline[-2]["event_id"], msg_id)
  101. self.assertEqual(timeline[-2]["unsigned"]["redacted_by"], redaction_id)
  102. self.assertEqual(timeline[-2]["content"], {})
  103. def test_redact_event_as_normal(self) -> None:
  104. # as a regular user, send a message to redact
  105. b = self.helper.send(room_id=self.room_id, tok=self.other_access_token)
  106. normal_msg_id = b["event_id"]
  107. # also send one as the admin
  108. b = self.helper.send(room_id=self.room_id, tok=self.mod_access_token)
  109. admin_msg_id = b["event_id"]
  110. # as a normal, try to redact the admin's event
  111. self._redact_event(
  112. self.other_access_token, self.room_id, admin_msg_id, expect_code=403
  113. )
  114. # now try to redact our own event
  115. b = self._redact_event(self.other_access_token, self.room_id, normal_msg_id)
  116. redaction_id = b["event_id"]
  117. # now sync
  118. timeline = self._sync_room_timeline(self.other_access_token, self.room_id)
  119. # the last event should be the redaction of the normal event
  120. self.assertEqual(timeline[-1]["event_id"], redaction_id)
  121. self.assertEqual(timeline[-1]["redacts"], normal_msg_id)
  122. # the penultimate should be the unredacted one from the admin
  123. self.assertEqual(timeline[-2]["event_id"], admin_msg_id)
  124. self.assertNotIn("redacted_by", timeline[-2]["unsigned"])
  125. self.assertTrue(timeline[-2]["content"]["body"], {})
  126. # and the antepenultimate should be the redacted normal
  127. self.assertEqual(timeline[-3]["event_id"], normal_msg_id)
  128. self.assertEqual(timeline[-3]["unsigned"]["redacted_by"], redaction_id)
  129. self.assertEqual(timeline[-3]["content"], {})
  130. def test_redact_nonexistent_event(self) -> None:
  131. # control case: an existing event
  132. b = self.helper.send(room_id=self.room_id, tok=self.other_access_token)
  133. msg_id = b["event_id"]
  134. b = self._redact_event(self.other_access_token, self.room_id, msg_id)
  135. redaction_id = b["event_id"]
  136. # room moderators can send redactions for non-existent events
  137. self._redact_event(self.mod_access_token, self.room_id, "$zzz")
  138. # ... but normals cannot
  139. self._redact_event(
  140. self.other_access_token, self.room_id, "$zzz", expect_code=404
  141. )
  142. # when we sync, we should see only the valid redaction
  143. timeline = self._sync_room_timeline(self.other_access_token, self.room_id)
  144. self.assertEqual(timeline[-1]["event_id"], redaction_id)
  145. self.assertEqual(timeline[-1]["redacts"], msg_id)
  146. # and the penultimate should be the redacted original
  147. self.assertEqual(timeline[-2]["event_id"], msg_id)
  148. self.assertEqual(timeline[-2]["unsigned"]["redacted_by"], redaction_id)
  149. self.assertEqual(timeline[-2]["content"], {})
  150. def test_redact_create_event(self) -> None:
  151. # control case: an existing event
  152. b = self.helper.send(room_id=self.room_id, tok=self.mod_access_token)
  153. msg_id = b["event_id"]
  154. self._redact_event(self.mod_access_token, self.room_id, msg_id)
  155. # sync the room, to get the id of the create event
  156. timeline = self._sync_room_timeline(self.other_access_token, self.room_id)
  157. create_event_id = timeline[0]["event_id"]
  158. # room moderators cannot send redactions for create events
  159. self._redact_event(
  160. self.mod_access_token, self.room_id, create_event_id, expect_code=403
  161. )
  162. # and nor can normals
  163. self._redact_event(
  164. self.other_access_token, self.room_id, create_event_id, expect_code=403
  165. )
  166. def test_redact_event_as_moderator_ratelimit(self) -> None:
  167. """Tests that the correct ratelimiting is applied to redactions"""
  168. message_ids = []
  169. # as a regular user, send messages to redact
  170. for _ in range(20):
  171. b = self.helper.send(room_id=self.room_id, tok=self.other_access_token)
  172. message_ids.append(b["event_id"])
  173. self.reactor.advance(10) # To get around ratelimits
  174. # as the moderator, send a bunch of redactions
  175. for msg_id in message_ids:
  176. # These should all succeed, even though this would be denied by
  177. # the standard message ratelimiter
  178. self._redact_event(self.mod_access_token, self.room_id, msg_id)
  179. @override_config({"experimental_features": {"msc3912_enabled": True}})
  180. def test_redact_relations_with_types(self) -> None:
  181. """Tests that we can redact the relations of an event of specific types
  182. at the same time as the event itself.
  183. """
  184. # Send a root event.
  185. res = self.helper.send_event(
  186. room_id=self.room_id,
  187. type=EventTypes.Message,
  188. content={"msgtype": "m.text", "body": "hello"},
  189. tok=self.mod_access_token,
  190. )
  191. root_event_id = res["event_id"]
  192. # Send an edit to this root event.
  193. res = self.helper.send_event(
  194. room_id=self.room_id,
  195. type=EventTypes.Message,
  196. content={
  197. "body": " * hello world",
  198. "m.new_content": {
  199. "body": "hello world",
  200. "msgtype": "m.text",
  201. },
  202. "m.relates_to": {
  203. "event_id": root_event_id,
  204. "rel_type": RelationTypes.REPLACE,
  205. },
  206. "msgtype": "m.text",
  207. },
  208. tok=self.mod_access_token,
  209. )
  210. edit_event_id = res["event_id"]
  211. # Also send a threaded message whose root is the same as the edit's.
  212. res = self.helper.send_event(
  213. room_id=self.room_id,
  214. type=EventTypes.Message,
  215. content={
  216. "msgtype": "m.text",
  217. "body": "message 1",
  218. "m.relates_to": {
  219. "event_id": root_event_id,
  220. "rel_type": RelationTypes.THREAD,
  221. },
  222. },
  223. tok=self.mod_access_token,
  224. )
  225. threaded_event_id = res["event_id"]
  226. # Also send a reaction, again with the same root.
  227. res = self.helper.send_event(
  228. room_id=self.room_id,
  229. type=EventTypes.Reaction,
  230. content={
  231. "m.relates_to": {
  232. "rel_type": RelationTypes.ANNOTATION,
  233. "event_id": root_event_id,
  234. "key": "👍",
  235. }
  236. },
  237. tok=self.mod_access_token,
  238. )
  239. reaction_event_id = res["event_id"]
  240. # Redact the root event, specifying that we also want to delete events that
  241. # relate to it with m.replace.
  242. self._redact_event(
  243. self.mod_access_token,
  244. self.room_id,
  245. root_event_id,
  246. with_relations=[
  247. RelationTypes.REPLACE,
  248. RelationTypes.THREAD,
  249. ],
  250. )
  251. # Check that the root event got redacted.
  252. event_dict = self.helper.get_event(
  253. self.room_id, root_event_id, self.mod_access_token
  254. )
  255. self.assertIn("redacted_because", event_dict, event_dict)
  256. # Check that the edit got redacted.
  257. event_dict = self.helper.get_event(
  258. self.room_id, edit_event_id, self.mod_access_token
  259. )
  260. self.assertIn("redacted_because", event_dict, event_dict)
  261. # Check that the threaded message got redacted.
  262. event_dict = self.helper.get_event(
  263. self.room_id, threaded_event_id, self.mod_access_token
  264. )
  265. self.assertIn("redacted_because", event_dict, event_dict)
  266. # Check that the reaction did not get redacted.
  267. event_dict = self.helper.get_event(
  268. self.room_id, reaction_event_id, self.mod_access_token
  269. )
  270. self.assertNotIn("redacted_because", event_dict, event_dict)
  271. @override_config({"experimental_features": {"msc3912_enabled": True}})
  272. def test_redact_all_relations(self) -> None:
  273. """Tests that we can redact all the relations of an event at the same time as the
  274. event itself.
  275. """
  276. # Send a root event.
  277. res = self.helper.send_event(
  278. room_id=self.room_id,
  279. type=EventTypes.Message,
  280. content={"msgtype": "m.text", "body": "hello"},
  281. tok=self.mod_access_token,
  282. )
  283. root_event_id = res["event_id"]
  284. # Send an edit to this root event.
  285. res = self.helper.send_event(
  286. room_id=self.room_id,
  287. type=EventTypes.Message,
  288. content={
  289. "body": " * hello world",
  290. "m.new_content": {
  291. "body": "hello world",
  292. "msgtype": "m.text",
  293. },
  294. "m.relates_to": {
  295. "event_id": root_event_id,
  296. "rel_type": RelationTypes.REPLACE,
  297. },
  298. "msgtype": "m.text",
  299. },
  300. tok=self.mod_access_token,
  301. )
  302. edit_event_id = res["event_id"]
  303. # Also send a threaded message whose root is the same as the edit's.
  304. res = self.helper.send_event(
  305. room_id=self.room_id,
  306. type=EventTypes.Message,
  307. content={
  308. "msgtype": "m.text",
  309. "body": "message 1",
  310. "m.relates_to": {
  311. "event_id": root_event_id,
  312. "rel_type": RelationTypes.THREAD,
  313. },
  314. },
  315. tok=self.mod_access_token,
  316. )
  317. threaded_event_id = res["event_id"]
  318. # Also send a reaction, again with the same root.
  319. res = self.helper.send_event(
  320. room_id=self.room_id,
  321. type=EventTypes.Reaction,
  322. content={
  323. "m.relates_to": {
  324. "rel_type": RelationTypes.ANNOTATION,
  325. "event_id": root_event_id,
  326. "key": "👍",
  327. }
  328. },
  329. tok=self.mod_access_token,
  330. )
  331. reaction_event_id = res["event_id"]
  332. # Redact the root event, specifying that we also want to delete all events that
  333. # relate to it.
  334. self._redact_event(
  335. self.mod_access_token,
  336. self.room_id,
  337. root_event_id,
  338. with_relations=["*"],
  339. )
  340. # Check that the root event got redacted.
  341. event_dict = self.helper.get_event(
  342. self.room_id, root_event_id, self.mod_access_token
  343. )
  344. self.assertIn("redacted_because", event_dict, event_dict)
  345. # Check that the edit got redacted.
  346. event_dict = self.helper.get_event(
  347. self.room_id, edit_event_id, self.mod_access_token
  348. )
  349. self.assertIn("redacted_because", event_dict, event_dict)
  350. # Check that the threaded message got redacted.
  351. event_dict = self.helper.get_event(
  352. self.room_id, threaded_event_id, self.mod_access_token
  353. )
  354. self.assertIn("redacted_because", event_dict, event_dict)
  355. # Check that the reaction got redacted.
  356. event_dict = self.helper.get_event(
  357. self.room_id, reaction_event_id, self.mod_access_token
  358. )
  359. self.assertIn("redacted_because", event_dict, event_dict)
  360. @override_config({"experimental_features": {"msc3912_enabled": True}})
  361. def test_redact_relations_no_perms(self) -> None:
  362. """Tests that, when redacting a message along with its relations, if not all
  363. the related messages can be redacted because of insufficient permissions, the
  364. server still redacts all the ones that can be.
  365. """
  366. # Send a root event.
  367. res = self.helper.send_event(
  368. room_id=self.room_id,
  369. type=EventTypes.Message,
  370. content={
  371. "msgtype": "m.text",
  372. "body": "root",
  373. },
  374. tok=self.other_access_token,
  375. )
  376. root_event_id = res["event_id"]
  377. # Send a first threaded message, this one from the moderator. We do this for the
  378. # first message with the m.thread relation (and not the last one) to ensure
  379. # that, when the server fails to redact it, it doesn't stop there, and it
  380. # instead goes on to redact the other one.
  381. res = self.helper.send_event(
  382. room_id=self.room_id,
  383. type=EventTypes.Message,
  384. content={
  385. "msgtype": "m.text",
  386. "body": "message 1",
  387. "m.relates_to": {
  388. "event_id": root_event_id,
  389. "rel_type": RelationTypes.THREAD,
  390. },
  391. },
  392. tok=self.mod_access_token,
  393. )
  394. first_threaded_event_id = res["event_id"]
  395. # Send a second threaded message, this time from the user who'll perform the
  396. # redaction.
  397. res = self.helper.send_event(
  398. room_id=self.room_id,
  399. type=EventTypes.Message,
  400. content={
  401. "msgtype": "m.text",
  402. "body": "message 2",
  403. "m.relates_to": {
  404. "event_id": root_event_id,
  405. "rel_type": RelationTypes.THREAD,
  406. },
  407. },
  408. tok=self.other_access_token,
  409. )
  410. second_threaded_event_id = res["event_id"]
  411. # Redact the thread's root, and request that all threaded messages are also
  412. # redacted. Send that request from the non-mod user, so that the first threaded
  413. # event cannot be redacted.
  414. self._redact_event(
  415. self.other_access_token,
  416. self.room_id,
  417. root_event_id,
  418. with_relations=[RelationTypes.THREAD],
  419. )
  420. # Check that the thread root got redacted.
  421. event_dict = self.helper.get_event(
  422. self.room_id, root_event_id, self.other_access_token
  423. )
  424. self.assertIn("redacted_because", event_dict, event_dict)
  425. # Check that the last message in the thread got redacted, despite failing to
  426. # redact the one before it.
  427. event_dict = self.helper.get_event(
  428. self.room_id, second_threaded_event_id, self.other_access_token
  429. )
  430. self.assertIn("redacted_because", event_dict, event_dict)
  431. # Check that the message that was sent into the tread by the mod user is not
  432. # redacted.
  433. event_dict = self.helper.get_event(
  434. self.room_id, first_threaded_event_id, self.other_access_token
  435. )
  436. self.assertIn("body", event_dict["content"], event_dict)
  437. self.assertEqual("message 1", event_dict["content"]["body"])
  438. @override_config({"experimental_features": {"msc3912_enabled": True}})
  439. def test_redact_relations_txn_id_reuse(self) -> None:
  440. """Tests that redacting a message using a transaction ID, then reusing the same
  441. transaction ID but providing an additional list of relations to redact, is
  442. effectively a no-op.
  443. """
  444. # Send a root event.
  445. res = self.helper.send_event(
  446. room_id=self.room_id,
  447. type=EventTypes.Message,
  448. content={
  449. "msgtype": "m.text",
  450. "body": "root",
  451. },
  452. tok=self.mod_access_token,
  453. )
  454. root_event_id = res["event_id"]
  455. # Send a first threaded message.
  456. res = self.helper.send_event(
  457. room_id=self.room_id,
  458. type=EventTypes.Message,
  459. content={
  460. "msgtype": "m.text",
  461. "body": "I'm in a thread!",
  462. "m.relates_to": {
  463. "event_id": root_event_id,
  464. "rel_type": RelationTypes.THREAD,
  465. },
  466. },
  467. tok=self.mod_access_token,
  468. )
  469. threaded_event_id = res["event_id"]
  470. # Send a first redaction request which redacts only the root event.
  471. channel = self.make_request(
  472. method="PUT",
  473. path=f"/rooms/{self.room_id}/redact/{root_event_id}/foo",
  474. content={},
  475. access_token=self.mod_access_token,
  476. )
  477. self.assertEqual(channel.code, 200)
  478. # Send a second redaction request which redacts the root event as well as
  479. # threaded messages.
  480. channel = self.make_request(
  481. method="PUT",
  482. path=f"/rooms/{self.room_id}/redact/{root_event_id}/foo",
  483. content={"org.matrix.msc3912.with_relations": [RelationTypes.THREAD]},
  484. access_token=self.mod_access_token,
  485. )
  486. self.assertEqual(channel.code, 200)
  487. # Check that the root event got redacted.
  488. event_dict = self.helper.get_event(
  489. self.room_id, root_event_id, self.mod_access_token
  490. )
  491. self.assertIn("redacted_because", event_dict)
  492. # Check that the threaded message didn't get redacted (since that wasn't part of
  493. # the original redaction).
  494. event_dict = self.helper.get_event(
  495. self.room_id, threaded_event_id, self.mod_access_token
  496. )
  497. self.assertIn("body", event_dict["content"], event_dict)
  498. self.assertEqual("I'm in a thread!", event_dict["content"]["body"])
  499. @parameterized.expand(
  500. [
  501. # Tuples of:
  502. # Room version
  503. # Boolean: True if the redaction event content should include the event ID.
  504. # Boolean: true if the resulting redaction event is expected to include the
  505. # event ID in the content.
  506. (RoomVersions.V10, False, False),
  507. (RoomVersions.V11, True, True),
  508. (RoomVersions.V11, False, True),
  509. ]
  510. )
  511. def test_redaction_content(
  512. self, room_version: RoomVersion, include_content: bool, expect_content: bool
  513. ) -> None:
  514. """
  515. Room version 11 moved the redacts property to the content.
  516. Ensure that the event gets created properly and that the Client-Server
  517. API servers the proper backwards-compatible version.
  518. """
  519. # Create a room with the newer room version.
  520. room_id = self.helper.create_room_as(
  521. self.mod_user_id,
  522. tok=self.mod_access_token,
  523. room_version=room_version.identifier,
  524. )
  525. # Create an event.
  526. b = self.helper.send(room_id=room_id, tok=self.mod_access_token)
  527. event_id = b["event_id"]
  528. # Ensure the event ID in the URL and the content must match.
  529. if include_content:
  530. self._redact_event(
  531. self.mod_access_token,
  532. room_id,
  533. event_id,
  534. expect_code=400,
  535. content={"redacts": "foo"},
  536. )
  537. # Redact it for real.
  538. result = self._redact_event(
  539. self.mod_access_token,
  540. room_id,
  541. event_id,
  542. content={"redacts": event_id} if include_content else {},
  543. )
  544. redaction_event_id = result["event_id"]
  545. # Sync the room, to get the id of the create event
  546. timeline = self._sync_room_timeline(self.mod_access_token, room_id)
  547. redact_event = timeline[-1]
  548. self.assertEqual(redact_event["type"], EventTypes.Redaction)
  549. # The redacts key should be in the content and the redacts keys.
  550. self.assertEqual(redact_event["content"]["redacts"], event_id)
  551. self.assertEqual(redact_event["redacts"], event_id)
  552. # But it isn't actually part of the event.
  553. def get_event(txn: LoggingTransaction) -> JsonDict:
  554. return db_to_json(
  555. main_datastore._fetch_event_rows(txn, [redaction_event_id])[
  556. redaction_event_id
  557. ].json
  558. )
  559. main_datastore = self.hs.get_datastores().main
  560. event_json = self.get_success(
  561. main_datastore.db_pool.runInteraction("get_event", get_event)
  562. )
  563. self.assertEqual(event_json["type"], EventTypes.Redaction)
  564. if expect_content:
  565. self.assertNotIn("redacts", event_json)
  566. self.assertEqual(event_json["content"]["redacts"], event_id)
  567. else:
  568. self.assertEqual(event_json["redacts"], event_id)
  569. self.assertNotIn("redacts", event_json["content"])