test_relations.py 70 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828
  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 _assert_edit_bundle(
  316. self, event_json: JsonDict, edit_event_id: str, edit_event_content: JsonDict
  317. ) -> None:
  318. """
  319. Assert that the given event has a correctly-serialised edit event in its
  320. bundled aggregations
  321. Args:
  322. event_json: the serialised event to be checked
  323. edit_event_id: the ID of the edit event that we expect to be bundled
  324. edit_event_content: the content of that event, excluding the 'm.relates_to`
  325. property
  326. """
  327. relations_dict = event_json["unsigned"].get("m.relations")
  328. self.assertIn(RelationTypes.REPLACE, relations_dict)
  329. m_replace_dict = relations_dict[RelationTypes.REPLACE]
  330. for key in [
  331. "event_id",
  332. "sender",
  333. "origin_server_ts",
  334. "content",
  335. "type",
  336. "unsigned",
  337. ]:
  338. self.assertIn(key, m_replace_dict)
  339. expected_edit_content = {
  340. "m.relates_to": {
  341. "event_id": event_json["event_id"],
  342. "rel_type": "m.replace",
  343. }
  344. }
  345. expected_edit_content.update(edit_event_content)
  346. self.assert_dict(
  347. {
  348. "event_id": edit_event_id,
  349. "sender": self.user_id,
  350. "content": expected_edit_content,
  351. "type": "m.room.message",
  352. },
  353. m_replace_dict,
  354. )
  355. def test_edit(self) -> None:
  356. """Test that a simple edit works."""
  357. orig_body = {"body": "Hi!", "msgtype": "m.text"}
  358. new_body = {"msgtype": "m.text", "body": "I've been edited!"}
  359. edit_event_content = {
  360. "msgtype": "m.text",
  361. "body": "foo",
  362. "m.new_content": new_body,
  363. }
  364. channel = self._send_relation(
  365. RelationTypes.REPLACE,
  366. "m.room.message",
  367. content=edit_event_content,
  368. )
  369. edit_event_id = channel.json_body["event_id"]
  370. # /event should return the *original* event
  371. channel = self.make_request(
  372. "GET",
  373. f"/rooms/{self.room}/event/{self.parent_id}",
  374. access_token=self.user_token,
  375. )
  376. self.assertEqual(200, channel.code, channel.json_body)
  377. self.assertEqual(channel.json_body["content"], orig_body)
  378. self._assert_edit_bundle(channel.json_body, edit_event_id, edit_event_content)
  379. # Request the room messages.
  380. channel = self.make_request(
  381. "GET",
  382. f"/rooms/{self.room}/messages?dir=b",
  383. access_token=self.user_token,
  384. )
  385. self.assertEqual(200, channel.code, channel.json_body)
  386. self._assert_edit_bundle(
  387. self._find_event_in_chunk(channel.json_body["chunk"]),
  388. edit_event_id,
  389. edit_event_content,
  390. )
  391. # Request the room context.
  392. # /context should return the event.
  393. channel = self.make_request(
  394. "GET",
  395. f"/rooms/{self.room}/context/{self.parent_id}",
  396. access_token=self.user_token,
  397. )
  398. self.assertEqual(200, channel.code, channel.json_body)
  399. self._assert_edit_bundle(
  400. channel.json_body["event"], edit_event_id, edit_event_content
  401. )
  402. self.assertEqual(channel.json_body["event"]["content"], orig_body)
  403. # Request sync, but limit the timeline so it becomes limited (and includes
  404. # bundled aggregations).
  405. filter = urllib.parse.quote_plus(b'{"room": {"timeline": {"limit": 2}}}')
  406. channel = self.make_request(
  407. "GET", f"/sync?filter={filter}", access_token=self.user_token
  408. )
  409. self.assertEqual(200, channel.code, channel.json_body)
  410. room_timeline = channel.json_body["rooms"]["join"][self.room]["timeline"]
  411. self.assertTrue(room_timeline["limited"])
  412. self._assert_edit_bundle(
  413. self._find_event_in_chunk(room_timeline["events"]),
  414. edit_event_id,
  415. edit_event_content,
  416. )
  417. # Request search.
  418. channel = self.make_request(
  419. "POST",
  420. "/search",
  421. # Search term matches the parent message.
  422. content={"search_categories": {"room_events": {"search_term": "Hi"}}},
  423. access_token=self.user_token,
  424. )
  425. self.assertEqual(200, channel.code, channel.json_body)
  426. chunk = [
  427. result["result"]
  428. for result in channel.json_body["search_categories"]["room_events"][
  429. "results"
  430. ]
  431. ]
  432. self._assert_edit_bundle(
  433. self._find_event_in_chunk(chunk),
  434. edit_event_id,
  435. edit_event_content,
  436. )
  437. def test_multi_edit(self) -> None:
  438. """Test that multiple edits, including attempts by people who
  439. shouldn't be allowed, are correctly handled.
  440. """
  441. orig_body = orig_body = {"body": "Hi!", "msgtype": "m.text"}
  442. self._send_relation(
  443. RelationTypes.REPLACE,
  444. "m.room.message",
  445. content={
  446. "msgtype": "m.text",
  447. "body": "Wibble",
  448. "m.new_content": {"msgtype": "m.text", "body": "First edit"},
  449. },
  450. )
  451. new_body = {"msgtype": "m.text", "body": "I've been edited!"}
  452. edit_event_content = {
  453. "msgtype": "m.text",
  454. "body": "foo",
  455. "m.new_content": new_body,
  456. }
  457. channel = self._send_relation(
  458. RelationTypes.REPLACE,
  459. "m.room.message",
  460. content=edit_event_content,
  461. )
  462. edit_event_id = channel.json_body["event_id"]
  463. self._send_relation(
  464. RelationTypes.REPLACE,
  465. "m.room.message.WRONG_TYPE",
  466. content={
  467. "msgtype": "m.text",
  468. "body": "Wibble",
  469. "m.new_content": {"msgtype": "m.text", "body": "Edit, but wrong type"},
  470. },
  471. )
  472. channel = self.make_request(
  473. "GET",
  474. f"/rooms/{self.room}/context/{self.parent_id}",
  475. access_token=self.user_token,
  476. )
  477. self.assertEqual(200, channel.code, channel.json_body)
  478. self.assertEqual(channel.json_body["event"]["content"], orig_body)
  479. self._assert_edit_bundle(
  480. channel.json_body["event"], edit_event_id, edit_event_content
  481. )
  482. def test_edit_reply(self) -> None:
  483. """Test that editing a reply works."""
  484. # Create a reply to edit.
  485. original_body = {"msgtype": "m.text", "body": "A reply!"}
  486. channel = self._send_relation(
  487. RelationTypes.REFERENCE, "m.room.message", content=original_body
  488. )
  489. reply = channel.json_body["event_id"]
  490. edit_event_content = {
  491. "msgtype": "m.text",
  492. "body": "foo",
  493. "m.new_content": {"msgtype": "m.text", "body": "I've been edited!"},
  494. }
  495. channel = self._send_relation(
  496. RelationTypes.REPLACE,
  497. "m.room.message",
  498. content=edit_event_content,
  499. parent_id=reply,
  500. )
  501. edit_event_id = channel.json_body["event_id"]
  502. # /event returns the original event
  503. channel = self.make_request(
  504. "GET",
  505. f"/rooms/{self.room}/event/{reply}",
  506. access_token=self.user_token,
  507. )
  508. self.assertEqual(200, channel.code, channel.json_body)
  509. event_result = channel.json_body
  510. self.assertDictContainsSubset(original_body, event_result["content"])
  511. # also check /context, which returns the *edited* event
  512. channel = self.make_request(
  513. "GET",
  514. f"/rooms/{self.room}/context/{reply}",
  515. access_token=self.user_token,
  516. )
  517. self.assertEqual(200, channel.code, channel.json_body)
  518. context_result = channel.json_body["event"]
  519. # check that the relations are correct for both APIs
  520. for result_event_dict, desc in (
  521. (event_result, "/event"),
  522. (context_result, "/context"),
  523. ):
  524. # The reference metadata should still be intact.
  525. self.assertDictContainsSubset(
  526. {
  527. "m.relates_to": {
  528. "event_id": self.parent_id,
  529. "rel_type": "m.reference",
  530. }
  531. },
  532. result_event_dict["content"],
  533. desc,
  534. )
  535. # We expect that the edit relation appears in the unsigned relations
  536. # section.
  537. self._assert_edit_bundle(
  538. result_event_dict, edit_event_id, edit_event_content
  539. )
  540. def test_edit_edit(self) -> None:
  541. """Test that an edit cannot be edited."""
  542. orig_body = {"body": "Hi!", "msgtype": "m.text"}
  543. new_body = {"msgtype": "m.text", "body": "Initial edit"}
  544. edit_event_content = {
  545. "msgtype": "m.text",
  546. "body": "Wibble",
  547. "m.new_content": new_body,
  548. }
  549. channel = self._send_relation(
  550. RelationTypes.REPLACE,
  551. "m.room.message",
  552. content=edit_event_content,
  553. )
  554. edit_event_id = channel.json_body["event_id"]
  555. # Edit the edit event.
  556. self._send_relation(
  557. RelationTypes.REPLACE,
  558. "m.room.message",
  559. content={
  560. "msgtype": "m.text",
  561. "body": "foo",
  562. "m.new_content": {"msgtype": "m.text", "body": "Ignored edit"},
  563. },
  564. parent_id=edit_event_id,
  565. )
  566. # Request the original event.
  567. # /event should return the original event.
  568. channel = self.make_request(
  569. "GET",
  570. f"/rooms/{self.room}/event/{self.parent_id}",
  571. access_token=self.user_token,
  572. )
  573. self.assertEqual(200, channel.code, channel.json_body)
  574. self.assertEqual(channel.json_body["content"], orig_body)
  575. # The relations information should not include the edit to the edit.
  576. self._assert_edit_bundle(channel.json_body, edit_event_id, edit_event_content)
  577. # /context should return the bundled edit for the *first* edit
  578. # (The edit to the edit should be ignored.)
  579. channel = self.make_request(
  580. "GET",
  581. f"/rooms/{self.room}/context/{self.parent_id}",
  582. access_token=self.user_token,
  583. )
  584. self.assertEqual(200, channel.code, channel.json_body)
  585. self.assertEqual(channel.json_body["event"]["content"], orig_body)
  586. self._assert_edit_bundle(
  587. channel.json_body["event"], edit_event_id, edit_event_content
  588. )
  589. # Directly requesting the edit should not have the edit to the edit applied.
  590. channel = self.make_request(
  591. "GET",
  592. f"/rooms/{self.room}/event/{edit_event_id}",
  593. access_token=self.user_token,
  594. )
  595. self.assertEqual(200, channel.code, channel.json_body)
  596. self.assertEqual("Wibble", channel.json_body["content"]["body"])
  597. self.assertIn("m.new_content", channel.json_body["content"])
  598. # The relations information should not include the edit to the edit.
  599. self.assertNotIn("m.relations", channel.json_body["unsigned"])
  600. def test_unknown_relations(self) -> None:
  601. """Unknown relations should be accepted."""
  602. channel = self._send_relation("m.relation.test", "m.room.test")
  603. event_id = channel.json_body["event_id"]
  604. channel = self.make_request(
  605. "GET",
  606. f"/_matrix/client/v1/rooms/{self.room}/relations/{self.parent_id}?limit=1",
  607. access_token=self.user_token,
  608. )
  609. self.assertEqual(200, channel.code, channel.json_body)
  610. # We expect to get back a single pagination result, which is the full
  611. # relation event we sent above.
  612. self.assertEqual(len(channel.json_body["chunk"]), 1, channel.json_body)
  613. self.assert_dict(
  614. {"event_id": event_id, "sender": self.user_id, "type": "m.room.test"},
  615. channel.json_body["chunk"][0],
  616. )
  617. # We also expect to get the original event (the id of which is self.parent_id)
  618. # when requesting the unstable endpoint.
  619. self.assertNotIn("original_event", channel.json_body)
  620. channel = self.make_request(
  621. "GET",
  622. f"/_matrix/client/unstable/rooms/{self.room}/relations/{self.parent_id}?limit=1",
  623. access_token=self.user_token,
  624. )
  625. self.assertEqual(200, channel.code, channel.json_body)
  626. self.assertEqual(
  627. channel.json_body["original_event"]["event_id"], self.parent_id
  628. )
  629. # When bundling the unknown relation is not included.
  630. channel = self.make_request(
  631. "GET",
  632. f"/rooms/{self.room}/event/{self.parent_id}",
  633. access_token=self.user_token,
  634. )
  635. self.assertEqual(200, channel.code, channel.json_body)
  636. self.assertNotIn("m.relations", channel.json_body["unsigned"])
  637. def test_background_update(self) -> None:
  638. """Test the event_arbitrary_relations background update."""
  639. channel = self._send_relation(RelationTypes.ANNOTATION, "m.reaction", key="👍")
  640. annotation_event_id_good = channel.json_body["event_id"]
  641. channel = self._send_relation(RelationTypes.ANNOTATION, "m.reaction", key="A")
  642. annotation_event_id_bad = channel.json_body["event_id"]
  643. channel = self._send_relation(RelationTypes.THREAD, "m.room.test")
  644. thread_event_id = channel.json_body["event_id"]
  645. # Clean-up the table as if the inserts did not happen during event creation.
  646. self.get_success(
  647. self.store.db_pool.simple_delete_many(
  648. table="event_relations",
  649. column="event_id",
  650. iterable=(annotation_event_id_bad, thread_event_id),
  651. keyvalues={},
  652. desc="RelationsTestCase.test_background_update",
  653. )
  654. )
  655. # Only the "good" annotation should be found.
  656. channel = self.make_request(
  657. "GET",
  658. f"/_matrix/client/v1/rooms/{self.room}/relations/{self.parent_id}?limit=10",
  659. access_token=self.user_token,
  660. )
  661. self.assertEqual(200, channel.code, channel.json_body)
  662. self.assertEqual(
  663. [ev["event_id"] for ev in channel.json_body["chunk"]],
  664. [annotation_event_id_good],
  665. )
  666. # Insert and run the background update.
  667. self.get_success(
  668. self.store.db_pool.simple_insert(
  669. "background_updates",
  670. {"update_name": "event_arbitrary_relations", "progress_json": "{}"},
  671. )
  672. )
  673. # Ugh, have to reset this flag
  674. self.store.db_pool.updates._all_done = False
  675. self.wait_for_background_updates()
  676. # The "good" annotation and the thread should be found, but not the "bad"
  677. # annotation.
  678. channel = self.make_request(
  679. "GET",
  680. f"/_matrix/client/v1/rooms/{self.room}/relations/{self.parent_id}?limit=10",
  681. access_token=self.user_token,
  682. )
  683. self.assertEqual(200, channel.code, channel.json_body)
  684. self.assertCountEqual(
  685. [ev["event_id"] for ev in channel.json_body["chunk"]],
  686. [annotation_event_id_good, thread_event_id],
  687. )
  688. class RelationPaginationTestCase(BaseRelationsTestCase):
  689. def test_basic_paginate_relations(self) -> None:
  690. """Tests that calling pagination API correctly the latest relations."""
  691. channel = self._send_relation(RelationTypes.ANNOTATION, "m.reaction", "a")
  692. first_annotation_id = channel.json_body["event_id"]
  693. channel = self._send_relation(RelationTypes.ANNOTATION, "m.reaction", "b")
  694. second_annotation_id = channel.json_body["event_id"]
  695. channel = self.make_request(
  696. "GET",
  697. f"/_matrix/client/v1/rooms/{self.room}/relations/{self.parent_id}?limit=1",
  698. access_token=self.user_token,
  699. )
  700. self.assertEqual(200, channel.code, channel.json_body)
  701. # We expect to get back a single pagination result, which is the latest
  702. # full relation event we sent above.
  703. self.assertEqual(len(channel.json_body["chunk"]), 1, channel.json_body)
  704. self.assert_dict(
  705. {
  706. "event_id": second_annotation_id,
  707. "sender": self.user_id,
  708. "type": "m.reaction",
  709. },
  710. channel.json_body["chunk"][0],
  711. )
  712. # Make sure next_batch has something in it that looks like it could be a
  713. # valid token.
  714. self.assertIsInstance(
  715. channel.json_body.get("next_batch"), str, channel.json_body
  716. )
  717. # Request the relations again, but with a different direction.
  718. channel = self.make_request(
  719. "GET",
  720. f"/_matrix/client/v1/rooms/{self.room}/relations"
  721. f"/{self.parent_id}?limit=1&dir=f",
  722. access_token=self.user_token,
  723. )
  724. self.assertEqual(200, channel.code, channel.json_body)
  725. # We expect to get back a single pagination result, which is the earliest
  726. # full relation event we sent above.
  727. self.assertEqual(len(channel.json_body["chunk"]), 1, channel.json_body)
  728. self.assert_dict(
  729. {
  730. "event_id": first_annotation_id,
  731. "sender": self.user_id,
  732. "type": "m.reaction",
  733. },
  734. channel.json_body["chunk"][0],
  735. )
  736. def test_repeated_paginate_relations(self) -> None:
  737. """Test that if we paginate using a limit and tokens then we get the
  738. expected events.
  739. """
  740. expected_event_ids = []
  741. for idx in range(10):
  742. channel = self._send_relation(
  743. RelationTypes.ANNOTATION, "m.reaction", chr(ord("a") + idx)
  744. )
  745. expected_event_ids.append(channel.json_body["event_id"])
  746. prev_token: Optional[str] = ""
  747. found_event_ids: List[str] = []
  748. for _ in range(20):
  749. from_token = ""
  750. if prev_token:
  751. from_token = "&from=" + prev_token
  752. channel = self.make_request(
  753. "GET",
  754. f"/_matrix/client/v1/rooms/{self.room}/relations/{self.parent_id}?limit=3{from_token}",
  755. access_token=self.user_token,
  756. )
  757. self.assertEqual(200, channel.code, channel.json_body)
  758. found_event_ids.extend(e["event_id"] for e in channel.json_body["chunk"])
  759. next_batch = channel.json_body.get("next_batch")
  760. self.assertNotEqual(prev_token, next_batch)
  761. prev_token = next_batch
  762. if not prev_token:
  763. break
  764. # We paginated backwards, so reverse
  765. found_event_ids.reverse()
  766. self.assertEqual(found_event_ids, expected_event_ids)
  767. # Test forward pagination.
  768. prev_token = ""
  769. found_event_ids = []
  770. for _ in range(20):
  771. from_token = ""
  772. if prev_token:
  773. from_token = "&from=" + prev_token
  774. channel = self.make_request(
  775. "GET",
  776. f"/_matrix/client/v1/rooms/{self.room}/relations/{self.parent_id}?dir=f&limit=3{from_token}",
  777. access_token=self.user_token,
  778. )
  779. self.assertEqual(200, channel.code, channel.json_body)
  780. found_event_ids.extend(e["event_id"] for e in channel.json_body["chunk"])
  781. next_batch = channel.json_body.get("next_batch")
  782. self.assertNotEqual(prev_token, next_batch)
  783. prev_token = next_batch
  784. if not prev_token:
  785. break
  786. self.assertEqual(found_event_ids, expected_event_ids)
  787. def test_pagination_from_sync_and_messages(self) -> None:
  788. """Pagination tokens from /sync and /messages can be used to paginate /relations."""
  789. channel = self._send_relation(RelationTypes.ANNOTATION, "m.reaction", "A")
  790. annotation_id = channel.json_body["event_id"]
  791. # Send an event after the relation events.
  792. self.helper.send(self.room, body="Latest event", tok=self.user_token)
  793. # Request /sync, limiting it such that only the latest event is returned
  794. # (and not the relation).
  795. filter = urllib.parse.quote_plus(b'{"room": {"timeline": {"limit": 1}}}')
  796. channel = self.make_request(
  797. "GET", f"/sync?filter={filter}", access_token=self.user_token
  798. )
  799. self.assertEqual(200, channel.code, channel.json_body)
  800. room_timeline = channel.json_body["rooms"]["join"][self.room]["timeline"]
  801. sync_prev_batch = room_timeline["prev_batch"]
  802. self.assertIsNotNone(sync_prev_batch)
  803. # Ensure the relation event is not in the batch returned from /sync.
  804. self.assertNotIn(
  805. annotation_id, [ev["event_id"] for ev in room_timeline["events"]]
  806. )
  807. # Request /messages, limiting it such that only the latest event is
  808. # returned (and not the relation).
  809. channel = self.make_request(
  810. "GET",
  811. f"/rooms/{self.room}/messages?dir=b&limit=1",
  812. access_token=self.user_token,
  813. )
  814. self.assertEqual(200, channel.code, channel.json_body)
  815. messages_end = channel.json_body["end"]
  816. self.assertIsNotNone(messages_end)
  817. # Ensure the relation event is not in the chunk returned from /messages.
  818. self.assertNotIn(
  819. annotation_id, [ev["event_id"] for ev in channel.json_body["chunk"]]
  820. )
  821. # Request /relations with the pagination tokens received from both the
  822. # /sync and /messages responses above, in turn.
  823. #
  824. # This is a tiny bit silly since the client wouldn't know the parent ID
  825. # from the requests above; consider the parent ID to be known from a
  826. # previous /sync.
  827. for from_token in (sync_prev_batch, messages_end):
  828. channel = self.make_request(
  829. "GET",
  830. f"/_matrix/client/v1/rooms/{self.room}/relations/{self.parent_id}?from={from_token}",
  831. access_token=self.user_token,
  832. )
  833. self.assertEqual(200, channel.code, channel.json_body)
  834. # The relation should be in the returned chunk.
  835. self.assertIn(
  836. annotation_id, [ev["event_id"] for ev in channel.json_body["chunk"]]
  837. )
  838. class BundledAggregationsTestCase(BaseRelationsTestCase):
  839. """
  840. See RelationsTestCase.test_edit for a similar test for edits.
  841. Note that this doesn't test against /relations since only thread relations
  842. get bundled via that API. See test_aggregation_get_event_for_thread.
  843. """
  844. def _test_bundled_aggregations(
  845. self,
  846. relation_type: str,
  847. assertion_callable: Callable[[JsonDict], None],
  848. expected_db_txn_for_event: int,
  849. access_token: Optional[str] = None,
  850. ) -> None:
  851. """
  852. Makes requests to various endpoints which should include bundled aggregations
  853. and then calls an assertion function on the bundled aggregations.
  854. Args:
  855. relation_type: The field to search for in the `m.relations` field in unsigned.
  856. assertion_callable: Called with the contents of unsigned["m.relations"][relation_type]
  857. for relation-specific assertions.
  858. expected_db_txn_for_event: The number of database transactions which
  859. are expected for a call to /event/.
  860. access_token: The access token to user, defaults to self.user_token.
  861. """
  862. access_token = access_token or self.user_token
  863. def assert_bundle(event_json: JsonDict) -> None:
  864. """Assert the expected values of the bundled aggregations."""
  865. relations_dict = event_json["unsigned"].get("m.relations")
  866. # Ensure the fields are as expected.
  867. self.assertCountEqual(relations_dict.keys(), (relation_type,))
  868. assertion_callable(relations_dict[relation_type])
  869. # Request the event directly.
  870. channel = self.make_request(
  871. "GET",
  872. f"/rooms/{self.room}/event/{self.parent_id}",
  873. access_token=access_token,
  874. )
  875. self.assertEqual(200, channel.code, channel.json_body)
  876. assert_bundle(channel.json_body)
  877. assert channel.resource_usage is not None
  878. self.assertEqual(channel.resource_usage.db_txn_count, expected_db_txn_for_event)
  879. # Request the room messages.
  880. channel = self.make_request(
  881. "GET",
  882. f"/rooms/{self.room}/messages?dir=b",
  883. access_token=access_token,
  884. )
  885. self.assertEqual(200, channel.code, channel.json_body)
  886. assert_bundle(self._find_event_in_chunk(channel.json_body["chunk"]))
  887. # Request the room context.
  888. channel = self.make_request(
  889. "GET",
  890. f"/rooms/{self.room}/context/{self.parent_id}",
  891. access_token=access_token,
  892. )
  893. self.assertEqual(200, channel.code, channel.json_body)
  894. assert_bundle(channel.json_body["event"])
  895. # Request sync.
  896. filter = urllib.parse.quote_plus(b'{"room": {"timeline": {"limit": 4}}}')
  897. channel = self.make_request(
  898. "GET", f"/sync?filter={filter}", access_token=access_token
  899. )
  900. self.assertEqual(200, channel.code, channel.json_body)
  901. room_timeline = channel.json_body["rooms"]["join"][self.room]["timeline"]
  902. self.assertTrue(room_timeline["limited"])
  903. assert_bundle(self._find_event_in_chunk(room_timeline["events"]))
  904. # Request search.
  905. channel = self.make_request(
  906. "POST",
  907. "/search",
  908. # Search term matches the parent message.
  909. content={"search_categories": {"room_events": {"search_term": "Hi"}}},
  910. access_token=access_token,
  911. )
  912. self.assertEqual(200, channel.code, channel.json_body)
  913. chunk = [
  914. result["result"]
  915. for result in channel.json_body["search_categories"]["room_events"][
  916. "results"
  917. ]
  918. ]
  919. assert_bundle(self._find_event_in_chunk(chunk))
  920. def test_reference(self) -> None:
  921. """
  922. Test that references get correctly bundled.
  923. """
  924. channel = self._send_relation(RelationTypes.REFERENCE, "m.room.test")
  925. reply_1 = channel.json_body["event_id"]
  926. channel = self._send_relation(RelationTypes.REFERENCE, "m.room.test")
  927. reply_2 = channel.json_body["event_id"]
  928. def assert_annotations(bundled_aggregations: JsonDict) -> None:
  929. self.assertEqual(
  930. {"chunk": [{"event_id": reply_1}, {"event_id": reply_2}]},
  931. bundled_aggregations,
  932. )
  933. self._test_bundled_aggregations(RelationTypes.REFERENCE, assert_annotations, 6)
  934. def test_thread(self) -> None:
  935. """
  936. Test that threads get correctly bundled.
  937. """
  938. # The root message is from "user", send replies as "user2".
  939. self._send_relation(
  940. RelationTypes.THREAD, "m.room.test", access_token=self.user2_token
  941. )
  942. channel = self._send_relation(
  943. RelationTypes.THREAD, "m.room.test", access_token=self.user2_token
  944. )
  945. thread_2 = channel.json_body["event_id"]
  946. # This needs two assertion functions which are identical except for whether
  947. # the current_user_participated flag is True, create a factory for the
  948. # two versions.
  949. def _gen_assert(participated: bool) -> Callable[[JsonDict], None]:
  950. def assert_thread(bundled_aggregations: JsonDict) -> None:
  951. self.assertEqual(2, bundled_aggregations.get("count"))
  952. self.assertEqual(
  953. participated, bundled_aggregations.get("current_user_participated")
  954. )
  955. # The latest thread event has some fields that don't matter.
  956. self.assertIn("latest_event", bundled_aggregations)
  957. self.assert_dict(
  958. {
  959. "content": {
  960. "m.relates_to": {
  961. "event_id": self.parent_id,
  962. "rel_type": RelationTypes.THREAD,
  963. }
  964. },
  965. "event_id": thread_2,
  966. "sender": self.user2_id,
  967. "type": "m.room.test",
  968. },
  969. bundled_aggregations["latest_event"],
  970. )
  971. return assert_thread
  972. # The "user" sent the root event and is making queries for the bundled
  973. # aggregations: they have participated.
  974. self._test_bundled_aggregations(RelationTypes.THREAD, _gen_assert(True), 6)
  975. # The "user2" sent replies in the thread and is making queries for the
  976. # bundled aggregations: they have participated.
  977. #
  978. # Note that this re-uses some cached values, so the total number of
  979. # queries is much smaller.
  980. self._test_bundled_aggregations(
  981. RelationTypes.THREAD, _gen_assert(True), 3, access_token=self.user2_token
  982. )
  983. # A user with no interactions with the thread: they have not participated.
  984. user3_id, user3_token = self._create_user("charlie")
  985. self.helper.join(self.room, user=user3_id, tok=user3_token)
  986. self._test_bundled_aggregations(
  987. RelationTypes.THREAD, _gen_assert(False), 3, access_token=user3_token
  988. )
  989. def test_thread_with_bundled_aggregations_for_latest(self) -> None:
  990. """
  991. Bundled aggregations should get applied to the latest thread event.
  992. """
  993. self._send_relation(RelationTypes.THREAD, "m.room.test")
  994. channel = self._send_relation(RelationTypes.THREAD, "m.room.test")
  995. thread_2 = channel.json_body["event_id"]
  996. channel = self._send_relation(
  997. RelationTypes.REFERENCE, "org.matrix.test", parent_id=thread_2
  998. )
  999. reference_event_id = channel.json_body["event_id"]
  1000. def assert_thread(bundled_aggregations: JsonDict) -> None:
  1001. self.assertEqual(2, bundled_aggregations.get("count"))
  1002. self.assertTrue(bundled_aggregations.get("current_user_participated"))
  1003. # The latest thread event has some fields that don't matter.
  1004. self.assertIn("latest_event", bundled_aggregations)
  1005. self.assert_dict(
  1006. {
  1007. "content": {
  1008. "m.relates_to": {
  1009. "event_id": self.parent_id,
  1010. "rel_type": RelationTypes.THREAD,
  1011. }
  1012. },
  1013. "event_id": thread_2,
  1014. "sender": self.user_id,
  1015. "type": "m.room.test",
  1016. },
  1017. bundled_aggregations["latest_event"],
  1018. )
  1019. # Check the unsigned field on the latest event.
  1020. self.assert_dict(
  1021. {
  1022. "m.relations": {
  1023. RelationTypes.REFERENCE: {
  1024. "chunk": [{"event_id": reference_event_id}]
  1025. },
  1026. }
  1027. },
  1028. bundled_aggregations["latest_event"].get("unsigned"),
  1029. )
  1030. self._test_bundled_aggregations(RelationTypes.THREAD, assert_thread, 6)
  1031. def test_nested_thread(self) -> None:
  1032. """
  1033. Ensure that a nested thread gets ignored by bundled aggregations, as
  1034. those are forbidden.
  1035. """
  1036. # Start a thread.
  1037. channel = self._send_relation(RelationTypes.THREAD, "m.room.test")
  1038. reply_event_id = channel.json_body["event_id"]
  1039. # Disable the validation to pretend this came over federation, since it is
  1040. # not an event the Client-Server API will allow..
  1041. with patch(
  1042. "synapse.handlers.message.EventCreationHandler._validate_event_relation",
  1043. new=lambda self, event: make_awaitable(None),
  1044. ):
  1045. # Create a sub-thread off the thread, which is not allowed.
  1046. self._send_relation(
  1047. RelationTypes.THREAD, "m.room.test", parent_id=reply_event_id
  1048. )
  1049. # Fetch the thread root, to get the bundled aggregation for the thread.
  1050. relations_from_event = self._get_bundled_aggregations()
  1051. # Ensure that requesting the room messages also does not return the sub-thread.
  1052. channel = self.make_request(
  1053. "GET",
  1054. f"/rooms/{self.room}/messages?dir=b",
  1055. access_token=self.user_token,
  1056. )
  1057. self.assertEqual(200, channel.code, channel.json_body)
  1058. event = self._find_event_in_chunk(channel.json_body["chunk"])
  1059. relations_from_messages = event["unsigned"]["m.relations"]
  1060. # Check the bundled aggregations from each point.
  1061. for aggregations, desc in (
  1062. (relations_from_event, "/event"),
  1063. (relations_from_messages, "/messages"),
  1064. ):
  1065. # The latest event should have bundled aggregations.
  1066. self.assertIn(RelationTypes.THREAD, aggregations, desc)
  1067. thread_summary = aggregations[RelationTypes.THREAD]
  1068. self.assertIn("latest_event", thread_summary, desc)
  1069. self.assertEqual(
  1070. thread_summary["latest_event"]["event_id"], reply_event_id, desc
  1071. )
  1072. # The latest event should not have any bundled aggregations (since the
  1073. # only relation to it is another thread, which is invalid).
  1074. self.assertNotIn(
  1075. "m.relations", thread_summary["latest_event"]["unsigned"], desc
  1076. )
  1077. def test_thread_edit_latest_event(self) -> None:
  1078. """Test that editing the latest event in a thread works."""
  1079. # Create a thread and edit the last event.
  1080. channel = self._send_relation(
  1081. RelationTypes.THREAD,
  1082. "m.room.message",
  1083. content={"msgtype": "m.text", "body": "A threaded reply!"},
  1084. )
  1085. threaded_event_id = channel.json_body["event_id"]
  1086. new_body = {"msgtype": "m.text", "body": "I've been edited!"}
  1087. channel = self._send_relation(
  1088. RelationTypes.REPLACE,
  1089. "m.room.message",
  1090. content={"msgtype": "m.text", "body": "foo", "m.new_content": new_body},
  1091. parent_id=threaded_event_id,
  1092. )
  1093. edit_event_id = channel.json_body["event_id"]
  1094. # Fetch the thread root, to get the bundled aggregation for the thread.
  1095. relations_dict = self._get_bundled_aggregations()
  1096. # We expect that the edit message appears in the thread summary in the
  1097. # unsigned relations section.
  1098. self.assertIn(RelationTypes.THREAD, relations_dict)
  1099. thread_summary = relations_dict[RelationTypes.THREAD]
  1100. self.assertIn("latest_event", thread_summary)
  1101. latest_event_in_thread = thread_summary["latest_event"]
  1102. # The latest event in the thread should have the edit appear under the
  1103. # bundled aggregations.
  1104. self.assertDictContainsSubset(
  1105. {"event_id": edit_event_id, "sender": "@alice:test"},
  1106. latest_event_in_thread["unsigned"]["m.relations"][RelationTypes.REPLACE],
  1107. )
  1108. def test_aggregation_get_event_for_annotation(self) -> None:
  1109. """Test that annotations do not get bundled aggregations included
  1110. when directly requested.
  1111. """
  1112. channel = self._send_relation(RelationTypes.ANNOTATION, "m.reaction", "a")
  1113. annotation_id = channel.json_body["event_id"]
  1114. # Annotate the annotation.
  1115. self._send_relation(
  1116. RelationTypes.ANNOTATION, "m.reaction", "a", parent_id=annotation_id
  1117. )
  1118. channel = self.make_request(
  1119. "GET",
  1120. f"/rooms/{self.room}/event/{annotation_id}",
  1121. access_token=self.user_token,
  1122. )
  1123. self.assertEqual(200, channel.code, channel.json_body)
  1124. self.assertIsNone(channel.json_body["unsigned"].get("m.relations"))
  1125. def test_aggregation_get_event_for_thread(self) -> None:
  1126. """Test that threads get bundled aggregations included when directly requested."""
  1127. channel = self._send_relation(RelationTypes.THREAD, "m.room.test")
  1128. thread_id = channel.json_body["event_id"]
  1129. # Make a reference to the thread.
  1130. channel = self._send_relation(
  1131. RelationTypes.REFERENCE, "org.matrix.test", parent_id=thread_id
  1132. )
  1133. reference_event_id = channel.json_body["event_id"]
  1134. channel = self.make_request(
  1135. "GET",
  1136. f"/rooms/{self.room}/event/{thread_id}",
  1137. access_token=self.user_token,
  1138. )
  1139. self.assertEqual(200, channel.code, channel.json_body)
  1140. self.assertEqual(
  1141. channel.json_body["unsigned"].get("m.relations"),
  1142. {
  1143. RelationTypes.REFERENCE: {"chunk": [{"event_id": reference_event_id}]},
  1144. },
  1145. )
  1146. # It should also be included when the entire thread is requested.
  1147. channel = self.make_request(
  1148. "GET",
  1149. f"/_matrix/client/v1/rooms/{self.room}/relations/{self.parent_id}?limit=1",
  1150. access_token=self.user_token,
  1151. )
  1152. self.assertEqual(200, channel.code, channel.json_body)
  1153. self.assertEqual(len(channel.json_body["chunk"]), 1)
  1154. thread_message = channel.json_body["chunk"][0]
  1155. self.assertEqual(
  1156. thread_message["unsigned"].get("m.relations"),
  1157. {
  1158. RelationTypes.REFERENCE: {"chunk": [{"event_id": reference_event_id}]},
  1159. },
  1160. )
  1161. def test_bundled_aggregations_with_filter(self) -> None:
  1162. """
  1163. If "unsigned" is an omitted field (due to filtering), adding the bundled
  1164. aggregations should not break.
  1165. Note that the spec allows for a server to return additional fields beyond
  1166. what is specified.
  1167. """
  1168. channel = self._send_relation(RelationTypes.REFERENCE, "org.matrix.test")
  1169. reference_event_id = channel.json_body["event_id"]
  1170. # Note that the sync filter does not include "unsigned" as a field.
  1171. filter = urllib.parse.quote_plus(
  1172. b'{"event_fields": ["content", "event_id"], "room": {"timeline": {"limit": 3}}}'
  1173. )
  1174. channel = self.make_request(
  1175. "GET", f"/sync?filter={filter}", access_token=self.user_token
  1176. )
  1177. self.assertEqual(200, channel.code, channel.json_body)
  1178. # Ensure the timeline is limited, find the parent event.
  1179. room_timeline = channel.json_body["rooms"]["join"][self.room]["timeline"]
  1180. self.assertTrue(room_timeline["limited"])
  1181. parent_event = self._find_event_in_chunk(room_timeline["events"])
  1182. # Ensure there's bundled aggregations on it.
  1183. self.assertIn("unsigned", parent_event)
  1184. self.assertEqual(
  1185. parent_event["unsigned"].get("m.relations"),
  1186. {
  1187. RelationTypes.REFERENCE: {"chunk": [{"event_id": reference_event_id}]},
  1188. },
  1189. )
  1190. class RelationIgnoredUserTestCase(BaseRelationsTestCase):
  1191. """Relations sent from an ignored user should be ignored."""
  1192. def _test_ignored_user(
  1193. self,
  1194. relation_type: str,
  1195. allowed_event_ids: List[str],
  1196. ignored_event_ids: List[str],
  1197. ) -> Tuple[JsonDict, JsonDict]:
  1198. """
  1199. Fetch the relations and ensure they're all there, then ignore user2, and
  1200. repeat.
  1201. Returns:
  1202. A tuple of two JSON dictionaries, each are bundled aggregations, the
  1203. first is from before the user is ignored, and the second is after.
  1204. """
  1205. # Get the relations.
  1206. event_ids = self._get_related_events()
  1207. self.assertCountEqual(event_ids, allowed_event_ids + ignored_event_ids)
  1208. # And the bundled aggregations.
  1209. before_aggregations = self._get_bundled_aggregations()
  1210. self.assertIn(relation_type, before_aggregations)
  1211. # Ignore user2 and re-do the requests.
  1212. self.get_success(
  1213. self.store.add_account_data_for_user(
  1214. self.user_id,
  1215. AccountDataTypes.IGNORED_USER_LIST,
  1216. {"ignored_users": {self.user2_id: {}}},
  1217. )
  1218. )
  1219. # Get the relations.
  1220. event_ids = self._get_related_events()
  1221. self.assertCountEqual(event_ids, allowed_event_ids)
  1222. # And the bundled aggregations.
  1223. after_aggregations = self._get_bundled_aggregations()
  1224. self.assertIn(relation_type, after_aggregations)
  1225. return before_aggregations[relation_type], after_aggregations[relation_type]
  1226. def test_reference(self) -> None:
  1227. """Aggregations should exclude reference relations from ignored users"""
  1228. channel = self._send_relation(RelationTypes.REFERENCE, "m.room.test")
  1229. allowed_event_ids = [channel.json_body["event_id"]]
  1230. channel = self._send_relation(
  1231. RelationTypes.REFERENCE, "m.room.test", access_token=self.user2_token
  1232. )
  1233. ignored_event_ids = [channel.json_body["event_id"]]
  1234. before_aggregations, after_aggregations = self._test_ignored_user(
  1235. RelationTypes.REFERENCE, allowed_event_ids, ignored_event_ids
  1236. )
  1237. self.assertCountEqual(
  1238. [e["event_id"] for e in before_aggregations["chunk"]],
  1239. allowed_event_ids + ignored_event_ids,
  1240. )
  1241. self.assertCountEqual(
  1242. [e["event_id"] for e in after_aggregations["chunk"]], allowed_event_ids
  1243. )
  1244. def test_thread(self) -> None:
  1245. """Aggregations should exclude thread releations from ignored users"""
  1246. channel = self._send_relation(RelationTypes.THREAD, "m.room.test")
  1247. allowed_event_ids = [channel.json_body["event_id"]]
  1248. channel = self._send_relation(
  1249. RelationTypes.THREAD, "m.room.test", access_token=self.user2_token
  1250. )
  1251. ignored_event_ids = [channel.json_body["event_id"]]
  1252. before_aggregations, after_aggregations = self._test_ignored_user(
  1253. RelationTypes.THREAD, allowed_event_ids, ignored_event_ids
  1254. )
  1255. self.assertEqual(before_aggregations["count"], 2)
  1256. self.assertTrue(before_aggregations["current_user_participated"])
  1257. # The latest thread event has some fields that don't matter.
  1258. self.assertEqual(
  1259. before_aggregations["latest_event"]["event_id"], ignored_event_ids[0]
  1260. )
  1261. self.assertEqual(after_aggregations["count"], 1)
  1262. self.assertTrue(after_aggregations["current_user_participated"])
  1263. # The latest thread event has some fields that don't matter.
  1264. self.assertEqual(
  1265. after_aggregations["latest_event"]["event_id"], allowed_event_ids[0]
  1266. )
  1267. class RelationRedactionTestCase(BaseRelationsTestCase):
  1268. """
  1269. Test the behaviour of relations when the parent or child event is redacted.
  1270. The behaviour of each relation type is subtly different which causes the tests
  1271. to be a bit repetitive, they follow a naming scheme of:
  1272. test_redact_(relation|parent)_{relation_type}
  1273. The first bit of "relation" means that the event with the relation defined
  1274. on it (the child event) is to be redacted. A "parent" means that the target
  1275. of the relation (the parent event) is to be redacted.
  1276. The relation_type describes which type of relation is under test (i.e. it is
  1277. related to the value of rel_type in the event content).
  1278. """
  1279. def _redact(self, event_id: str) -> None:
  1280. channel = self.make_request(
  1281. "POST",
  1282. f"/_matrix/client/r0/rooms/{self.room}/redact/{event_id}",
  1283. access_token=self.user_token,
  1284. content={},
  1285. )
  1286. self.assertEqual(200, channel.code, channel.json_body)
  1287. def _get_threads(self) -> List[Tuple[str, str]]:
  1288. """Request the threads in the room and returns a list of thread ID and latest event ID."""
  1289. # Request the threads in the room.
  1290. channel = self.make_request(
  1291. "GET",
  1292. f"/_matrix/client/v1/rooms/{self.room}/threads",
  1293. access_token=self.user_token,
  1294. )
  1295. self.assertEquals(200, channel.code, channel.json_body)
  1296. threads = channel.json_body["chunk"]
  1297. return [
  1298. (
  1299. t["event_id"],
  1300. t["unsigned"]["m.relations"][RelationTypes.THREAD]["latest_event"][
  1301. "event_id"
  1302. ],
  1303. )
  1304. for t in threads
  1305. ]
  1306. def test_redact_relation_thread(self) -> None:
  1307. """
  1308. Test that thread replies are properly handled after the thread reply redacted.
  1309. The redacted event should not be included in bundled aggregations or
  1310. the response to relations.
  1311. """
  1312. # Create a thread with a few events in it.
  1313. thread_replies = []
  1314. for i in range(3):
  1315. channel = self._send_relation(
  1316. RelationTypes.THREAD,
  1317. EventTypes.Message,
  1318. content={"body": f"reply {i}", "msgtype": "m.text"},
  1319. )
  1320. thread_replies.append(channel.json_body["event_id"])
  1321. ##################################################
  1322. # Check the test data is configured as expected. #
  1323. ##################################################
  1324. self.assertEquals(self._get_related_events(), list(reversed(thread_replies)))
  1325. relations = self._get_bundled_aggregations()
  1326. self.assertDictContainsSubset(
  1327. {"count": 3, "current_user_participated": True},
  1328. relations[RelationTypes.THREAD],
  1329. )
  1330. # The latest event is the last sent event.
  1331. self.assertEqual(
  1332. relations[RelationTypes.THREAD]["latest_event"]["event_id"],
  1333. thread_replies[-1],
  1334. )
  1335. # There should be one thread, the latest event is the event that will be redacted.
  1336. self.assertEqual(self._get_threads(), [(self.parent_id, thread_replies[-1])])
  1337. ##########################
  1338. # Redact the last event. #
  1339. ##########################
  1340. self._redact(thread_replies.pop())
  1341. # The thread should still exist, but the latest event should be updated.
  1342. self.assertEquals(self._get_related_events(), list(reversed(thread_replies)))
  1343. relations = self._get_bundled_aggregations()
  1344. self.assertDictContainsSubset(
  1345. {"count": 2, "current_user_participated": True},
  1346. relations[RelationTypes.THREAD],
  1347. )
  1348. # And the latest event is the last unredacted event.
  1349. self.assertEqual(
  1350. relations[RelationTypes.THREAD]["latest_event"]["event_id"],
  1351. thread_replies[-1],
  1352. )
  1353. self.assertEqual(self._get_threads(), [(self.parent_id, thread_replies[-1])])
  1354. ###########################################
  1355. # Redact the *first* event in the thread. #
  1356. ###########################################
  1357. self._redact(thread_replies.pop(0))
  1358. # Nothing should have changed (except the thread count).
  1359. self.assertEquals(self._get_related_events(), thread_replies)
  1360. relations = self._get_bundled_aggregations()
  1361. self.assertDictContainsSubset(
  1362. {"count": 1, "current_user_participated": True},
  1363. relations[RelationTypes.THREAD],
  1364. )
  1365. # And the latest event is the last unredacted event.
  1366. self.assertEqual(
  1367. relations[RelationTypes.THREAD]["latest_event"]["event_id"],
  1368. thread_replies[-1],
  1369. )
  1370. self.assertEqual(self._get_threads(), [(self.parent_id, thread_replies[-1])])
  1371. ####################################
  1372. # Redact the last remaining event. #
  1373. ####################################
  1374. self._redact(thread_replies.pop(0))
  1375. self.assertEquals(thread_replies, [])
  1376. # The event should no longer be considered a thread.
  1377. self.assertEquals(self._get_related_events(), [])
  1378. self.assertEquals(self._get_bundled_aggregations(), {})
  1379. self.assertEqual(self._get_threads(), [])
  1380. def test_redact_parent_edit(self) -> None:
  1381. """Test that edits of an event are redacted when the original event
  1382. is redacted.
  1383. """
  1384. # Add a relation
  1385. self._send_relation(
  1386. RelationTypes.REPLACE,
  1387. "m.room.message",
  1388. parent_id=self.parent_id,
  1389. content={
  1390. "msgtype": "m.text",
  1391. "body": "Wibble",
  1392. "m.new_content": {"msgtype": "m.text", "body": "First edit"},
  1393. },
  1394. )
  1395. # Check the relation is returned
  1396. event_ids = self._get_related_events()
  1397. relations = self._get_bundled_aggregations()
  1398. self.assertEqual(len(event_ids), 1)
  1399. self.assertIn(RelationTypes.REPLACE, relations)
  1400. # Redact the original event
  1401. self._redact(self.parent_id)
  1402. # The relations are not returned.
  1403. event_ids = self._get_related_events()
  1404. relations = self._get_bundled_aggregations()
  1405. self.assertEqual(len(event_ids), 0)
  1406. self.assertEqual(relations, {})
  1407. def test_redact_parent_annotation(self) -> None:
  1408. """Test that annotations of an event are viewable when the original event
  1409. is redacted.
  1410. """
  1411. # Add a relation
  1412. channel = self._send_relation(RelationTypes.REFERENCE, "org.matrix.test")
  1413. related_event_id = channel.json_body["event_id"]
  1414. # The relations should exist.
  1415. event_ids = self._get_related_events()
  1416. relations = self._get_bundled_aggregations()
  1417. self.assertEqual(len(event_ids), 1)
  1418. self.assertIn(RelationTypes.REFERENCE, relations)
  1419. # Redact the original event.
  1420. self._redact(self.parent_id)
  1421. # The relations are returned.
  1422. event_ids = self._get_related_events()
  1423. relations = self._get_bundled_aggregations()
  1424. self.assertEquals(event_ids, [related_event_id])
  1425. self.assertEquals(
  1426. relations[RelationTypes.REFERENCE],
  1427. {"chunk": [{"event_id": related_event_id}]},
  1428. )
  1429. def test_redact_parent_thread(self) -> None:
  1430. """
  1431. Test that thread replies are still available when the root event is redacted.
  1432. """
  1433. channel = self._send_relation(
  1434. RelationTypes.THREAD,
  1435. EventTypes.Message,
  1436. content={"body": "reply 1", "msgtype": "m.text"},
  1437. )
  1438. related_event_id = channel.json_body["event_id"]
  1439. # Redact one of the reactions.
  1440. self._redact(self.parent_id)
  1441. # The unredacted relation should still exist.
  1442. event_ids = self._get_related_events()
  1443. relations = self._get_bundled_aggregations()
  1444. self.assertEquals(len(event_ids), 1)
  1445. self.assertDictContainsSubset(
  1446. {
  1447. "count": 1,
  1448. "current_user_participated": True,
  1449. },
  1450. relations[RelationTypes.THREAD],
  1451. )
  1452. self.assertEqual(
  1453. relations[RelationTypes.THREAD]["latest_event"]["event_id"],
  1454. related_event_id,
  1455. )
  1456. class ThreadsTestCase(BaseRelationsTestCase):
  1457. def _get_threads(self, body: JsonDict) -> List[Tuple[str, str]]:
  1458. return [
  1459. (
  1460. ev["event_id"],
  1461. ev["unsigned"]["m.relations"]["m.thread"]["latest_event"]["event_id"],
  1462. )
  1463. for ev in body["chunk"]
  1464. ]
  1465. def test_threads(self) -> None:
  1466. """Create threads and ensure the ordering is due to their latest event."""
  1467. # Create 2 threads.
  1468. thread_1 = self.parent_id
  1469. res = self.helper.send(self.room, body="Thread Root!", tok=self.user_token)
  1470. thread_2 = res["event_id"]
  1471. channel = self._send_relation(RelationTypes.THREAD, "m.room.test")
  1472. reply_1 = channel.json_body["event_id"]
  1473. channel = self._send_relation(
  1474. RelationTypes.THREAD, "m.room.test", parent_id=thread_2
  1475. )
  1476. reply_2 = channel.json_body["event_id"]
  1477. # Request the threads in the room.
  1478. channel = self.make_request(
  1479. "GET",
  1480. f"/_matrix/client/v1/rooms/{self.room}/threads",
  1481. access_token=self.user_token,
  1482. )
  1483. self.assertEquals(200, channel.code, channel.json_body)
  1484. threads = self._get_threads(channel.json_body)
  1485. self.assertEqual(threads, [(thread_2, reply_2), (thread_1, reply_1)])
  1486. # Update the first thread, the ordering should swap.
  1487. channel = self._send_relation(RelationTypes.THREAD, "m.room.test")
  1488. reply_3 = channel.json_body["event_id"]
  1489. channel = self.make_request(
  1490. "GET",
  1491. f"/_matrix/client/v1/rooms/{self.room}/threads",
  1492. access_token=self.user_token,
  1493. )
  1494. self.assertEquals(200, channel.code, channel.json_body)
  1495. # Tuple of (thread ID, latest event ID) for each thread.
  1496. threads = self._get_threads(channel.json_body)
  1497. self.assertEqual(threads, [(thread_1, reply_3), (thread_2, reply_2)])
  1498. def test_pagination(self) -> None:
  1499. """Create threads and paginate through them."""
  1500. # Create 2 threads.
  1501. thread_1 = self.parent_id
  1502. res = self.helper.send(self.room, body="Thread Root!", tok=self.user_token)
  1503. thread_2 = res["event_id"]
  1504. self._send_relation(RelationTypes.THREAD, "m.room.test")
  1505. self._send_relation(RelationTypes.THREAD, "m.room.test", parent_id=thread_2)
  1506. # Request the threads in the room.
  1507. channel = self.make_request(
  1508. "GET",
  1509. f"/_matrix/client/v1/rooms/{self.room}/threads?limit=1",
  1510. access_token=self.user_token,
  1511. )
  1512. self.assertEquals(200, channel.code, channel.json_body)
  1513. thread_roots = [ev["event_id"] for ev in channel.json_body["chunk"]]
  1514. self.assertEqual(thread_roots, [thread_2])
  1515. # Make sure next_batch has something in it that looks like it could be a
  1516. # valid token.
  1517. next_batch = channel.json_body.get("next_batch")
  1518. self.assertIsInstance(next_batch, str, channel.json_body)
  1519. channel = self.make_request(
  1520. "GET",
  1521. f"/_matrix/client/v1/rooms/{self.room}/threads?limit=1&from={next_batch}",
  1522. access_token=self.user_token,
  1523. )
  1524. self.assertEquals(200, channel.code, channel.json_body)
  1525. thread_roots = [ev["event_id"] for ev in channel.json_body["chunk"]]
  1526. self.assertEqual(thread_roots, [thread_1], channel.json_body)
  1527. self.assertNotIn("next_batch", channel.json_body, channel.json_body)
  1528. def test_include(self) -> None:
  1529. """Filtering threads to all or participated in should work."""
  1530. # Thread 1 has the user as the root event.
  1531. thread_1 = self.parent_id
  1532. self._send_relation(
  1533. RelationTypes.THREAD, "m.room.test", access_token=self.user2_token
  1534. )
  1535. # Thread 2 has the user replying.
  1536. res = self.helper.send(self.room, body="Thread Root!", tok=self.user2_token)
  1537. thread_2 = res["event_id"]
  1538. self._send_relation(RelationTypes.THREAD, "m.room.test", parent_id=thread_2)
  1539. # Thread 3 has the user not participating in.
  1540. res = self.helper.send(self.room, body="Another thread!", tok=self.user2_token)
  1541. thread_3 = res["event_id"]
  1542. self._send_relation(
  1543. RelationTypes.THREAD,
  1544. "m.room.test",
  1545. access_token=self.user2_token,
  1546. parent_id=thread_3,
  1547. )
  1548. # All threads in the room.
  1549. channel = self.make_request(
  1550. "GET",
  1551. f"/_matrix/client/v1/rooms/{self.room}/threads",
  1552. access_token=self.user_token,
  1553. )
  1554. self.assertEquals(200, channel.code, channel.json_body)
  1555. thread_roots = [ev["event_id"] for ev in channel.json_body["chunk"]]
  1556. self.assertEqual(
  1557. thread_roots, [thread_3, thread_2, thread_1], channel.json_body
  1558. )
  1559. # Only participated threads.
  1560. channel = self.make_request(
  1561. "GET",
  1562. f"/_matrix/client/v1/rooms/{self.room}/threads?include=participated",
  1563. access_token=self.user_token,
  1564. )
  1565. self.assertEquals(200, channel.code, channel.json_body)
  1566. thread_roots = [ev["event_id"] for ev in channel.json_body["chunk"]]
  1567. self.assertEqual(thread_roots, [thread_2, thread_1], channel.json_body)
  1568. def test_ignored_user(self) -> None:
  1569. """Events from ignored users should be ignored."""
  1570. # Thread 1 has a reply from an ignored user.
  1571. thread_1 = self.parent_id
  1572. self._send_relation(
  1573. RelationTypes.THREAD, "m.room.test", access_token=self.user2_token
  1574. )
  1575. # Thread 2 is created by an ignored user.
  1576. res = self.helper.send(self.room, body="Thread Root!", tok=self.user2_token)
  1577. thread_2 = res["event_id"]
  1578. self._send_relation(RelationTypes.THREAD, "m.room.test", parent_id=thread_2)
  1579. # Ignore user2.
  1580. self.get_success(
  1581. self.store.add_account_data_for_user(
  1582. self.user_id,
  1583. AccountDataTypes.IGNORED_USER_LIST,
  1584. {"ignored_users": {self.user2_id: {}}},
  1585. )
  1586. )
  1587. # Only thread 1 is returned.
  1588. channel = self.make_request(
  1589. "GET",
  1590. f"/_matrix/client/v1/rooms/{self.room}/threads",
  1591. access_token=self.user_token,
  1592. )
  1593. self.assertEquals(200, channel.code, channel.json_body)
  1594. thread_roots = [ev["event_id"] for ev in channel.json_body["chunk"]]
  1595. self.assertEqual(thread_roots, [thread_1], channel.json_body)