test_relations.py 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813
  1. # Copyright 2019 New Vector Ltd
  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. import itertools
  15. import urllib.parse
  16. from typing import Dict, List, Optional, Tuple
  17. from synapse.api.constants import EventTypes, RelationTypes
  18. from synapse.rest import admin
  19. from synapse.rest.client import login, register, relations, room
  20. from tests import unittest
  21. from tests.server import FakeChannel
  22. class RelationsTestCase(unittest.HomeserverTestCase):
  23. servlets = [
  24. relations.register_servlets,
  25. room.register_servlets,
  26. login.register_servlets,
  27. register.register_servlets,
  28. admin.register_servlets_for_client_rest_resource,
  29. ]
  30. hijack_auth = False
  31. def default_config(self) -> dict:
  32. # We need to enable msc1849 support for aggregations
  33. config = super().default_config()
  34. config["experimental_msc1849_support_enabled"] = True
  35. # We enable frozen dicts as relations/edits change event contents, so we
  36. # want to test that we don't modify the events in the caches.
  37. config["use_frozen_dicts"] = True
  38. return config
  39. def prepare(self, reactor, clock, hs):
  40. self.user_id, self.user_token = self._create_user("alice")
  41. self.user2_id, self.user2_token = self._create_user("bob")
  42. self.room = self.helper.create_room_as(self.user_id, tok=self.user_token)
  43. self.helper.join(self.room, user=self.user2_id, tok=self.user2_token)
  44. res = self.helper.send(self.room, body="Hi!", tok=self.user_token)
  45. self.parent_id = res["event_id"]
  46. def test_send_relation(self):
  47. """Tests that sending a relation using the new /send_relation works
  48. creates the right shape of event.
  49. """
  50. channel = self._send_relation(RelationTypes.ANNOTATION, "m.reaction", key="👍")
  51. self.assertEquals(200, channel.code, channel.json_body)
  52. event_id = channel.json_body["event_id"]
  53. channel = self.make_request(
  54. "GET",
  55. "/rooms/%s/event/%s" % (self.room, event_id),
  56. access_token=self.user_token,
  57. )
  58. self.assertEquals(200, channel.code, channel.json_body)
  59. self.assert_dict(
  60. {
  61. "type": "m.reaction",
  62. "sender": self.user_id,
  63. "content": {
  64. "m.relates_to": {
  65. "event_id": self.parent_id,
  66. "key": "👍",
  67. "rel_type": RelationTypes.ANNOTATION,
  68. }
  69. },
  70. },
  71. channel.json_body,
  72. )
  73. def test_deny_membership(self):
  74. """Test that we deny relations on membership events"""
  75. channel = self._send_relation(RelationTypes.ANNOTATION, EventTypes.Member)
  76. self.assertEquals(400, channel.code, channel.json_body)
  77. def test_deny_invalid_event(self):
  78. """Test that we deny relations on non-existant events"""
  79. channel = self._send_relation(
  80. RelationTypes.ANNOTATION,
  81. EventTypes.Message,
  82. parent_id="foo",
  83. content={"body": "foo", "msgtype": "m.text"},
  84. )
  85. self.assertEquals(400, channel.code, channel.json_body)
  86. # Unless that event is referenced from another event!
  87. self.get_success(
  88. self.hs.get_datastore().db_pool.simple_insert(
  89. table="event_relations",
  90. values={
  91. "event_id": "bar",
  92. "relates_to_id": "foo",
  93. "relation_type": RelationTypes.THREAD,
  94. },
  95. desc="test_deny_invalid_event",
  96. )
  97. )
  98. channel = self._send_relation(
  99. RelationTypes.THREAD,
  100. EventTypes.Message,
  101. parent_id="foo",
  102. content={"body": "foo", "msgtype": "m.text"},
  103. )
  104. self.assertEquals(200, channel.code, channel.json_body)
  105. def test_deny_invalid_room(self):
  106. """Test that we deny relations on non-existant events"""
  107. # Create another room and send a message in it.
  108. room2 = self.helper.create_room_as(self.user_id, tok=self.user_token)
  109. res = self.helper.send(room2, body="Hi!", tok=self.user_token)
  110. parent_id = res["event_id"]
  111. # Attempt to send an annotation to that event.
  112. channel = self._send_relation(
  113. RelationTypes.ANNOTATION, "m.reaction", parent_id=parent_id, key="A"
  114. )
  115. self.assertEquals(400, channel.code, channel.json_body)
  116. def test_deny_double_react(self):
  117. """Test that we deny relations on membership events"""
  118. channel = self._send_relation(RelationTypes.ANNOTATION, "m.reaction", key="a")
  119. self.assertEquals(200, channel.code, channel.json_body)
  120. channel = self._send_relation(RelationTypes.ANNOTATION, "m.reaction", "a")
  121. self.assertEquals(400, channel.code, channel.json_body)
  122. def test_deny_forked_thread(self):
  123. """It is invalid to start a thread off a thread."""
  124. channel = self._send_relation(
  125. RelationTypes.THREAD,
  126. "m.room.message",
  127. content={"msgtype": "m.text", "body": "foo"},
  128. parent_id=self.parent_id,
  129. )
  130. self.assertEquals(200, channel.code, channel.json_body)
  131. parent_id = channel.json_body["event_id"]
  132. channel = self._send_relation(
  133. RelationTypes.THREAD,
  134. "m.room.message",
  135. content={"msgtype": "m.text", "body": "foo"},
  136. parent_id=parent_id,
  137. )
  138. self.assertEquals(400, channel.code, channel.json_body)
  139. def test_basic_paginate_relations(self):
  140. """Tests that calling pagination API correctly the latest relations."""
  141. channel = self._send_relation(RelationTypes.ANNOTATION, "m.reaction", "a")
  142. self.assertEquals(200, channel.code, channel.json_body)
  143. channel = self._send_relation(RelationTypes.ANNOTATION, "m.reaction", "b")
  144. self.assertEquals(200, channel.code, channel.json_body)
  145. annotation_id = channel.json_body["event_id"]
  146. channel = self.make_request(
  147. "GET",
  148. "/_matrix/client/unstable/rooms/%s/relations/%s?limit=1"
  149. % (self.room, self.parent_id),
  150. access_token=self.user_token,
  151. )
  152. self.assertEquals(200, channel.code, channel.json_body)
  153. # We expect to get back a single pagination result, which is the full
  154. # relation event we sent above.
  155. self.assertEquals(len(channel.json_body["chunk"]), 1, channel.json_body)
  156. self.assert_dict(
  157. {"event_id": annotation_id, "sender": self.user_id, "type": "m.reaction"},
  158. channel.json_body["chunk"][0],
  159. )
  160. # We also expect to get the original event (the id of which is self.parent_id)
  161. self.assertEquals(
  162. channel.json_body["original_event"]["event_id"], self.parent_id
  163. )
  164. # Make sure next_batch has something in it that looks like it could be a
  165. # valid token.
  166. self.assertIsInstance(
  167. channel.json_body.get("next_batch"), str, channel.json_body
  168. )
  169. def test_repeated_paginate_relations(self):
  170. """Test that if we paginate using a limit and tokens then we get the
  171. expected events.
  172. """
  173. expected_event_ids = []
  174. for idx in range(10):
  175. channel = self._send_relation(
  176. RelationTypes.ANNOTATION, "m.reaction", chr(ord("a") + idx)
  177. )
  178. self.assertEquals(200, channel.code, channel.json_body)
  179. expected_event_ids.append(channel.json_body["event_id"])
  180. prev_token: Optional[str] = None
  181. found_event_ids: List[str] = []
  182. for _ in range(20):
  183. from_token = ""
  184. if prev_token:
  185. from_token = "&from=" + prev_token
  186. channel = self.make_request(
  187. "GET",
  188. "/_matrix/client/unstable/rooms/%s/relations/%s?limit=1%s"
  189. % (self.room, self.parent_id, from_token),
  190. access_token=self.user_token,
  191. )
  192. self.assertEquals(200, channel.code, channel.json_body)
  193. found_event_ids.extend(e["event_id"] for e in channel.json_body["chunk"])
  194. next_batch = channel.json_body.get("next_batch")
  195. self.assertNotEquals(prev_token, next_batch)
  196. prev_token = next_batch
  197. if not prev_token:
  198. break
  199. # We paginated backwards, so reverse
  200. found_event_ids.reverse()
  201. self.assertEquals(found_event_ids, expected_event_ids)
  202. def test_aggregation_pagination_groups(self):
  203. """Test that we can paginate annotation groups correctly."""
  204. # We need to create ten separate users to send each reaction.
  205. access_tokens = [self.user_token, self.user2_token]
  206. idx = 0
  207. while len(access_tokens) < 10:
  208. user_id, token = self._create_user("test" + str(idx))
  209. idx += 1
  210. self.helper.join(self.room, user=user_id, tok=token)
  211. access_tokens.append(token)
  212. idx = 0
  213. sent_groups = {"👍": 10, "a": 7, "b": 5, "c": 3, "d": 2, "e": 1}
  214. for key in itertools.chain.from_iterable(
  215. itertools.repeat(key, num) for key, num in sent_groups.items()
  216. ):
  217. channel = self._send_relation(
  218. RelationTypes.ANNOTATION,
  219. "m.reaction",
  220. key=key,
  221. access_token=access_tokens[idx],
  222. )
  223. self.assertEquals(200, channel.code, channel.json_body)
  224. idx += 1
  225. idx %= len(access_tokens)
  226. prev_token: Optional[str] = None
  227. found_groups: Dict[str, int] = {}
  228. for _ in range(20):
  229. from_token = ""
  230. if prev_token:
  231. from_token = "&from=" + prev_token
  232. channel = self.make_request(
  233. "GET",
  234. "/_matrix/client/unstable/rooms/%s/aggregations/%s?limit=1%s"
  235. % (self.room, self.parent_id, from_token),
  236. access_token=self.user_token,
  237. )
  238. self.assertEquals(200, channel.code, channel.json_body)
  239. self.assertEqual(len(channel.json_body["chunk"]), 1, channel.json_body)
  240. for groups in channel.json_body["chunk"]:
  241. # We only expect reactions
  242. self.assertEqual(groups["type"], "m.reaction", channel.json_body)
  243. # We should only see each key once
  244. self.assertNotIn(groups["key"], found_groups, channel.json_body)
  245. found_groups[groups["key"]] = groups["count"]
  246. next_batch = channel.json_body.get("next_batch")
  247. self.assertNotEquals(prev_token, next_batch)
  248. prev_token = next_batch
  249. if not prev_token:
  250. break
  251. self.assertEquals(sent_groups, found_groups)
  252. def test_aggregation_pagination_within_group(self):
  253. """Test that we can paginate within an annotation group."""
  254. # We need to create ten separate users to send each reaction.
  255. access_tokens = [self.user_token, self.user2_token]
  256. idx = 0
  257. while len(access_tokens) < 10:
  258. user_id, token = self._create_user("test" + str(idx))
  259. idx += 1
  260. self.helper.join(self.room, user=user_id, tok=token)
  261. access_tokens.append(token)
  262. idx = 0
  263. expected_event_ids = []
  264. for _ in range(10):
  265. channel = self._send_relation(
  266. RelationTypes.ANNOTATION,
  267. "m.reaction",
  268. key="👍",
  269. access_token=access_tokens[idx],
  270. )
  271. self.assertEquals(200, channel.code, channel.json_body)
  272. expected_event_ids.append(channel.json_body["event_id"])
  273. idx += 1
  274. # Also send a different type of reaction so that we test we don't see it
  275. channel = self._send_relation(RelationTypes.ANNOTATION, "m.reaction", key="a")
  276. self.assertEquals(200, channel.code, channel.json_body)
  277. prev_token: Optional[str] = None
  278. found_event_ids: List[str] = []
  279. encoded_key = urllib.parse.quote_plus("👍".encode())
  280. for _ in range(20):
  281. from_token = ""
  282. if prev_token:
  283. from_token = "&from=" + prev_token
  284. channel = self.make_request(
  285. "GET",
  286. "/_matrix/client/unstable/rooms/%s"
  287. "/aggregations/%s/%s/m.reaction/%s?limit=1%s"
  288. % (
  289. self.room,
  290. self.parent_id,
  291. RelationTypes.ANNOTATION,
  292. encoded_key,
  293. from_token,
  294. ),
  295. access_token=self.user_token,
  296. )
  297. self.assertEquals(200, channel.code, channel.json_body)
  298. self.assertEqual(len(channel.json_body["chunk"]), 1, channel.json_body)
  299. found_event_ids.extend(e["event_id"] for e in channel.json_body["chunk"])
  300. next_batch = channel.json_body.get("next_batch")
  301. self.assertNotEquals(prev_token, next_batch)
  302. prev_token = next_batch
  303. if not prev_token:
  304. break
  305. # We paginated backwards, so reverse
  306. found_event_ids.reverse()
  307. self.assertEquals(found_event_ids, expected_event_ids)
  308. def test_aggregation(self):
  309. """Test that annotations get correctly aggregated."""
  310. channel = self._send_relation(RelationTypes.ANNOTATION, "m.reaction", "a")
  311. self.assertEquals(200, channel.code, channel.json_body)
  312. channel = self._send_relation(
  313. RelationTypes.ANNOTATION, "m.reaction", "a", access_token=self.user2_token
  314. )
  315. self.assertEquals(200, channel.code, channel.json_body)
  316. channel = self._send_relation(RelationTypes.ANNOTATION, "m.reaction", "b")
  317. self.assertEquals(200, channel.code, channel.json_body)
  318. channel = self.make_request(
  319. "GET",
  320. "/_matrix/client/unstable/rooms/%s/aggregations/%s"
  321. % (self.room, self.parent_id),
  322. access_token=self.user_token,
  323. )
  324. self.assertEquals(200, channel.code, channel.json_body)
  325. self.assertEquals(
  326. channel.json_body,
  327. {
  328. "chunk": [
  329. {"type": "m.reaction", "key": "a", "count": 2},
  330. {"type": "m.reaction", "key": "b", "count": 1},
  331. ]
  332. },
  333. )
  334. def test_aggregation_redactions(self):
  335. """Test that annotations get correctly aggregated after a redaction."""
  336. channel = self._send_relation(RelationTypes.ANNOTATION, "m.reaction", "a")
  337. self.assertEquals(200, channel.code, channel.json_body)
  338. to_redact_event_id = channel.json_body["event_id"]
  339. channel = self._send_relation(
  340. RelationTypes.ANNOTATION, "m.reaction", "a", access_token=self.user2_token
  341. )
  342. self.assertEquals(200, channel.code, channel.json_body)
  343. # Now lets redact one of the 'a' reactions
  344. channel = self.make_request(
  345. "POST",
  346. "/_matrix/client/r0/rooms/%s/redact/%s" % (self.room, to_redact_event_id),
  347. access_token=self.user_token,
  348. content={},
  349. )
  350. self.assertEquals(200, channel.code, channel.json_body)
  351. channel = self.make_request(
  352. "GET",
  353. "/_matrix/client/unstable/rooms/%s/aggregations/%s"
  354. % (self.room, self.parent_id),
  355. access_token=self.user_token,
  356. )
  357. self.assertEquals(200, channel.code, channel.json_body)
  358. self.assertEquals(
  359. channel.json_body,
  360. {"chunk": [{"type": "m.reaction", "key": "a", "count": 1}]},
  361. )
  362. def test_aggregation_must_be_annotation(self):
  363. """Test that aggregations must be annotations."""
  364. channel = self.make_request(
  365. "GET",
  366. "/_matrix/client/unstable/rooms/%s/aggregations/%s/%s?limit=1"
  367. % (self.room, self.parent_id, RelationTypes.REPLACE),
  368. access_token=self.user_token,
  369. )
  370. self.assertEquals(400, channel.code, channel.json_body)
  371. @unittest.override_config({"experimental_features": {"msc3440_enabled": True}})
  372. def test_aggregation_get_event(self):
  373. """Test that annotations, references, and threads get correctly bundled when
  374. getting the parent event.
  375. """
  376. channel = self._send_relation(RelationTypes.ANNOTATION, "m.reaction", "a")
  377. self.assertEquals(200, channel.code, channel.json_body)
  378. channel = self._send_relation(
  379. RelationTypes.ANNOTATION, "m.reaction", "a", access_token=self.user2_token
  380. )
  381. self.assertEquals(200, channel.code, channel.json_body)
  382. channel = self._send_relation(RelationTypes.ANNOTATION, "m.reaction", "b")
  383. self.assertEquals(200, channel.code, channel.json_body)
  384. channel = self._send_relation(RelationTypes.REFERENCE, "m.room.test")
  385. self.assertEquals(200, channel.code, channel.json_body)
  386. reply_1 = channel.json_body["event_id"]
  387. channel = self._send_relation(RelationTypes.REFERENCE, "m.room.test")
  388. self.assertEquals(200, channel.code, channel.json_body)
  389. reply_2 = channel.json_body["event_id"]
  390. channel = self._send_relation(RelationTypes.THREAD, "m.room.test")
  391. self.assertEquals(200, channel.code, channel.json_body)
  392. channel = self._send_relation(RelationTypes.THREAD, "m.room.test")
  393. self.assertEquals(200, channel.code, channel.json_body)
  394. thread_2 = channel.json_body["event_id"]
  395. channel = self.make_request(
  396. "GET",
  397. "/rooms/%s/event/%s" % (self.room, self.parent_id),
  398. access_token=self.user_token,
  399. )
  400. self.assertEquals(200, channel.code, channel.json_body)
  401. self.assertEquals(
  402. channel.json_body["unsigned"].get("m.relations"),
  403. {
  404. RelationTypes.ANNOTATION: {
  405. "chunk": [
  406. {"type": "m.reaction", "key": "a", "count": 2},
  407. {"type": "m.reaction", "key": "b", "count": 1},
  408. ]
  409. },
  410. RelationTypes.REFERENCE: {
  411. "chunk": [{"event_id": reply_1}, {"event_id": reply_2}]
  412. },
  413. RelationTypes.THREAD: {
  414. "count": 2,
  415. "latest_event": {
  416. "age": 100,
  417. "content": {
  418. "m.relates_to": {
  419. "event_id": self.parent_id,
  420. "rel_type": RelationTypes.THREAD,
  421. }
  422. },
  423. "event_id": thread_2,
  424. "origin_server_ts": 1600,
  425. "room_id": self.room,
  426. "sender": self.user_id,
  427. "type": "m.room.test",
  428. "unsigned": {"age": 100},
  429. "user_id": self.user_id,
  430. },
  431. },
  432. },
  433. )
  434. def test_edit(self):
  435. """Test that a simple edit works."""
  436. new_body = {"msgtype": "m.text", "body": "I've been edited!"}
  437. channel = self._send_relation(
  438. RelationTypes.REPLACE,
  439. "m.room.message",
  440. content={"msgtype": "m.text", "body": "foo", "m.new_content": new_body},
  441. )
  442. self.assertEquals(200, channel.code, channel.json_body)
  443. edit_event_id = channel.json_body["event_id"]
  444. channel = self.make_request(
  445. "GET",
  446. "/rooms/%s/event/%s" % (self.room, self.parent_id),
  447. access_token=self.user_token,
  448. )
  449. self.assertEquals(200, channel.code, channel.json_body)
  450. self.assertEquals(channel.json_body["content"], new_body)
  451. relations_dict = channel.json_body["unsigned"].get("m.relations")
  452. self.assertIn(RelationTypes.REPLACE, relations_dict)
  453. m_replace_dict = relations_dict[RelationTypes.REPLACE]
  454. for key in ["event_id", "sender", "origin_server_ts"]:
  455. self.assertIn(key, m_replace_dict)
  456. self.assert_dict(
  457. {"event_id": edit_event_id, "sender": self.user_id}, m_replace_dict
  458. )
  459. def test_multi_edit(self):
  460. """Test that multiple edits, including attempts by people who
  461. shouldn't be allowed, are correctly handled.
  462. """
  463. channel = self._send_relation(
  464. RelationTypes.REPLACE,
  465. "m.room.message",
  466. content={
  467. "msgtype": "m.text",
  468. "body": "Wibble",
  469. "m.new_content": {"msgtype": "m.text", "body": "First edit"},
  470. },
  471. )
  472. self.assertEquals(200, channel.code, channel.json_body)
  473. new_body = {"msgtype": "m.text", "body": "I've been edited!"}
  474. channel = self._send_relation(
  475. RelationTypes.REPLACE,
  476. "m.room.message",
  477. content={"msgtype": "m.text", "body": "foo", "m.new_content": new_body},
  478. )
  479. self.assertEquals(200, channel.code, channel.json_body)
  480. edit_event_id = channel.json_body["event_id"]
  481. channel = self._send_relation(
  482. RelationTypes.REPLACE,
  483. "m.room.message.WRONG_TYPE",
  484. content={
  485. "msgtype": "m.text",
  486. "body": "Wibble",
  487. "m.new_content": {"msgtype": "m.text", "body": "Edit, but wrong type"},
  488. },
  489. )
  490. self.assertEquals(200, channel.code, channel.json_body)
  491. channel = self.make_request(
  492. "GET",
  493. "/rooms/%s/event/%s" % (self.room, self.parent_id),
  494. access_token=self.user_token,
  495. )
  496. self.assertEquals(200, channel.code, channel.json_body)
  497. self.assertEquals(channel.json_body["content"], new_body)
  498. relations_dict = channel.json_body["unsigned"].get("m.relations")
  499. self.assertIn(RelationTypes.REPLACE, relations_dict)
  500. m_replace_dict = relations_dict[RelationTypes.REPLACE]
  501. for key in ["event_id", "sender", "origin_server_ts"]:
  502. self.assertIn(key, m_replace_dict)
  503. self.assert_dict(
  504. {"event_id": edit_event_id, "sender": self.user_id}, m_replace_dict
  505. )
  506. def test_edit_reply(self):
  507. """Test that editing a reply works."""
  508. # Create a reply to edit.
  509. channel = self._send_relation(
  510. RelationTypes.REFERENCE,
  511. "m.room.message",
  512. content={"msgtype": "m.text", "body": "A reply!"},
  513. )
  514. self.assertEquals(200, channel.code, channel.json_body)
  515. reply = channel.json_body["event_id"]
  516. new_body = {"msgtype": "m.text", "body": "I've been edited!"}
  517. channel = self._send_relation(
  518. RelationTypes.REPLACE,
  519. "m.room.message",
  520. content={"msgtype": "m.text", "body": "foo", "m.new_content": new_body},
  521. parent_id=reply,
  522. )
  523. self.assertEquals(200, channel.code, channel.json_body)
  524. edit_event_id = channel.json_body["event_id"]
  525. channel = self.make_request(
  526. "GET",
  527. "/rooms/%s/event/%s" % (self.room, reply),
  528. access_token=self.user_token,
  529. )
  530. self.assertEquals(200, channel.code, channel.json_body)
  531. # We expect to see the new body in the dict, as well as the reference
  532. # metadata sill intact.
  533. self.assertDictContainsSubset(new_body, channel.json_body["content"])
  534. self.assertDictContainsSubset(
  535. {
  536. "m.relates_to": {
  537. "event_id": self.parent_id,
  538. "rel_type": "m.reference",
  539. }
  540. },
  541. channel.json_body["content"],
  542. )
  543. # We expect that the edit relation appears in the unsigned relations
  544. # section.
  545. relations_dict = channel.json_body["unsigned"].get("m.relations")
  546. self.assertIn(RelationTypes.REPLACE, relations_dict)
  547. m_replace_dict = relations_dict[RelationTypes.REPLACE]
  548. for key in ["event_id", "sender", "origin_server_ts"]:
  549. self.assertIn(key, m_replace_dict)
  550. self.assert_dict(
  551. {"event_id": edit_event_id, "sender": self.user_id}, m_replace_dict
  552. )
  553. def test_relations_redaction_redacts_edits(self):
  554. """Test that edits of an event are redacted when the original event
  555. is redacted.
  556. """
  557. # Send a new event
  558. res = self.helper.send(self.room, body="Heyo!", tok=self.user_token)
  559. original_event_id = res["event_id"]
  560. # Add a relation
  561. channel = self._send_relation(
  562. RelationTypes.REPLACE,
  563. "m.room.message",
  564. parent_id=original_event_id,
  565. content={
  566. "msgtype": "m.text",
  567. "body": "Wibble",
  568. "m.new_content": {"msgtype": "m.text", "body": "First edit"},
  569. },
  570. )
  571. self.assertEquals(200, channel.code, channel.json_body)
  572. # Check the relation is returned
  573. channel = self.make_request(
  574. "GET",
  575. "/_matrix/client/unstable/rooms/%s/relations/%s/m.replace/m.room.message"
  576. % (self.room, original_event_id),
  577. access_token=self.user_token,
  578. )
  579. self.assertEquals(200, channel.code, channel.json_body)
  580. self.assertIn("chunk", channel.json_body)
  581. self.assertEquals(len(channel.json_body["chunk"]), 1)
  582. # Redact the original event
  583. channel = self.make_request(
  584. "PUT",
  585. "/rooms/%s/redact/%s/%s"
  586. % (self.room, original_event_id, "test_relations_redaction_redacts_edits"),
  587. access_token=self.user_token,
  588. content="{}",
  589. )
  590. self.assertEquals(200, channel.code, channel.json_body)
  591. # Try to check for remaining m.replace relations
  592. channel = self.make_request(
  593. "GET",
  594. "/_matrix/client/unstable/rooms/%s/relations/%s/m.replace/m.room.message"
  595. % (self.room, original_event_id),
  596. access_token=self.user_token,
  597. )
  598. self.assertEquals(200, channel.code, channel.json_body)
  599. # Check that no relations are returned
  600. self.assertIn("chunk", channel.json_body)
  601. self.assertEquals(channel.json_body["chunk"], [])
  602. def test_aggregations_redaction_prevents_access_to_aggregations(self):
  603. """Test that annotations of an event are redacted when the original event
  604. is redacted.
  605. """
  606. # Send a new event
  607. res = self.helper.send(self.room, body="Hello!", tok=self.user_token)
  608. original_event_id = res["event_id"]
  609. # Add a relation
  610. channel = self._send_relation(
  611. RelationTypes.ANNOTATION, "m.reaction", key="👍", parent_id=original_event_id
  612. )
  613. self.assertEquals(200, channel.code, channel.json_body)
  614. # Redact the original
  615. channel = self.make_request(
  616. "PUT",
  617. "/rooms/%s/redact/%s/%s"
  618. % (
  619. self.room,
  620. original_event_id,
  621. "test_aggregations_redaction_prevents_access_to_aggregations",
  622. ),
  623. access_token=self.user_token,
  624. content="{}",
  625. )
  626. self.assertEquals(200, channel.code, channel.json_body)
  627. # Check that aggregations returns zero
  628. channel = self.make_request(
  629. "GET",
  630. "/_matrix/client/unstable/rooms/%s/aggregations/%s/m.annotation/m.reaction"
  631. % (self.room, original_event_id),
  632. access_token=self.user_token,
  633. )
  634. self.assertEquals(200, channel.code, channel.json_body)
  635. self.assertIn("chunk", channel.json_body)
  636. self.assertEquals(channel.json_body["chunk"], [])
  637. def _send_relation(
  638. self,
  639. relation_type: str,
  640. event_type: str,
  641. key: Optional[str] = None,
  642. content: Optional[dict] = None,
  643. access_token: Optional[str] = None,
  644. parent_id: Optional[str] = None,
  645. ) -> FakeChannel:
  646. """Helper function to send a relation pointing at `self.parent_id`
  647. Args:
  648. relation_type: One of `RelationTypes`
  649. event_type: The type of the event to create
  650. key: The aggregation key used for m.annotation relation type.
  651. content: The content of the created event.
  652. access_token: The access token used to send the relation, defaults
  653. to `self.user_token`
  654. parent_id: The event_id this relation relates to. If None, then self.parent_id
  655. Returns:
  656. FakeChannel
  657. """
  658. if not access_token:
  659. access_token = self.user_token
  660. query = ""
  661. if key:
  662. query = "?key=" + urllib.parse.quote_plus(key.encode("utf-8"))
  663. original_id = parent_id if parent_id else self.parent_id
  664. channel = self.make_request(
  665. "POST",
  666. "/_matrix/client/unstable/rooms/%s/send_relation/%s/%s/%s%s"
  667. % (self.room, original_id, relation_type, event_type, query),
  668. content or {},
  669. access_token=access_token,
  670. )
  671. return channel
  672. def _create_user(self, localpart: str) -> Tuple[str, str]:
  673. user_id = self.register_user(localpart, "abc123")
  674. access_token = self.login(localpart, "abc123")
  675. return user_id, access_token