test_rooms.py 106 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902
  1. # Copyright 2014-2016 OpenMarket Ltd
  2. # Copyright 2017 Vector Creations Ltd
  3. # Copyright 2018-2019 New Vector Ltd
  4. # Copyright 2019 The Matrix.org Foundation C.I.C.
  5. #
  6. # Licensed under the Apache License, Version 2.0 (the "License");
  7. # you may not use this file except in compliance with the License.
  8. # You may obtain a copy of the License at
  9. #
  10. # http://www.apache.org/licenses/LICENSE-2.0
  11. #
  12. # Unless required by applicable law or agreed to in writing, software
  13. # distributed under the License is distributed on an "AS IS" BASIS,
  14. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  15. # See the License for the specific language governing permissions and
  16. # limitations under the License.
  17. """Tests REST events for /rooms paths."""
  18. import json
  19. from typing import Any, Dict, Iterable, List, Optional
  20. from unittest.mock import Mock, call
  21. from urllib import parse as urlparse
  22. from twisted.test.proto_helpers import MemoryReactor
  23. import synapse.rest.admin
  24. from synapse.api.constants import (
  25. EventContentFields,
  26. EventTypes,
  27. Membership,
  28. RelationTypes,
  29. )
  30. from synapse.api.errors import Codes, HttpResponseException
  31. from synapse.handlers.pagination import PurgeStatus
  32. from synapse.rest import admin
  33. from synapse.rest.client import account, directory, login, profile, room, sync
  34. from synapse.server import HomeServer
  35. from synapse.types import JsonDict, RoomAlias, UserID, create_requester
  36. from synapse.util import Clock
  37. from synapse.util.stringutils import random_string
  38. from tests import unittest
  39. from tests.test_utils import make_awaitable
  40. PATH_PREFIX = b"/_matrix/client/api/v1"
  41. class RoomBase(unittest.HomeserverTestCase):
  42. rmcreator_id: Optional[str] = None
  43. servlets = [room.register_servlets, room.register_deprecated_servlets]
  44. def make_homeserver(self, reactor: MemoryReactor, clock: Clock) -> HomeServer:
  45. self.hs = self.setup_test_homeserver(
  46. "red",
  47. federation_http_client=None,
  48. federation_client=Mock(),
  49. )
  50. self.hs.get_federation_handler = Mock() # type: ignore[assignment]
  51. self.hs.get_federation_handler.return_value.maybe_backfill = Mock(
  52. return_value=make_awaitable(None)
  53. )
  54. async def _insert_client_ip(*args: Any, **kwargs: Any) -> None:
  55. return None
  56. self.hs.get_datastores().main.insert_client_ip = _insert_client_ip # type: ignore[assignment]
  57. return self.hs
  58. class RoomPermissionsTestCase(RoomBase):
  59. """Tests room permissions."""
  60. user_id = "@sid1:red"
  61. rmcreator_id = "@notme:red"
  62. def prepare(self, reactor: MemoryReactor, clock: Clock, hs: HomeServer) -> None:
  63. self.helper.auth_user_id = self.rmcreator_id
  64. # create some rooms under the name rmcreator_id
  65. self.uncreated_rmid = "!aa:test"
  66. self.created_rmid = self.helper.create_room_as(
  67. self.rmcreator_id, is_public=False
  68. )
  69. self.created_public_rmid = self.helper.create_room_as(
  70. self.rmcreator_id, is_public=True
  71. )
  72. # send a message in one of the rooms
  73. self.created_rmid_msg_path = (
  74. "rooms/%s/send/m.room.message/a1" % (self.created_rmid)
  75. ).encode("ascii")
  76. channel = self.make_request(
  77. "PUT", self.created_rmid_msg_path, b'{"msgtype":"m.text","body":"test msg"}'
  78. )
  79. self.assertEqual(200, channel.code, channel.result)
  80. # set topic for public room
  81. channel = self.make_request(
  82. "PUT",
  83. ("rooms/%s/state/m.room.topic" % self.created_public_rmid).encode("ascii"),
  84. b'{"topic":"Public Room Topic"}',
  85. )
  86. self.assertEqual(200, channel.code, channel.result)
  87. # auth as user_id now
  88. self.helper.auth_user_id = self.user_id
  89. def test_can_do_action(self) -> None:
  90. msg_content = b'{"msgtype":"m.text","body":"hello"}'
  91. seq = iter(range(100))
  92. def send_msg_path() -> str:
  93. return "/rooms/%s/send/m.room.message/mid%s" % (
  94. self.created_rmid,
  95. str(next(seq)),
  96. )
  97. # send message in uncreated room, expect 403
  98. channel = self.make_request(
  99. "PUT",
  100. "/rooms/%s/send/m.room.message/mid2" % (self.uncreated_rmid,),
  101. msg_content,
  102. )
  103. self.assertEqual(403, channel.code, msg=channel.result["body"])
  104. # send message in created room not joined (no state), expect 403
  105. channel = self.make_request("PUT", send_msg_path(), msg_content)
  106. self.assertEqual(403, channel.code, msg=channel.result["body"])
  107. # send message in created room and invited, expect 403
  108. self.helper.invite(
  109. room=self.created_rmid, src=self.rmcreator_id, targ=self.user_id
  110. )
  111. channel = self.make_request("PUT", send_msg_path(), msg_content)
  112. self.assertEqual(403, channel.code, msg=channel.result["body"])
  113. # send message in created room and joined, expect 200
  114. self.helper.join(room=self.created_rmid, user=self.user_id)
  115. channel = self.make_request("PUT", send_msg_path(), msg_content)
  116. self.assertEqual(200, channel.code, msg=channel.result["body"])
  117. # send message in created room and left, expect 403
  118. self.helper.leave(room=self.created_rmid, user=self.user_id)
  119. channel = self.make_request("PUT", send_msg_path(), msg_content)
  120. self.assertEqual(403, channel.code, msg=channel.result["body"])
  121. def test_topic_perms(self) -> None:
  122. topic_content = b'{"topic":"My Topic Name"}'
  123. topic_path = "/rooms/%s/state/m.room.topic" % self.created_rmid
  124. # set/get topic in uncreated room, expect 403
  125. channel = self.make_request(
  126. "PUT", "/rooms/%s/state/m.room.topic" % self.uncreated_rmid, topic_content
  127. )
  128. self.assertEqual(403, channel.code, msg=channel.result["body"])
  129. channel = self.make_request(
  130. "GET", "/rooms/%s/state/m.room.topic" % self.uncreated_rmid
  131. )
  132. self.assertEqual(403, channel.code, msg=channel.result["body"])
  133. # set/get topic in created PRIVATE room not joined, expect 403
  134. channel = self.make_request("PUT", topic_path, topic_content)
  135. self.assertEqual(403, channel.code, msg=channel.result["body"])
  136. channel = self.make_request("GET", topic_path)
  137. self.assertEqual(403, channel.code, msg=channel.result["body"])
  138. # set topic in created PRIVATE room and invited, expect 403
  139. self.helper.invite(
  140. room=self.created_rmid, src=self.rmcreator_id, targ=self.user_id
  141. )
  142. channel = self.make_request("PUT", topic_path, topic_content)
  143. self.assertEqual(403, channel.code, msg=channel.result["body"])
  144. # get topic in created PRIVATE room and invited, expect 403
  145. channel = self.make_request("GET", topic_path)
  146. self.assertEqual(403, channel.code, msg=channel.result["body"])
  147. # set/get topic in created PRIVATE room and joined, expect 200
  148. self.helper.join(room=self.created_rmid, user=self.user_id)
  149. # Only room ops can set topic by default
  150. self.helper.auth_user_id = self.rmcreator_id
  151. channel = self.make_request("PUT", topic_path, topic_content)
  152. self.assertEqual(200, channel.code, msg=channel.result["body"])
  153. self.helper.auth_user_id = self.user_id
  154. channel = self.make_request("GET", topic_path)
  155. self.assertEqual(200, channel.code, msg=channel.result["body"])
  156. self.assert_dict(json.loads(topic_content.decode("utf8")), channel.json_body)
  157. # set/get topic in created PRIVATE room and left, expect 403
  158. self.helper.leave(room=self.created_rmid, user=self.user_id)
  159. channel = self.make_request("PUT", topic_path, topic_content)
  160. self.assertEqual(403, channel.code, msg=channel.result["body"])
  161. channel = self.make_request("GET", topic_path)
  162. self.assertEqual(200, channel.code, msg=channel.result["body"])
  163. # get topic in PUBLIC room, not joined, expect 403
  164. channel = self.make_request(
  165. "GET", "/rooms/%s/state/m.room.topic" % self.created_public_rmid
  166. )
  167. self.assertEqual(403, channel.code, msg=channel.result["body"])
  168. # set topic in PUBLIC room, not joined, expect 403
  169. channel = self.make_request(
  170. "PUT",
  171. "/rooms/%s/state/m.room.topic" % self.created_public_rmid,
  172. topic_content,
  173. )
  174. self.assertEqual(403, channel.code, msg=channel.result["body"])
  175. def _test_get_membership(
  176. self, room: str, members: Iterable = frozenset(), expect_code: int = 200
  177. ) -> None:
  178. for member in members:
  179. path = "/rooms/%s/state/m.room.member/%s" % (room, member)
  180. channel = self.make_request("GET", path)
  181. self.assertEqual(expect_code, channel.code)
  182. def test_membership_basic_room_perms(self) -> None:
  183. # === room does not exist ===
  184. room = self.uncreated_rmid
  185. # get membership of self, get membership of other, uncreated room
  186. # expect all 403s
  187. self._test_get_membership(
  188. members=[self.user_id, self.rmcreator_id], room=room, expect_code=403
  189. )
  190. # trying to invite people to this room should 403
  191. self.helper.invite(
  192. room=room, src=self.user_id, targ=self.rmcreator_id, expect_code=403
  193. )
  194. # set [invite/join/left] of self, set [invite/join/left] of other,
  195. # expect all 404s because room doesn't exist on any server
  196. for usr in [self.user_id, self.rmcreator_id]:
  197. self.helper.join(room=room, user=usr, expect_code=404)
  198. self.helper.leave(room=room, user=usr, expect_code=404)
  199. def test_membership_private_room_perms(self) -> None:
  200. room = self.created_rmid
  201. # get membership of self, get membership of other, private room + invite
  202. # expect all 403s
  203. self.helper.invite(room=room, src=self.rmcreator_id, targ=self.user_id)
  204. self._test_get_membership(
  205. members=[self.user_id, self.rmcreator_id], room=room, expect_code=403
  206. )
  207. # get membership of self, get membership of other, private room + joined
  208. # expect all 200s
  209. self.helper.join(room=room, user=self.user_id)
  210. self._test_get_membership(
  211. members=[self.user_id, self.rmcreator_id], room=room, expect_code=200
  212. )
  213. # get membership of self, get membership of other, private room + left
  214. # expect all 200s
  215. self.helper.leave(room=room, user=self.user_id)
  216. self._test_get_membership(
  217. members=[self.user_id, self.rmcreator_id], room=room, expect_code=200
  218. )
  219. def test_membership_public_room_perms(self) -> None:
  220. room = self.created_public_rmid
  221. # get membership of self, get membership of other, public room + invite
  222. # expect 403
  223. self.helper.invite(room=room, src=self.rmcreator_id, targ=self.user_id)
  224. self._test_get_membership(
  225. members=[self.user_id, self.rmcreator_id], room=room, expect_code=403
  226. )
  227. # get membership of self, get membership of other, public room + joined
  228. # expect all 200s
  229. self.helper.join(room=room, user=self.user_id)
  230. self._test_get_membership(
  231. members=[self.user_id, self.rmcreator_id], room=room, expect_code=200
  232. )
  233. # get membership of self, get membership of other, public room + left
  234. # expect 200.
  235. self.helper.leave(room=room, user=self.user_id)
  236. self._test_get_membership(
  237. members=[self.user_id, self.rmcreator_id], room=room, expect_code=200
  238. )
  239. def test_invited_permissions(self) -> None:
  240. room = self.created_rmid
  241. self.helper.invite(room=room, src=self.rmcreator_id, targ=self.user_id)
  242. # set [invite/join/left] of other user, expect 403s
  243. self.helper.invite(
  244. room=room, src=self.user_id, targ=self.rmcreator_id, expect_code=403
  245. )
  246. self.helper.change_membership(
  247. room=room,
  248. src=self.user_id,
  249. targ=self.rmcreator_id,
  250. membership=Membership.JOIN,
  251. expect_code=403,
  252. )
  253. self.helper.change_membership(
  254. room=room,
  255. src=self.user_id,
  256. targ=self.rmcreator_id,
  257. membership=Membership.LEAVE,
  258. expect_code=403,
  259. )
  260. def test_joined_permissions(self) -> None:
  261. room = self.created_rmid
  262. self.helper.invite(room=room, src=self.rmcreator_id, targ=self.user_id)
  263. self.helper.join(room=room, user=self.user_id)
  264. # set invited of self, expect 403
  265. self.helper.invite(
  266. room=room, src=self.user_id, targ=self.user_id, expect_code=403
  267. )
  268. # set joined of self, expect 200 (NOOP)
  269. self.helper.join(room=room, user=self.user_id)
  270. other = "@burgundy:red"
  271. # set invited of other, expect 200
  272. self.helper.invite(room=room, src=self.user_id, targ=other, expect_code=200)
  273. # set joined of other, expect 403
  274. self.helper.change_membership(
  275. room=room,
  276. src=self.user_id,
  277. targ=other,
  278. membership=Membership.JOIN,
  279. expect_code=403,
  280. )
  281. # set left of other, expect 403
  282. self.helper.change_membership(
  283. room=room,
  284. src=self.user_id,
  285. targ=other,
  286. membership=Membership.LEAVE,
  287. expect_code=403,
  288. )
  289. # set left of self, expect 200
  290. self.helper.leave(room=room, user=self.user_id)
  291. def test_leave_permissions(self) -> None:
  292. room = self.created_rmid
  293. self.helper.invite(room=room, src=self.rmcreator_id, targ=self.user_id)
  294. self.helper.join(room=room, user=self.user_id)
  295. self.helper.leave(room=room, user=self.user_id)
  296. # set [invite/join/left] of self, set [invite/join/left] of other,
  297. # expect all 403s
  298. for usr in [self.user_id, self.rmcreator_id]:
  299. self.helper.change_membership(
  300. room=room,
  301. src=self.user_id,
  302. targ=usr,
  303. membership=Membership.INVITE,
  304. expect_code=403,
  305. )
  306. self.helper.change_membership(
  307. room=room,
  308. src=self.user_id,
  309. targ=usr,
  310. membership=Membership.JOIN,
  311. expect_code=403,
  312. )
  313. # It is always valid to LEAVE if you've already left (currently.)
  314. self.helper.change_membership(
  315. room=room,
  316. src=self.user_id,
  317. targ=self.rmcreator_id,
  318. membership=Membership.LEAVE,
  319. expect_code=403,
  320. )
  321. # tests the "from banned" line from the table in https://spec.matrix.org/unstable/client-server-api/#mroommember
  322. def test_member_event_from_ban(self) -> None:
  323. room = self.created_rmid
  324. self.helper.invite(room=room, src=self.rmcreator_id, targ=self.user_id)
  325. self.helper.join(room=room, user=self.user_id)
  326. other = "@burgundy:red"
  327. # User cannot ban other since they do not have required power level
  328. self.helper.change_membership(
  329. room=room,
  330. src=self.user_id,
  331. targ=other,
  332. membership=Membership.BAN,
  333. expect_code=403, # expect failure
  334. expect_errcode=Codes.FORBIDDEN,
  335. )
  336. # Admin bans other
  337. self.helper.change_membership(
  338. room=room,
  339. src=self.rmcreator_id,
  340. targ=other,
  341. membership=Membership.BAN,
  342. expect_code=200,
  343. )
  344. # from ban to invite: Must never happen.
  345. self.helper.change_membership(
  346. room=room,
  347. src=self.rmcreator_id,
  348. targ=other,
  349. membership=Membership.INVITE,
  350. expect_code=403, # expect failure
  351. expect_errcode=Codes.BAD_STATE,
  352. )
  353. # from ban to join: Must never happen.
  354. self.helper.change_membership(
  355. room=room,
  356. src=other,
  357. targ=other,
  358. membership=Membership.JOIN,
  359. expect_code=403, # expect failure
  360. expect_errcode=Codes.BAD_STATE,
  361. )
  362. # from ban to ban: No change.
  363. self.helper.change_membership(
  364. room=room,
  365. src=self.rmcreator_id,
  366. targ=other,
  367. membership=Membership.BAN,
  368. expect_code=200,
  369. )
  370. # from ban to knock: Must never happen.
  371. self.helper.change_membership(
  372. room=room,
  373. src=self.rmcreator_id,
  374. targ=other,
  375. membership=Membership.KNOCK,
  376. expect_code=403, # expect failure
  377. expect_errcode=Codes.BAD_STATE,
  378. )
  379. # User cannot unban other since they do not have required power level
  380. self.helper.change_membership(
  381. room=room,
  382. src=self.user_id,
  383. targ=other,
  384. membership=Membership.LEAVE,
  385. expect_code=403, # expect failure
  386. expect_errcode=Codes.FORBIDDEN,
  387. )
  388. # from ban to leave: User was unbanned.
  389. self.helper.change_membership(
  390. room=room,
  391. src=self.rmcreator_id,
  392. targ=other,
  393. membership=Membership.LEAVE,
  394. expect_code=200,
  395. )
  396. class RoomsMemberListTestCase(RoomBase):
  397. """Tests /rooms/$room_id/members/list REST events."""
  398. servlets = RoomBase.servlets + [sync.register_servlets]
  399. user_id = "@sid1:red"
  400. def test_get_member_list(self) -> None:
  401. room_id = self.helper.create_room_as(self.user_id)
  402. channel = self.make_request("GET", "/rooms/%s/members" % room_id)
  403. self.assertEqual(200, channel.code, msg=channel.result["body"])
  404. def test_get_member_list_no_room(self) -> None:
  405. channel = self.make_request("GET", "/rooms/roomdoesnotexist/members")
  406. self.assertEqual(403, channel.code, msg=channel.result["body"])
  407. def test_get_member_list_no_permission(self) -> None:
  408. room_id = self.helper.create_room_as("@some_other_guy:red")
  409. channel = self.make_request("GET", "/rooms/%s/members" % room_id)
  410. self.assertEqual(403, channel.code, msg=channel.result["body"])
  411. def test_get_member_list_no_permission_with_at_token(self) -> None:
  412. """
  413. Tests that a stranger to the room cannot get the member list
  414. (in the case that they use an at token).
  415. """
  416. room_id = self.helper.create_room_as("@someone.else:red")
  417. # first sync to get an at token
  418. channel = self.make_request("GET", "/sync")
  419. self.assertEqual(200, channel.code)
  420. sync_token = channel.json_body["next_batch"]
  421. # check that permission is denied for @sid1:red to get the
  422. # memberships of @someone.else:red's room.
  423. channel = self.make_request(
  424. "GET",
  425. f"/rooms/{room_id}/members?at={sync_token}",
  426. )
  427. self.assertEqual(403, channel.code, msg=channel.result["body"])
  428. def test_get_member_list_no_permission_former_member(self) -> None:
  429. """
  430. Tests that a former member of the room can not get the member list.
  431. """
  432. # create a room, invite the user and the user joins
  433. room_id = self.helper.create_room_as("@alice:red")
  434. self.helper.invite(room_id, "@alice:red", self.user_id)
  435. self.helper.join(room_id, self.user_id)
  436. # check that the user can see the member list to start with
  437. channel = self.make_request("GET", "/rooms/%s/members" % room_id)
  438. self.assertEqual(200, channel.code, msg=channel.result["body"])
  439. # ban the user
  440. self.helper.change_membership(room_id, "@alice:red", self.user_id, "ban")
  441. # check the user can no longer see the member list
  442. channel = self.make_request("GET", "/rooms/%s/members" % room_id)
  443. self.assertEqual(403, channel.code, msg=channel.result["body"])
  444. def test_get_member_list_no_permission_former_member_with_at_token(self) -> None:
  445. """
  446. Tests that a former member of the room can not get the member list
  447. (in the case that they use an at token).
  448. """
  449. # create a room, invite the user and the user joins
  450. room_id = self.helper.create_room_as("@alice:red")
  451. self.helper.invite(room_id, "@alice:red", self.user_id)
  452. self.helper.join(room_id, self.user_id)
  453. # sync to get an at token
  454. channel = self.make_request("GET", "/sync")
  455. self.assertEqual(200, channel.code)
  456. sync_token = channel.json_body["next_batch"]
  457. # check that the user can see the member list to start with
  458. channel = self.make_request(
  459. "GET", "/rooms/%s/members?at=%s" % (room_id, sync_token)
  460. )
  461. self.assertEqual(200, channel.code, msg=channel.result["body"])
  462. # ban the user (Note: the user is actually allowed to see this event and
  463. # state so that they know they're banned!)
  464. self.helper.change_membership(room_id, "@alice:red", self.user_id, "ban")
  465. # invite a third user and let them join
  466. self.helper.invite(room_id, "@alice:red", "@bob:red")
  467. self.helper.join(room_id, "@bob:red")
  468. # now, with the original user, sync again to get a new at token
  469. channel = self.make_request("GET", "/sync")
  470. self.assertEqual(200, channel.code)
  471. sync_token = channel.json_body["next_batch"]
  472. # check the user can no longer see the updated member list
  473. channel = self.make_request(
  474. "GET", "/rooms/%s/members?at=%s" % (room_id, sync_token)
  475. )
  476. self.assertEqual(403, channel.code, msg=channel.result["body"])
  477. def test_get_member_list_mixed_memberships(self) -> None:
  478. room_creator = "@some_other_guy:red"
  479. room_id = self.helper.create_room_as(room_creator)
  480. room_path = "/rooms/%s/members" % room_id
  481. self.helper.invite(room=room_id, src=room_creator, targ=self.user_id)
  482. # can't see list if you're just invited.
  483. channel = self.make_request("GET", room_path)
  484. self.assertEqual(403, channel.code, msg=channel.result["body"])
  485. self.helper.join(room=room_id, user=self.user_id)
  486. # can see list now joined
  487. channel = self.make_request("GET", room_path)
  488. self.assertEqual(200, channel.code, msg=channel.result["body"])
  489. self.helper.leave(room=room_id, user=self.user_id)
  490. # can see old list once left
  491. channel = self.make_request("GET", room_path)
  492. self.assertEqual(200, channel.code, msg=channel.result["body"])
  493. class RoomsCreateTestCase(RoomBase):
  494. """Tests /rooms and /rooms/$room_id REST events."""
  495. user_id = "@sid1:red"
  496. def test_post_room_no_keys(self) -> None:
  497. # POST with no config keys, expect new room id
  498. channel = self.make_request("POST", "/createRoom", "{}")
  499. self.assertEqual(200, channel.code, channel.result)
  500. self.assertTrue("room_id" in channel.json_body)
  501. def test_post_room_visibility_key(self) -> None:
  502. # POST with visibility config key, expect new room id
  503. channel = self.make_request("POST", "/createRoom", b'{"visibility":"private"}')
  504. self.assertEqual(200, channel.code)
  505. self.assertTrue("room_id" in channel.json_body)
  506. def test_post_room_custom_key(self) -> None:
  507. # POST with custom config keys, expect new room id
  508. channel = self.make_request("POST", "/createRoom", b'{"custom":"stuff"}')
  509. self.assertEqual(200, channel.code)
  510. self.assertTrue("room_id" in channel.json_body)
  511. def test_post_room_known_and_unknown_keys(self) -> None:
  512. # POST with custom + known config keys, expect new room id
  513. channel = self.make_request(
  514. "POST", "/createRoom", b'{"visibility":"private","custom":"things"}'
  515. )
  516. self.assertEqual(200, channel.code)
  517. self.assertTrue("room_id" in channel.json_body)
  518. def test_post_room_invalid_content(self) -> None:
  519. # POST with invalid content / paths, expect 400
  520. channel = self.make_request("POST", "/createRoom", b'{"visibili')
  521. self.assertEqual(400, channel.code)
  522. channel = self.make_request("POST", "/createRoom", b'["hello"]')
  523. self.assertEqual(400, channel.code)
  524. def test_post_room_invitees_invalid_mxid(self) -> None:
  525. # POST with invalid invitee, see https://github.com/matrix-org/synapse/issues/4088
  526. # Note the trailing space in the MXID here!
  527. channel = self.make_request(
  528. "POST", "/createRoom", b'{"invite":["@alice:example.com "]}'
  529. )
  530. self.assertEqual(400, channel.code)
  531. @unittest.override_config({"rc_invites": {"per_room": {"burst_count": 3}}})
  532. def test_post_room_invitees_ratelimit(self) -> None:
  533. """Test that invites sent when creating a room are ratelimited by a RateLimiter,
  534. which ratelimits them correctly, including by not limiting when the requester is
  535. exempt from ratelimiting.
  536. """
  537. # Build the request's content. We use local MXIDs because invites over federation
  538. # are more difficult to mock.
  539. content = json.dumps(
  540. {
  541. "invite": [
  542. "@alice1:red",
  543. "@alice2:red",
  544. "@alice3:red",
  545. "@alice4:red",
  546. ]
  547. }
  548. ).encode("utf8")
  549. # Test that the invites are correctly ratelimited.
  550. channel = self.make_request("POST", "/createRoom", content)
  551. self.assertEqual(400, channel.code)
  552. self.assertEqual(
  553. "Cannot invite so many users at once",
  554. channel.json_body["error"],
  555. )
  556. # Add the current user to the ratelimit overrides, allowing them no ratelimiting.
  557. self.get_success(
  558. self.hs.get_datastores().main.set_ratelimit_for_user(self.user_id, 0, 0)
  559. )
  560. # Test that the invites aren't ratelimited anymore.
  561. channel = self.make_request("POST", "/createRoom", content)
  562. self.assertEqual(200, channel.code)
  563. def test_spam_checker_may_join_room(self) -> None:
  564. """Tests that the user_may_join_room spam checker callback is correctly bypassed
  565. when creating a new room.
  566. """
  567. async def user_may_join_room(
  568. mxid: str,
  569. room_id: str,
  570. is_invite: bool,
  571. ) -> bool:
  572. return False
  573. join_mock = Mock(side_effect=user_may_join_room)
  574. self.hs.get_spam_checker()._user_may_join_room_callbacks.append(join_mock)
  575. channel = self.make_request(
  576. "POST",
  577. "/createRoom",
  578. {},
  579. )
  580. self.assertEqual(channel.code, 200, channel.json_body)
  581. self.assertEqual(join_mock.call_count, 0)
  582. class RoomTopicTestCase(RoomBase):
  583. """Tests /rooms/$room_id/topic REST events."""
  584. user_id = "@sid1:red"
  585. def prepare(self, reactor: MemoryReactor, clock: Clock, hs: HomeServer) -> None:
  586. # create the room
  587. self.room_id = self.helper.create_room_as(self.user_id)
  588. self.path = "/rooms/%s/state/m.room.topic" % (self.room_id,)
  589. def test_invalid_puts(self) -> None:
  590. # missing keys or invalid json
  591. channel = self.make_request("PUT", self.path, "{}")
  592. self.assertEqual(400, channel.code, msg=channel.result["body"])
  593. channel = self.make_request("PUT", self.path, '{"_name":"bo"}')
  594. self.assertEqual(400, channel.code, msg=channel.result["body"])
  595. channel = self.make_request("PUT", self.path, '{"nao')
  596. self.assertEqual(400, channel.code, msg=channel.result["body"])
  597. channel = self.make_request(
  598. "PUT", self.path, '[{"_name":"bo"},{"_name":"jill"}]'
  599. )
  600. self.assertEqual(400, channel.code, msg=channel.result["body"])
  601. channel = self.make_request("PUT", self.path, "text only")
  602. self.assertEqual(400, channel.code, msg=channel.result["body"])
  603. channel = self.make_request("PUT", self.path, "")
  604. self.assertEqual(400, channel.code, msg=channel.result["body"])
  605. # valid key, wrong type
  606. content = '{"topic":["Topic name"]}'
  607. channel = self.make_request("PUT", self.path, content)
  608. self.assertEqual(400, channel.code, msg=channel.result["body"])
  609. def test_rooms_topic(self) -> None:
  610. # nothing should be there
  611. channel = self.make_request("GET", self.path)
  612. self.assertEqual(404, channel.code, msg=channel.result["body"])
  613. # valid put
  614. content = '{"topic":"Topic name"}'
  615. channel = self.make_request("PUT", self.path, content)
  616. self.assertEqual(200, channel.code, msg=channel.result["body"])
  617. # valid get
  618. channel = self.make_request("GET", self.path)
  619. self.assertEqual(200, channel.code, msg=channel.result["body"])
  620. self.assert_dict(json.loads(content), channel.json_body)
  621. def test_rooms_topic_with_extra_keys(self) -> None:
  622. # valid put with extra keys
  623. content = '{"topic":"Seasons","subtopic":"Summer"}'
  624. channel = self.make_request("PUT", self.path, content)
  625. self.assertEqual(200, channel.code, msg=channel.result["body"])
  626. # valid get
  627. channel = self.make_request("GET", self.path)
  628. self.assertEqual(200, channel.code, msg=channel.result["body"])
  629. self.assert_dict(json.loads(content), channel.json_body)
  630. class RoomMemberStateTestCase(RoomBase):
  631. """Tests /rooms/$room_id/members/$user_id/state REST events."""
  632. user_id = "@sid1:red"
  633. def prepare(self, reactor: MemoryReactor, clock: Clock, hs: HomeServer) -> None:
  634. self.room_id = self.helper.create_room_as(self.user_id)
  635. def test_invalid_puts(self) -> None:
  636. path = "/rooms/%s/state/m.room.member/%s" % (self.room_id, self.user_id)
  637. # missing keys or invalid json
  638. channel = self.make_request("PUT", path, "{}")
  639. self.assertEqual(400, channel.code, msg=channel.result["body"])
  640. channel = self.make_request("PUT", path, '{"_name":"bo"}')
  641. self.assertEqual(400, channel.code, msg=channel.result["body"])
  642. channel = self.make_request("PUT", path, '{"nao')
  643. self.assertEqual(400, channel.code, msg=channel.result["body"])
  644. channel = self.make_request("PUT", path, b'[{"_name":"bo"},{"_name":"jill"}]')
  645. self.assertEqual(400, channel.code, msg=channel.result["body"])
  646. channel = self.make_request("PUT", path, "text only")
  647. self.assertEqual(400, channel.code, msg=channel.result["body"])
  648. channel = self.make_request("PUT", path, "")
  649. self.assertEqual(400, channel.code, msg=channel.result["body"])
  650. # valid keys, wrong types
  651. content = '{"membership":["%s","%s","%s"]}' % (
  652. Membership.INVITE,
  653. Membership.JOIN,
  654. Membership.LEAVE,
  655. )
  656. channel = self.make_request("PUT", path, content.encode("ascii"))
  657. self.assertEqual(400, channel.code, msg=channel.result["body"])
  658. def test_rooms_members_self(self) -> None:
  659. path = "/rooms/%s/state/m.room.member/%s" % (
  660. urlparse.quote(self.room_id),
  661. self.user_id,
  662. )
  663. # valid join message (NOOP since we made the room)
  664. content = '{"membership":"%s"}' % Membership.JOIN
  665. channel = self.make_request("PUT", path, content.encode("ascii"))
  666. self.assertEqual(200, channel.code, msg=channel.result["body"])
  667. channel = self.make_request("GET", path, content=b"")
  668. self.assertEqual(200, channel.code, msg=channel.result["body"])
  669. expected_response = {"membership": Membership.JOIN}
  670. self.assertEqual(expected_response, channel.json_body)
  671. def test_rooms_members_other(self) -> None:
  672. self.other_id = "@zzsid1:red"
  673. path = "/rooms/%s/state/m.room.member/%s" % (
  674. urlparse.quote(self.room_id),
  675. self.other_id,
  676. )
  677. # valid invite message
  678. content = '{"membership":"%s"}' % Membership.INVITE
  679. channel = self.make_request("PUT", path, content)
  680. self.assertEqual(200, channel.code, msg=channel.result["body"])
  681. channel = self.make_request("GET", path, content=b"")
  682. self.assertEqual(200, channel.code, msg=channel.result["body"])
  683. self.assertEqual(json.loads(content), channel.json_body)
  684. def test_rooms_members_other_custom_keys(self) -> None:
  685. self.other_id = "@zzsid1:red"
  686. path = "/rooms/%s/state/m.room.member/%s" % (
  687. urlparse.quote(self.room_id),
  688. self.other_id,
  689. )
  690. # valid invite message with custom key
  691. content = '{"membership":"%s","invite_text":"%s"}' % (
  692. Membership.INVITE,
  693. "Join us!",
  694. )
  695. channel = self.make_request("PUT", path, content)
  696. self.assertEqual(200, channel.code, msg=channel.result["body"])
  697. channel = self.make_request("GET", path, content=b"")
  698. self.assertEqual(200, channel.code, msg=channel.result["body"])
  699. self.assertEqual(json.loads(content), channel.json_body)
  700. class RoomInviteRatelimitTestCase(RoomBase):
  701. user_id = "@sid1:red"
  702. servlets = [
  703. admin.register_servlets,
  704. profile.register_servlets,
  705. room.register_servlets,
  706. ]
  707. @unittest.override_config(
  708. {"rc_invites": {"per_room": {"per_second": 0.5, "burst_count": 3}}}
  709. )
  710. def test_invites_by_rooms_ratelimit(self) -> None:
  711. """Tests that invites in a room are actually rate-limited."""
  712. room_id = self.helper.create_room_as(self.user_id)
  713. for i in range(3):
  714. self.helper.invite(room_id, self.user_id, "@user-%s:red" % (i,))
  715. self.helper.invite(room_id, self.user_id, "@user-4:red", expect_code=429)
  716. @unittest.override_config(
  717. {"rc_invites": {"per_user": {"per_second": 0.5, "burst_count": 3}}}
  718. )
  719. def test_invites_by_users_ratelimit(self) -> None:
  720. """Tests that invites to a specific user are actually rate-limited."""
  721. for _ in range(3):
  722. room_id = self.helper.create_room_as(self.user_id)
  723. self.helper.invite(room_id, self.user_id, "@other-users:red")
  724. room_id = self.helper.create_room_as(self.user_id)
  725. self.helper.invite(room_id, self.user_id, "@other-users:red", expect_code=429)
  726. class RoomJoinTestCase(RoomBase):
  727. servlets = [
  728. admin.register_servlets,
  729. login.register_servlets,
  730. room.register_servlets,
  731. ]
  732. def prepare(self, reactor: MemoryReactor, clock: Clock, hs: HomeServer) -> None:
  733. self.user1 = self.register_user("thomas", "hackme")
  734. self.tok1 = self.login("thomas", "hackme")
  735. self.user2 = self.register_user("teresa", "hackme")
  736. self.tok2 = self.login("teresa", "hackme")
  737. self.room1 = self.helper.create_room_as(room_creator=self.user1, tok=self.tok1)
  738. self.room2 = self.helper.create_room_as(room_creator=self.user1, tok=self.tok1)
  739. self.room3 = self.helper.create_room_as(room_creator=self.user1, tok=self.tok1)
  740. def test_spam_checker_may_join_room(self) -> None:
  741. """Tests that the user_may_join_room spam checker callback is correctly called
  742. and blocks room joins when needed.
  743. """
  744. # Register a dummy callback. Make it allow all room joins for now.
  745. return_value = True
  746. async def user_may_join_room(
  747. userid: str,
  748. room_id: str,
  749. is_invited: bool,
  750. ) -> bool:
  751. return return_value
  752. callback_mock = Mock(side_effect=user_may_join_room, spec=lambda *x: None)
  753. self.hs.get_spam_checker()._user_may_join_room_callbacks.append(callback_mock)
  754. # Join a first room, without being invited to it.
  755. self.helper.join(self.room1, self.user2, tok=self.tok2)
  756. # Check that the callback was called with the right arguments.
  757. expected_call_args = (
  758. (
  759. self.user2,
  760. self.room1,
  761. False,
  762. ),
  763. )
  764. self.assertEqual(
  765. callback_mock.call_args,
  766. expected_call_args,
  767. callback_mock.call_args,
  768. )
  769. # Join a second room, this time with an invite for it.
  770. self.helper.invite(self.room2, self.user1, self.user2, tok=self.tok1)
  771. self.helper.join(self.room2, self.user2, tok=self.tok2)
  772. # Check that the callback was called with the right arguments.
  773. expected_call_args = (
  774. (
  775. self.user2,
  776. self.room2,
  777. True,
  778. ),
  779. )
  780. self.assertEqual(
  781. callback_mock.call_args,
  782. expected_call_args,
  783. callback_mock.call_args,
  784. )
  785. # Now make the callback deny all room joins, and check that a join actually fails.
  786. return_value = False
  787. self.helper.join(self.room3, self.user2, expect_code=403, tok=self.tok2)
  788. class RoomJoinRatelimitTestCase(RoomBase):
  789. user_id = "@sid1:red"
  790. servlets = [
  791. admin.register_servlets,
  792. profile.register_servlets,
  793. room.register_servlets,
  794. ]
  795. def prepare(self, reactor: MemoryReactor, clock: Clock, hs: HomeServer) -> None:
  796. super().prepare(reactor, clock, hs)
  797. # profile changes expect that the user is actually registered
  798. user = UserID.from_string(self.user_id)
  799. self.register_user(user.localpart, "supersecretpassword")
  800. @unittest.override_config(
  801. {"rc_joins": {"local": {"per_second": 0.5, "burst_count": 3}}}
  802. )
  803. def test_join_local_ratelimit(self) -> None:
  804. """Tests that local joins are actually rate-limited."""
  805. for _ in range(3):
  806. self.helper.create_room_as(self.user_id)
  807. self.helper.create_room_as(self.user_id, expect_code=429)
  808. @unittest.override_config(
  809. {"rc_joins": {"local": {"per_second": 0.5, "burst_count": 3}}}
  810. )
  811. def test_join_local_ratelimit_profile_change(self) -> None:
  812. """Tests that sending a profile update into all of the user's joined rooms isn't
  813. rate-limited by the rate-limiter on joins."""
  814. # Create and join as many rooms as the rate-limiting config allows in a second.
  815. room_ids = [
  816. self.helper.create_room_as(self.user_id),
  817. self.helper.create_room_as(self.user_id),
  818. self.helper.create_room_as(self.user_id),
  819. ]
  820. # Let some time for the rate-limiter to forget about our multi-join.
  821. self.reactor.advance(2)
  822. # Add one to make sure we're joined to more rooms than the config allows us to
  823. # join in a second.
  824. room_ids.append(self.helper.create_room_as(self.user_id))
  825. # Update the display name for the user.
  826. path = "/_matrix/client/r0/profile/%s/displayname" % self.user_id
  827. channel = self.make_request("PUT", path, {"displayname": "John Doe"})
  828. self.assertEqual(channel.code, 200, channel.json_body)
  829. # Check that all the rooms have been sent a profile update into.
  830. for room_id in room_ids:
  831. path = "/_matrix/client/r0/rooms/%s/state/m.room.member/%s" % (
  832. room_id,
  833. self.user_id,
  834. )
  835. channel = self.make_request("GET", path)
  836. self.assertEqual(channel.code, 200)
  837. self.assertIn("displayname", channel.json_body)
  838. self.assertEqual(channel.json_body["displayname"], "John Doe")
  839. @unittest.override_config(
  840. {"rc_joins": {"local": {"per_second": 0.5, "burst_count": 3}}}
  841. )
  842. def test_join_local_ratelimit_idempotent(self) -> None:
  843. """Tests that the room join endpoints remain idempotent despite rate-limiting
  844. on room joins."""
  845. room_id = self.helper.create_room_as(self.user_id)
  846. # Let's test both paths to be sure.
  847. paths_to_test = [
  848. "/_matrix/client/r0/rooms/%s/join",
  849. "/_matrix/client/r0/join/%s",
  850. ]
  851. for path in paths_to_test:
  852. # Make sure we send more requests than the rate-limiting config would allow
  853. # if all of these requests ended up joining the user to a room.
  854. for _ in range(4):
  855. channel = self.make_request("POST", path % room_id, {})
  856. self.assertEqual(channel.code, 200)
  857. @unittest.override_config(
  858. {
  859. "rc_joins": {"local": {"per_second": 0.5, "burst_count": 3}},
  860. "auto_join_rooms": ["#room:red", "#room2:red", "#room3:red", "#room4:red"],
  861. "autocreate_auto_join_rooms": True,
  862. },
  863. )
  864. def test_autojoin_rooms(self) -> None:
  865. user_id = self.register_user("testuser", "password")
  866. # Check that the new user successfully joined the four rooms
  867. rooms = self.get_success(
  868. self.hs.get_datastores().main.get_rooms_for_user(user_id)
  869. )
  870. self.assertEqual(len(rooms), 4)
  871. class RoomMessagesTestCase(RoomBase):
  872. """Tests /rooms/$room_id/messages/$user_id/$msg_id REST events."""
  873. user_id = "@sid1:red"
  874. def prepare(self, reactor: MemoryReactor, clock: Clock, hs: HomeServer) -> None:
  875. self.room_id = self.helper.create_room_as(self.user_id)
  876. def test_invalid_puts(self) -> None:
  877. path = "/rooms/%s/send/m.room.message/mid1" % (urlparse.quote(self.room_id))
  878. # missing keys or invalid json
  879. channel = self.make_request("PUT", path, b"{}")
  880. self.assertEqual(400, channel.code, msg=channel.result["body"])
  881. channel = self.make_request("PUT", path, b'{"_name":"bo"}')
  882. self.assertEqual(400, channel.code, msg=channel.result["body"])
  883. channel = self.make_request("PUT", path, b'{"nao')
  884. self.assertEqual(400, channel.code, msg=channel.result["body"])
  885. channel = self.make_request("PUT", path, b'[{"_name":"bo"},{"_name":"jill"}]')
  886. self.assertEqual(400, channel.code, msg=channel.result["body"])
  887. channel = self.make_request("PUT", path, b"text only")
  888. self.assertEqual(400, channel.code, msg=channel.result["body"])
  889. channel = self.make_request("PUT", path, b"")
  890. self.assertEqual(400, channel.code, msg=channel.result["body"])
  891. def test_rooms_messages_sent(self) -> None:
  892. path = "/rooms/%s/send/m.room.message/mid1" % (urlparse.quote(self.room_id))
  893. content = b'{"body":"test","msgtype":{"type":"a"}}'
  894. channel = self.make_request("PUT", path, content)
  895. self.assertEqual(400, channel.code, msg=channel.result["body"])
  896. # custom message types
  897. content = b'{"body":"test","msgtype":"test.custom.text"}'
  898. channel = self.make_request("PUT", path, content)
  899. self.assertEqual(200, channel.code, msg=channel.result["body"])
  900. # m.text message type
  901. path = "/rooms/%s/send/m.room.message/mid2" % (urlparse.quote(self.room_id))
  902. content = b'{"body":"test2","msgtype":"m.text"}'
  903. channel = self.make_request("PUT", path, content)
  904. self.assertEqual(200, channel.code, msg=channel.result["body"])
  905. class RoomPowerLevelOverridesTestCase(RoomBase):
  906. """Tests that the power levels can be overridden with server config."""
  907. user_id = "@sid1:red"
  908. servlets = [
  909. admin.register_servlets,
  910. room.register_servlets,
  911. login.register_servlets,
  912. ]
  913. def prepare(self, reactor: MemoryReactor, clock: Clock, hs: HomeServer) -> None:
  914. self.admin_user_id = self.register_user("admin", "pass")
  915. self.admin_access_token = self.login("admin", "pass")
  916. def power_levels(self, room_id: str) -> Dict[str, Any]:
  917. return self.helper.get_state(
  918. room_id, "m.room.power_levels", self.admin_access_token
  919. )
  920. def test_default_power_levels_with_room_override(self) -> None:
  921. """
  922. Create a room, providing power level overrides.
  923. Confirm that the room's power levels reflect the overrides.
  924. See https://github.com/matrix-org/matrix-spec/issues/492
  925. - currently we overwrite each key of power_level_content_override
  926. completely.
  927. """
  928. room_id = self.helper.create_room_as(
  929. self.user_id,
  930. extra_content={
  931. "power_level_content_override": {"events": {"custom.event": 0}}
  932. },
  933. )
  934. self.assertEqual(
  935. {
  936. "custom.event": 0,
  937. },
  938. self.power_levels(room_id)["events"],
  939. )
  940. @unittest.override_config(
  941. {
  942. "default_power_level_content_override": {
  943. "public_chat": {"events": {"custom.event": 0}},
  944. }
  945. },
  946. )
  947. def test_power_levels_with_server_override(self) -> None:
  948. """
  949. With a server configured to modify the room-level defaults,
  950. Create a room, without providing any extra power level overrides.
  951. Confirm that the room's power levels reflect the server-level overrides.
  952. Similar to https://github.com/matrix-org/matrix-spec/issues/492,
  953. we overwrite each key of power_level_content_override completely.
  954. """
  955. room_id = self.helper.create_room_as(self.user_id)
  956. self.assertEqual(
  957. {
  958. "custom.event": 0,
  959. },
  960. self.power_levels(room_id)["events"],
  961. )
  962. @unittest.override_config(
  963. {
  964. "default_power_level_content_override": {
  965. "public_chat": {
  966. "events": {"server.event": 0},
  967. "ban": 13,
  968. },
  969. }
  970. },
  971. )
  972. def test_power_levels_with_server_and_room_overrides(self) -> None:
  973. """
  974. With a server configured to modify the room-level defaults,
  975. create a room, providing different overrides.
  976. Confirm that the room's power levels reflect both overrides, and
  977. choose the room overrides where they clash.
  978. """
  979. room_id = self.helper.create_room_as(
  980. self.user_id,
  981. extra_content={
  982. "power_level_content_override": {"events": {"room.event": 0}}
  983. },
  984. )
  985. # Room override wins over server config
  986. self.assertEqual(
  987. {"room.event": 0},
  988. self.power_levels(room_id)["events"],
  989. )
  990. # But where there is no room override, server config wins
  991. self.assertEqual(13, self.power_levels(room_id)["ban"])
  992. class RoomPowerLevelOverridesInPracticeTestCase(RoomBase):
  993. """
  994. Tests that we can really do various otherwise-prohibited actions
  995. based on overriding the power levels in config.
  996. """
  997. user_id = "@sid1:red"
  998. def test_creator_can_post_state_event(self) -> None:
  999. # Given I am the creator of a room
  1000. room_id = self.helper.create_room_as(self.user_id)
  1001. # When I send a state event
  1002. path = "/rooms/{room_id}/state/custom.event/my_state_key".format(
  1003. room_id=urlparse.quote(room_id),
  1004. )
  1005. channel = self.make_request("PUT", path, "{}")
  1006. # Then I am allowed
  1007. self.assertEqual(200, channel.code, msg=channel.result["body"])
  1008. def test_normal_user_can_not_post_state_event(self) -> None:
  1009. # Given I am a normal member of a room
  1010. room_id = self.helper.create_room_as("@some_other_guy:red")
  1011. self.helper.join(room=room_id, user=self.user_id)
  1012. # When I send a state event
  1013. path = "/rooms/{room_id}/state/custom.event/my_state_key".format(
  1014. room_id=urlparse.quote(room_id),
  1015. )
  1016. channel = self.make_request("PUT", path, "{}")
  1017. # Then I am not allowed because state events require PL>=50
  1018. self.assertEqual(403, channel.code, msg=channel.result["body"])
  1019. self.assertEqual(
  1020. "You don't have permission to post that to the room. "
  1021. "user_level (0) < send_level (50)",
  1022. channel.json_body["error"],
  1023. )
  1024. @unittest.override_config(
  1025. {
  1026. "default_power_level_content_override": {
  1027. "public_chat": {"events": {"custom.event": 0}},
  1028. }
  1029. },
  1030. )
  1031. def test_with_config_override_normal_user_can_post_state_event(self) -> None:
  1032. # Given the server has config allowing normal users to post my event type,
  1033. # and I am a normal member of a room
  1034. room_id = self.helper.create_room_as("@some_other_guy:red")
  1035. self.helper.join(room=room_id, user=self.user_id)
  1036. # When I send a state event
  1037. path = "/rooms/{room_id}/state/custom.event/my_state_key".format(
  1038. room_id=urlparse.quote(room_id),
  1039. )
  1040. channel = self.make_request("PUT", path, "{}")
  1041. # Then I am allowed
  1042. self.assertEqual(200, channel.code, msg=channel.result["body"])
  1043. @unittest.override_config(
  1044. {
  1045. "default_power_level_content_override": {
  1046. "public_chat": {"events": {"custom.event": 0}},
  1047. }
  1048. },
  1049. )
  1050. def test_any_room_override_defeats_config_override(self) -> None:
  1051. # Given the server has config allowing normal users to post my event type
  1052. # And I am a normal member of a room
  1053. # But the room was created with special permissions
  1054. extra_content: Dict[str, Any] = {
  1055. "power_level_content_override": {"events": {}},
  1056. }
  1057. room_id = self.helper.create_room_as(
  1058. "@some_other_guy:red", extra_content=extra_content
  1059. )
  1060. self.helper.join(room=room_id, user=self.user_id)
  1061. # When I send a state event
  1062. path = "/rooms/{room_id}/state/custom.event/my_state_key".format(
  1063. room_id=urlparse.quote(room_id),
  1064. )
  1065. channel = self.make_request("PUT", path, "{}")
  1066. # Then I am not allowed
  1067. self.assertEqual(403, channel.code, msg=channel.result["body"])
  1068. @unittest.override_config(
  1069. {
  1070. "default_power_level_content_override": {
  1071. "public_chat": {"events": {"custom.event": 0}},
  1072. }
  1073. },
  1074. )
  1075. def test_specific_room_override_defeats_config_override(self) -> None:
  1076. # Given the server has config allowing normal users to post my event type,
  1077. # and I am a normal member of a room,
  1078. # but the room was created with special permissions for this event type
  1079. extra_content = {
  1080. "power_level_content_override": {"events": {"custom.event": 1}},
  1081. }
  1082. room_id = self.helper.create_room_as(
  1083. "@some_other_guy:red", extra_content=extra_content
  1084. )
  1085. self.helper.join(room=room_id, user=self.user_id)
  1086. # When I send a state event
  1087. path = "/rooms/{room_id}/state/custom.event/my_state_key".format(
  1088. room_id=urlparse.quote(room_id),
  1089. )
  1090. channel = self.make_request("PUT", path, "{}")
  1091. # Then I am not allowed
  1092. self.assertEqual(403, channel.code, msg=channel.result["body"])
  1093. self.assertEqual(
  1094. "You don't have permission to post that to the room. "
  1095. + "user_level (0) < send_level (1)",
  1096. channel.json_body["error"],
  1097. )
  1098. @unittest.override_config(
  1099. {
  1100. "default_power_level_content_override": {
  1101. "public_chat": {"events": {"custom.event": 0}},
  1102. "private_chat": None,
  1103. "trusted_private_chat": None,
  1104. }
  1105. },
  1106. )
  1107. def test_config_override_applies_only_to_specific_preset(self) -> None:
  1108. # Given the server has config for public_chats,
  1109. # and I am a normal member of a private_chat room
  1110. room_id = self.helper.create_room_as("@some_other_guy:red", is_public=False)
  1111. self.helper.invite(room=room_id, src="@some_other_guy:red", targ=self.user_id)
  1112. self.helper.join(room=room_id, user=self.user_id)
  1113. # When I send a state event
  1114. path = "/rooms/{room_id}/state/custom.event/my_state_key".format(
  1115. room_id=urlparse.quote(room_id),
  1116. )
  1117. channel = self.make_request("PUT", path, "{}")
  1118. # Then I am not allowed because the public_chat config does not
  1119. # affect this room, because this room is a private_chat
  1120. self.assertEqual(403, channel.code, msg=channel.result["body"])
  1121. self.assertEqual(
  1122. "You don't have permission to post that to the room. "
  1123. + "user_level (0) < send_level (50)",
  1124. channel.json_body["error"],
  1125. )
  1126. class RoomInitialSyncTestCase(RoomBase):
  1127. """Tests /rooms/$room_id/initialSync."""
  1128. user_id = "@sid1:red"
  1129. def prepare(self, reactor: MemoryReactor, clock: Clock, hs: HomeServer) -> None:
  1130. # create the room
  1131. self.room_id = self.helper.create_room_as(self.user_id)
  1132. def test_initial_sync(self) -> None:
  1133. channel = self.make_request("GET", "/rooms/%s/initialSync" % self.room_id)
  1134. self.assertEqual(200, channel.code)
  1135. self.assertEqual(self.room_id, channel.json_body["room_id"])
  1136. self.assertEqual("join", channel.json_body["membership"])
  1137. # Room state is easier to assert on if we unpack it into a dict
  1138. state: JsonDict = {}
  1139. for event in channel.json_body["state"]:
  1140. if "state_key" not in event:
  1141. continue
  1142. t = event["type"]
  1143. if t not in state:
  1144. state[t] = []
  1145. state[t].append(event)
  1146. self.assertTrue("m.room.create" in state)
  1147. self.assertTrue("messages" in channel.json_body)
  1148. self.assertTrue("chunk" in channel.json_body["messages"])
  1149. self.assertTrue("end" in channel.json_body["messages"])
  1150. self.assertTrue("presence" in channel.json_body)
  1151. presence_by_user = {
  1152. e["content"]["user_id"]: e for e in channel.json_body["presence"]
  1153. }
  1154. self.assertTrue(self.user_id in presence_by_user)
  1155. self.assertEqual("m.presence", presence_by_user[self.user_id]["type"])
  1156. class RoomMessageListTestCase(RoomBase):
  1157. """Tests /rooms/$room_id/messages REST events."""
  1158. user_id = "@sid1:red"
  1159. def prepare(self, reactor: MemoryReactor, clock: Clock, hs: HomeServer) -> None:
  1160. self.room_id = self.helper.create_room_as(self.user_id)
  1161. def test_topo_token_is_accepted(self) -> None:
  1162. token = "t1-0_0_0_0_0_0_0_0_0"
  1163. channel = self.make_request(
  1164. "GET", "/rooms/%s/messages?access_token=x&from=%s" % (self.room_id, token)
  1165. )
  1166. self.assertEqual(200, channel.code)
  1167. self.assertTrue("start" in channel.json_body)
  1168. self.assertEqual(token, channel.json_body["start"])
  1169. self.assertTrue("chunk" in channel.json_body)
  1170. self.assertTrue("end" in channel.json_body)
  1171. def test_stream_token_is_accepted_for_fwd_pagianation(self) -> None:
  1172. token = "s0_0_0_0_0_0_0_0_0"
  1173. channel = self.make_request(
  1174. "GET", "/rooms/%s/messages?access_token=x&from=%s" % (self.room_id, token)
  1175. )
  1176. self.assertEqual(200, channel.code)
  1177. self.assertTrue("start" in channel.json_body)
  1178. self.assertEqual(token, channel.json_body["start"])
  1179. self.assertTrue("chunk" in channel.json_body)
  1180. self.assertTrue("end" in channel.json_body)
  1181. def test_room_messages_purge(self) -> None:
  1182. store = self.hs.get_datastores().main
  1183. pagination_handler = self.hs.get_pagination_handler()
  1184. # Send a first message in the room, which will be removed by the purge.
  1185. first_event_id = self.helper.send(self.room_id, "message 1")["event_id"]
  1186. first_token = self.get_success(
  1187. store.get_topological_token_for_event(first_event_id)
  1188. )
  1189. first_token_str = self.get_success(first_token.to_string(store))
  1190. # Send a second message in the room, which won't be removed, and which we'll
  1191. # use as the marker to purge events before.
  1192. second_event_id = self.helper.send(self.room_id, "message 2")["event_id"]
  1193. second_token = self.get_success(
  1194. store.get_topological_token_for_event(second_event_id)
  1195. )
  1196. second_token_str = self.get_success(second_token.to_string(store))
  1197. # Send a third event in the room to ensure we don't fall under any edge case
  1198. # due to our marker being the latest forward extremity in the room.
  1199. self.helper.send(self.room_id, "message 3")
  1200. # Check that we get the first and second message when querying /messages.
  1201. channel = self.make_request(
  1202. "GET",
  1203. "/rooms/%s/messages?access_token=x&from=%s&dir=b&filter=%s"
  1204. % (
  1205. self.room_id,
  1206. second_token_str,
  1207. json.dumps({"types": [EventTypes.Message]}),
  1208. ),
  1209. )
  1210. self.assertEqual(channel.code, 200, channel.json_body)
  1211. chunk = channel.json_body["chunk"]
  1212. self.assertEqual(len(chunk), 2, [event["content"] for event in chunk])
  1213. # Purge every event before the second event.
  1214. purge_id = random_string(16)
  1215. pagination_handler._purges_by_id[purge_id] = PurgeStatus()
  1216. self.get_success(
  1217. pagination_handler._purge_history(
  1218. purge_id=purge_id,
  1219. room_id=self.room_id,
  1220. token=second_token_str,
  1221. delete_local_events=True,
  1222. )
  1223. )
  1224. # Check that we only get the second message through /message now that the first
  1225. # has been purged.
  1226. channel = self.make_request(
  1227. "GET",
  1228. "/rooms/%s/messages?access_token=x&from=%s&dir=b&filter=%s"
  1229. % (
  1230. self.room_id,
  1231. second_token_str,
  1232. json.dumps({"types": [EventTypes.Message]}),
  1233. ),
  1234. )
  1235. self.assertEqual(channel.code, 200, channel.json_body)
  1236. chunk = channel.json_body["chunk"]
  1237. self.assertEqual(len(chunk), 1, [event["content"] for event in chunk])
  1238. # Check that we get no event, but also no error, when querying /messages with
  1239. # the token that was pointing at the first event, because we don't have it
  1240. # anymore.
  1241. channel = self.make_request(
  1242. "GET",
  1243. "/rooms/%s/messages?access_token=x&from=%s&dir=b&filter=%s"
  1244. % (
  1245. self.room_id,
  1246. first_token_str,
  1247. json.dumps({"types": [EventTypes.Message]}),
  1248. ),
  1249. )
  1250. self.assertEqual(channel.code, 200, channel.json_body)
  1251. chunk = channel.json_body["chunk"]
  1252. self.assertEqual(len(chunk), 0, [event["content"] for event in chunk])
  1253. class RoomSearchTestCase(unittest.HomeserverTestCase):
  1254. servlets = [
  1255. synapse.rest.admin.register_servlets_for_client_rest_resource,
  1256. room.register_servlets,
  1257. login.register_servlets,
  1258. ]
  1259. user_id = True
  1260. hijack_auth = False
  1261. def prepare(self, reactor: MemoryReactor, clock: Clock, hs: HomeServer) -> None:
  1262. # Register the user who does the searching
  1263. self.user_id2 = self.register_user("user", "pass")
  1264. self.access_token = self.login("user", "pass")
  1265. # Register the user who sends the message
  1266. self.other_user_id = self.register_user("otheruser", "pass")
  1267. self.other_access_token = self.login("otheruser", "pass")
  1268. # Create a room
  1269. self.room = self.helper.create_room_as(self.user_id2, tok=self.access_token)
  1270. # Invite the other person
  1271. self.helper.invite(
  1272. room=self.room,
  1273. src=self.user_id2,
  1274. tok=self.access_token,
  1275. targ=self.other_user_id,
  1276. )
  1277. # The other user joins
  1278. self.helper.join(
  1279. room=self.room, user=self.other_user_id, tok=self.other_access_token
  1280. )
  1281. def test_finds_message(self) -> None:
  1282. """
  1283. The search functionality will search for content in messages if asked to
  1284. do so.
  1285. """
  1286. # The other user sends some messages
  1287. self.helper.send(self.room, body="Hi!", tok=self.other_access_token)
  1288. self.helper.send(self.room, body="There!", tok=self.other_access_token)
  1289. channel = self.make_request(
  1290. "POST",
  1291. "/search?access_token=%s" % (self.access_token,),
  1292. {
  1293. "search_categories": {
  1294. "room_events": {"keys": ["content.body"], "search_term": "Hi"}
  1295. }
  1296. },
  1297. )
  1298. # Check we get the results we expect -- one search result, of the sent
  1299. # messages
  1300. self.assertEqual(channel.code, 200)
  1301. results = channel.json_body["search_categories"]["room_events"]
  1302. self.assertEqual(results["count"], 1)
  1303. self.assertEqual(results["results"][0]["result"]["content"]["body"], "Hi!")
  1304. # No context was requested, so we should get none.
  1305. self.assertEqual(results["results"][0]["context"], {})
  1306. def test_include_context(self) -> None:
  1307. """
  1308. When event_context includes include_profile, profile information will be
  1309. included in the search response.
  1310. """
  1311. # The other user sends some messages
  1312. self.helper.send(self.room, body="Hi!", tok=self.other_access_token)
  1313. self.helper.send(self.room, body="There!", tok=self.other_access_token)
  1314. channel = self.make_request(
  1315. "POST",
  1316. "/search?access_token=%s" % (self.access_token,),
  1317. {
  1318. "search_categories": {
  1319. "room_events": {
  1320. "keys": ["content.body"],
  1321. "search_term": "Hi",
  1322. "event_context": {"include_profile": True},
  1323. }
  1324. }
  1325. },
  1326. )
  1327. # Check we get the results we expect -- one search result, of the sent
  1328. # messages
  1329. self.assertEqual(channel.code, 200)
  1330. results = channel.json_body["search_categories"]["room_events"]
  1331. self.assertEqual(results["count"], 1)
  1332. self.assertEqual(results["results"][0]["result"]["content"]["body"], "Hi!")
  1333. # We should get context info, like the two users, and the display names.
  1334. context = results["results"][0]["context"]
  1335. self.assertEqual(len(context["profile_info"].keys()), 2)
  1336. self.assertEqual(
  1337. context["profile_info"][self.other_user_id]["displayname"], "otheruser"
  1338. )
  1339. class PublicRoomsRestrictedTestCase(unittest.HomeserverTestCase):
  1340. servlets = [
  1341. synapse.rest.admin.register_servlets_for_client_rest_resource,
  1342. room.register_servlets,
  1343. login.register_servlets,
  1344. ]
  1345. def make_homeserver(self, reactor: MemoryReactor, clock: Clock) -> HomeServer:
  1346. self.url = b"/_matrix/client/r0/publicRooms"
  1347. config = self.default_config()
  1348. config["allow_public_rooms_without_auth"] = False
  1349. self.hs = self.setup_test_homeserver(config=config)
  1350. return self.hs
  1351. def test_restricted_no_auth(self) -> None:
  1352. channel = self.make_request("GET", self.url)
  1353. self.assertEqual(channel.code, 401, channel.result)
  1354. def test_restricted_auth(self) -> None:
  1355. self.register_user("user", "pass")
  1356. tok = self.login("user", "pass")
  1357. channel = self.make_request("GET", self.url, access_token=tok)
  1358. self.assertEqual(channel.code, 200, channel.result)
  1359. class PublicRoomsTestRemoteSearchFallbackTestCase(unittest.HomeserverTestCase):
  1360. """Test that we correctly fallback to local filtering if a remote server
  1361. doesn't support search.
  1362. """
  1363. servlets = [
  1364. synapse.rest.admin.register_servlets_for_client_rest_resource,
  1365. room.register_servlets,
  1366. login.register_servlets,
  1367. ]
  1368. def make_homeserver(self, reactor: MemoryReactor, clock: Clock) -> HomeServer:
  1369. return self.setup_test_homeserver(federation_client=Mock())
  1370. def prepare(self, reactor: MemoryReactor, clock: Clock, hs: HomeServer) -> None:
  1371. self.register_user("user", "pass")
  1372. self.token = self.login("user", "pass")
  1373. self.federation_client = hs.get_federation_client()
  1374. def test_simple(self) -> None:
  1375. "Simple test for searching rooms over federation"
  1376. self.federation_client.get_public_rooms.return_value = make_awaitable({}) # type: ignore[attr-defined]
  1377. search_filter = {"generic_search_term": "foobar"}
  1378. channel = self.make_request(
  1379. "POST",
  1380. b"/_matrix/client/r0/publicRooms?server=testserv",
  1381. content={"filter": search_filter},
  1382. access_token=self.token,
  1383. )
  1384. self.assertEqual(channel.code, 200, channel.result)
  1385. self.federation_client.get_public_rooms.assert_called_once_with( # type: ignore[attr-defined]
  1386. "testserv",
  1387. limit=100,
  1388. since_token=None,
  1389. search_filter=search_filter,
  1390. include_all_networks=False,
  1391. third_party_instance_id=None,
  1392. )
  1393. def test_fallback(self) -> None:
  1394. "Test that searching public rooms over federation falls back if it gets a 404"
  1395. # The `get_public_rooms` should be called again if the first call fails
  1396. # with a 404, when using search filters.
  1397. self.federation_client.get_public_rooms.side_effect = ( # type: ignore[attr-defined]
  1398. HttpResponseException(404, "Not Found", b""),
  1399. make_awaitable({}),
  1400. )
  1401. search_filter = {"generic_search_term": "foobar"}
  1402. channel = self.make_request(
  1403. "POST",
  1404. b"/_matrix/client/r0/publicRooms?server=testserv",
  1405. content={"filter": search_filter},
  1406. access_token=self.token,
  1407. )
  1408. self.assertEqual(channel.code, 200, channel.result)
  1409. self.federation_client.get_public_rooms.assert_has_calls( # type: ignore[attr-defined]
  1410. [
  1411. call(
  1412. "testserv",
  1413. limit=100,
  1414. since_token=None,
  1415. search_filter=search_filter,
  1416. include_all_networks=False,
  1417. third_party_instance_id=None,
  1418. ),
  1419. call(
  1420. "testserv",
  1421. limit=None,
  1422. since_token=None,
  1423. search_filter=None,
  1424. include_all_networks=False,
  1425. third_party_instance_id=None,
  1426. ),
  1427. ]
  1428. )
  1429. class PerRoomProfilesForbiddenTestCase(unittest.HomeserverTestCase):
  1430. servlets = [
  1431. synapse.rest.admin.register_servlets_for_client_rest_resource,
  1432. room.register_servlets,
  1433. login.register_servlets,
  1434. profile.register_servlets,
  1435. ]
  1436. def make_homeserver(self, reactor: MemoryReactor, clock: Clock) -> HomeServer:
  1437. config = self.default_config()
  1438. config["allow_per_room_profiles"] = False
  1439. self.hs = self.setup_test_homeserver(config=config)
  1440. return self.hs
  1441. def prepare(self, reactor: MemoryReactor, clock: Clock, hs: HomeServer) -> None:
  1442. self.user_id = self.register_user("test", "test")
  1443. self.tok = self.login("test", "test")
  1444. # Set a profile for the test user
  1445. self.displayname = "test user"
  1446. data = {"displayname": self.displayname}
  1447. request_data = json.dumps(data)
  1448. channel = self.make_request(
  1449. "PUT",
  1450. "/_matrix/client/r0/profile/%s/displayname" % (self.user_id,),
  1451. request_data,
  1452. access_token=self.tok,
  1453. )
  1454. self.assertEqual(channel.code, 200, channel.result)
  1455. self.room_id = self.helper.create_room_as(self.user_id, tok=self.tok)
  1456. def test_per_room_profile_forbidden(self) -> None:
  1457. data = {"membership": "join", "displayname": "other test user"}
  1458. request_data = json.dumps(data)
  1459. channel = self.make_request(
  1460. "PUT",
  1461. "/_matrix/client/r0/rooms/%s/state/m.room.member/%s"
  1462. % (self.room_id, self.user_id),
  1463. request_data,
  1464. access_token=self.tok,
  1465. )
  1466. self.assertEqual(channel.code, 200, channel.result)
  1467. event_id = channel.json_body["event_id"]
  1468. channel = self.make_request(
  1469. "GET",
  1470. "/_matrix/client/r0/rooms/%s/event/%s" % (self.room_id, event_id),
  1471. access_token=self.tok,
  1472. )
  1473. self.assertEqual(channel.code, 200, channel.result)
  1474. res_displayname = channel.json_body["content"]["displayname"]
  1475. self.assertEqual(res_displayname, self.displayname, channel.result)
  1476. class RoomMembershipReasonTestCase(unittest.HomeserverTestCase):
  1477. """Tests that clients can add a "reason" field to membership events and
  1478. that they get correctly added to the generated events and propagated.
  1479. """
  1480. servlets = [
  1481. synapse.rest.admin.register_servlets_for_client_rest_resource,
  1482. room.register_servlets,
  1483. login.register_servlets,
  1484. ]
  1485. def prepare(self, reactor: MemoryReactor, clock: Clock, hs: HomeServer) -> None:
  1486. self.creator = self.register_user("creator", "test")
  1487. self.creator_tok = self.login("creator", "test")
  1488. self.second_user_id = self.register_user("second", "test")
  1489. self.second_tok = self.login("second", "test")
  1490. self.room_id = self.helper.create_room_as(self.creator, tok=self.creator_tok)
  1491. def test_join_reason(self) -> None:
  1492. reason = "hello"
  1493. channel = self.make_request(
  1494. "POST",
  1495. f"/_matrix/client/r0/rooms/{self.room_id}/join",
  1496. content={"reason": reason},
  1497. access_token=self.second_tok,
  1498. )
  1499. self.assertEqual(channel.code, 200, channel.result)
  1500. self._check_for_reason(reason)
  1501. def test_leave_reason(self) -> None:
  1502. self.helper.join(self.room_id, user=self.second_user_id, tok=self.second_tok)
  1503. reason = "hello"
  1504. channel = self.make_request(
  1505. "POST",
  1506. f"/_matrix/client/r0/rooms/{self.room_id}/leave",
  1507. content={"reason": reason},
  1508. access_token=self.second_tok,
  1509. )
  1510. self.assertEqual(channel.code, 200, channel.result)
  1511. self._check_for_reason(reason)
  1512. def test_kick_reason(self) -> None:
  1513. self.helper.join(self.room_id, user=self.second_user_id, tok=self.second_tok)
  1514. reason = "hello"
  1515. channel = self.make_request(
  1516. "POST",
  1517. f"/_matrix/client/r0/rooms/{self.room_id}/kick",
  1518. content={"reason": reason, "user_id": self.second_user_id},
  1519. access_token=self.second_tok,
  1520. )
  1521. self.assertEqual(channel.code, 200, channel.result)
  1522. self._check_for_reason(reason)
  1523. def test_ban_reason(self) -> None:
  1524. self.helper.join(self.room_id, user=self.second_user_id, tok=self.second_tok)
  1525. reason = "hello"
  1526. channel = self.make_request(
  1527. "POST",
  1528. f"/_matrix/client/r0/rooms/{self.room_id}/ban",
  1529. content={"reason": reason, "user_id": self.second_user_id},
  1530. access_token=self.creator_tok,
  1531. )
  1532. self.assertEqual(channel.code, 200, channel.result)
  1533. self._check_for_reason(reason)
  1534. def test_unban_reason(self) -> None:
  1535. reason = "hello"
  1536. channel = self.make_request(
  1537. "POST",
  1538. f"/_matrix/client/r0/rooms/{self.room_id}/unban",
  1539. content={"reason": reason, "user_id": self.second_user_id},
  1540. access_token=self.creator_tok,
  1541. )
  1542. self.assertEqual(channel.code, 200, channel.result)
  1543. self._check_for_reason(reason)
  1544. def test_invite_reason(self) -> None:
  1545. reason = "hello"
  1546. channel = self.make_request(
  1547. "POST",
  1548. f"/_matrix/client/r0/rooms/{self.room_id}/invite",
  1549. content={"reason": reason, "user_id": self.second_user_id},
  1550. access_token=self.creator_tok,
  1551. )
  1552. self.assertEqual(channel.code, 200, channel.result)
  1553. self._check_for_reason(reason)
  1554. def test_reject_invite_reason(self) -> None:
  1555. self.helper.invite(
  1556. self.room_id,
  1557. src=self.creator,
  1558. targ=self.second_user_id,
  1559. tok=self.creator_tok,
  1560. )
  1561. reason = "hello"
  1562. channel = self.make_request(
  1563. "POST",
  1564. f"/_matrix/client/r0/rooms/{self.room_id}/leave",
  1565. content={"reason": reason},
  1566. access_token=self.second_tok,
  1567. )
  1568. self.assertEqual(channel.code, 200, channel.result)
  1569. self._check_for_reason(reason)
  1570. def _check_for_reason(self, reason: str) -> None:
  1571. channel = self.make_request(
  1572. "GET",
  1573. "/_matrix/client/r0/rooms/{}/state/m.room.member/{}".format(
  1574. self.room_id, self.second_user_id
  1575. ),
  1576. access_token=self.creator_tok,
  1577. )
  1578. self.assertEqual(channel.code, 200, channel.result)
  1579. event_content = channel.json_body
  1580. self.assertEqual(event_content.get("reason"), reason, channel.result)
  1581. class LabelsTestCase(unittest.HomeserverTestCase):
  1582. servlets = [
  1583. synapse.rest.admin.register_servlets_for_client_rest_resource,
  1584. room.register_servlets,
  1585. login.register_servlets,
  1586. profile.register_servlets,
  1587. ]
  1588. # Filter that should only catch messages with the label "#fun".
  1589. FILTER_LABELS = {
  1590. "types": [EventTypes.Message],
  1591. "org.matrix.labels": ["#fun"],
  1592. }
  1593. # Filter that should only catch messages without the label "#fun".
  1594. FILTER_NOT_LABELS = {
  1595. "types": [EventTypes.Message],
  1596. "org.matrix.not_labels": ["#fun"],
  1597. }
  1598. # Filter that should only catch messages with the label "#work" but without the label
  1599. # "#notfun".
  1600. FILTER_LABELS_NOT_LABELS = {
  1601. "types": [EventTypes.Message],
  1602. "org.matrix.labels": ["#work"],
  1603. "org.matrix.not_labels": ["#notfun"],
  1604. }
  1605. def prepare(self, reactor: MemoryReactor, clock: Clock, hs: HomeServer) -> None:
  1606. self.user_id = self.register_user("test", "test")
  1607. self.tok = self.login("test", "test")
  1608. self.room_id = self.helper.create_room_as(self.user_id, tok=self.tok)
  1609. def test_context_filter_labels(self) -> None:
  1610. """Test that we can filter by a label on a /context request."""
  1611. event_id = self._send_labelled_messages_in_room()
  1612. channel = self.make_request(
  1613. "GET",
  1614. "/rooms/%s/context/%s?filter=%s"
  1615. % (self.room_id, event_id, json.dumps(self.FILTER_LABELS)),
  1616. access_token=self.tok,
  1617. )
  1618. self.assertEqual(channel.code, 200, channel.result)
  1619. events_before = channel.json_body["events_before"]
  1620. self.assertEqual(
  1621. len(events_before), 1, [event["content"] for event in events_before]
  1622. )
  1623. self.assertEqual(
  1624. events_before[0]["content"]["body"], "with right label", events_before[0]
  1625. )
  1626. events_after = channel.json_body["events_before"]
  1627. self.assertEqual(
  1628. len(events_after), 1, [event["content"] for event in events_after]
  1629. )
  1630. self.assertEqual(
  1631. events_after[0]["content"]["body"], "with right label", events_after[0]
  1632. )
  1633. def test_context_filter_not_labels(self) -> None:
  1634. """Test that we can filter by the absence of a label on a /context request."""
  1635. event_id = self._send_labelled_messages_in_room()
  1636. channel = self.make_request(
  1637. "GET",
  1638. "/rooms/%s/context/%s?filter=%s"
  1639. % (self.room_id, event_id, json.dumps(self.FILTER_NOT_LABELS)),
  1640. access_token=self.tok,
  1641. )
  1642. self.assertEqual(channel.code, 200, channel.result)
  1643. events_before = channel.json_body["events_before"]
  1644. self.assertEqual(
  1645. len(events_before), 1, [event["content"] for event in events_before]
  1646. )
  1647. self.assertEqual(
  1648. events_before[0]["content"]["body"], "without label", events_before[0]
  1649. )
  1650. events_after = channel.json_body["events_after"]
  1651. self.assertEqual(
  1652. len(events_after), 2, [event["content"] for event in events_after]
  1653. )
  1654. self.assertEqual(
  1655. events_after[0]["content"]["body"], "with wrong label", events_after[0]
  1656. )
  1657. self.assertEqual(
  1658. events_after[1]["content"]["body"], "with two wrong labels", events_after[1]
  1659. )
  1660. def test_context_filter_labels_not_labels(self) -> None:
  1661. """Test that we can filter by both a label and the absence of another label on a
  1662. /context request.
  1663. """
  1664. event_id = self._send_labelled_messages_in_room()
  1665. channel = self.make_request(
  1666. "GET",
  1667. "/rooms/%s/context/%s?filter=%s"
  1668. % (self.room_id, event_id, json.dumps(self.FILTER_LABELS_NOT_LABELS)),
  1669. access_token=self.tok,
  1670. )
  1671. self.assertEqual(channel.code, 200, channel.result)
  1672. events_before = channel.json_body["events_before"]
  1673. self.assertEqual(
  1674. len(events_before), 0, [event["content"] for event in events_before]
  1675. )
  1676. events_after = channel.json_body["events_after"]
  1677. self.assertEqual(
  1678. len(events_after), 1, [event["content"] for event in events_after]
  1679. )
  1680. self.assertEqual(
  1681. events_after[0]["content"]["body"], "with wrong label", events_after[0]
  1682. )
  1683. def test_messages_filter_labels(self) -> None:
  1684. """Test that we can filter by a label on a /messages request."""
  1685. self._send_labelled_messages_in_room()
  1686. token = "s0_0_0_0_0_0_0_0_0"
  1687. channel = self.make_request(
  1688. "GET",
  1689. "/rooms/%s/messages?access_token=%s&from=%s&filter=%s"
  1690. % (self.room_id, self.tok, token, json.dumps(self.FILTER_LABELS)),
  1691. )
  1692. events = channel.json_body["chunk"]
  1693. self.assertEqual(len(events), 2, [event["content"] for event in events])
  1694. self.assertEqual(events[0]["content"]["body"], "with right label", events[0])
  1695. self.assertEqual(events[1]["content"]["body"], "with right label", events[1])
  1696. def test_messages_filter_not_labels(self) -> None:
  1697. """Test that we can filter by the absence of a label on a /messages request."""
  1698. self._send_labelled_messages_in_room()
  1699. token = "s0_0_0_0_0_0_0_0_0"
  1700. channel = self.make_request(
  1701. "GET",
  1702. "/rooms/%s/messages?access_token=%s&from=%s&filter=%s"
  1703. % (self.room_id, self.tok, token, json.dumps(self.FILTER_NOT_LABELS)),
  1704. )
  1705. events = channel.json_body["chunk"]
  1706. self.assertEqual(len(events), 4, [event["content"] for event in events])
  1707. self.assertEqual(events[0]["content"]["body"], "without label", events[0])
  1708. self.assertEqual(events[1]["content"]["body"], "without label", events[1])
  1709. self.assertEqual(events[2]["content"]["body"], "with wrong label", events[2])
  1710. self.assertEqual(
  1711. events[3]["content"]["body"], "with two wrong labels", events[3]
  1712. )
  1713. def test_messages_filter_labels_not_labels(self) -> None:
  1714. """Test that we can filter by both a label and the absence of another label on a
  1715. /messages request.
  1716. """
  1717. self._send_labelled_messages_in_room()
  1718. token = "s0_0_0_0_0_0_0_0_0"
  1719. channel = self.make_request(
  1720. "GET",
  1721. "/rooms/%s/messages?access_token=%s&from=%s&filter=%s"
  1722. % (
  1723. self.room_id,
  1724. self.tok,
  1725. token,
  1726. json.dumps(self.FILTER_LABELS_NOT_LABELS),
  1727. ),
  1728. )
  1729. events = channel.json_body["chunk"]
  1730. self.assertEqual(len(events), 1, [event["content"] for event in events])
  1731. self.assertEqual(events[0]["content"]["body"], "with wrong label", events[0])
  1732. def test_search_filter_labels(self) -> None:
  1733. """Test that we can filter by a label on a /search request."""
  1734. request_data = json.dumps(
  1735. {
  1736. "search_categories": {
  1737. "room_events": {
  1738. "search_term": "label",
  1739. "filter": self.FILTER_LABELS,
  1740. }
  1741. }
  1742. }
  1743. )
  1744. self._send_labelled_messages_in_room()
  1745. channel = self.make_request(
  1746. "POST", "/search?access_token=%s" % self.tok, request_data
  1747. )
  1748. results = channel.json_body["search_categories"]["room_events"]["results"]
  1749. self.assertEqual(
  1750. len(results),
  1751. 2,
  1752. [result["result"]["content"] for result in results],
  1753. )
  1754. self.assertEqual(
  1755. results[0]["result"]["content"]["body"],
  1756. "with right label",
  1757. results[0]["result"]["content"]["body"],
  1758. )
  1759. self.assertEqual(
  1760. results[1]["result"]["content"]["body"],
  1761. "with right label",
  1762. results[1]["result"]["content"]["body"],
  1763. )
  1764. def test_search_filter_not_labels(self) -> None:
  1765. """Test that we can filter by the absence of a label on a /search request."""
  1766. request_data = json.dumps(
  1767. {
  1768. "search_categories": {
  1769. "room_events": {
  1770. "search_term": "label",
  1771. "filter": self.FILTER_NOT_LABELS,
  1772. }
  1773. }
  1774. }
  1775. )
  1776. self._send_labelled_messages_in_room()
  1777. channel = self.make_request(
  1778. "POST", "/search?access_token=%s" % self.tok, request_data
  1779. )
  1780. results = channel.json_body["search_categories"]["room_events"]["results"]
  1781. self.assertEqual(
  1782. len(results),
  1783. 4,
  1784. [result["result"]["content"] for result in results],
  1785. )
  1786. self.assertEqual(
  1787. results[0]["result"]["content"]["body"],
  1788. "without label",
  1789. results[0]["result"]["content"]["body"],
  1790. )
  1791. self.assertEqual(
  1792. results[1]["result"]["content"]["body"],
  1793. "without label",
  1794. results[1]["result"]["content"]["body"],
  1795. )
  1796. self.assertEqual(
  1797. results[2]["result"]["content"]["body"],
  1798. "with wrong label",
  1799. results[2]["result"]["content"]["body"],
  1800. )
  1801. self.assertEqual(
  1802. results[3]["result"]["content"]["body"],
  1803. "with two wrong labels",
  1804. results[3]["result"]["content"]["body"],
  1805. )
  1806. def test_search_filter_labels_not_labels(self) -> None:
  1807. """Test that we can filter by both a label and the absence of another label on a
  1808. /search request.
  1809. """
  1810. request_data = json.dumps(
  1811. {
  1812. "search_categories": {
  1813. "room_events": {
  1814. "search_term": "label",
  1815. "filter": self.FILTER_LABELS_NOT_LABELS,
  1816. }
  1817. }
  1818. }
  1819. )
  1820. self._send_labelled_messages_in_room()
  1821. channel = self.make_request(
  1822. "POST", "/search?access_token=%s" % self.tok, request_data
  1823. )
  1824. results = channel.json_body["search_categories"]["room_events"]["results"]
  1825. self.assertEqual(
  1826. len(results),
  1827. 1,
  1828. [result["result"]["content"] for result in results],
  1829. )
  1830. self.assertEqual(
  1831. results[0]["result"]["content"]["body"],
  1832. "with wrong label",
  1833. results[0]["result"]["content"]["body"],
  1834. )
  1835. def _send_labelled_messages_in_room(self) -> str:
  1836. """Sends several messages to a room with different labels (or without any) to test
  1837. filtering by label.
  1838. Returns:
  1839. The ID of the event to use if we're testing filtering on /context.
  1840. """
  1841. self.helper.send_event(
  1842. room_id=self.room_id,
  1843. type=EventTypes.Message,
  1844. content={
  1845. "msgtype": "m.text",
  1846. "body": "with right label",
  1847. EventContentFields.LABELS: ["#fun"],
  1848. },
  1849. tok=self.tok,
  1850. )
  1851. self.helper.send_event(
  1852. room_id=self.room_id,
  1853. type=EventTypes.Message,
  1854. content={"msgtype": "m.text", "body": "without label"},
  1855. tok=self.tok,
  1856. )
  1857. res = self.helper.send_event(
  1858. room_id=self.room_id,
  1859. type=EventTypes.Message,
  1860. content={"msgtype": "m.text", "body": "without label"},
  1861. tok=self.tok,
  1862. )
  1863. # Return this event's ID when we test filtering in /context requests.
  1864. event_id = res["event_id"]
  1865. self.helper.send_event(
  1866. room_id=self.room_id,
  1867. type=EventTypes.Message,
  1868. content={
  1869. "msgtype": "m.text",
  1870. "body": "with wrong label",
  1871. EventContentFields.LABELS: ["#work"],
  1872. },
  1873. tok=self.tok,
  1874. )
  1875. self.helper.send_event(
  1876. room_id=self.room_id,
  1877. type=EventTypes.Message,
  1878. content={
  1879. "msgtype": "m.text",
  1880. "body": "with two wrong labels",
  1881. EventContentFields.LABELS: ["#work", "#notfun"],
  1882. },
  1883. tok=self.tok,
  1884. )
  1885. self.helper.send_event(
  1886. room_id=self.room_id,
  1887. type=EventTypes.Message,
  1888. content={
  1889. "msgtype": "m.text",
  1890. "body": "with right label",
  1891. EventContentFields.LABELS: ["#fun"],
  1892. },
  1893. tok=self.tok,
  1894. )
  1895. return event_id
  1896. class RelationsTestCase(unittest.HomeserverTestCase):
  1897. servlets = [
  1898. synapse.rest.admin.register_servlets_for_client_rest_resource,
  1899. room.register_servlets,
  1900. login.register_servlets,
  1901. ]
  1902. def default_config(self) -> Dict[str, Any]:
  1903. config = super().default_config()
  1904. config["experimental_features"] = {"msc3440_enabled": True}
  1905. return config
  1906. def prepare(self, reactor: MemoryReactor, clock: Clock, hs: HomeServer) -> None:
  1907. self.user_id = self.register_user("test", "test")
  1908. self.tok = self.login("test", "test")
  1909. self.room_id = self.helper.create_room_as(self.user_id, tok=self.tok)
  1910. self.second_user_id = self.register_user("second", "test")
  1911. self.second_tok = self.login("second", "test")
  1912. self.helper.join(
  1913. room=self.room_id, user=self.second_user_id, tok=self.second_tok
  1914. )
  1915. self.third_user_id = self.register_user("third", "test")
  1916. self.third_tok = self.login("third", "test")
  1917. self.helper.join(room=self.room_id, user=self.third_user_id, tok=self.third_tok)
  1918. # An initial event with a relation from second user.
  1919. res = self.helper.send_event(
  1920. room_id=self.room_id,
  1921. type=EventTypes.Message,
  1922. content={"msgtype": "m.text", "body": "Message 1"},
  1923. tok=self.tok,
  1924. )
  1925. self.event_id_1 = res["event_id"]
  1926. self.helper.send_event(
  1927. room_id=self.room_id,
  1928. type="m.reaction",
  1929. content={
  1930. "m.relates_to": {
  1931. "rel_type": RelationTypes.ANNOTATION,
  1932. "event_id": self.event_id_1,
  1933. "key": "👍",
  1934. }
  1935. },
  1936. tok=self.second_tok,
  1937. )
  1938. # Another event with a relation from third user.
  1939. res = self.helper.send_event(
  1940. room_id=self.room_id,
  1941. type=EventTypes.Message,
  1942. content={"msgtype": "m.text", "body": "Message 2"},
  1943. tok=self.tok,
  1944. )
  1945. self.event_id_2 = res["event_id"]
  1946. self.helper.send_event(
  1947. room_id=self.room_id,
  1948. type="m.reaction",
  1949. content={
  1950. "m.relates_to": {
  1951. "rel_type": RelationTypes.REFERENCE,
  1952. "event_id": self.event_id_2,
  1953. }
  1954. },
  1955. tok=self.third_tok,
  1956. )
  1957. # An event with no relations.
  1958. self.helper.send_event(
  1959. room_id=self.room_id,
  1960. type=EventTypes.Message,
  1961. content={"msgtype": "m.text", "body": "No relations"},
  1962. tok=self.tok,
  1963. )
  1964. def _filter_messages(self, filter: JsonDict) -> List[JsonDict]:
  1965. """Make a request to /messages with a filter, returns the chunk of events."""
  1966. channel = self.make_request(
  1967. "GET",
  1968. "/rooms/%s/messages?filter=%s&dir=b" % (self.room_id, json.dumps(filter)),
  1969. access_token=self.tok,
  1970. )
  1971. self.assertEqual(channel.code, 200, channel.result)
  1972. return channel.json_body["chunk"]
  1973. def test_filter_relation_senders(self) -> None:
  1974. # Messages which second user reacted to.
  1975. filter = {"related_by_senders": [self.second_user_id]}
  1976. chunk = self._filter_messages(filter)
  1977. self.assertEqual(len(chunk), 1, chunk)
  1978. self.assertEqual(chunk[0]["event_id"], self.event_id_1)
  1979. # Messages which third user reacted to.
  1980. filter = {"related_by_senders": [self.third_user_id]}
  1981. chunk = self._filter_messages(filter)
  1982. self.assertEqual(len(chunk), 1, chunk)
  1983. self.assertEqual(chunk[0]["event_id"], self.event_id_2)
  1984. # Messages which either user reacted to.
  1985. filter = {"related_by_senders": [self.second_user_id, self.third_user_id]}
  1986. chunk = self._filter_messages(filter)
  1987. self.assertEqual(len(chunk), 2, chunk)
  1988. self.assertCountEqual(
  1989. [c["event_id"] for c in chunk], [self.event_id_1, self.event_id_2]
  1990. )
  1991. def test_filter_relation_type(self) -> None:
  1992. # Messages which have annotations.
  1993. filter = {"related_by_rel_types": [RelationTypes.ANNOTATION]}
  1994. chunk = self._filter_messages(filter)
  1995. self.assertEqual(len(chunk), 1, chunk)
  1996. self.assertEqual(chunk[0]["event_id"], self.event_id_1)
  1997. # Messages which have references.
  1998. filter = {"related_by_rel_types": [RelationTypes.REFERENCE]}
  1999. chunk = self._filter_messages(filter)
  2000. self.assertEqual(len(chunk), 1, chunk)
  2001. self.assertEqual(chunk[0]["event_id"], self.event_id_2)
  2002. # Messages which have either annotations or references.
  2003. filter = {
  2004. "related_by_rel_types": [
  2005. RelationTypes.ANNOTATION,
  2006. RelationTypes.REFERENCE,
  2007. ]
  2008. }
  2009. chunk = self._filter_messages(filter)
  2010. self.assertEqual(len(chunk), 2, chunk)
  2011. self.assertCountEqual(
  2012. [c["event_id"] for c in chunk], [self.event_id_1, self.event_id_2]
  2013. )
  2014. def test_filter_relation_senders_and_type(self) -> None:
  2015. # Messages which second user reacted to.
  2016. filter = {
  2017. "related_by_senders": [self.second_user_id],
  2018. "related_by_rel_types": [RelationTypes.ANNOTATION],
  2019. }
  2020. chunk = self._filter_messages(filter)
  2021. self.assertEqual(len(chunk), 1, chunk)
  2022. self.assertEqual(chunk[0]["event_id"], self.event_id_1)
  2023. class ContextTestCase(unittest.HomeserverTestCase):
  2024. servlets = [
  2025. synapse.rest.admin.register_servlets_for_client_rest_resource,
  2026. room.register_servlets,
  2027. login.register_servlets,
  2028. account.register_servlets,
  2029. ]
  2030. def prepare(self, reactor: MemoryReactor, clock: Clock, hs: HomeServer) -> None:
  2031. self.user_id = self.register_user("user", "password")
  2032. self.tok = self.login("user", "password")
  2033. self.room_id = self.helper.create_room_as(
  2034. self.user_id, tok=self.tok, is_public=False
  2035. )
  2036. self.other_user_id = self.register_user("user2", "password")
  2037. self.other_tok = self.login("user2", "password")
  2038. self.helper.invite(self.room_id, self.user_id, self.other_user_id, tok=self.tok)
  2039. self.helper.join(self.room_id, self.other_user_id, tok=self.other_tok)
  2040. def test_erased_sender(self) -> None:
  2041. """Test that an erasure request results in the requester's events being hidden
  2042. from any new member of the room.
  2043. """
  2044. # Send a bunch of events in the room.
  2045. self.helper.send(self.room_id, "message 1", tok=self.tok)
  2046. self.helper.send(self.room_id, "message 2", tok=self.tok)
  2047. event_id = self.helper.send(self.room_id, "message 3", tok=self.tok)["event_id"]
  2048. self.helper.send(self.room_id, "message 4", tok=self.tok)
  2049. self.helper.send(self.room_id, "message 5", tok=self.tok)
  2050. # Check that we can still see the messages before the erasure request.
  2051. channel = self.make_request(
  2052. "GET",
  2053. '/rooms/%s/context/%s?filter={"types":["m.room.message"]}'
  2054. % (self.room_id, event_id),
  2055. access_token=self.tok,
  2056. )
  2057. self.assertEqual(channel.code, 200, channel.result)
  2058. events_before = channel.json_body["events_before"]
  2059. self.assertEqual(len(events_before), 2, events_before)
  2060. self.assertEqual(
  2061. events_before[0].get("content", {}).get("body"),
  2062. "message 2",
  2063. events_before[0],
  2064. )
  2065. self.assertEqual(
  2066. events_before[1].get("content", {}).get("body"),
  2067. "message 1",
  2068. events_before[1],
  2069. )
  2070. self.assertEqual(
  2071. channel.json_body["event"].get("content", {}).get("body"),
  2072. "message 3",
  2073. channel.json_body["event"],
  2074. )
  2075. events_after = channel.json_body["events_after"]
  2076. self.assertEqual(len(events_after), 2, events_after)
  2077. self.assertEqual(
  2078. events_after[0].get("content", {}).get("body"),
  2079. "message 4",
  2080. events_after[0],
  2081. )
  2082. self.assertEqual(
  2083. events_after[1].get("content", {}).get("body"),
  2084. "message 5",
  2085. events_after[1],
  2086. )
  2087. # Deactivate the first account and erase the user's data.
  2088. deactivate_account_handler = self.hs.get_deactivate_account_handler()
  2089. self.get_success(
  2090. deactivate_account_handler.deactivate_account(
  2091. self.user_id, True, create_requester(self.user_id)
  2092. )
  2093. )
  2094. # Invite another user in the room. This is needed because messages will be
  2095. # pruned only if the user wasn't a member of the room when the messages were
  2096. # sent.
  2097. invited_user_id = self.register_user("user3", "password")
  2098. invited_tok = self.login("user3", "password")
  2099. self.helper.invite(
  2100. self.room_id, self.other_user_id, invited_user_id, tok=self.other_tok
  2101. )
  2102. self.helper.join(self.room_id, invited_user_id, tok=invited_tok)
  2103. # Check that a user that joined the room after the erasure request can't see
  2104. # the messages anymore.
  2105. channel = self.make_request(
  2106. "GET",
  2107. '/rooms/%s/context/%s?filter={"types":["m.room.message"]}'
  2108. % (self.room_id, event_id),
  2109. access_token=invited_tok,
  2110. )
  2111. self.assertEqual(channel.code, 200, channel.result)
  2112. events_before = channel.json_body["events_before"]
  2113. self.assertEqual(len(events_before), 2, events_before)
  2114. self.assertDictEqual(events_before[0].get("content"), {}, events_before[0])
  2115. self.assertDictEqual(events_before[1].get("content"), {}, events_before[1])
  2116. self.assertDictEqual(
  2117. channel.json_body["event"].get("content"), {}, channel.json_body["event"]
  2118. )
  2119. events_after = channel.json_body["events_after"]
  2120. self.assertEqual(len(events_after), 2, events_after)
  2121. self.assertDictEqual(events_after[0].get("content"), {}, events_after[0])
  2122. self.assertEqual(events_after[1].get("content"), {}, events_after[1])
  2123. class RoomAliasListTestCase(unittest.HomeserverTestCase):
  2124. servlets = [
  2125. synapse.rest.admin.register_servlets_for_client_rest_resource,
  2126. directory.register_servlets,
  2127. login.register_servlets,
  2128. room.register_servlets,
  2129. ]
  2130. def prepare(self, reactor: MemoryReactor, clock: Clock, hs: HomeServer) -> None:
  2131. self.room_owner = self.register_user("room_owner", "test")
  2132. self.room_owner_tok = self.login("room_owner", "test")
  2133. self.room_id = self.helper.create_room_as(
  2134. self.room_owner, tok=self.room_owner_tok
  2135. )
  2136. def test_no_aliases(self) -> None:
  2137. res = self._get_aliases(self.room_owner_tok)
  2138. self.assertEqual(res["aliases"], [])
  2139. def test_not_in_room(self) -> None:
  2140. self.register_user("user", "test")
  2141. user_tok = self.login("user", "test")
  2142. res = self._get_aliases(user_tok, expected_code=403)
  2143. self.assertEqual(res["errcode"], "M_FORBIDDEN")
  2144. def test_admin_user(self) -> None:
  2145. alias1 = self._random_alias()
  2146. self._set_alias_via_directory(alias1)
  2147. self.register_user("user", "test", admin=True)
  2148. user_tok = self.login("user", "test")
  2149. res = self._get_aliases(user_tok)
  2150. self.assertEqual(res["aliases"], [alias1])
  2151. def test_with_aliases(self) -> None:
  2152. alias1 = self._random_alias()
  2153. alias2 = self._random_alias()
  2154. self._set_alias_via_directory(alias1)
  2155. self._set_alias_via_directory(alias2)
  2156. res = self._get_aliases(self.room_owner_tok)
  2157. self.assertEqual(set(res["aliases"]), {alias1, alias2})
  2158. def test_peekable_room(self) -> None:
  2159. alias1 = self._random_alias()
  2160. self._set_alias_via_directory(alias1)
  2161. self.helper.send_state(
  2162. self.room_id,
  2163. EventTypes.RoomHistoryVisibility,
  2164. body={"history_visibility": "world_readable"},
  2165. tok=self.room_owner_tok,
  2166. )
  2167. self.register_user("user", "test")
  2168. user_tok = self.login("user", "test")
  2169. res = self._get_aliases(user_tok)
  2170. self.assertEqual(res["aliases"], [alias1])
  2171. def _get_aliases(self, access_token: str, expected_code: int = 200) -> JsonDict:
  2172. """Calls the endpoint under test. returns the json response object."""
  2173. channel = self.make_request(
  2174. "GET",
  2175. "/_matrix/client/r0/rooms/%s/aliases" % (self.room_id,),
  2176. access_token=access_token,
  2177. )
  2178. self.assertEqual(channel.code, expected_code, channel.result)
  2179. res = channel.json_body
  2180. self.assertIsInstance(res, dict)
  2181. if expected_code == 200:
  2182. self.assertIsInstance(res["aliases"], list)
  2183. return res
  2184. def _random_alias(self) -> str:
  2185. return RoomAlias(random_string(5), self.hs.hostname).to_string()
  2186. def _set_alias_via_directory(self, alias: str, expected_code: int = 200) -> None:
  2187. url = "/_matrix/client/r0/directory/room/" + alias
  2188. data = {"room_id": self.room_id}
  2189. request_data = json.dumps(data)
  2190. channel = self.make_request(
  2191. "PUT", url, request_data, access_token=self.room_owner_tok
  2192. )
  2193. self.assertEqual(channel.code, expected_code, channel.result)
  2194. class RoomCanonicalAliasTestCase(unittest.HomeserverTestCase):
  2195. servlets = [
  2196. synapse.rest.admin.register_servlets_for_client_rest_resource,
  2197. directory.register_servlets,
  2198. login.register_servlets,
  2199. room.register_servlets,
  2200. ]
  2201. def prepare(self, reactor: MemoryReactor, clock: Clock, hs: HomeServer) -> None:
  2202. self.room_owner = self.register_user("room_owner", "test")
  2203. self.room_owner_tok = self.login("room_owner", "test")
  2204. self.room_id = self.helper.create_room_as(
  2205. self.room_owner, tok=self.room_owner_tok
  2206. )
  2207. self.alias = "#alias:test"
  2208. self._set_alias_via_directory(self.alias)
  2209. def _set_alias_via_directory(self, alias: str, expected_code: int = 200) -> None:
  2210. url = "/_matrix/client/r0/directory/room/" + alias
  2211. data = {"room_id": self.room_id}
  2212. request_data = json.dumps(data)
  2213. channel = self.make_request(
  2214. "PUT", url, request_data, access_token=self.room_owner_tok
  2215. )
  2216. self.assertEqual(channel.code, expected_code, channel.result)
  2217. def _get_canonical_alias(self, expected_code: int = 200) -> JsonDict:
  2218. """Calls the endpoint under test. returns the json response object."""
  2219. channel = self.make_request(
  2220. "GET",
  2221. "rooms/%s/state/m.room.canonical_alias" % (self.room_id,),
  2222. access_token=self.room_owner_tok,
  2223. )
  2224. self.assertEqual(channel.code, expected_code, channel.result)
  2225. res = channel.json_body
  2226. self.assertIsInstance(res, dict)
  2227. return res
  2228. def _set_canonical_alias(
  2229. self, content: JsonDict, expected_code: int = 200
  2230. ) -> JsonDict:
  2231. """Calls the endpoint under test. returns the json response object."""
  2232. channel = self.make_request(
  2233. "PUT",
  2234. "rooms/%s/state/m.room.canonical_alias" % (self.room_id,),
  2235. json.dumps(content),
  2236. access_token=self.room_owner_tok,
  2237. )
  2238. self.assertEqual(channel.code, expected_code, channel.result)
  2239. res = channel.json_body
  2240. self.assertIsInstance(res, dict)
  2241. return res
  2242. def test_canonical_alias(self) -> None:
  2243. """Test a basic alias message."""
  2244. # There is no canonical alias to start with.
  2245. self._get_canonical_alias(expected_code=404)
  2246. # Create an alias.
  2247. self._set_canonical_alias({"alias": self.alias})
  2248. # Canonical alias now exists!
  2249. res = self._get_canonical_alias()
  2250. self.assertEqual(res, {"alias": self.alias})
  2251. # Now remove the alias.
  2252. self._set_canonical_alias({})
  2253. # There is an alias event, but it is empty.
  2254. res = self._get_canonical_alias()
  2255. self.assertEqual(res, {})
  2256. def test_alt_aliases(self) -> None:
  2257. """Test a canonical alias message with alt_aliases."""
  2258. # Create an alias.
  2259. self._set_canonical_alias({"alt_aliases": [self.alias]})
  2260. # Canonical alias now exists!
  2261. res = self._get_canonical_alias()
  2262. self.assertEqual(res, {"alt_aliases": [self.alias]})
  2263. # Now remove the alt_aliases.
  2264. self._set_canonical_alias({})
  2265. # There is an alias event, but it is empty.
  2266. res = self._get_canonical_alias()
  2267. self.assertEqual(res, {})
  2268. def test_alias_alt_aliases(self) -> None:
  2269. """Test a canonical alias message with an alias and alt_aliases."""
  2270. # Create an alias.
  2271. self._set_canonical_alias({"alias": self.alias, "alt_aliases": [self.alias]})
  2272. # Canonical alias now exists!
  2273. res = self._get_canonical_alias()
  2274. self.assertEqual(res, {"alias": self.alias, "alt_aliases": [self.alias]})
  2275. # Now remove the alias and alt_aliases.
  2276. self._set_canonical_alias({})
  2277. # There is an alias event, but it is empty.
  2278. res = self._get_canonical_alias()
  2279. self.assertEqual(res, {})
  2280. def test_partial_modify(self) -> None:
  2281. """Test removing only the alt_aliases."""
  2282. # Create an alias.
  2283. self._set_canonical_alias({"alias": self.alias, "alt_aliases": [self.alias]})
  2284. # Canonical alias now exists!
  2285. res = self._get_canonical_alias()
  2286. self.assertEqual(res, {"alias": self.alias, "alt_aliases": [self.alias]})
  2287. # Now remove the alt_aliases.
  2288. self._set_canonical_alias({"alias": self.alias})
  2289. # There is an alias event, but it is empty.
  2290. res = self._get_canonical_alias()
  2291. self.assertEqual(res, {"alias": self.alias})
  2292. def test_add_alias(self) -> None:
  2293. """Test removing only the alt_aliases."""
  2294. # Create an additional alias.
  2295. second_alias = "#second:test"
  2296. self._set_alias_via_directory(second_alias)
  2297. # Add the canonical alias.
  2298. self._set_canonical_alias({"alias": self.alias, "alt_aliases": [self.alias]})
  2299. # Then add the second alias.
  2300. self._set_canonical_alias(
  2301. {"alias": self.alias, "alt_aliases": [self.alias, second_alias]}
  2302. )
  2303. # Canonical alias now exists!
  2304. res = self._get_canonical_alias()
  2305. self.assertEqual(
  2306. res, {"alias": self.alias, "alt_aliases": [self.alias, second_alias]}
  2307. )
  2308. def test_bad_data(self) -> None:
  2309. """Invalid data for alt_aliases should cause errors."""
  2310. self._set_canonical_alias({"alt_aliases": "@bad:test"}, expected_code=400)
  2311. self._set_canonical_alias({"alt_aliases": None}, expected_code=400)
  2312. self._set_canonical_alias({"alt_aliases": 0}, expected_code=400)
  2313. self._set_canonical_alias({"alt_aliases": 1}, expected_code=400)
  2314. self._set_canonical_alias({"alt_aliases": False}, expected_code=400)
  2315. self._set_canonical_alias({"alt_aliases": True}, expected_code=400)
  2316. self._set_canonical_alias({"alt_aliases": {}}, expected_code=400)
  2317. def test_bad_alias(self) -> None:
  2318. """An alias which does not point to the room raises a SynapseError."""
  2319. self._set_canonical_alias({"alias": "@unknown:test"}, expected_code=400)
  2320. self._set_canonical_alias({"alt_aliases": ["@unknown:test"]}, expected_code=400)
  2321. class ThreepidInviteTestCase(unittest.HomeserverTestCase):
  2322. servlets = [
  2323. admin.register_servlets,
  2324. login.register_servlets,
  2325. room.register_servlets,
  2326. ]
  2327. def prepare(self, reactor: MemoryReactor, clock: Clock, hs: HomeServer) -> None:
  2328. self.user_id = self.register_user("thomas", "hackme")
  2329. self.tok = self.login("thomas", "hackme")
  2330. self.room_id = self.helper.create_room_as(self.user_id, tok=self.tok)
  2331. def test_threepid_invite_spamcheck(self) -> None:
  2332. # Mock a few functions to prevent the test from failing due to failing to talk to
  2333. # a remote IS. We keep the mock for _mock_make_and_store_3pid_invite around so we
  2334. # can check its call_count later on during the test.
  2335. make_invite_mock = Mock(return_value=make_awaitable(0))
  2336. self.hs.get_room_member_handler()._make_and_store_3pid_invite = make_invite_mock
  2337. self.hs.get_identity_handler().lookup_3pid = Mock(
  2338. return_value=make_awaitable(None),
  2339. )
  2340. # Add a mock to the spamchecker callbacks for user_may_send_3pid_invite. Make it
  2341. # allow everything for now.
  2342. # `spec` argument is needed for this function mock to have `__qualname__`, which
  2343. # is needed for `Measure` metrics buried in SpamChecker.
  2344. mock = Mock(return_value=make_awaitable(True), spec=lambda *x: None)
  2345. self.hs.get_spam_checker()._user_may_send_3pid_invite_callbacks.append(mock)
  2346. # Send a 3PID invite into the room and check that it succeeded.
  2347. email_to_invite = "teresa@example.com"
  2348. channel = self.make_request(
  2349. method="POST",
  2350. path="/rooms/" + self.room_id + "/invite",
  2351. content={
  2352. "id_server": "example.com",
  2353. "id_access_token": "sometoken",
  2354. "medium": "email",
  2355. "address": email_to_invite,
  2356. },
  2357. access_token=self.tok,
  2358. )
  2359. self.assertEqual(channel.code, 200)
  2360. # Check that the callback was called with the right params.
  2361. mock.assert_called_with(self.user_id, "email", email_to_invite, self.room_id)
  2362. # Check that the call to send the invite was made.
  2363. make_invite_mock.assert_called_once()
  2364. # Now change the return value of the callback to deny any invite and test that
  2365. # we can't send the invite.
  2366. mock.return_value = make_awaitable(False)
  2367. channel = self.make_request(
  2368. method="POST",
  2369. path="/rooms/" + self.room_id + "/invite",
  2370. content={
  2371. "id_server": "example.com",
  2372. "id_access_token": "sometoken",
  2373. "medium": "email",
  2374. "address": email_to_invite,
  2375. },
  2376. access_token=self.tok,
  2377. )
  2378. self.assertEqual(channel.code, 403)
  2379. # Also check that it stopped before calling _make_and_store_3pid_invite.
  2380. make_invite_mock.assert_called_once()