test_relations.py 62 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645
  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. def test_basic_paginate_relations(self) -> None:
  638. """Tests that calling pagination API correctly the latest relations."""
  639. channel = self._send_relation(RelationTypes.ANNOTATION, "m.reaction", "a")
  640. first_annotation_id = channel.json_body["event_id"]
  641. channel = self._send_relation(RelationTypes.ANNOTATION, "m.reaction", "b")
  642. second_annotation_id = channel.json_body["event_id"]
  643. channel = self.make_request(
  644. "GET",
  645. f"/_matrix/client/v1/rooms/{self.room}/relations/{self.parent_id}?limit=1",
  646. access_token=self.user_token,
  647. )
  648. self.assertEqual(200, channel.code, channel.json_body)
  649. # We expect to get back a single pagination result, which is the latest
  650. # full relation event we sent above.
  651. self.assertEqual(len(channel.json_body["chunk"]), 1, channel.json_body)
  652. self.assert_dict(
  653. {
  654. "event_id": second_annotation_id,
  655. "sender": self.user_id,
  656. "type": "m.reaction",
  657. },
  658. channel.json_body["chunk"][0],
  659. )
  660. # We also expect to get the original event (the id of which is self.parent_id)
  661. self.assertEqual(
  662. channel.json_body["original_event"]["event_id"], self.parent_id
  663. )
  664. # Make sure next_batch has something in it that looks like it could be a
  665. # valid token.
  666. self.assertIsInstance(
  667. channel.json_body.get("next_batch"), str, channel.json_body
  668. )
  669. # Request the relations again, but with a different direction.
  670. channel = self.make_request(
  671. "GET",
  672. f"/_matrix/client/v1/rooms/{self.room}/relations"
  673. f"/{self.parent_id}?limit=1&org.matrix.msc3715.dir=f",
  674. access_token=self.user_token,
  675. )
  676. self.assertEqual(200, channel.code, channel.json_body)
  677. # We expect to get back a single pagination result, which is the earliest
  678. # full relation event we sent above.
  679. self.assertEqual(len(channel.json_body["chunk"]), 1, channel.json_body)
  680. self.assert_dict(
  681. {
  682. "event_id": first_annotation_id,
  683. "sender": self.user_id,
  684. "type": "m.reaction",
  685. },
  686. channel.json_body["chunk"][0],
  687. )
  688. def test_repeated_paginate_relations(self) -> None:
  689. """Test that if we paginate using a limit and tokens then we get the
  690. expected events.
  691. """
  692. expected_event_ids = []
  693. for idx in range(10):
  694. channel = self._send_relation(
  695. RelationTypes.ANNOTATION, "m.reaction", chr(ord("a") + idx)
  696. )
  697. expected_event_ids.append(channel.json_body["event_id"])
  698. prev_token = ""
  699. found_event_ids: List[str] = []
  700. for _ in range(20):
  701. from_token = ""
  702. if prev_token:
  703. from_token = "&from=" + prev_token
  704. channel = self.make_request(
  705. "GET",
  706. f"/_matrix/client/v1/rooms/{self.room}/relations/{self.parent_id}?limit=1{from_token}",
  707. access_token=self.user_token,
  708. )
  709. self.assertEqual(200, channel.code, channel.json_body)
  710. found_event_ids.extend(e["event_id"] for e in channel.json_body["chunk"])
  711. next_batch = channel.json_body.get("next_batch")
  712. self.assertNotEqual(prev_token, next_batch)
  713. prev_token = next_batch
  714. if not prev_token:
  715. break
  716. # We paginated backwards, so reverse
  717. found_event_ids.reverse()
  718. self.assertEqual(found_event_ids, expected_event_ids)
  719. def test_pagination_from_sync_and_messages(self) -> None:
  720. """Pagination tokens from /sync and /messages can be used to paginate /relations."""
  721. channel = self._send_relation(RelationTypes.ANNOTATION, "m.reaction", "A")
  722. annotation_id = channel.json_body["event_id"]
  723. # Send an event after the relation events.
  724. self.helper.send(self.room, body="Latest event", tok=self.user_token)
  725. # Request /sync, limiting it such that only the latest event is returned
  726. # (and not the relation).
  727. filter = urllib.parse.quote_plus(b'{"room": {"timeline": {"limit": 1}}}')
  728. channel = self.make_request(
  729. "GET", f"/sync?filter={filter}", access_token=self.user_token
  730. )
  731. self.assertEqual(200, channel.code, channel.json_body)
  732. room_timeline = channel.json_body["rooms"]["join"][self.room]["timeline"]
  733. sync_prev_batch = room_timeline["prev_batch"]
  734. self.assertIsNotNone(sync_prev_batch)
  735. # Ensure the relation event is not in the batch returned from /sync.
  736. self.assertNotIn(
  737. annotation_id, [ev["event_id"] for ev in room_timeline["events"]]
  738. )
  739. # Request /messages, limiting it such that only the latest event is
  740. # returned (and not the relation).
  741. channel = self.make_request(
  742. "GET",
  743. f"/rooms/{self.room}/messages?dir=b&limit=1",
  744. access_token=self.user_token,
  745. )
  746. self.assertEqual(200, channel.code, channel.json_body)
  747. messages_end = channel.json_body["end"]
  748. self.assertIsNotNone(messages_end)
  749. # Ensure the relation event is not in the chunk returned from /messages.
  750. self.assertNotIn(
  751. annotation_id, [ev["event_id"] for ev in channel.json_body["chunk"]]
  752. )
  753. # Request /relations with the pagination tokens received from both the
  754. # /sync and /messages responses above, in turn.
  755. #
  756. # This is a tiny bit silly since the client wouldn't know the parent ID
  757. # from the requests above; consider the parent ID to be known from a
  758. # previous /sync.
  759. for from_token in (sync_prev_batch, messages_end):
  760. channel = self.make_request(
  761. "GET",
  762. f"/_matrix/client/v1/rooms/{self.room}/relations/{self.parent_id}?from={from_token}",
  763. access_token=self.user_token,
  764. )
  765. self.assertEqual(200, channel.code, channel.json_body)
  766. # The relation should be in the returned chunk.
  767. self.assertIn(
  768. annotation_id, [ev["event_id"] for ev in channel.json_body["chunk"]]
  769. )
  770. class BundledAggregationsTestCase(BaseRelationsTestCase):
  771. """
  772. See RelationsTestCase.test_edit for a similar test for edits.
  773. Note that this doesn't test against /relations since only thread relations
  774. get bundled via that API. See test_aggregation_get_event_for_thread.
  775. """
  776. def _test_bundled_aggregations(
  777. self,
  778. relation_type: str,
  779. assertion_callable: Callable[[JsonDict], None],
  780. expected_db_txn_for_event: int,
  781. ) -> None:
  782. """
  783. Makes requests to various endpoints which should include bundled aggregations
  784. and then calls an assertion function on the bundled aggregations.
  785. Args:
  786. relation_type: The field to search for in the `m.relations` field in unsigned.
  787. assertion_callable: Called with the contents of unsigned["m.relations"][relation_type]
  788. for relation-specific assertions.
  789. expected_db_txn_for_event: The number of database transactions which
  790. are expected for a call to /event/.
  791. """
  792. def assert_bundle(event_json: JsonDict) -> None:
  793. """Assert the expected values of the bundled aggregations."""
  794. relations_dict = event_json["unsigned"].get("m.relations")
  795. # Ensure the fields are as expected.
  796. self.assertCountEqual(relations_dict.keys(), (relation_type,))
  797. assertion_callable(relations_dict[relation_type])
  798. # Request the event directly.
  799. channel = self.make_request(
  800. "GET",
  801. f"/rooms/{self.room}/event/{self.parent_id}",
  802. access_token=self.user_token,
  803. )
  804. self.assertEqual(200, channel.code, channel.json_body)
  805. assert_bundle(channel.json_body)
  806. assert channel.resource_usage is not None
  807. self.assertEqual(channel.resource_usage.db_txn_count, expected_db_txn_for_event)
  808. # Request the room messages.
  809. channel = self.make_request(
  810. "GET",
  811. f"/rooms/{self.room}/messages?dir=b",
  812. access_token=self.user_token,
  813. )
  814. self.assertEqual(200, channel.code, channel.json_body)
  815. assert_bundle(self._find_event_in_chunk(channel.json_body["chunk"]))
  816. # Request the room context.
  817. channel = self.make_request(
  818. "GET",
  819. f"/rooms/{self.room}/context/{self.parent_id}",
  820. access_token=self.user_token,
  821. )
  822. self.assertEqual(200, channel.code, channel.json_body)
  823. assert_bundle(channel.json_body["event"])
  824. # Request sync.
  825. filter = urllib.parse.quote_plus(b'{"room": {"timeline": {"limit": 4}}}')
  826. channel = self.make_request(
  827. "GET", f"/sync?filter={filter}", access_token=self.user_token
  828. )
  829. self.assertEqual(200, channel.code, channel.json_body)
  830. room_timeline = channel.json_body["rooms"]["join"][self.room]["timeline"]
  831. self.assertTrue(room_timeline["limited"])
  832. assert_bundle(self._find_event_in_chunk(room_timeline["events"]))
  833. # Request search.
  834. channel = self.make_request(
  835. "POST",
  836. "/search",
  837. # Search term matches the parent message.
  838. content={"search_categories": {"room_events": {"search_term": "Hi"}}},
  839. access_token=self.user_token,
  840. )
  841. self.assertEqual(200, channel.code, channel.json_body)
  842. chunk = [
  843. result["result"]
  844. for result in channel.json_body["search_categories"]["room_events"][
  845. "results"
  846. ]
  847. ]
  848. assert_bundle(self._find_event_in_chunk(chunk))
  849. def test_annotation(self) -> None:
  850. """
  851. Test that annotations get correctly bundled.
  852. """
  853. # Setup by sending a variety of relations.
  854. self._send_relation(RelationTypes.ANNOTATION, "m.reaction", "a")
  855. self._send_relation(
  856. RelationTypes.ANNOTATION, "m.reaction", "a", access_token=self.user2_token
  857. )
  858. self._send_relation(RelationTypes.ANNOTATION, "m.reaction", "b")
  859. def assert_annotations(bundled_aggregations: JsonDict) -> None:
  860. self.assertEqual(
  861. {
  862. "chunk": [
  863. {"type": "m.reaction", "key": "a", "count": 2},
  864. {"type": "m.reaction", "key": "b", "count": 1},
  865. ]
  866. },
  867. bundled_aggregations,
  868. )
  869. self._test_bundled_aggregations(RelationTypes.ANNOTATION, assert_annotations, 6)
  870. def test_annotation_to_annotation(self) -> None:
  871. """Any relation to an annotation should be ignored."""
  872. channel = self._send_relation(RelationTypes.ANNOTATION, "m.reaction", "a")
  873. event_id = channel.json_body["event_id"]
  874. self._send_relation(
  875. RelationTypes.ANNOTATION, "m.reaction", "b", parent_id=event_id
  876. )
  877. # Fetch the initial annotation event to see if it has bundled aggregations.
  878. channel = self.make_request(
  879. "GET",
  880. f"/_matrix/client/v3/rooms/{self.room}/event/{event_id}",
  881. access_token=self.user_token,
  882. )
  883. self.assertEquals(200, channel.code, channel.json_body)
  884. # The first annotationt should not have any bundled aggregations.
  885. self.assertNotIn("m.relations", channel.json_body["unsigned"])
  886. def test_reference(self) -> None:
  887. """
  888. Test that references get correctly bundled.
  889. """
  890. channel = self._send_relation(RelationTypes.REFERENCE, "m.room.test")
  891. reply_1 = channel.json_body["event_id"]
  892. channel = self._send_relation(RelationTypes.REFERENCE, "m.room.test")
  893. reply_2 = channel.json_body["event_id"]
  894. def assert_annotations(bundled_aggregations: JsonDict) -> None:
  895. self.assertEqual(
  896. {"chunk": [{"event_id": reply_1}, {"event_id": reply_2}]},
  897. bundled_aggregations,
  898. )
  899. self._test_bundled_aggregations(RelationTypes.REFERENCE, assert_annotations, 6)
  900. def test_thread(self) -> None:
  901. """
  902. Test that threads get correctly bundled.
  903. """
  904. self._send_relation(RelationTypes.THREAD, "m.room.test")
  905. channel = self._send_relation(RelationTypes.THREAD, "m.room.test")
  906. thread_2 = channel.json_body["event_id"]
  907. def assert_thread(bundled_aggregations: JsonDict) -> None:
  908. self.assertEqual(2, bundled_aggregations.get("count"))
  909. self.assertTrue(bundled_aggregations.get("current_user_participated"))
  910. # The latest thread event has some fields that don't matter.
  911. self.assert_dict(
  912. {
  913. "content": {
  914. "m.relates_to": {
  915. "event_id": self.parent_id,
  916. "rel_type": RelationTypes.THREAD,
  917. }
  918. },
  919. "event_id": thread_2,
  920. "sender": self.user_id,
  921. "type": "m.room.test",
  922. },
  923. bundled_aggregations.get("latest_event"),
  924. )
  925. self._test_bundled_aggregations(RelationTypes.THREAD, assert_thread, 9)
  926. def test_thread_with_bundled_aggregations_for_latest(self) -> None:
  927. """
  928. Bundled aggregations should get applied to the latest thread event.
  929. """
  930. self._send_relation(RelationTypes.THREAD, "m.room.test")
  931. channel = self._send_relation(RelationTypes.THREAD, "m.room.test")
  932. thread_2 = channel.json_body["event_id"]
  933. self._send_relation(
  934. RelationTypes.ANNOTATION, "m.reaction", "a", parent_id=thread_2
  935. )
  936. def assert_thread(bundled_aggregations: JsonDict) -> None:
  937. self.assertEqual(2, bundled_aggregations.get("count"))
  938. self.assertTrue(bundled_aggregations.get("current_user_participated"))
  939. # The latest thread event has some fields that don't matter.
  940. self.assert_dict(
  941. {
  942. "content": {
  943. "m.relates_to": {
  944. "event_id": self.parent_id,
  945. "rel_type": RelationTypes.THREAD,
  946. }
  947. },
  948. "event_id": thread_2,
  949. "sender": self.user_id,
  950. "type": "m.room.test",
  951. },
  952. bundled_aggregations.get("latest_event"),
  953. )
  954. # Check the unsigned field on the latest event.
  955. self.assert_dict(
  956. {
  957. "m.relations": {
  958. RelationTypes.ANNOTATION: {
  959. "chunk": [
  960. {"type": "m.reaction", "key": "a", "count": 1},
  961. ]
  962. },
  963. }
  964. },
  965. bundled_aggregations["latest_event"].get("unsigned"),
  966. )
  967. self._test_bundled_aggregations(RelationTypes.THREAD, assert_thread, 9)
  968. def test_nested_thread(self) -> None:
  969. """
  970. Ensure that a nested thread gets ignored by bundled aggregations, as
  971. those are forbidden.
  972. """
  973. # Start a thread.
  974. channel = self._send_relation(RelationTypes.THREAD, "m.room.test")
  975. reply_event_id = channel.json_body["event_id"]
  976. # Disable the validation to pretend this came over federation, since it is
  977. # not an event the Client-Server API will allow..
  978. with patch(
  979. "synapse.handlers.message.EventCreationHandler._validate_event_relation",
  980. new=lambda self, event: make_awaitable(None),
  981. ):
  982. # Create a sub-thread off the thread, which is not allowed.
  983. self._send_relation(
  984. RelationTypes.THREAD, "m.room.test", parent_id=reply_event_id
  985. )
  986. # Fetch the thread root, to get the bundled aggregation for the thread.
  987. relations_from_event = self._get_bundled_aggregations()
  988. # Ensure that requesting the room messages also does not return the sub-thread.
  989. channel = self.make_request(
  990. "GET",
  991. f"/rooms/{self.room}/messages?dir=b",
  992. access_token=self.user_token,
  993. )
  994. self.assertEqual(200, channel.code, channel.json_body)
  995. event = self._find_event_in_chunk(channel.json_body["chunk"])
  996. relations_from_messages = event["unsigned"]["m.relations"]
  997. # Check the bundled aggregations from each point.
  998. for aggregations, desc in (
  999. (relations_from_event, "/event"),
  1000. (relations_from_messages, "/messages"),
  1001. ):
  1002. # The latest event should have bundled aggregations.
  1003. self.assertIn(RelationTypes.THREAD, aggregations, desc)
  1004. thread_summary = aggregations[RelationTypes.THREAD]
  1005. self.assertIn("latest_event", thread_summary, desc)
  1006. self.assertEqual(
  1007. thread_summary["latest_event"]["event_id"], reply_event_id, desc
  1008. )
  1009. # The latest event should not have any bundled aggregations (since the
  1010. # only relation to it is another thread, which is invalid).
  1011. self.assertNotIn(
  1012. "m.relations", thread_summary["latest_event"]["unsigned"], desc
  1013. )
  1014. def test_thread_edit_latest_event(self) -> None:
  1015. """Test that editing the latest event in a thread works."""
  1016. # Create a thread and edit the last event.
  1017. channel = self._send_relation(
  1018. RelationTypes.THREAD,
  1019. "m.room.message",
  1020. content={"msgtype": "m.text", "body": "A threaded reply!"},
  1021. )
  1022. threaded_event_id = channel.json_body["event_id"]
  1023. new_body = {"msgtype": "m.text", "body": "I've been edited!"}
  1024. channel = self._send_relation(
  1025. RelationTypes.REPLACE,
  1026. "m.room.message",
  1027. content={"msgtype": "m.text", "body": "foo", "m.new_content": new_body},
  1028. parent_id=threaded_event_id,
  1029. )
  1030. edit_event_id = channel.json_body["event_id"]
  1031. # Fetch the thread root, to get the bundled aggregation for the thread.
  1032. relations_dict = self._get_bundled_aggregations()
  1033. # We expect that the edit message appears in the thread summary in the
  1034. # unsigned relations section.
  1035. self.assertIn(RelationTypes.THREAD, relations_dict)
  1036. thread_summary = relations_dict[RelationTypes.THREAD]
  1037. self.assertIn("latest_event", thread_summary)
  1038. latest_event_in_thread = thread_summary["latest_event"]
  1039. self.assertEqual(latest_event_in_thread["content"]["body"], "I've been edited!")
  1040. # The latest event in the thread should have the edit appear under the
  1041. # bundled aggregations.
  1042. self.assertDictContainsSubset(
  1043. {"event_id": edit_event_id, "sender": "@alice:test"},
  1044. latest_event_in_thread["unsigned"]["m.relations"][RelationTypes.REPLACE],
  1045. )
  1046. def test_aggregation_get_event_for_annotation(self) -> None:
  1047. """Test that annotations do not get bundled aggregations included
  1048. when directly requested.
  1049. """
  1050. channel = self._send_relation(RelationTypes.ANNOTATION, "m.reaction", "a")
  1051. annotation_id = channel.json_body["event_id"]
  1052. # Annotate the annotation.
  1053. self._send_relation(
  1054. RelationTypes.ANNOTATION, "m.reaction", "a", parent_id=annotation_id
  1055. )
  1056. channel = self.make_request(
  1057. "GET",
  1058. f"/rooms/{self.room}/event/{annotation_id}",
  1059. access_token=self.user_token,
  1060. )
  1061. self.assertEqual(200, channel.code, channel.json_body)
  1062. self.assertIsNone(channel.json_body["unsigned"].get("m.relations"))
  1063. def test_aggregation_get_event_for_thread(self) -> None:
  1064. """Test that threads get bundled aggregations included when directly requested."""
  1065. channel = self._send_relation(RelationTypes.THREAD, "m.room.test")
  1066. thread_id = channel.json_body["event_id"]
  1067. # Annotate the thread.
  1068. self._send_relation(
  1069. RelationTypes.ANNOTATION, "m.reaction", "a", parent_id=thread_id
  1070. )
  1071. channel = self.make_request(
  1072. "GET",
  1073. f"/rooms/{self.room}/event/{thread_id}",
  1074. access_token=self.user_token,
  1075. )
  1076. self.assertEqual(200, channel.code, channel.json_body)
  1077. self.assertEqual(
  1078. channel.json_body["unsigned"].get("m.relations"),
  1079. {
  1080. RelationTypes.ANNOTATION: {
  1081. "chunk": [{"count": 1, "key": "a", "type": "m.reaction"}]
  1082. },
  1083. },
  1084. )
  1085. # It should also be included when the entire thread is requested.
  1086. channel = self.make_request(
  1087. "GET",
  1088. f"/_matrix/client/v1/rooms/{self.room}/relations/{self.parent_id}?limit=1",
  1089. access_token=self.user_token,
  1090. )
  1091. self.assertEqual(200, channel.code, channel.json_body)
  1092. self.assertEqual(len(channel.json_body["chunk"]), 1)
  1093. thread_message = channel.json_body["chunk"][0]
  1094. self.assertEqual(
  1095. thread_message["unsigned"].get("m.relations"),
  1096. {
  1097. RelationTypes.ANNOTATION: {
  1098. "chunk": [{"count": 1, "key": "a", "type": "m.reaction"}]
  1099. },
  1100. },
  1101. )
  1102. def test_bundled_aggregations_with_filter(self) -> None:
  1103. """
  1104. If "unsigned" is an omitted field (due to filtering), adding the bundled
  1105. aggregations should not break.
  1106. Note that the spec allows for a server to return additional fields beyond
  1107. what is specified.
  1108. """
  1109. self._send_relation(RelationTypes.ANNOTATION, "m.reaction", "a")
  1110. # Note that the sync filter does not include "unsigned" as a field.
  1111. filter = urllib.parse.quote_plus(
  1112. b'{"event_fields": ["content", "event_id"], "room": {"timeline": {"limit": 3}}}'
  1113. )
  1114. channel = self.make_request(
  1115. "GET", f"/sync?filter={filter}", access_token=self.user_token
  1116. )
  1117. self.assertEqual(200, channel.code, channel.json_body)
  1118. # Ensure the timeline is limited, find the parent event.
  1119. room_timeline = channel.json_body["rooms"]["join"][self.room]["timeline"]
  1120. self.assertTrue(room_timeline["limited"])
  1121. parent_event = self._find_event_in_chunk(room_timeline["events"])
  1122. # Ensure there's bundled aggregations on it.
  1123. self.assertIn("unsigned", parent_event)
  1124. self.assertIn("m.relations", parent_event["unsigned"])
  1125. class RelationIgnoredUserTestCase(BaseRelationsTestCase):
  1126. """Relations sent from an ignored user should be ignored."""
  1127. def _test_ignored_user(
  1128. self,
  1129. relation_type: str,
  1130. allowed_event_ids: List[str],
  1131. ignored_event_ids: List[str],
  1132. ) -> Tuple[JsonDict, JsonDict]:
  1133. """
  1134. Fetch the relations and ensure they're all there, then ignore user2, and
  1135. repeat.
  1136. Returns:
  1137. A tuple of two JSON dictionaries, each are bundled aggregations, the
  1138. first is from before the user is ignored, and the second is after.
  1139. """
  1140. # Get the relations.
  1141. event_ids = self._get_related_events()
  1142. self.assertCountEqual(event_ids, allowed_event_ids + ignored_event_ids)
  1143. # And the bundled aggregations.
  1144. before_aggregations = self._get_bundled_aggregations()
  1145. self.assertIn(relation_type, before_aggregations)
  1146. # Ignore user2 and re-do the requests.
  1147. self.get_success(
  1148. self.store.add_account_data_for_user(
  1149. self.user_id,
  1150. AccountDataTypes.IGNORED_USER_LIST,
  1151. {"ignored_users": {self.user2_id: {}}},
  1152. )
  1153. )
  1154. # Get the relations.
  1155. event_ids = self._get_related_events()
  1156. self.assertCountEqual(event_ids, allowed_event_ids)
  1157. # And the bundled aggregations.
  1158. after_aggregations = self._get_bundled_aggregations()
  1159. self.assertIn(relation_type, after_aggregations)
  1160. return before_aggregations[relation_type], after_aggregations[relation_type]
  1161. def test_annotation(self) -> None:
  1162. """Annotations should ignore"""
  1163. # Send 2 from us, 2 from the to be ignored user.
  1164. allowed_event_ids = []
  1165. ignored_event_ids = []
  1166. channel = self._send_relation(RelationTypes.ANNOTATION, "m.reaction", key="a")
  1167. allowed_event_ids.append(channel.json_body["event_id"])
  1168. channel = self._send_relation(RelationTypes.ANNOTATION, "m.reaction", key="b")
  1169. allowed_event_ids.append(channel.json_body["event_id"])
  1170. channel = self._send_relation(
  1171. RelationTypes.ANNOTATION,
  1172. "m.reaction",
  1173. key="a",
  1174. access_token=self.user2_token,
  1175. )
  1176. ignored_event_ids.append(channel.json_body["event_id"])
  1177. channel = self._send_relation(
  1178. RelationTypes.ANNOTATION,
  1179. "m.reaction",
  1180. key="c",
  1181. access_token=self.user2_token,
  1182. )
  1183. ignored_event_ids.append(channel.json_body["event_id"])
  1184. before_aggregations, after_aggregations = self._test_ignored_user(
  1185. RelationTypes.ANNOTATION, allowed_event_ids, ignored_event_ids
  1186. )
  1187. self.assertCountEqual(
  1188. before_aggregations["chunk"],
  1189. [
  1190. {"type": "m.reaction", "key": "a", "count": 2},
  1191. {"type": "m.reaction", "key": "b", "count": 1},
  1192. {"type": "m.reaction", "key": "c", "count": 1},
  1193. ],
  1194. )
  1195. self.assertCountEqual(
  1196. after_aggregations["chunk"],
  1197. [
  1198. {"type": "m.reaction", "key": "a", "count": 1},
  1199. {"type": "m.reaction", "key": "b", "count": 1},
  1200. ],
  1201. )
  1202. def test_reference(self) -> None:
  1203. """Annotations should ignore"""
  1204. channel = self._send_relation(RelationTypes.REFERENCE, "m.room.test")
  1205. allowed_event_ids = [channel.json_body["event_id"]]
  1206. channel = self._send_relation(
  1207. RelationTypes.REFERENCE, "m.room.test", access_token=self.user2_token
  1208. )
  1209. ignored_event_ids = [channel.json_body["event_id"]]
  1210. before_aggregations, after_aggregations = self._test_ignored_user(
  1211. RelationTypes.REFERENCE, allowed_event_ids, ignored_event_ids
  1212. )
  1213. self.assertCountEqual(
  1214. [e["event_id"] for e in before_aggregations["chunk"]],
  1215. allowed_event_ids + ignored_event_ids,
  1216. )
  1217. self.assertCountEqual(
  1218. [e["event_id"] for e in after_aggregations["chunk"]], allowed_event_ids
  1219. )
  1220. def test_thread(self) -> None:
  1221. """Annotations should ignore"""
  1222. channel = self._send_relation(RelationTypes.THREAD, "m.room.test")
  1223. allowed_event_ids = [channel.json_body["event_id"]]
  1224. channel = self._send_relation(
  1225. RelationTypes.THREAD, "m.room.test", access_token=self.user2_token
  1226. )
  1227. ignored_event_ids = [channel.json_body["event_id"]]
  1228. before_aggregations, after_aggregations = self._test_ignored_user(
  1229. RelationTypes.THREAD, allowed_event_ids, ignored_event_ids
  1230. )
  1231. self.assertEqual(before_aggregations["count"], 2)
  1232. self.assertTrue(before_aggregations["current_user_participated"])
  1233. # The latest thread event has some fields that don't matter.
  1234. self.assertEqual(
  1235. before_aggregations["latest_event"]["event_id"], ignored_event_ids[0]
  1236. )
  1237. self.assertEqual(after_aggregations["count"], 1)
  1238. self.assertTrue(after_aggregations["current_user_participated"])
  1239. # The latest thread event has some fields that don't matter.
  1240. self.assertEqual(
  1241. after_aggregations["latest_event"]["event_id"], allowed_event_ids[0]
  1242. )
  1243. class RelationRedactionTestCase(BaseRelationsTestCase):
  1244. """
  1245. Test the behaviour of relations when the parent or child event is redacted.
  1246. The behaviour of each relation type is subtly different which causes the tests
  1247. to be a bit repetitive, they follow a naming scheme of:
  1248. test_redact_(relation|parent)_{relation_type}
  1249. The first bit of "relation" means that the event with the relation defined
  1250. on it (the child event) is to be redacted. A "parent" means that the target
  1251. of the relation (the parent event) is to be redacted.
  1252. The relation_type describes which type of relation is under test (i.e. it is
  1253. related to the value of rel_type in the event content).
  1254. """
  1255. def _redact(self, event_id: str) -> None:
  1256. channel = self.make_request(
  1257. "POST",
  1258. f"/_matrix/client/r0/rooms/{self.room}/redact/{event_id}",
  1259. access_token=self.user_token,
  1260. content={},
  1261. )
  1262. self.assertEqual(200, channel.code, channel.json_body)
  1263. def test_redact_relation_annotation(self) -> None:
  1264. """
  1265. Test that annotations of an event are properly handled after the
  1266. annotation is redacted.
  1267. The redacted relation should not be included in bundled aggregations or
  1268. the response to relations.
  1269. """
  1270. channel = self._send_relation(RelationTypes.ANNOTATION, "m.reaction", "a")
  1271. to_redact_event_id = channel.json_body["event_id"]
  1272. channel = self._send_relation(
  1273. RelationTypes.ANNOTATION, "m.reaction", "a", access_token=self.user2_token
  1274. )
  1275. unredacted_event_id = channel.json_body["event_id"]
  1276. # Both relations should exist.
  1277. event_ids = self._get_related_events()
  1278. relations = self._get_bundled_aggregations()
  1279. self.assertCountEqual(event_ids, [to_redact_event_id, unredacted_event_id])
  1280. self.assertEquals(
  1281. relations["m.annotation"],
  1282. {"chunk": [{"type": "m.reaction", "key": "a", "count": 2}]},
  1283. )
  1284. # Redact one of the reactions.
  1285. self._redact(to_redact_event_id)
  1286. # The unredacted relation should still exist.
  1287. event_ids = self._get_related_events()
  1288. relations = self._get_bundled_aggregations()
  1289. self.assertEquals(event_ids, [unredacted_event_id])
  1290. self.assertEquals(
  1291. relations["m.annotation"],
  1292. {"chunk": [{"type": "m.reaction", "key": "a", "count": 1}]},
  1293. )
  1294. def test_redact_relation_thread(self) -> None:
  1295. """
  1296. Test that thread replies are properly handled after the thread reply redacted.
  1297. The redacted event should not be included in bundled aggregations or
  1298. the response to relations.
  1299. """
  1300. channel = self._send_relation(
  1301. RelationTypes.THREAD,
  1302. EventTypes.Message,
  1303. content={"body": "reply 1", "msgtype": "m.text"},
  1304. )
  1305. unredacted_event_id = channel.json_body["event_id"]
  1306. # Note that the *last* event in the thread is redacted, as that gets
  1307. # included in the bundled aggregation.
  1308. channel = self._send_relation(
  1309. RelationTypes.THREAD,
  1310. EventTypes.Message,
  1311. content={"body": "reply 2", "msgtype": "m.text"},
  1312. )
  1313. to_redact_event_id = channel.json_body["event_id"]
  1314. # Both relations exist.
  1315. event_ids = self._get_related_events()
  1316. relations = self._get_bundled_aggregations()
  1317. self.assertEquals(event_ids, [to_redact_event_id, unredacted_event_id])
  1318. self.assertDictContainsSubset(
  1319. {
  1320. "count": 2,
  1321. "current_user_participated": True,
  1322. },
  1323. relations[RelationTypes.THREAD],
  1324. )
  1325. # And the latest event returned is the event that will be redacted.
  1326. self.assertEqual(
  1327. relations[RelationTypes.THREAD]["latest_event"]["event_id"],
  1328. to_redact_event_id,
  1329. )
  1330. # Redact one of the reactions.
  1331. self._redact(to_redact_event_id)
  1332. # The unredacted relation should still exist.
  1333. event_ids = self._get_related_events()
  1334. relations = self._get_bundled_aggregations()
  1335. self.assertEquals(event_ids, [unredacted_event_id])
  1336. self.assertDictContainsSubset(
  1337. {
  1338. "count": 1,
  1339. "current_user_participated": True,
  1340. },
  1341. relations[RelationTypes.THREAD],
  1342. )
  1343. # And the latest event is now the unredacted event.
  1344. self.assertEqual(
  1345. relations[RelationTypes.THREAD]["latest_event"]["event_id"],
  1346. unredacted_event_id,
  1347. )
  1348. def test_redact_parent_edit(self) -> None:
  1349. """Test that edits of an event are redacted when the original event
  1350. is redacted.
  1351. """
  1352. # Add a relation
  1353. self._send_relation(
  1354. RelationTypes.REPLACE,
  1355. "m.room.message",
  1356. parent_id=self.parent_id,
  1357. content={
  1358. "msgtype": "m.text",
  1359. "body": "Wibble",
  1360. "m.new_content": {"msgtype": "m.text", "body": "First edit"},
  1361. },
  1362. )
  1363. # Check the relation is returned
  1364. event_ids = self._get_related_events()
  1365. relations = self._get_bundled_aggregations()
  1366. self.assertEqual(len(event_ids), 1)
  1367. self.assertIn(RelationTypes.REPLACE, relations)
  1368. # Redact the original event
  1369. self._redact(self.parent_id)
  1370. # The relations are not returned.
  1371. event_ids = self._get_related_events()
  1372. relations = self._get_bundled_aggregations()
  1373. self.assertEqual(len(event_ids), 0)
  1374. self.assertEqual(relations, {})
  1375. def test_redact_parent_annotation(self) -> None:
  1376. """Test that annotations of an event are viewable when the original event
  1377. is redacted.
  1378. """
  1379. # Add a relation
  1380. channel = self._send_relation(RelationTypes.ANNOTATION, "m.reaction", key="👍")
  1381. related_event_id = channel.json_body["event_id"]
  1382. # The relations should exist.
  1383. event_ids = self._get_related_events()
  1384. relations = self._get_bundled_aggregations()
  1385. self.assertEqual(len(event_ids), 1)
  1386. self.assertIn(RelationTypes.ANNOTATION, relations)
  1387. # Redact the original event.
  1388. self._redact(self.parent_id)
  1389. # The relations are returned.
  1390. event_ids = self._get_related_events()
  1391. relations = self._get_bundled_aggregations()
  1392. self.assertEquals(event_ids, [related_event_id])
  1393. self.assertEquals(
  1394. relations["m.annotation"],
  1395. {"chunk": [{"type": "m.reaction", "key": "👍", "count": 1}]},
  1396. )
  1397. @unittest.override_config({"experimental_features": {"msc3440_enabled": True}})
  1398. def test_redact_parent_thread(self) -> None:
  1399. """
  1400. Test that thread replies are still available when the root event is redacted.
  1401. """
  1402. channel = self._send_relation(
  1403. RelationTypes.THREAD,
  1404. EventTypes.Message,
  1405. content={"body": "reply 1", "msgtype": "m.text"},
  1406. )
  1407. related_event_id = channel.json_body["event_id"]
  1408. # Redact one of the reactions.
  1409. self._redact(self.parent_id)
  1410. # The unredacted relation should still exist.
  1411. event_ids = self._get_related_events()
  1412. relations = self._get_bundled_aggregations()
  1413. self.assertEquals(len(event_ids), 1)
  1414. self.assertDictContainsSubset(
  1415. {
  1416. "count": 1,
  1417. "current_user_participated": True,
  1418. },
  1419. relations[RelationTypes.THREAD],
  1420. )
  1421. self.assertEqual(
  1422. relations[RelationTypes.THREAD]["latest_event"]["event_id"],
  1423. related_event_id,
  1424. )