test_relations.py 64 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681
  1. # Copyright 2019 New Vector Ltd
  2. # Copyright 2021 The Matrix.org Foundation C.I.C.
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. import urllib.parse
  16. from typing import Any, Callable, Dict, List, Optional, Tuple
  17. from unittest.mock import patch
  18. from twisted.test.proto_helpers import MemoryReactor
  19. from synapse.api.constants import AccountDataTypes, EventTypes, RelationTypes
  20. from synapse.rest import admin
  21. from synapse.rest.client import login, register, relations, room, sync
  22. from synapse.server import HomeServer
  23. from synapse.types import JsonDict
  24. from synapse.util import Clock
  25. from tests import unittest
  26. from tests.server import FakeChannel
  27. from tests.test_utils import make_awaitable
  28. from tests.test_utils.event_injection import inject_event
  29. class BaseRelationsTestCase(unittest.HomeserverTestCase):
  30. servlets = [
  31. relations.register_servlets,
  32. room.register_servlets,
  33. sync.register_servlets,
  34. login.register_servlets,
  35. register.register_servlets,
  36. admin.register_servlets_for_client_rest_resource,
  37. ]
  38. hijack_auth = False
  39. def default_config(self) -> Dict[str, Any]:
  40. # We need to enable msc1849 support for aggregations
  41. config = super().default_config()
  42. # We enable frozen dicts as relations/edits change event contents, so we
  43. # want to test that we don't modify the events in the caches.
  44. config["use_frozen_dicts"] = True
  45. return config
  46. def prepare(self, reactor: MemoryReactor, clock: Clock, hs: HomeServer) -> None:
  47. self.store = hs.get_datastores().main
  48. self.user_id, self.user_token = self._create_user("alice")
  49. self.user2_id, self.user2_token = self._create_user("bob")
  50. self.room = self.helper.create_room_as(self.user_id, tok=self.user_token)
  51. self.helper.join(self.room, user=self.user2_id, tok=self.user2_token)
  52. res = self.helper.send(self.room, body="Hi!", tok=self.user_token)
  53. self.parent_id = res["event_id"]
  54. def _create_user(self, localpart: str) -> Tuple[str, str]:
  55. user_id = self.register_user(localpart, "abc123")
  56. access_token = self.login(localpart, "abc123")
  57. return user_id, access_token
  58. def _send_relation(
  59. self,
  60. relation_type: str,
  61. event_type: str,
  62. key: Optional[str] = None,
  63. content: Optional[dict] = None,
  64. access_token: Optional[str] = None,
  65. parent_id: Optional[str] = None,
  66. expected_response_code: int = 200,
  67. ) -> FakeChannel:
  68. """Helper function to send a relation pointing at `self.parent_id`
  69. Args:
  70. relation_type: One of `RelationTypes`
  71. event_type: The type of the event to create
  72. key: The aggregation key used for m.annotation relation type.
  73. content: The content of the created event. Will be modified to configure
  74. the m.relates_to key based on the other provided parameters.
  75. access_token: The access token used to send the relation, defaults
  76. to `self.user_token`
  77. parent_id: The event_id this relation relates to. If None, then self.parent_id
  78. Returns:
  79. FakeChannel
  80. """
  81. if not access_token:
  82. access_token = self.user_token
  83. original_id = parent_id if parent_id else self.parent_id
  84. if content is None:
  85. content = {}
  86. content["m.relates_to"] = {
  87. "event_id": original_id,
  88. "rel_type": relation_type,
  89. }
  90. if key is not None:
  91. content["m.relates_to"]["key"] = key
  92. channel = self.make_request(
  93. "POST",
  94. f"/_matrix/client/v3/rooms/{self.room}/send/{event_type}",
  95. content,
  96. access_token=access_token,
  97. )
  98. self.assertEqual(expected_response_code, channel.code, channel.json_body)
  99. return channel
  100. def _get_related_events(self) -> List[str]:
  101. """
  102. Requests /relations on the parent ID and returns a list of event IDs.
  103. """
  104. # Request the relations of the event.
  105. channel = self.make_request(
  106. "GET",
  107. f"/_matrix/client/v1/rooms/{self.room}/relations/{self.parent_id}",
  108. access_token=self.user_token,
  109. )
  110. self.assertEquals(200, channel.code, channel.json_body)
  111. return [ev["event_id"] for ev in channel.json_body["chunk"]]
  112. def _get_bundled_aggregations(self) -> JsonDict:
  113. """
  114. Requests /event on the parent ID and returns the m.relations field (from unsigned), if it exists.
  115. """
  116. # Fetch the bundled aggregations of the event.
  117. channel = self.make_request(
  118. "GET",
  119. f"/_matrix/client/v3/rooms/{self.room}/event/{self.parent_id}",
  120. access_token=self.user_token,
  121. )
  122. self.assertEquals(200, channel.code, channel.json_body)
  123. return channel.json_body["unsigned"].get("m.relations", {})
  124. def _find_event_in_chunk(self, events: List[JsonDict]) -> JsonDict:
  125. """
  126. Find the parent event in a chunk of events and assert that it has the proper bundled aggregations.
  127. """
  128. for event in events:
  129. if event["event_id"] == self.parent_id:
  130. return event
  131. raise AssertionError(f"Event {self.parent_id} not found in chunk")
  132. class RelationsTestCase(BaseRelationsTestCase):
  133. def test_send_relation(self) -> None:
  134. """Tests that sending a relation works."""
  135. channel = self._send_relation(RelationTypes.ANNOTATION, "m.reaction", key="👍")
  136. event_id = channel.json_body["event_id"]
  137. channel = self.make_request(
  138. "GET",
  139. f"/rooms/{self.room}/event/{event_id}",
  140. access_token=self.user_token,
  141. )
  142. self.assertEqual(200, channel.code, channel.json_body)
  143. self.assert_dict(
  144. {
  145. "type": "m.reaction",
  146. "sender": self.user_id,
  147. "content": {
  148. "m.relates_to": {
  149. "event_id": self.parent_id,
  150. "key": "👍",
  151. "rel_type": RelationTypes.ANNOTATION,
  152. }
  153. },
  154. },
  155. channel.json_body,
  156. )
  157. def test_deny_invalid_event(self) -> None:
  158. """Test that we deny relations on non-existant events"""
  159. self._send_relation(
  160. RelationTypes.ANNOTATION,
  161. EventTypes.Message,
  162. parent_id="foo",
  163. content={"body": "foo", "msgtype": "m.text"},
  164. expected_response_code=400,
  165. )
  166. # Unless that event is referenced from another event!
  167. self.get_success(
  168. self.hs.get_datastores().main.db_pool.simple_insert(
  169. table="event_relations",
  170. values={
  171. "event_id": "bar",
  172. "relates_to_id": "foo",
  173. "relation_type": RelationTypes.THREAD,
  174. },
  175. desc="test_deny_invalid_event",
  176. )
  177. )
  178. self._send_relation(
  179. RelationTypes.THREAD,
  180. EventTypes.Message,
  181. parent_id="foo",
  182. content={"body": "foo", "msgtype": "m.text"},
  183. )
  184. def test_deny_invalid_room(self) -> None:
  185. """Test that we deny relations on non-existant events"""
  186. # Create another room and send a message in it.
  187. room2 = self.helper.create_room_as(self.user_id, tok=self.user_token)
  188. res = self.helper.send(room2, body="Hi!", tok=self.user_token)
  189. parent_id = res["event_id"]
  190. # Attempt to send an annotation to that event.
  191. self._send_relation(
  192. RelationTypes.ANNOTATION,
  193. "m.reaction",
  194. parent_id=parent_id,
  195. key="A",
  196. expected_response_code=400,
  197. )
  198. def test_deny_double_react(self) -> None:
  199. """Test that we deny relations on membership events"""
  200. self._send_relation(RelationTypes.ANNOTATION, "m.reaction", key="a")
  201. self._send_relation(
  202. RelationTypes.ANNOTATION, "m.reaction", "a", expected_response_code=400
  203. )
  204. def test_deny_forked_thread(self) -> None:
  205. """It is invalid to start a thread off a thread."""
  206. channel = self._send_relation(
  207. RelationTypes.THREAD,
  208. "m.room.message",
  209. content={"msgtype": "m.text", "body": "foo"},
  210. parent_id=self.parent_id,
  211. )
  212. parent_id = channel.json_body["event_id"]
  213. self._send_relation(
  214. RelationTypes.THREAD,
  215. "m.room.message",
  216. content={"msgtype": "m.text", "body": "foo"},
  217. parent_id=parent_id,
  218. expected_response_code=400,
  219. )
  220. def test_ignore_invalid_room(self) -> None:
  221. """Test that we ignore invalid relations over federation."""
  222. # Create another room and send a message in it.
  223. room2 = self.helper.create_room_as(self.user_id, tok=self.user_token)
  224. res = self.helper.send(room2, body="Hi!", tok=self.user_token)
  225. parent_id = res["event_id"]
  226. # Disable the validation to pretend this came over federation.
  227. with patch(
  228. "synapse.handlers.message.EventCreationHandler._validate_event_relation",
  229. new=lambda self, event: make_awaitable(None),
  230. ):
  231. # Generate a various relations from a different room.
  232. self.get_success(
  233. inject_event(
  234. self.hs,
  235. room_id=self.room,
  236. type="m.reaction",
  237. sender=self.user_id,
  238. content={
  239. "m.relates_to": {
  240. "rel_type": RelationTypes.ANNOTATION,
  241. "event_id": parent_id,
  242. "key": "A",
  243. }
  244. },
  245. )
  246. )
  247. self.get_success(
  248. inject_event(
  249. self.hs,
  250. room_id=self.room,
  251. type="m.room.message",
  252. sender=self.user_id,
  253. content={
  254. "body": "foo",
  255. "msgtype": "m.text",
  256. "m.relates_to": {
  257. "rel_type": RelationTypes.REFERENCE,
  258. "event_id": parent_id,
  259. },
  260. },
  261. )
  262. )
  263. self.get_success(
  264. inject_event(
  265. self.hs,
  266. room_id=self.room,
  267. type="m.room.message",
  268. sender=self.user_id,
  269. content={
  270. "body": "foo",
  271. "msgtype": "m.text",
  272. "m.relates_to": {
  273. "rel_type": RelationTypes.THREAD,
  274. "event_id": parent_id,
  275. },
  276. },
  277. )
  278. )
  279. self.get_success(
  280. inject_event(
  281. self.hs,
  282. room_id=self.room,
  283. type="m.room.message",
  284. sender=self.user_id,
  285. content={
  286. "body": "foo",
  287. "msgtype": "m.text",
  288. "new_content": {
  289. "body": "new content",
  290. "msgtype": "m.text",
  291. },
  292. "m.relates_to": {
  293. "rel_type": RelationTypes.REPLACE,
  294. "event_id": parent_id,
  295. },
  296. },
  297. )
  298. )
  299. # They should be ignored when fetching relations.
  300. channel = self.make_request(
  301. "GET",
  302. f"/_matrix/client/v1/rooms/{room2}/relations/{parent_id}",
  303. access_token=self.user_token,
  304. )
  305. self.assertEqual(200, channel.code, channel.json_body)
  306. self.assertEqual(channel.json_body["chunk"], [])
  307. # And for bundled aggregations.
  308. channel = self.make_request(
  309. "GET",
  310. f"/rooms/{room2}/event/{parent_id}",
  311. access_token=self.user_token,
  312. )
  313. self.assertEqual(200, channel.code, channel.json_body)
  314. self.assertNotIn("m.relations", channel.json_body["unsigned"])
  315. def test_edit(self) -> None:
  316. """Test that a simple edit works."""
  317. new_body = {"msgtype": "m.text", "body": "I've been edited!"}
  318. channel = self._send_relation(
  319. RelationTypes.REPLACE,
  320. "m.room.message",
  321. content={"msgtype": "m.text", "body": "foo", "m.new_content": new_body},
  322. )
  323. edit_event_id = channel.json_body["event_id"]
  324. def assert_bundle(event_json: JsonDict) -> None:
  325. """Assert the expected values of the bundled aggregations."""
  326. relations_dict = event_json["unsigned"].get("m.relations")
  327. self.assertIn(RelationTypes.REPLACE, relations_dict)
  328. m_replace_dict = relations_dict[RelationTypes.REPLACE]
  329. for key in ["event_id", "sender", "origin_server_ts"]:
  330. self.assertIn(key, m_replace_dict)
  331. self.assert_dict(
  332. {"event_id": edit_event_id, "sender": self.user_id}, m_replace_dict
  333. )
  334. # /event should return the *original* event
  335. channel = self.make_request(
  336. "GET",
  337. f"/rooms/{self.room}/event/{self.parent_id}",
  338. access_token=self.user_token,
  339. )
  340. self.assertEqual(200, channel.code, channel.json_body)
  341. self.assertEqual(
  342. channel.json_body["content"], {"body": "Hi!", "msgtype": "m.text"}
  343. )
  344. assert_bundle(channel.json_body)
  345. # Request the room messages.
  346. channel = self.make_request(
  347. "GET",
  348. f"/rooms/{self.room}/messages?dir=b",
  349. access_token=self.user_token,
  350. )
  351. self.assertEqual(200, channel.code, channel.json_body)
  352. assert_bundle(self._find_event_in_chunk(channel.json_body["chunk"]))
  353. # Request the room context.
  354. # /context should return the edited event.
  355. channel = self.make_request(
  356. "GET",
  357. f"/rooms/{self.room}/context/{self.parent_id}",
  358. access_token=self.user_token,
  359. )
  360. self.assertEqual(200, channel.code, channel.json_body)
  361. assert_bundle(channel.json_body["event"])
  362. self.assertEqual(channel.json_body["event"]["content"], new_body)
  363. # Request sync, but limit the timeline so it becomes limited (and includes
  364. # bundled aggregations).
  365. filter = urllib.parse.quote_plus(b'{"room": {"timeline": {"limit": 2}}}')
  366. channel = self.make_request(
  367. "GET", f"/sync?filter={filter}", access_token=self.user_token
  368. )
  369. self.assertEqual(200, channel.code, channel.json_body)
  370. room_timeline = channel.json_body["rooms"]["join"][self.room]["timeline"]
  371. self.assertTrue(room_timeline["limited"])
  372. assert_bundle(self._find_event_in_chunk(room_timeline["events"]))
  373. # Request search.
  374. channel = self.make_request(
  375. "POST",
  376. "/search",
  377. # Search term matches the parent message.
  378. content={"search_categories": {"room_events": {"search_term": "Hi"}}},
  379. access_token=self.user_token,
  380. )
  381. self.assertEqual(200, channel.code, channel.json_body)
  382. chunk = [
  383. result["result"]
  384. for result in channel.json_body["search_categories"]["room_events"][
  385. "results"
  386. ]
  387. ]
  388. assert_bundle(self._find_event_in_chunk(chunk))
  389. def test_multi_edit(self) -> None:
  390. """Test that multiple edits, including attempts by people who
  391. shouldn't be allowed, are correctly handled.
  392. """
  393. self._send_relation(
  394. RelationTypes.REPLACE,
  395. "m.room.message",
  396. content={
  397. "msgtype": "m.text",
  398. "body": "Wibble",
  399. "m.new_content": {"msgtype": "m.text", "body": "First edit"},
  400. },
  401. )
  402. new_body = {"msgtype": "m.text", "body": "I've been edited!"}
  403. channel = self._send_relation(
  404. RelationTypes.REPLACE,
  405. "m.room.message",
  406. content={"msgtype": "m.text", "body": "foo", "m.new_content": new_body},
  407. )
  408. edit_event_id = channel.json_body["event_id"]
  409. self._send_relation(
  410. RelationTypes.REPLACE,
  411. "m.room.message.WRONG_TYPE",
  412. content={
  413. "msgtype": "m.text",
  414. "body": "Wibble",
  415. "m.new_content": {"msgtype": "m.text", "body": "Edit, but wrong type"},
  416. },
  417. )
  418. channel = self.make_request(
  419. "GET",
  420. f"/rooms/{self.room}/context/{self.parent_id}",
  421. access_token=self.user_token,
  422. )
  423. self.assertEqual(200, channel.code, channel.json_body)
  424. self.assertEqual(channel.json_body["event"]["content"], new_body)
  425. relations_dict = channel.json_body["event"]["unsigned"].get("m.relations")
  426. self.assertIn(RelationTypes.REPLACE, relations_dict)
  427. m_replace_dict = relations_dict[RelationTypes.REPLACE]
  428. for key in ["event_id", "sender", "origin_server_ts"]:
  429. self.assertIn(key, m_replace_dict)
  430. self.assert_dict(
  431. {"event_id": edit_event_id, "sender": self.user_id}, m_replace_dict
  432. )
  433. def test_edit_reply(self) -> None:
  434. """Test that editing a reply works."""
  435. # Create a reply to edit.
  436. original_body = {"msgtype": "m.text", "body": "A reply!"}
  437. channel = self._send_relation(
  438. RelationTypes.REFERENCE, "m.room.message", content=original_body
  439. )
  440. reply = channel.json_body["event_id"]
  441. new_body = {"msgtype": "m.text", "body": "I've been edited!"}
  442. channel = self._send_relation(
  443. RelationTypes.REPLACE,
  444. "m.room.message",
  445. content={"msgtype": "m.text", "body": "foo", "m.new_content": new_body},
  446. parent_id=reply,
  447. )
  448. edit_event_id = channel.json_body["event_id"]
  449. # /event returns the original event
  450. channel = self.make_request(
  451. "GET",
  452. f"/rooms/{self.room}/event/{reply}",
  453. access_token=self.user_token,
  454. )
  455. self.assertEqual(200, channel.code, channel.json_body)
  456. event_result = channel.json_body
  457. self.assertDictContainsSubset(original_body, event_result["content"])
  458. # also check /context, which returns the *edited* event
  459. channel = self.make_request(
  460. "GET",
  461. f"/rooms/{self.room}/context/{reply}",
  462. access_token=self.user_token,
  463. )
  464. self.assertEqual(200, channel.code, channel.json_body)
  465. context_result = channel.json_body["event"]
  466. # check that the relations are correct for both APIs
  467. for result_event_dict, desc in (
  468. (event_result, "/event"),
  469. (context_result, "/context"),
  470. ):
  471. # The reference metadata should still be intact.
  472. self.assertDictContainsSubset(
  473. {
  474. "m.relates_to": {
  475. "event_id": self.parent_id,
  476. "rel_type": "m.reference",
  477. }
  478. },
  479. result_event_dict["content"],
  480. desc,
  481. )
  482. # We expect that the edit relation appears in the unsigned relations
  483. # section.
  484. relations_dict = result_event_dict["unsigned"].get("m.relations")
  485. self.assertIn(RelationTypes.REPLACE, relations_dict, desc)
  486. m_replace_dict = relations_dict[RelationTypes.REPLACE]
  487. for key in ["event_id", "sender", "origin_server_ts"]:
  488. self.assertIn(key, m_replace_dict, desc)
  489. self.assert_dict(
  490. {"event_id": edit_event_id, "sender": self.user_id}, m_replace_dict
  491. )
  492. def test_edit_edit(self) -> None:
  493. """Test that an edit cannot be edited."""
  494. new_body = {"msgtype": "m.text", "body": "Initial edit"}
  495. channel = self._send_relation(
  496. RelationTypes.REPLACE,
  497. "m.room.message",
  498. content={
  499. "msgtype": "m.text",
  500. "body": "Wibble",
  501. "m.new_content": new_body,
  502. },
  503. )
  504. edit_event_id = channel.json_body["event_id"]
  505. # Edit the edit event.
  506. self._send_relation(
  507. RelationTypes.REPLACE,
  508. "m.room.message",
  509. content={
  510. "msgtype": "m.text",
  511. "body": "foo",
  512. "m.new_content": {"msgtype": "m.text", "body": "Ignored edit"},
  513. },
  514. parent_id=edit_event_id,
  515. )
  516. # Request the original event.
  517. # /event should return the original event.
  518. channel = self.make_request(
  519. "GET",
  520. f"/rooms/{self.room}/event/{self.parent_id}",
  521. access_token=self.user_token,
  522. )
  523. self.assertEqual(200, channel.code, channel.json_body)
  524. self.assertEqual(
  525. channel.json_body["content"], {"body": "Hi!", "msgtype": "m.text"}
  526. )
  527. # The relations information should not include the edit to the edit.
  528. relations_dict = channel.json_body["unsigned"].get("m.relations")
  529. self.assertIn(RelationTypes.REPLACE, relations_dict)
  530. # /context should return the event updated for the *first* edit
  531. # (The edit to the edit should be ignored.)
  532. channel = self.make_request(
  533. "GET",
  534. f"/rooms/{self.room}/context/{self.parent_id}",
  535. access_token=self.user_token,
  536. )
  537. self.assertEqual(200, channel.code, channel.json_body)
  538. self.assertEqual(channel.json_body["event"]["content"], new_body)
  539. m_replace_dict = relations_dict[RelationTypes.REPLACE]
  540. for key in ["event_id", "sender", "origin_server_ts"]:
  541. self.assertIn(key, m_replace_dict)
  542. self.assert_dict(
  543. {"event_id": edit_event_id, "sender": self.user_id}, m_replace_dict
  544. )
  545. # Directly requesting the edit should not have the edit to the edit applied.
  546. channel = self.make_request(
  547. "GET",
  548. f"/rooms/{self.room}/event/{edit_event_id}",
  549. access_token=self.user_token,
  550. )
  551. self.assertEqual(200, channel.code, channel.json_body)
  552. self.assertEqual("Wibble", channel.json_body["content"]["body"])
  553. self.assertIn("m.new_content", channel.json_body["content"])
  554. # The relations information should not include the edit to the edit.
  555. self.assertNotIn("m.relations", channel.json_body["unsigned"])
  556. def test_unknown_relations(self) -> None:
  557. """Unknown relations should be accepted."""
  558. channel = self._send_relation("m.relation.test", "m.room.test")
  559. event_id = channel.json_body["event_id"]
  560. channel = self.make_request(
  561. "GET",
  562. f"/_matrix/client/v1/rooms/{self.room}/relations/{self.parent_id}?limit=1",
  563. access_token=self.user_token,
  564. )
  565. self.assertEqual(200, channel.code, channel.json_body)
  566. # We expect to get back a single pagination result, which is the full
  567. # relation event we sent above.
  568. self.assertEqual(len(channel.json_body["chunk"]), 1, channel.json_body)
  569. self.assert_dict(
  570. {"event_id": event_id, "sender": self.user_id, "type": "m.room.test"},
  571. channel.json_body["chunk"][0],
  572. )
  573. # We also expect to get the original event (the id of which is self.parent_id)
  574. self.assertEqual(
  575. channel.json_body["original_event"]["event_id"], self.parent_id
  576. )
  577. # When bundling the unknown relation is not included.
  578. channel = self.make_request(
  579. "GET",
  580. f"/rooms/{self.room}/event/{self.parent_id}",
  581. access_token=self.user_token,
  582. )
  583. self.assertEqual(200, channel.code, channel.json_body)
  584. self.assertNotIn("m.relations", channel.json_body["unsigned"])
  585. def test_background_update(self) -> None:
  586. """Test the event_arbitrary_relations background update."""
  587. channel = self._send_relation(RelationTypes.ANNOTATION, "m.reaction", key="👍")
  588. annotation_event_id_good = channel.json_body["event_id"]
  589. channel = self._send_relation(RelationTypes.ANNOTATION, "m.reaction", key="A")
  590. annotation_event_id_bad = channel.json_body["event_id"]
  591. channel = self._send_relation(RelationTypes.THREAD, "m.room.test")
  592. thread_event_id = channel.json_body["event_id"]
  593. # Clean-up the table as if the inserts did not happen during event creation.
  594. self.get_success(
  595. self.store.db_pool.simple_delete_many(
  596. table="event_relations",
  597. column="event_id",
  598. iterable=(annotation_event_id_bad, thread_event_id),
  599. keyvalues={},
  600. desc="RelationsTestCase.test_background_update",
  601. )
  602. )
  603. # Only the "good" annotation should be found.
  604. channel = self.make_request(
  605. "GET",
  606. f"/_matrix/client/v1/rooms/{self.room}/relations/{self.parent_id}?limit=10",
  607. access_token=self.user_token,
  608. )
  609. self.assertEqual(200, channel.code, channel.json_body)
  610. self.assertEqual(
  611. [ev["event_id"] for ev in channel.json_body["chunk"]],
  612. [annotation_event_id_good],
  613. )
  614. # Insert and run the background update.
  615. self.get_success(
  616. self.store.db_pool.simple_insert(
  617. "background_updates",
  618. {"update_name": "event_arbitrary_relations", "progress_json": "{}"},
  619. )
  620. )
  621. # Ugh, have to reset this flag
  622. self.store.db_pool.updates._all_done = False
  623. self.wait_for_background_updates()
  624. # The "good" annotation and the thread should be found, but not the "bad"
  625. # annotation.
  626. channel = self.make_request(
  627. "GET",
  628. f"/_matrix/client/v1/rooms/{self.room}/relations/{self.parent_id}?limit=10",
  629. access_token=self.user_token,
  630. )
  631. self.assertEqual(200, channel.code, channel.json_body)
  632. self.assertCountEqual(
  633. [ev["event_id"] for ev in channel.json_body["chunk"]],
  634. [annotation_event_id_good, thread_event_id],
  635. )
  636. class RelationPaginationTestCase(BaseRelationsTestCase):
  637. @unittest.override_config({"experimental_features": {"msc3715_enabled": True}})
  638. def test_basic_paginate_relations(self) -> None:
  639. """Tests that calling pagination API correctly the latest relations."""
  640. channel = self._send_relation(RelationTypes.ANNOTATION, "m.reaction", "a")
  641. first_annotation_id = channel.json_body["event_id"]
  642. channel = self._send_relation(RelationTypes.ANNOTATION, "m.reaction", "b")
  643. second_annotation_id = channel.json_body["event_id"]
  644. channel = self.make_request(
  645. "GET",
  646. f"/_matrix/client/v1/rooms/{self.room}/relations/{self.parent_id}?limit=1",
  647. access_token=self.user_token,
  648. )
  649. self.assertEqual(200, channel.code, channel.json_body)
  650. # We expect to get back a single pagination result, which is the latest
  651. # full relation event we sent above.
  652. self.assertEqual(len(channel.json_body["chunk"]), 1, channel.json_body)
  653. self.assert_dict(
  654. {
  655. "event_id": second_annotation_id,
  656. "sender": self.user_id,
  657. "type": "m.reaction",
  658. },
  659. channel.json_body["chunk"][0],
  660. )
  661. # We also expect to get the original event (the id of which is self.parent_id)
  662. self.assertEqual(
  663. channel.json_body["original_event"]["event_id"], self.parent_id
  664. )
  665. # Make sure next_batch has something in it that looks like it could be a
  666. # valid token.
  667. self.assertIsInstance(
  668. channel.json_body.get("next_batch"), str, channel.json_body
  669. )
  670. # Request the relations again, but with a different direction.
  671. channel = self.make_request(
  672. "GET",
  673. f"/_matrix/client/v1/rooms/{self.room}/relations"
  674. f"/{self.parent_id}?limit=1&org.matrix.msc3715.dir=f",
  675. access_token=self.user_token,
  676. )
  677. self.assertEqual(200, channel.code, channel.json_body)
  678. # We expect to get back a single pagination result, which is the earliest
  679. # full relation event we sent above.
  680. self.assertEqual(len(channel.json_body["chunk"]), 1, channel.json_body)
  681. self.assert_dict(
  682. {
  683. "event_id": first_annotation_id,
  684. "sender": self.user_id,
  685. "type": "m.reaction",
  686. },
  687. channel.json_body["chunk"][0],
  688. )
  689. def test_repeated_paginate_relations(self) -> None:
  690. """Test that if we paginate using a limit and tokens then we get the
  691. expected events.
  692. """
  693. expected_event_ids = []
  694. for idx in range(10):
  695. channel = self._send_relation(
  696. RelationTypes.ANNOTATION, "m.reaction", chr(ord("a") + idx)
  697. )
  698. expected_event_ids.append(channel.json_body["event_id"])
  699. prev_token: Optional[str] = ""
  700. found_event_ids: List[str] = []
  701. for _ in range(20):
  702. from_token = ""
  703. if prev_token:
  704. from_token = "&from=" + prev_token
  705. channel = self.make_request(
  706. "GET",
  707. f"/_matrix/client/v1/rooms/{self.room}/relations/{self.parent_id}?limit=1{from_token}",
  708. access_token=self.user_token,
  709. )
  710. self.assertEqual(200, channel.code, channel.json_body)
  711. found_event_ids.extend(e["event_id"] for e in channel.json_body["chunk"])
  712. next_batch = channel.json_body.get("next_batch")
  713. self.assertNotEqual(prev_token, next_batch)
  714. prev_token = next_batch
  715. if not prev_token:
  716. break
  717. # We paginated backwards, so reverse
  718. found_event_ids.reverse()
  719. self.assertEqual(found_event_ids, expected_event_ids)
  720. def test_pagination_from_sync_and_messages(self) -> None:
  721. """Pagination tokens from /sync and /messages can be used to paginate /relations."""
  722. channel = self._send_relation(RelationTypes.ANNOTATION, "m.reaction", "A")
  723. annotation_id = channel.json_body["event_id"]
  724. # Send an event after the relation events.
  725. self.helper.send(self.room, body="Latest event", tok=self.user_token)
  726. # Request /sync, limiting it such that only the latest event is returned
  727. # (and not the relation).
  728. filter = urllib.parse.quote_plus(b'{"room": {"timeline": {"limit": 1}}}')
  729. channel = self.make_request(
  730. "GET", f"/sync?filter={filter}", access_token=self.user_token
  731. )
  732. self.assertEqual(200, channel.code, channel.json_body)
  733. room_timeline = channel.json_body["rooms"]["join"][self.room]["timeline"]
  734. sync_prev_batch = room_timeline["prev_batch"]
  735. self.assertIsNotNone(sync_prev_batch)
  736. # Ensure the relation event is not in the batch returned from /sync.
  737. self.assertNotIn(
  738. annotation_id, [ev["event_id"] for ev in room_timeline["events"]]
  739. )
  740. # Request /messages, limiting it such that only the latest event is
  741. # returned (and not the relation).
  742. channel = self.make_request(
  743. "GET",
  744. f"/rooms/{self.room}/messages?dir=b&limit=1",
  745. access_token=self.user_token,
  746. )
  747. self.assertEqual(200, channel.code, channel.json_body)
  748. messages_end = channel.json_body["end"]
  749. self.assertIsNotNone(messages_end)
  750. # Ensure the relation event is not in the chunk returned from /messages.
  751. self.assertNotIn(
  752. annotation_id, [ev["event_id"] for ev in channel.json_body["chunk"]]
  753. )
  754. # Request /relations with the pagination tokens received from both the
  755. # /sync and /messages responses above, in turn.
  756. #
  757. # This is a tiny bit silly since the client wouldn't know the parent ID
  758. # from the requests above; consider the parent ID to be known from a
  759. # previous /sync.
  760. for from_token in (sync_prev_batch, messages_end):
  761. channel = self.make_request(
  762. "GET",
  763. f"/_matrix/client/v1/rooms/{self.room}/relations/{self.parent_id}?from={from_token}",
  764. access_token=self.user_token,
  765. )
  766. self.assertEqual(200, channel.code, channel.json_body)
  767. # The relation should be in the returned chunk.
  768. self.assertIn(
  769. annotation_id, [ev["event_id"] for ev in channel.json_body["chunk"]]
  770. )
  771. class BundledAggregationsTestCase(BaseRelationsTestCase):
  772. """
  773. See RelationsTestCase.test_edit for a similar test for edits.
  774. Note that this doesn't test against /relations since only thread relations
  775. get bundled via that API. See test_aggregation_get_event_for_thread.
  776. """
  777. def _test_bundled_aggregations(
  778. self,
  779. relation_type: str,
  780. assertion_callable: Callable[[JsonDict], None],
  781. expected_db_txn_for_event: int,
  782. access_token: Optional[str] = None,
  783. ) -> None:
  784. """
  785. Makes requests to various endpoints which should include bundled aggregations
  786. and then calls an assertion function on the bundled aggregations.
  787. Args:
  788. relation_type: The field to search for in the `m.relations` field in unsigned.
  789. assertion_callable: Called with the contents of unsigned["m.relations"][relation_type]
  790. for relation-specific assertions.
  791. expected_db_txn_for_event: The number of database transactions which
  792. are expected for a call to /event/.
  793. access_token: The access token to user, defaults to self.user_token.
  794. """
  795. access_token = access_token or self.user_token
  796. def assert_bundle(event_json: JsonDict) -> None:
  797. """Assert the expected values of the bundled aggregations."""
  798. relations_dict = event_json["unsigned"].get("m.relations")
  799. # Ensure the fields are as expected.
  800. self.assertCountEqual(relations_dict.keys(), (relation_type,))
  801. assertion_callable(relations_dict[relation_type])
  802. # Request the event directly.
  803. channel = self.make_request(
  804. "GET",
  805. f"/rooms/{self.room}/event/{self.parent_id}",
  806. access_token=access_token,
  807. )
  808. self.assertEqual(200, channel.code, channel.json_body)
  809. assert_bundle(channel.json_body)
  810. assert channel.resource_usage is not None
  811. self.assertEqual(channel.resource_usage.db_txn_count, expected_db_txn_for_event)
  812. # Request the room messages.
  813. channel = self.make_request(
  814. "GET",
  815. f"/rooms/{self.room}/messages?dir=b",
  816. access_token=access_token,
  817. )
  818. self.assertEqual(200, channel.code, channel.json_body)
  819. assert_bundle(self._find_event_in_chunk(channel.json_body["chunk"]))
  820. # Request the room context.
  821. channel = self.make_request(
  822. "GET",
  823. f"/rooms/{self.room}/context/{self.parent_id}",
  824. access_token=access_token,
  825. )
  826. self.assertEqual(200, channel.code, channel.json_body)
  827. assert_bundle(channel.json_body["event"])
  828. # Request sync.
  829. filter = urllib.parse.quote_plus(b'{"room": {"timeline": {"limit": 4}}}')
  830. channel = self.make_request(
  831. "GET", f"/sync?filter={filter}", access_token=access_token
  832. )
  833. self.assertEqual(200, channel.code, channel.json_body)
  834. room_timeline = channel.json_body["rooms"]["join"][self.room]["timeline"]
  835. self.assertTrue(room_timeline["limited"])
  836. assert_bundle(self._find_event_in_chunk(room_timeline["events"]))
  837. # Request search.
  838. channel = self.make_request(
  839. "POST",
  840. "/search",
  841. # Search term matches the parent message.
  842. content={"search_categories": {"room_events": {"search_term": "Hi"}}},
  843. access_token=access_token,
  844. )
  845. self.assertEqual(200, channel.code, channel.json_body)
  846. chunk = [
  847. result["result"]
  848. for result in channel.json_body["search_categories"]["room_events"][
  849. "results"
  850. ]
  851. ]
  852. assert_bundle(self._find_event_in_chunk(chunk))
  853. def test_annotation(self) -> None:
  854. """
  855. Test that annotations get correctly bundled.
  856. """
  857. # Setup by sending a variety of relations.
  858. self._send_relation(RelationTypes.ANNOTATION, "m.reaction", "a")
  859. self._send_relation(
  860. RelationTypes.ANNOTATION, "m.reaction", "a", access_token=self.user2_token
  861. )
  862. self._send_relation(RelationTypes.ANNOTATION, "m.reaction", "b")
  863. def assert_annotations(bundled_aggregations: JsonDict) -> None:
  864. self.assertEqual(
  865. {
  866. "chunk": [
  867. {"type": "m.reaction", "key": "a", "count": 2},
  868. {"type": "m.reaction", "key": "b", "count": 1},
  869. ]
  870. },
  871. bundled_aggregations,
  872. )
  873. self._test_bundled_aggregations(RelationTypes.ANNOTATION, assert_annotations, 6)
  874. def test_annotation_to_annotation(self) -> None:
  875. """Any relation to an annotation should be ignored."""
  876. channel = self._send_relation(RelationTypes.ANNOTATION, "m.reaction", "a")
  877. event_id = channel.json_body["event_id"]
  878. self._send_relation(
  879. RelationTypes.ANNOTATION, "m.reaction", "b", parent_id=event_id
  880. )
  881. # Fetch the initial annotation event to see if it has bundled aggregations.
  882. channel = self.make_request(
  883. "GET",
  884. f"/_matrix/client/v3/rooms/{self.room}/event/{event_id}",
  885. access_token=self.user_token,
  886. )
  887. self.assertEquals(200, channel.code, channel.json_body)
  888. # The first annotationt should not have any bundled aggregations.
  889. self.assertNotIn("m.relations", channel.json_body["unsigned"])
  890. def test_reference(self) -> None:
  891. """
  892. Test that references get correctly bundled.
  893. """
  894. channel = self._send_relation(RelationTypes.REFERENCE, "m.room.test")
  895. reply_1 = channel.json_body["event_id"]
  896. channel = self._send_relation(RelationTypes.REFERENCE, "m.room.test")
  897. reply_2 = channel.json_body["event_id"]
  898. def assert_annotations(bundled_aggregations: JsonDict) -> None:
  899. self.assertEqual(
  900. {"chunk": [{"event_id": reply_1}, {"event_id": reply_2}]},
  901. bundled_aggregations,
  902. )
  903. self._test_bundled_aggregations(RelationTypes.REFERENCE, assert_annotations, 6)
  904. def test_thread(self) -> None:
  905. """
  906. Test that threads get correctly bundled.
  907. """
  908. # The root message is from "user", send replies as "user2".
  909. self._send_relation(
  910. RelationTypes.THREAD, "m.room.test", access_token=self.user2_token
  911. )
  912. channel = self._send_relation(
  913. RelationTypes.THREAD, "m.room.test", access_token=self.user2_token
  914. )
  915. thread_2 = channel.json_body["event_id"]
  916. # This needs two assertion functions which are identical except for whether
  917. # the current_user_participated flag is True, create a factory for the
  918. # two versions.
  919. def _gen_assert(participated: bool) -> Callable[[JsonDict], None]:
  920. def assert_thread(bundled_aggregations: JsonDict) -> None:
  921. self.assertEqual(2, bundled_aggregations.get("count"))
  922. self.assertEqual(
  923. participated, bundled_aggregations.get("current_user_participated")
  924. )
  925. # The latest thread event has some fields that don't matter.
  926. self.assertIn("latest_event", bundled_aggregations)
  927. self.assert_dict(
  928. {
  929. "content": {
  930. "m.relates_to": {
  931. "event_id": self.parent_id,
  932. "rel_type": RelationTypes.THREAD,
  933. }
  934. },
  935. "event_id": thread_2,
  936. "sender": self.user2_id,
  937. "type": "m.room.test",
  938. },
  939. bundled_aggregations["latest_event"],
  940. )
  941. return assert_thread
  942. # The "user" sent the root event and is making queries for the bundled
  943. # aggregations: they have participated.
  944. self._test_bundled_aggregations(RelationTypes.THREAD, _gen_assert(True), 8)
  945. # The "user2" sent replies in the thread and is making queries for the
  946. # bundled aggregations: they have participated.
  947. #
  948. # Note that this re-uses some cached values, so the total number of
  949. # queries is much smaller.
  950. self._test_bundled_aggregations(
  951. RelationTypes.THREAD, _gen_assert(True), 2, access_token=self.user2_token
  952. )
  953. # A user with no interactions with the thread: they have not participated.
  954. user3_id, user3_token = self._create_user("charlie")
  955. self.helper.join(self.room, user=user3_id, tok=user3_token)
  956. self._test_bundled_aggregations(
  957. RelationTypes.THREAD, _gen_assert(False), 2, access_token=user3_token
  958. )
  959. def test_thread_with_bundled_aggregations_for_latest(self) -> None:
  960. """
  961. Bundled aggregations should get applied to the latest thread event.
  962. """
  963. self._send_relation(RelationTypes.THREAD, "m.room.test")
  964. channel = self._send_relation(RelationTypes.THREAD, "m.room.test")
  965. thread_2 = channel.json_body["event_id"]
  966. self._send_relation(
  967. RelationTypes.ANNOTATION, "m.reaction", "a", parent_id=thread_2
  968. )
  969. def assert_thread(bundled_aggregations: JsonDict) -> None:
  970. self.assertEqual(2, bundled_aggregations.get("count"))
  971. self.assertTrue(bundled_aggregations.get("current_user_participated"))
  972. # The latest thread event has some fields that don't matter.
  973. self.assertIn("latest_event", bundled_aggregations)
  974. self.assert_dict(
  975. {
  976. "content": {
  977. "m.relates_to": {
  978. "event_id": self.parent_id,
  979. "rel_type": RelationTypes.THREAD,
  980. }
  981. },
  982. "event_id": thread_2,
  983. "sender": self.user_id,
  984. "type": "m.room.test",
  985. },
  986. bundled_aggregations["latest_event"],
  987. )
  988. # Check the unsigned field on the latest event.
  989. self.assert_dict(
  990. {
  991. "m.relations": {
  992. RelationTypes.ANNOTATION: {
  993. "chunk": [
  994. {"type": "m.reaction", "key": "a", "count": 1},
  995. ]
  996. },
  997. }
  998. },
  999. bundled_aggregations["latest_event"].get("unsigned"),
  1000. )
  1001. self._test_bundled_aggregations(RelationTypes.THREAD, assert_thread, 8)
  1002. def test_nested_thread(self) -> None:
  1003. """
  1004. Ensure that a nested thread gets ignored by bundled aggregations, as
  1005. those are forbidden.
  1006. """
  1007. # Start a thread.
  1008. channel = self._send_relation(RelationTypes.THREAD, "m.room.test")
  1009. reply_event_id = channel.json_body["event_id"]
  1010. # Disable the validation to pretend this came over federation, since it is
  1011. # not an event the Client-Server API will allow..
  1012. with patch(
  1013. "synapse.handlers.message.EventCreationHandler._validate_event_relation",
  1014. new=lambda self, event: make_awaitable(None),
  1015. ):
  1016. # Create a sub-thread off the thread, which is not allowed.
  1017. self._send_relation(
  1018. RelationTypes.THREAD, "m.room.test", parent_id=reply_event_id
  1019. )
  1020. # Fetch the thread root, to get the bundled aggregation for the thread.
  1021. relations_from_event = self._get_bundled_aggregations()
  1022. # Ensure that requesting the room messages also does not return the sub-thread.
  1023. channel = self.make_request(
  1024. "GET",
  1025. f"/rooms/{self.room}/messages?dir=b",
  1026. access_token=self.user_token,
  1027. )
  1028. self.assertEqual(200, channel.code, channel.json_body)
  1029. event = self._find_event_in_chunk(channel.json_body["chunk"])
  1030. relations_from_messages = event["unsigned"]["m.relations"]
  1031. # Check the bundled aggregations from each point.
  1032. for aggregations, desc in (
  1033. (relations_from_event, "/event"),
  1034. (relations_from_messages, "/messages"),
  1035. ):
  1036. # The latest event should have bundled aggregations.
  1037. self.assertIn(RelationTypes.THREAD, aggregations, desc)
  1038. thread_summary = aggregations[RelationTypes.THREAD]
  1039. self.assertIn("latest_event", thread_summary, desc)
  1040. self.assertEqual(
  1041. thread_summary["latest_event"]["event_id"], reply_event_id, desc
  1042. )
  1043. # The latest event should not have any bundled aggregations (since the
  1044. # only relation to it is another thread, which is invalid).
  1045. self.assertNotIn(
  1046. "m.relations", thread_summary["latest_event"]["unsigned"], desc
  1047. )
  1048. def test_thread_edit_latest_event(self) -> None:
  1049. """Test that editing the latest event in a thread works."""
  1050. # Create a thread and edit the last event.
  1051. channel = self._send_relation(
  1052. RelationTypes.THREAD,
  1053. "m.room.message",
  1054. content={"msgtype": "m.text", "body": "A threaded reply!"},
  1055. )
  1056. threaded_event_id = channel.json_body["event_id"]
  1057. new_body = {"msgtype": "m.text", "body": "I've been edited!"}
  1058. channel = self._send_relation(
  1059. RelationTypes.REPLACE,
  1060. "m.room.message",
  1061. content={"msgtype": "m.text", "body": "foo", "m.new_content": new_body},
  1062. parent_id=threaded_event_id,
  1063. )
  1064. edit_event_id = channel.json_body["event_id"]
  1065. # Fetch the thread root, to get the bundled aggregation for the thread.
  1066. relations_dict = self._get_bundled_aggregations()
  1067. # We expect that the edit message appears in the thread summary in the
  1068. # unsigned relations section.
  1069. self.assertIn(RelationTypes.THREAD, relations_dict)
  1070. thread_summary = relations_dict[RelationTypes.THREAD]
  1071. self.assertIn("latest_event", thread_summary)
  1072. latest_event_in_thread = thread_summary["latest_event"]
  1073. self.assertEqual(latest_event_in_thread["content"]["body"], "I've been edited!")
  1074. # The latest event in the thread should have the edit appear under the
  1075. # bundled aggregations.
  1076. self.assertDictContainsSubset(
  1077. {"event_id": edit_event_id, "sender": "@alice:test"},
  1078. latest_event_in_thread["unsigned"]["m.relations"][RelationTypes.REPLACE],
  1079. )
  1080. def test_aggregation_get_event_for_annotation(self) -> None:
  1081. """Test that annotations do not get bundled aggregations included
  1082. when directly requested.
  1083. """
  1084. channel = self._send_relation(RelationTypes.ANNOTATION, "m.reaction", "a")
  1085. annotation_id = channel.json_body["event_id"]
  1086. # Annotate the annotation.
  1087. self._send_relation(
  1088. RelationTypes.ANNOTATION, "m.reaction", "a", parent_id=annotation_id
  1089. )
  1090. channel = self.make_request(
  1091. "GET",
  1092. f"/rooms/{self.room}/event/{annotation_id}",
  1093. access_token=self.user_token,
  1094. )
  1095. self.assertEqual(200, channel.code, channel.json_body)
  1096. self.assertIsNone(channel.json_body["unsigned"].get("m.relations"))
  1097. def test_aggregation_get_event_for_thread(self) -> None:
  1098. """Test that threads get bundled aggregations included when directly requested."""
  1099. channel = self._send_relation(RelationTypes.THREAD, "m.room.test")
  1100. thread_id = channel.json_body["event_id"]
  1101. # Annotate the thread.
  1102. self._send_relation(
  1103. RelationTypes.ANNOTATION, "m.reaction", "a", parent_id=thread_id
  1104. )
  1105. channel = self.make_request(
  1106. "GET",
  1107. f"/rooms/{self.room}/event/{thread_id}",
  1108. access_token=self.user_token,
  1109. )
  1110. self.assertEqual(200, channel.code, channel.json_body)
  1111. self.assertEqual(
  1112. channel.json_body["unsigned"].get("m.relations"),
  1113. {
  1114. RelationTypes.ANNOTATION: {
  1115. "chunk": [{"count": 1, "key": "a", "type": "m.reaction"}]
  1116. },
  1117. },
  1118. )
  1119. # It should also be included when the entire thread is requested.
  1120. channel = self.make_request(
  1121. "GET",
  1122. f"/_matrix/client/v1/rooms/{self.room}/relations/{self.parent_id}?limit=1",
  1123. access_token=self.user_token,
  1124. )
  1125. self.assertEqual(200, channel.code, channel.json_body)
  1126. self.assertEqual(len(channel.json_body["chunk"]), 1)
  1127. thread_message = channel.json_body["chunk"][0]
  1128. self.assertEqual(
  1129. thread_message["unsigned"].get("m.relations"),
  1130. {
  1131. RelationTypes.ANNOTATION: {
  1132. "chunk": [{"count": 1, "key": "a", "type": "m.reaction"}]
  1133. },
  1134. },
  1135. )
  1136. def test_bundled_aggregations_with_filter(self) -> None:
  1137. """
  1138. If "unsigned" is an omitted field (due to filtering), adding the bundled
  1139. aggregations should not break.
  1140. Note that the spec allows for a server to return additional fields beyond
  1141. what is specified.
  1142. """
  1143. self._send_relation(RelationTypes.ANNOTATION, "m.reaction", "a")
  1144. # Note that the sync filter does not include "unsigned" as a field.
  1145. filter = urllib.parse.quote_plus(
  1146. b'{"event_fields": ["content", "event_id"], "room": {"timeline": {"limit": 3}}}'
  1147. )
  1148. channel = self.make_request(
  1149. "GET", f"/sync?filter={filter}", access_token=self.user_token
  1150. )
  1151. self.assertEqual(200, channel.code, channel.json_body)
  1152. # Ensure the timeline is limited, find the parent event.
  1153. room_timeline = channel.json_body["rooms"]["join"][self.room]["timeline"]
  1154. self.assertTrue(room_timeline["limited"])
  1155. parent_event = self._find_event_in_chunk(room_timeline["events"])
  1156. # Ensure there's bundled aggregations on it.
  1157. self.assertIn("unsigned", parent_event)
  1158. self.assertIn("m.relations", parent_event["unsigned"])
  1159. class RelationIgnoredUserTestCase(BaseRelationsTestCase):
  1160. """Relations sent from an ignored user should be ignored."""
  1161. def _test_ignored_user(
  1162. self,
  1163. relation_type: str,
  1164. allowed_event_ids: List[str],
  1165. ignored_event_ids: List[str],
  1166. ) -> Tuple[JsonDict, JsonDict]:
  1167. """
  1168. Fetch the relations and ensure they're all there, then ignore user2, and
  1169. repeat.
  1170. Returns:
  1171. A tuple of two JSON dictionaries, each are bundled aggregations, the
  1172. first is from before the user is ignored, and the second is after.
  1173. """
  1174. # Get the relations.
  1175. event_ids = self._get_related_events()
  1176. self.assertCountEqual(event_ids, allowed_event_ids + ignored_event_ids)
  1177. # And the bundled aggregations.
  1178. before_aggregations = self._get_bundled_aggregations()
  1179. self.assertIn(relation_type, before_aggregations)
  1180. # Ignore user2 and re-do the requests.
  1181. self.get_success(
  1182. self.store.add_account_data_for_user(
  1183. self.user_id,
  1184. AccountDataTypes.IGNORED_USER_LIST,
  1185. {"ignored_users": {self.user2_id: {}}},
  1186. )
  1187. )
  1188. # Get the relations.
  1189. event_ids = self._get_related_events()
  1190. self.assertCountEqual(event_ids, allowed_event_ids)
  1191. # And the bundled aggregations.
  1192. after_aggregations = self._get_bundled_aggregations()
  1193. self.assertIn(relation_type, after_aggregations)
  1194. return before_aggregations[relation_type], after_aggregations[relation_type]
  1195. def test_annotation(self) -> None:
  1196. """Annotations should ignore"""
  1197. # Send 2 from us, 2 from the to be ignored user.
  1198. allowed_event_ids = []
  1199. ignored_event_ids = []
  1200. channel = self._send_relation(RelationTypes.ANNOTATION, "m.reaction", key="a")
  1201. allowed_event_ids.append(channel.json_body["event_id"])
  1202. channel = self._send_relation(RelationTypes.ANNOTATION, "m.reaction", key="b")
  1203. allowed_event_ids.append(channel.json_body["event_id"])
  1204. channel = self._send_relation(
  1205. RelationTypes.ANNOTATION,
  1206. "m.reaction",
  1207. key="a",
  1208. access_token=self.user2_token,
  1209. )
  1210. ignored_event_ids.append(channel.json_body["event_id"])
  1211. channel = self._send_relation(
  1212. RelationTypes.ANNOTATION,
  1213. "m.reaction",
  1214. key="c",
  1215. access_token=self.user2_token,
  1216. )
  1217. ignored_event_ids.append(channel.json_body["event_id"])
  1218. before_aggregations, after_aggregations = self._test_ignored_user(
  1219. RelationTypes.ANNOTATION, allowed_event_ids, ignored_event_ids
  1220. )
  1221. self.assertCountEqual(
  1222. before_aggregations["chunk"],
  1223. [
  1224. {"type": "m.reaction", "key": "a", "count": 2},
  1225. {"type": "m.reaction", "key": "b", "count": 1},
  1226. {"type": "m.reaction", "key": "c", "count": 1},
  1227. ],
  1228. )
  1229. self.assertCountEqual(
  1230. after_aggregations["chunk"],
  1231. [
  1232. {"type": "m.reaction", "key": "a", "count": 1},
  1233. {"type": "m.reaction", "key": "b", "count": 1},
  1234. ],
  1235. )
  1236. def test_reference(self) -> None:
  1237. """Annotations should ignore"""
  1238. channel = self._send_relation(RelationTypes.REFERENCE, "m.room.test")
  1239. allowed_event_ids = [channel.json_body["event_id"]]
  1240. channel = self._send_relation(
  1241. RelationTypes.REFERENCE, "m.room.test", access_token=self.user2_token
  1242. )
  1243. ignored_event_ids = [channel.json_body["event_id"]]
  1244. before_aggregations, after_aggregations = self._test_ignored_user(
  1245. RelationTypes.REFERENCE, allowed_event_ids, ignored_event_ids
  1246. )
  1247. self.assertCountEqual(
  1248. [e["event_id"] for e in before_aggregations["chunk"]],
  1249. allowed_event_ids + ignored_event_ids,
  1250. )
  1251. self.assertCountEqual(
  1252. [e["event_id"] for e in after_aggregations["chunk"]], allowed_event_ids
  1253. )
  1254. def test_thread(self) -> None:
  1255. """Annotations should ignore"""
  1256. channel = self._send_relation(RelationTypes.THREAD, "m.room.test")
  1257. allowed_event_ids = [channel.json_body["event_id"]]
  1258. channel = self._send_relation(
  1259. RelationTypes.THREAD, "m.room.test", access_token=self.user2_token
  1260. )
  1261. ignored_event_ids = [channel.json_body["event_id"]]
  1262. before_aggregations, after_aggregations = self._test_ignored_user(
  1263. RelationTypes.THREAD, allowed_event_ids, ignored_event_ids
  1264. )
  1265. self.assertEqual(before_aggregations["count"], 2)
  1266. self.assertTrue(before_aggregations["current_user_participated"])
  1267. # The latest thread event has some fields that don't matter.
  1268. self.assertEqual(
  1269. before_aggregations["latest_event"]["event_id"], ignored_event_ids[0]
  1270. )
  1271. self.assertEqual(after_aggregations["count"], 1)
  1272. self.assertTrue(after_aggregations["current_user_participated"])
  1273. # The latest thread event has some fields that don't matter.
  1274. self.assertEqual(
  1275. after_aggregations["latest_event"]["event_id"], allowed_event_ids[0]
  1276. )
  1277. class RelationRedactionTestCase(BaseRelationsTestCase):
  1278. """
  1279. Test the behaviour of relations when the parent or child event is redacted.
  1280. The behaviour of each relation type is subtly different which causes the tests
  1281. to be a bit repetitive, they follow a naming scheme of:
  1282. test_redact_(relation|parent)_{relation_type}
  1283. The first bit of "relation" means that the event with the relation defined
  1284. on it (the child event) is to be redacted. A "parent" means that the target
  1285. of the relation (the parent event) is to be redacted.
  1286. The relation_type describes which type of relation is under test (i.e. it is
  1287. related to the value of rel_type in the event content).
  1288. """
  1289. def _redact(self, event_id: str) -> None:
  1290. channel = self.make_request(
  1291. "POST",
  1292. f"/_matrix/client/r0/rooms/{self.room}/redact/{event_id}",
  1293. access_token=self.user_token,
  1294. content={},
  1295. )
  1296. self.assertEqual(200, channel.code, channel.json_body)
  1297. def test_redact_relation_annotation(self) -> None:
  1298. """
  1299. Test that annotations of an event are properly handled after the
  1300. annotation is redacted.
  1301. The redacted relation should not be included in bundled aggregations or
  1302. the response to relations.
  1303. """
  1304. channel = self._send_relation(RelationTypes.ANNOTATION, "m.reaction", "a")
  1305. to_redact_event_id = channel.json_body["event_id"]
  1306. channel = self._send_relation(
  1307. RelationTypes.ANNOTATION, "m.reaction", "a", access_token=self.user2_token
  1308. )
  1309. unredacted_event_id = channel.json_body["event_id"]
  1310. # Both relations should exist.
  1311. event_ids = self._get_related_events()
  1312. relations = self._get_bundled_aggregations()
  1313. self.assertCountEqual(event_ids, [to_redact_event_id, unredacted_event_id])
  1314. self.assertEquals(
  1315. relations["m.annotation"],
  1316. {"chunk": [{"type": "m.reaction", "key": "a", "count": 2}]},
  1317. )
  1318. # Redact one of the reactions.
  1319. self._redact(to_redact_event_id)
  1320. # The unredacted relation should still exist.
  1321. event_ids = self._get_related_events()
  1322. relations = self._get_bundled_aggregations()
  1323. self.assertEquals(event_ids, [unredacted_event_id])
  1324. self.assertEquals(
  1325. relations["m.annotation"],
  1326. {"chunk": [{"type": "m.reaction", "key": "a", "count": 1}]},
  1327. )
  1328. def test_redact_relation_thread(self) -> None:
  1329. """
  1330. Test that thread replies are properly handled after the thread reply redacted.
  1331. The redacted event should not be included in bundled aggregations or
  1332. the response to relations.
  1333. """
  1334. channel = self._send_relation(
  1335. RelationTypes.THREAD,
  1336. EventTypes.Message,
  1337. content={"body": "reply 1", "msgtype": "m.text"},
  1338. )
  1339. unredacted_event_id = channel.json_body["event_id"]
  1340. # Note that the *last* event in the thread is redacted, as that gets
  1341. # included in the bundled aggregation.
  1342. channel = self._send_relation(
  1343. RelationTypes.THREAD,
  1344. EventTypes.Message,
  1345. content={"body": "reply 2", "msgtype": "m.text"},
  1346. )
  1347. to_redact_event_id = channel.json_body["event_id"]
  1348. # Both relations exist.
  1349. event_ids = self._get_related_events()
  1350. relations = self._get_bundled_aggregations()
  1351. self.assertEquals(event_ids, [to_redact_event_id, unredacted_event_id])
  1352. self.assertDictContainsSubset(
  1353. {
  1354. "count": 2,
  1355. "current_user_participated": True,
  1356. },
  1357. relations[RelationTypes.THREAD],
  1358. )
  1359. # And the latest event returned is the event that will be redacted.
  1360. self.assertEqual(
  1361. relations[RelationTypes.THREAD]["latest_event"]["event_id"],
  1362. to_redact_event_id,
  1363. )
  1364. # Redact one of the reactions.
  1365. self._redact(to_redact_event_id)
  1366. # The unredacted relation should still exist.
  1367. event_ids = self._get_related_events()
  1368. relations = self._get_bundled_aggregations()
  1369. self.assertEquals(event_ids, [unredacted_event_id])
  1370. self.assertDictContainsSubset(
  1371. {
  1372. "count": 1,
  1373. "current_user_participated": True,
  1374. },
  1375. relations[RelationTypes.THREAD],
  1376. )
  1377. # And the latest event is now the unredacted event.
  1378. self.assertEqual(
  1379. relations[RelationTypes.THREAD]["latest_event"]["event_id"],
  1380. unredacted_event_id,
  1381. )
  1382. def test_redact_parent_edit(self) -> None:
  1383. """Test that edits of an event are redacted when the original event
  1384. is redacted.
  1385. """
  1386. # Add a relation
  1387. self._send_relation(
  1388. RelationTypes.REPLACE,
  1389. "m.room.message",
  1390. parent_id=self.parent_id,
  1391. content={
  1392. "msgtype": "m.text",
  1393. "body": "Wibble",
  1394. "m.new_content": {"msgtype": "m.text", "body": "First edit"},
  1395. },
  1396. )
  1397. # Check the relation is returned
  1398. event_ids = self._get_related_events()
  1399. relations = self._get_bundled_aggregations()
  1400. self.assertEqual(len(event_ids), 1)
  1401. self.assertIn(RelationTypes.REPLACE, relations)
  1402. # Redact the original event
  1403. self._redact(self.parent_id)
  1404. # The relations are not returned.
  1405. event_ids = self._get_related_events()
  1406. relations = self._get_bundled_aggregations()
  1407. self.assertEqual(len(event_ids), 0)
  1408. self.assertEqual(relations, {})
  1409. def test_redact_parent_annotation(self) -> None:
  1410. """Test that annotations of an event are viewable when the original event
  1411. is redacted.
  1412. """
  1413. # Add a relation
  1414. channel = self._send_relation(RelationTypes.ANNOTATION, "m.reaction", key="👍")
  1415. related_event_id = channel.json_body["event_id"]
  1416. # The relations should exist.
  1417. event_ids = self._get_related_events()
  1418. relations = self._get_bundled_aggregations()
  1419. self.assertEqual(len(event_ids), 1)
  1420. self.assertIn(RelationTypes.ANNOTATION, relations)
  1421. # Redact the original event.
  1422. self._redact(self.parent_id)
  1423. # The relations are returned.
  1424. event_ids = self._get_related_events()
  1425. relations = self._get_bundled_aggregations()
  1426. self.assertEquals(event_ids, [related_event_id])
  1427. self.assertEquals(
  1428. relations["m.annotation"],
  1429. {"chunk": [{"type": "m.reaction", "key": "👍", "count": 1}]},
  1430. )
  1431. @unittest.override_config({"experimental_features": {"msc3440_enabled": True}})
  1432. def test_redact_parent_thread(self) -> None:
  1433. """
  1434. Test that thread replies are still available when the root event is redacted.
  1435. """
  1436. channel = self._send_relation(
  1437. RelationTypes.THREAD,
  1438. EventTypes.Message,
  1439. content={"body": "reply 1", "msgtype": "m.text"},
  1440. )
  1441. related_event_id = channel.json_body["event_id"]
  1442. # Redact one of the reactions.
  1443. self._redact(self.parent_id)
  1444. # The unredacted relation should still exist.
  1445. event_ids = self._get_related_events()
  1446. relations = self._get_bundled_aggregations()
  1447. self.assertEquals(len(event_ids), 1)
  1448. self.assertDictContainsSubset(
  1449. {
  1450. "count": 1,
  1451. "current_user_participated": True,
  1452. },
  1453. relations[RelationTypes.THREAD],
  1454. )
  1455. self.assertEqual(
  1456. relations[RelationTypes.THREAD]["latest_event"]["event_id"],
  1457. related_event_id,
  1458. )