test_rooms.py 73 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016
  1. # -*- coding: utf-8 -*-
  2. # Copyright 2014-2016 OpenMarket Ltd
  3. # Copyright 2017 Vector Creations Ltd
  4. # Copyright 2018-2019 New Vector Ltd
  5. # Copyright 2019 The Matrix.org Foundation C.I.C.
  6. #
  7. # Licensed under the Apache License, Version 2.0 (the "License");
  8. # you may not use this file except in compliance with the License.
  9. # You may obtain a copy of the License at
  10. #
  11. # http://www.apache.org/licenses/LICENSE-2.0
  12. #
  13. # Unless required by applicable law or agreed to in writing, software
  14. # distributed under the License is distributed on an "AS IS" BASIS,
  15. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  16. # See the License for the specific language governing permissions and
  17. # limitations under the License.
  18. """Tests REST events for /rooms paths."""
  19. import json
  20. from urllib import parse as urlparse
  21. from mock import Mock
  22. import synapse.rest.admin
  23. from synapse.api.constants import EventContentFields, EventTypes, Membership
  24. from synapse.handlers.pagination import PurgeStatus
  25. from synapse.rest import admin
  26. from synapse.rest.client.v1 import directory, login, profile, room
  27. from synapse.rest.client.v2_alpha import account
  28. from synapse.types import JsonDict, RoomAlias, UserID, create_requester
  29. from synapse.util.stringutils import random_string
  30. from tests import unittest
  31. from tests.test_utils import make_awaitable
  32. PATH_PREFIX = b"/_matrix/client/api/v1"
  33. class RoomBase(unittest.HomeserverTestCase):
  34. rmcreator_id = None
  35. servlets = [room.register_servlets, room.register_deprecated_servlets]
  36. def make_homeserver(self, reactor, clock):
  37. self.hs = self.setup_test_homeserver(
  38. "red", federation_http_client=None, federation_client=Mock(),
  39. )
  40. self.hs.get_federation_handler = Mock()
  41. self.hs.get_federation_handler.return_value.maybe_backfill = Mock(
  42. return_value=make_awaitable(None)
  43. )
  44. async def _insert_client_ip(*args, **kwargs):
  45. return None
  46. self.hs.get_datastore().insert_client_ip = _insert_client_ip
  47. return self.hs
  48. class RoomPermissionsTestCase(RoomBase):
  49. """ Tests room permissions. """
  50. user_id = "@sid1:red"
  51. rmcreator_id = "@notme:red"
  52. def prepare(self, reactor, clock, hs):
  53. self.helper.auth_user_id = self.rmcreator_id
  54. # create some rooms under the name rmcreator_id
  55. self.uncreated_rmid = "!aa:test"
  56. self.created_rmid = self.helper.create_room_as(
  57. self.rmcreator_id, is_public=False
  58. )
  59. self.created_public_rmid = self.helper.create_room_as(
  60. self.rmcreator_id, is_public=True
  61. )
  62. # send a message in one of the rooms
  63. self.created_rmid_msg_path = (
  64. "rooms/%s/send/m.room.message/a1" % (self.created_rmid)
  65. ).encode("ascii")
  66. channel = self.make_request(
  67. "PUT", self.created_rmid_msg_path, b'{"msgtype":"m.text","body":"test msg"}'
  68. )
  69. self.assertEquals(200, channel.code, channel.result)
  70. # set topic for public room
  71. channel = self.make_request(
  72. "PUT",
  73. ("rooms/%s/state/m.room.topic" % self.created_public_rmid).encode("ascii"),
  74. b'{"topic":"Public Room Topic"}',
  75. )
  76. self.assertEquals(200, channel.code, channel.result)
  77. # auth as user_id now
  78. self.helper.auth_user_id = self.user_id
  79. def test_can_do_action(self):
  80. msg_content = b'{"msgtype":"m.text","body":"hello"}'
  81. seq = iter(range(100))
  82. def send_msg_path():
  83. return "/rooms/%s/send/m.room.message/mid%s" % (
  84. self.created_rmid,
  85. str(next(seq)),
  86. )
  87. # send message in uncreated room, expect 403
  88. channel = self.make_request(
  89. "PUT",
  90. "/rooms/%s/send/m.room.message/mid2" % (self.uncreated_rmid,),
  91. msg_content,
  92. )
  93. self.assertEquals(403, channel.code, msg=channel.result["body"])
  94. # send message in created room not joined (no state), expect 403
  95. channel = self.make_request("PUT", send_msg_path(), msg_content)
  96. self.assertEquals(403, channel.code, msg=channel.result["body"])
  97. # send message in created room and invited, expect 403
  98. self.helper.invite(
  99. room=self.created_rmid, src=self.rmcreator_id, targ=self.user_id
  100. )
  101. channel = self.make_request("PUT", send_msg_path(), msg_content)
  102. self.assertEquals(403, channel.code, msg=channel.result["body"])
  103. # send message in created room and joined, expect 200
  104. self.helper.join(room=self.created_rmid, user=self.user_id)
  105. channel = self.make_request("PUT", send_msg_path(), msg_content)
  106. self.assertEquals(200, channel.code, msg=channel.result["body"])
  107. # send message in created room and left, expect 403
  108. self.helper.leave(room=self.created_rmid, user=self.user_id)
  109. channel = self.make_request("PUT", send_msg_path(), msg_content)
  110. self.assertEquals(403, channel.code, msg=channel.result["body"])
  111. def test_topic_perms(self):
  112. topic_content = b'{"topic":"My Topic Name"}'
  113. topic_path = "/rooms/%s/state/m.room.topic" % self.created_rmid
  114. # set/get topic in uncreated room, expect 403
  115. channel = self.make_request(
  116. "PUT", "/rooms/%s/state/m.room.topic" % self.uncreated_rmid, topic_content
  117. )
  118. self.assertEquals(403, channel.code, msg=channel.result["body"])
  119. channel = self.make_request(
  120. "GET", "/rooms/%s/state/m.room.topic" % self.uncreated_rmid
  121. )
  122. self.assertEquals(403, channel.code, msg=channel.result["body"])
  123. # set/get topic in created PRIVATE room not joined, expect 403
  124. channel = self.make_request("PUT", topic_path, topic_content)
  125. self.assertEquals(403, channel.code, msg=channel.result["body"])
  126. channel = self.make_request("GET", topic_path)
  127. self.assertEquals(403, channel.code, msg=channel.result["body"])
  128. # set topic in created PRIVATE room and invited, expect 403
  129. self.helper.invite(
  130. room=self.created_rmid, src=self.rmcreator_id, targ=self.user_id
  131. )
  132. channel = self.make_request("PUT", topic_path, topic_content)
  133. self.assertEquals(403, channel.code, msg=channel.result["body"])
  134. # get topic in created PRIVATE room and invited, expect 403
  135. channel = self.make_request("GET", topic_path)
  136. self.assertEquals(403, channel.code, msg=channel.result["body"])
  137. # set/get topic in created PRIVATE room and joined, expect 200
  138. self.helper.join(room=self.created_rmid, user=self.user_id)
  139. # Only room ops can set topic by default
  140. self.helper.auth_user_id = self.rmcreator_id
  141. channel = self.make_request("PUT", topic_path, topic_content)
  142. self.assertEquals(200, channel.code, msg=channel.result["body"])
  143. self.helper.auth_user_id = self.user_id
  144. channel = self.make_request("GET", topic_path)
  145. self.assertEquals(200, channel.code, msg=channel.result["body"])
  146. self.assert_dict(json.loads(topic_content.decode("utf8")), channel.json_body)
  147. # set/get topic in created PRIVATE room and left, expect 403
  148. self.helper.leave(room=self.created_rmid, user=self.user_id)
  149. channel = self.make_request("PUT", topic_path, topic_content)
  150. self.assertEquals(403, channel.code, msg=channel.result["body"])
  151. channel = self.make_request("GET", topic_path)
  152. self.assertEquals(200, channel.code, msg=channel.result["body"])
  153. # get topic in PUBLIC room, not joined, expect 403
  154. channel = self.make_request(
  155. "GET", "/rooms/%s/state/m.room.topic" % self.created_public_rmid
  156. )
  157. self.assertEquals(403, channel.code, msg=channel.result["body"])
  158. # set topic in PUBLIC room, not joined, expect 403
  159. channel = self.make_request(
  160. "PUT",
  161. "/rooms/%s/state/m.room.topic" % self.created_public_rmid,
  162. topic_content,
  163. )
  164. self.assertEquals(403, channel.code, msg=channel.result["body"])
  165. def _test_get_membership(self, room=None, members=[], expect_code=None):
  166. for member in members:
  167. path = "/rooms/%s/state/m.room.member/%s" % (room, member)
  168. channel = self.make_request("GET", path)
  169. self.assertEquals(expect_code, channel.code)
  170. def test_membership_basic_room_perms(self):
  171. # === room does not exist ===
  172. room = self.uncreated_rmid
  173. # get membership of self, get membership of other, uncreated room
  174. # expect all 403s
  175. self._test_get_membership(
  176. members=[self.user_id, self.rmcreator_id], room=room, expect_code=403
  177. )
  178. # trying to invite people to this room should 403
  179. self.helper.invite(
  180. room=room, src=self.user_id, targ=self.rmcreator_id, expect_code=403
  181. )
  182. # set [invite/join/left] of self, set [invite/join/left] of other,
  183. # expect all 404s because room doesn't exist on any server
  184. for usr in [self.user_id, self.rmcreator_id]:
  185. self.helper.join(room=room, user=usr, expect_code=404)
  186. self.helper.leave(room=room, user=usr, expect_code=404)
  187. def test_membership_private_room_perms(self):
  188. room = self.created_rmid
  189. # get membership of self, get membership of other, private room + invite
  190. # expect all 403s
  191. self.helper.invite(room=room, src=self.rmcreator_id, targ=self.user_id)
  192. self._test_get_membership(
  193. members=[self.user_id, self.rmcreator_id], room=room, expect_code=403
  194. )
  195. # get membership of self, get membership of other, private room + joined
  196. # expect all 200s
  197. self.helper.join(room=room, user=self.user_id)
  198. self._test_get_membership(
  199. members=[self.user_id, self.rmcreator_id], room=room, expect_code=200
  200. )
  201. # get membership of self, get membership of other, private room + left
  202. # expect all 200s
  203. self.helper.leave(room=room, user=self.user_id)
  204. self._test_get_membership(
  205. members=[self.user_id, self.rmcreator_id], room=room, expect_code=200
  206. )
  207. def test_membership_public_room_perms(self):
  208. room = self.created_public_rmid
  209. # get membership of self, get membership of other, public room + invite
  210. # expect 403
  211. self.helper.invite(room=room, src=self.rmcreator_id, targ=self.user_id)
  212. self._test_get_membership(
  213. members=[self.user_id, self.rmcreator_id], room=room, expect_code=403
  214. )
  215. # get membership of self, get membership of other, public room + joined
  216. # expect all 200s
  217. self.helper.join(room=room, user=self.user_id)
  218. self._test_get_membership(
  219. members=[self.user_id, self.rmcreator_id], room=room, expect_code=200
  220. )
  221. # get membership of self, get membership of other, public room + left
  222. # expect 200.
  223. self.helper.leave(room=room, user=self.user_id)
  224. self._test_get_membership(
  225. members=[self.user_id, self.rmcreator_id], room=room, expect_code=200
  226. )
  227. def test_invited_permissions(self):
  228. room = self.created_rmid
  229. self.helper.invite(room=room, src=self.rmcreator_id, targ=self.user_id)
  230. # set [invite/join/left] of other user, expect 403s
  231. self.helper.invite(
  232. room=room, src=self.user_id, targ=self.rmcreator_id, expect_code=403
  233. )
  234. self.helper.change_membership(
  235. room=room,
  236. src=self.user_id,
  237. targ=self.rmcreator_id,
  238. membership=Membership.JOIN,
  239. expect_code=403,
  240. )
  241. self.helper.change_membership(
  242. room=room,
  243. src=self.user_id,
  244. targ=self.rmcreator_id,
  245. membership=Membership.LEAVE,
  246. expect_code=403,
  247. )
  248. def test_joined_permissions(self):
  249. room = self.created_rmid
  250. self.helper.invite(room=room, src=self.rmcreator_id, targ=self.user_id)
  251. self.helper.join(room=room, user=self.user_id)
  252. # set invited of self, expect 403
  253. self.helper.invite(
  254. room=room, src=self.user_id, targ=self.user_id, expect_code=403
  255. )
  256. # set joined of self, expect 200 (NOOP)
  257. self.helper.join(room=room, user=self.user_id)
  258. other = "@burgundy:red"
  259. # set invited of other, expect 200
  260. self.helper.invite(room=room, src=self.user_id, targ=other, expect_code=200)
  261. # set joined of other, expect 403
  262. self.helper.change_membership(
  263. room=room,
  264. src=self.user_id,
  265. targ=other,
  266. membership=Membership.JOIN,
  267. expect_code=403,
  268. )
  269. # set left of other, expect 403
  270. self.helper.change_membership(
  271. room=room,
  272. src=self.user_id,
  273. targ=other,
  274. membership=Membership.LEAVE,
  275. expect_code=403,
  276. )
  277. # set left of self, expect 200
  278. self.helper.leave(room=room, user=self.user_id)
  279. def test_leave_permissions(self):
  280. room = self.created_rmid
  281. self.helper.invite(room=room, src=self.rmcreator_id, targ=self.user_id)
  282. self.helper.join(room=room, user=self.user_id)
  283. self.helper.leave(room=room, user=self.user_id)
  284. # set [invite/join/left] of self, set [invite/join/left] of other,
  285. # expect all 403s
  286. for usr in [self.user_id, self.rmcreator_id]:
  287. self.helper.change_membership(
  288. room=room,
  289. src=self.user_id,
  290. targ=usr,
  291. membership=Membership.INVITE,
  292. expect_code=403,
  293. )
  294. self.helper.change_membership(
  295. room=room,
  296. src=self.user_id,
  297. targ=usr,
  298. membership=Membership.JOIN,
  299. expect_code=403,
  300. )
  301. # It is always valid to LEAVE if you've already left (currently.)
  302. self.helper.change_membership(
  303. room=room,
  304. src=self.user_id,
  305. targ=self.rmcreator_id,
  306. membership=Membership.LEAVE,
  307. expect_code=403,
  308. )
  309. class RoomsMemberListTestCase(RoomBase):
  310. """ Tests /rooms/$room_id/members/list REST events."""
  311. user_id = "@sid1:red"
  312. def test_get_member_list(self):
  313. room_id = self.helper.create_room_as(self.user_id)
  314. channel = self.make_request("GET", "/rooms/%s/members" % room_id)
  315. self.assertEquals(200, channel.code, msg=channel.result["body"])
  316. def test_get_member_list_no_room(self):
  317. channel = self.make_request("GET", "/rooms/roomdoesnotexist/members")
  318. self.assertEquals(403, channel.code, msg=channel.result["body"])
  319. def test_get_member_list_no_permission(self):
  320. room_id = self.helper.create_room_as("@some_other_guy:red")
  321. channel = self.make_request("GET", "/rooms/%s/members" % room_id)
  322. self.assertEquals(403, channel.code, msg=channel.result["body"])
  323. def test_get_member_list_mixed_memberships(self):
  324. room_creator = "@some_other_guy:red"
  325. room_id = self.helper.create_room_as(room_creator)
  326. room_path = "/rooms/%s/members" % room_id
  327. self.helper.invite(room=room_id, src=room_creator, targ=self.user_id)
  328. # can't see list if you're just invited.
  329. channel = self.make_request("GET", room_path)
  330. self.assertEquals(403, channel.code, msg=channel.result["body"])
  331. self.helper.join(room=room_id, user=self.user_id)
  332. # can see list now joined
  333. channel = self.make_request("GET", room_path)
  334. self.assertEquals(200, channel.code, msg=channel.result["body"])
  335. self.helper.leave(room=room_id, user=self.user_id)
  336. # can see old list once left
  337. channel = self.make_request("GET", room_path)
  338. self.assertEquals(200, channel.code, msg=channel.result["body"])
  339. class RoomsCreateTestCase(RoomBase):
  340. """ Tests /rooms and /rooms/$room_id REST events. """
  341. user_id = "@sid1:red"
  342. def test_post_room_no_keys(self):
  343. # POST with no config keys, expect new room id
  344. channel = self.make_request("POST", "/createRoom", "{}")
  345. self.assertEquals(200, channel.code, channel.result)
  346. self.assertTrue("room_id" in channel.json_body)
  347. def test_post_room_visibility_key(self):
  348. # POST with visibility config key, expect new room id
  349. channel = self.make_request("POST", "/createRoom", b'{"visibility":"private"}')
  350. self.assertEquals(200, channel.code)
  351. self.assertTrue("room_id" in channel.json_body)
  352. def test_post_room_custom_key(self):
  353. # POST with custom config keys, expect new room id
  354. channel = self.make_request("POST", "/createRoom", b'{"custom":"stuff"}')
  355. self.assertEquals(200, channel.code)
  356. self.assertTrue("room_id" in channel.json_body)
  357. def test_post_room_known_and_unknown_keys(self):
  358. # POST with custom + known config keys, expect new room id
  359. channel = self.make_request(
  360. "POST", "/createRoom", b'{"visibility":"private","custom":"things"}'
  361. )
  362. self.assertEquals(200, channel.code)
  363. self.assertTrue("room_id" in channel.json_body)
  364. def test_post_room_invalid_content(self):
  365. # POST with invalid content / paths, expect 400
  366. channel = self.make_request("POST", "/createRoom", b'{"visibili')
  367. self.assertEquals(400, channel.code)
  368. channel = self.make_request("POST", "/createRoom", b'["hello"]')
  369. self.assertEquals(400, channel.code)
  370. def test_post_room_invitees_invalid_mxid(self):
  371. # POST with invalid invitee, see https://github.com/matrix-org/synapse/issues/4088
  372. # Note the trailing space in the MXID here!
  373. channel = self.make_request(
  374. "POST", "/createRoom", b'{"invite":["@alice:example.com "]}'
  375. )
  376. self.assertEquals(400, channel.code)
  377. class RoomTopicTestCase(RoomBase):
  378. """ Tests /rooms/$room_id/topic REST events. """
  379. user_id = "@sid1:red"
  380. def prepare(self, reactor, clock, hs):
  381. # create the room
  382. self.room_id = self.helper.create_room_as(self.user_id)
  383. self.path = "/rooms/%s/state/m.room.topic" % (self.room_id,)
  384. def test_invalid_puts(self):
  385. # missing keys or invalid json
  386. channel = self.make_request("PUT", self.path, "{}")
  387. self.assertEquals(400, channel.code, msg=channel.result["body"])
  388. channel = self.make_request("PUT", self.path, '{"_name":"bo"}')
  389. self.assertEquals(400, channel.code, msg=channel.result["body"])
  390. channel = self.make_request("PUT", self.path, '{"nao')
  391. self.assertEquals(400, channel.code, msg=channel.result["body"])
  392. channel = self.make_request(
  393. "PUT", self.path, '[{"_name":"bo"},{"_name":"jill"}]'
  394. )
  395. self.assertEquals(400, channel.code, msg=channel.result["body"])
  396. channel = self.make_request("PUT", self.path, "text only")
  397. self.assertEquals(400, channel.code, msg=channel.result["body"])
  398. channel = self.make_request("PUT", self.path, "")
  399. self.assertEquals(400, channel.code, msg=channel.result["body"])
  400. # valid key, wrong type
  401. content = '{"topic":["Topic name"]}'
  402. channel = self.make_request("PUT", self.path, content)
  403. self.assertEquals(400, channel.code, msg=channel.result["body"])
  404. def test_rooms_topic(self):
  405. # nothing should be there
  406. channel = self.make_request("GET", self.path)
  407. self.assertEquals(404, channel.code, msg=channel.result["body"])
  408. # valid put
  409. content = '{"topic":"Topic name"}'
  410. channel = self.make_request("PUT", self.path, content)
  411. self.assertEquals(200, channel.code, msg=channel.result["body"])
  412. # valid get
  413. channel = self.make_request("GET", self.path)
  414. self.assertEquals(200, channel.code, msg=channel.result["body"])
  415. self.assert_dict(json.loads(content), channel.json_body)
  416. def test_rooms_topic_with_extra_keys(self):
  417. # valid put with extra keys
  418. content = '{"topic":"Seasons","subtopic":"Summer"}'
  419. channel = self.make_request("PUT", self.path, content)
  420. self.assertEquals(200, channel.code, msg=channel.result["body"])
  421. # valid get
  422. channel = self.make_request("GET", self.path)
  423. self.assertEquals(200, channel.code, msg=channel.result["body"])
  424. self.assert_dict(json.loads(content), channel.json_body)
  425. class RoomMemberStateTestCase(RoomBase):
  426. """ Tests /rooms/$room_id/members/$user_id/state REST events. """
  427. user_id = "@sid1:red"
  428. def prepare(self, reactor, clock, hs):
  429. self.room_id = self.helper.create_room_as(self.user_id)
  430. def test_invalid_puts(self):
  431. path = "/rooms/%s/state/m.room.member/%s" % (self.room_id, self.user_id)
  432. # missing keys or invalid json
  433. channel = self.make_request("PUT", path, "{}")
  434. self.assertEquals(400, channel.code, msg=channel.result["body"])
  435. channel = self.make_request("PUT", path, '{"_name":"bo"}')
  436. self.assertEquals(400, channel.code, msg=channel.result["body"])
  437. channel = self.make_request("PUT", path, '{"nao')
  438. self.assertEquals(400, channel.code, msg=channel.result["body"])
  439. channel = self.make_request("PUT", path, b'[{"_name":"bo"},{"_name":"jill"}]')
  440. self.assertEquals(400, channel.code, msg=channel.result["body"])
  441. channel = self.make_request("PUT", path, "text only")
  442. self.assertEquals(400, channel.code, msg=channel.result["body"])
  443. channel = self.make_request("PUT", path, "")
  444. self.assertEquals(400, channel.code, msg=channel.result["body"])
  445. # valid keys, wrong types
  446. content = '{"membership":["%s","%s","%s"]}' % (
  447. Membership.INVITE,
  448. Membership.JOIN,
  449. Membership.LEAVE,
  450. )
  451. channel = self.make_request("PUT", path, content.encode("ascii"))
  452. self.assertEquals(400, channel.code, msg=channel.result["body"])
  453. def test_rooms_members_self(self):
  454. path = "/rooms/%s/state/m.room.member/%s" % (
  455. urlparse.quote(self.room_id),
  456. self.user_id,
  457. )
  458. # valid join message (NOOP since we made the room)
  459. content = '{"membership":"%s"}' % Membership.JOIN
  460. channel = self.make_request("PUT", path, content.encode("ascii"))
  461. self.assertEquals(200, channel.code, msg=channel.result["body"])
  462. channel = self.make_request("GET", path, None)
  463. self.assertEquals(200, channel.code, msg=channel.result["body"])
  464. expected_response = {"membership": Membership.JOIN}
  465. self.assertEquals(expected_response, channel.json_body)
  466. def test_rooms_members_other(self):
  467. self.other_id = "@zzsid1:red"
  468. path = "/rooms/%s/state/m.room.member/%s" % (
  469. urlparse.quote(self.room_id),
  470. self.other_id,
  471. )
  472. # valid invite message
  473. content = '{"membership":"%s"}' % Membership.INVITE
  474. channel = self.make_request("PUT", path, content)
  475. self.assertEquals(200, channel.code, msg=channel.result["body"])
  476. channel = self.make_request("GET", path, None)
  477. self.assertEquals(200, channel.code, msg=channel.result["body"])
  478. self.assertEquals(json.loads(content), channel.json_body)
  479. def test_rooms_members_other_custom_keys(self):
  480. self.other_id = "@zzsid1:red"
  481. path = "/rooms/%s/state/m.room.member/%s" % (
  482. urlparse.quote(self.room_id),
  483. self.other_id,
  484. )
  485. # valid invite message with custom key
  486. content = '{"membership":"%s","invite_text":"%s"}' % (
  487. Membership.INVITE,
  488. "Join us!",
  489. )
  490. channel = self.make_request("PUT", path, content)
  491. self.assertEquals(200, channel.code, msg=channel.result["body"])
  492. channel = self.make_request("GET", path, None)
  493. self.assertEquals(200, channel.code, msg=channel.result["body"])
  494. self.assertEquals(json.loads(content), channel.json_body)
  495. class RoomInviteRatelimitTestCase(RoomBase):
  496. user_id = "@sid1:red"
  497. servlets = [
  498. admin.register_servlets,
  499. profile.register_servlets,
  500. room.register_servlets,
  501. ]
  502. @unittest.override_config(
  503. {"rc_invites": {"per_room": {"per_second": 0.5, "burst_count": 3}}}
  504. )
  505. def test_invites_by_rooms_ratelimit(self):
  506. """Tests that invites in a room are actually rate-limited."""
  507. room_id = self.helper.create_room_as(self.user_id)
  508. for i in range(3):
  509. self.helper.invite(room_id, self.user_id, "@user-%s:red" % (i,))
  510. self.helper.invite(room_id, self.user_id, "@user-4:red", expect_code=429)
  511. @unittest.override_config(
  512. {"rc_invites": {"per_user": {"per_second": 0.5, "burst_count": 3}}}
  513. )
  514. def test_invites_by_users_ratelimit(self):
  515. """Tests that invites to a specific user are actually rate-limited."""
  516. for i in range(3):
  517. room_id = self.helper.create_room_as(self.user_id)
  518. self.helper.invite(room_id, self.user_id, "@other-users:red")
  519. room_id = self.helper.create_room_as(self.user_id)
  520. self.helper.invite(room_id, self.user_id, "@other-users:red", expect_code=429)
  521. class RoomJoinRatelimitTestCase(RoomBase):
  522. user_id = "@sid1:red"
  523. servlets = [
  524. admin.register_servlets,
  525. profile.register_servlets,
  526. room.register_servlets,
  527. ]
  528. @unittest.override_config(
  529. {"rc_joins": {"local": {"per_second": 0.5, "burst_count": 3}}}
  530. )
  531. def test_join_local_ratelimit(self):
  532. """Tests that local joins are actually rate-limited."""
  533. for i in range(3):
  534. self.helper.create_room_as(self.user_id)
  535. self.helper.create_room_as(self.user_id, expect_code=429)
  536. @unittest.override_config(
  537. {"rc_joins": {"local": {"per_second": 0.5, "burst_count": 3}}}
  538. )
  539. def test_join_local_ratelimit_profile_change(self):
  540. """Tests that sending a profile update into all of the user's joined rooms isn't
  541. rate-limited by the rate-limiter on joins."""
  542. # Create and join as many rooms as the rate-limiting config allows in a second.
  543. room_ids = [
  544. self.helper.create_room_as(self.user_id),
  545. self.helper.create_room_as(self.user_id),
  546. self.helper.create_room_as(self.user_id),
  547. ]
  548. # Let some time for the rate-limiter to forget about our multi-join.
  549. self.reactor.advance(2)
  550. # Add one to make sure we're joined to more rooms than the config allows us to
  551. # join in a second.
  552. room_ids.append(self.helper.create_room_as(self.user_id))
  553. # Create a profile for the user, since it hasn't been done on registration.
  554. store = self.hs.get_datastore()
  555. self.get_success(
  556. store.create_profile(UserID.from_string(self.user_id).localpart)
  557. )
  558. # Update the display name for the user.
  559. path = "/_matrix/client/r0/profile/%s/displayname" % self.user_id
  560. channel = self.make_request("PUT", path, {"displayname": "John Doe"})
  561. self.assertEquals(channel.code, 200, channel.json_body)
  562. # Check that all the rooms have been sent a profile update into.
  563. for room_id in room_ids:
  564. path = "/_matrix/client/r0/rooms/%s/state/m.room.member/%s" % (
  565. room_id,
  566. self.user_id,
  567. )
  568. channel = self.make_request("GET", path)
  569. self.assertEquals(channel.code, 200)
  570. self.assertIn("displayname", channel.json_body)
  571. self.assertEquals(channel.json_body["displayname"], "John Doe")
  572. @unittest.override_config(
  573. {"rc_joins": {"local": {"per_second": 0.5, "burst_count": 3}}}
  574. )
  575. def test_join_local_ratelimit_idempotent(self):
  576. """Tests that the room join endpoints remain idempotent despite rate-limiting
  577. on room joins."""
  578. room_id = self.helper.create_room_as(self.user_id)
  579. # Let's test both paths to be sure.
  580. paths_to_test = [
  581. "/_matrix/client/r0/rooms/%s/join",
  582. "/_matrix/client/r0/join/%s",
  583. ]
  584. for path in paths_to_test:
  585. # Make sure we send more requests than the rate-limiting config would allow
  586. # if all of these requests ended up joining the user to a room.
  587. for i in range(4):
  588. channel = self.make_request("POST", path % room_id, {})
  589. self.assertEquals(channel.code, 200)
  590. @unittest.override_config(
  591. {
  592. "rc_joins": {"local": {"per_second": 0.5, "burst_count": 3}},
  593. "auto_join_rooms": ["#room:red", "#room2:red", "#room3:red", "#room4:red"],
  594. "autocreate_auto_join_rooms": True,
  595. },
  596. )
  597. def test_autojoin_rooms(self):
  598. user_id = self.register_user("testuser", "password")
  599. # Check that the new user successfully joined the four rooms
  600. rooms = self.get_success(self.hs.get_datastore().get_rooms_for_user(user_id))
  601. self.assertEqual(len(rooms), 4)
  602. class RoomMessagesTestCase(RoomBase):
  603. """ Tests /rooms/$room_id/messages/$user_id/$msg_id REST events. """
  604. user_id = "@sid1:red"
  605. def prepare(self, reactor, clock, hs):
  606. self.room_id = self.helper.create_room_as(self.user_id)
  607. def test_invalid_puts(self):
  608. path = "/rooms/%s/send/m.room.message/mid1" % (urlparse.quote(self.room_id))
  609. # missing keys or invalid json
  610. channel = self.make_request("PUT", path, b"{}")
  611. self.assertEquals(400, channel.code, msg=channel.result["body"])
  612. channel = self.make_request("PUT", path, b'{"_name":"bo"}')
  613. self.assertEquals(400, channel.code, msg=channel.result["body"])
  614. channel = self.make_request("PUT", path, b'{"nao')
  615. self.assertEquals(400, channel.code, msg=channel.result["body"])
  616. channel = self.make_request("PUT", path, b'[{"_name":"bo"},{"_name":"jill"}]')
  617. self.assertEquals(400, channel.code, msg=channel.result["body"])
  618. channel = self.make_request("PUT", path, b"text only")
  619. self.assertEquals(400, channel.code, msg=channel.result["body"])
  620. channel = self.make_request("PUT", path, b"")
  621. self.assertEquals(400, channel.code, msg=channel.result["body"])
  622. def test_rooms_messages_sent(self):
  623. path = "/rooms/%s/send/m.room.message/mid1" % (urlparse.quote(self.room_id))
  624. content = b'{"body":"test","msgtype":{"type":"a"}}'
  625. channel = self.make_request("PUT", path, content)
  626. self.assertEquals(400, channel.code, msg=channel.result["body"])
  627. # custom message types
  628. content = b'{"body":"test","msgtype":"test.custom.text"}'
  629. channel = self.make_request("PUT", path, content)
  630. self.assertEquals(200, channel.code, msg=channel.result["body"])
  631. # m.text message type
  632. path = "/rooms/%s/send/m.room.message/mid2" % (urlparse.quote(self.room_id))
  633. content = b'{"body":"test2","msgtype":"m.text"}'
  634. channel = self.make_request("PUT", path, content)
  635. self.assertEquals(200, channel.code, msg=channel.result["body"])
  636. class RoomInitialSyncTestCase(RoomBase):
  637. """ Tests /rooms/$room_id/initialSync. """
  638. user_id = "@sid1:red"
  639. def prepare(self, reactor, clock, hs):
  640. # create the room
  641. self.room_id = self.helper.create_room_as(self.user_id)
  642. def test_initial_sync(self):
  643. channel = self.make_request("GET", "/rooms/%s/initialSync" % self.room_id)
  644. self.assertEquals(200, channel.code)
  645. self.assertEquals(self.room_id, channel.json_body["room_id"])
  646. self.assertEquals("join", channel.json_body["membership"])
  647. # Room state is easier to assert on if we unpack it into a dict
  648. state = {}
  649. for event in channel.json_body["state"]:
  650. if "state_key" not in event:
  651. continue
  652. t = event["type"]
  653. if t not in state:
  654. state[t] = []
  655. state[t].append(event)
  656. self.assertTrue("m.room.create" in state)
  657. self.assertTrue("messages" in channel.json_body)
  658. self.assertTrue("chunk" in channel.json_body["messages"])
  659. self.assertTrue("end" in channel.json_body["messages"])
  660. self.assertTrue("presence" in channel.json_body)
  661. presence_by_user = {
  662. e["content"]["user_id"]: e for e in channel.json_body["presence"]
  663. }
  664. self.assertTrue(self.user_id in presence_by_user)
  665. self.assertEquals("m.presence", presence_by_user[self.user_id]["type"])
  666. class RoomMessageListTestCase(RoomBase):
  667. """ Tests /rooms/$room_id/messages REST events. """
  668. user_id = "@sid1:red"
  669. def prepare(self, reactor, clock, hs):
  670. self.room_id = self.helper.create_room_as(self.user_id)
  671. def test_topo_token_is_accepted(self):
  672. token = "t1-0_0_0_0_0_0_0_0_0"
  673. channel = self.make_request(
  674. "GET", "/rooms/%s/messages?access_token=x&from=%s" % (self.room_id, token)
  675. )
  676. self.assertEquals(200, channel.code)
  677. self.assertTrue("start" in channel.json_body)
  678. self.assertEquals(token, channel.json_body["start"])
  679. self.assertTrue("chunk" in channel.json_body)
  680. self.assertTrue("end" in channel.json_body)
  681. def test_stream_token_is_accepted_for_fwd_pagianation(self):
  682. token = "s0_0_0_0_0_0_0_0_0"
  683. channel = self.make_request(
  684. "GET", "/rooms/%s/messages?access_token=x&from=%s" % (self.room_id, token)
  685. )
  686. self.assertEquals(200, channel.code)
  687. self.assertTrue("start" in channel.json_body)
  688. self.assertEquals(token, channel.json_body["start"])
  689. self.assertTrue("chunk" in channel.json_body)
  690. self.assertTrue("end" in channel.json_body)
  691. def test_room_messages_purge(self):
  692. store = self.hs.get_datastore()
  693. pagination_handler = self.hs.get_pagination_handler()
  694. # Send a first message in the room, which will be removed by the purge.
  695. first_event_id = self.helper.send(self.room_id, "message 1")["event_id"]
  696. first_token = self.get_success(
  697. store.get_topological_token_for_event(first_event_id)
  698. )
  699. first_token_str = self.get_success(first_token.to_string(store))
  700. # Send a second message in the room, which won't be removed, and which we'll
  701. # use as the marker to purge events before.
  702. second_event_id = self.helper.send(self.room_id, "message 2")["event_id"]
  703. second_token = self.get_success(
  704. store.get_topological_token_for_event(second_event_id)
  705. )
  706. second_token_str = self.get_success(second_token.to_string(store))
  707. # Send a third event in the room to ensure we don't fall under any edge case
  708. # due to our marker being the latest forward extremity in the room.
  709. self.helper.send(self.room_id, "message 3")
  710. # Check that we get the first and second message when querying /messages.
  711. channel = self.make_request(
  712. "GET",
  713. "/rooms/%s/messages?access_token=x&from=%s&dir=b&filter=%s"
  714. % (
  715. self.room_id,
  716. second_token_str,
  717. json.dumps({"types": [EventTypes.Message]}),
  718. ),
  719. )
  720. self.assertEqual(channel.code, 200, channel.json_body)
  721. chunk = channel.json_body["chunk"]
  722. self.assertEqual(len(chunk), 2, [event["content"] for event in chunk])
  723. # Purge every event before the second event.
  724. purge_id = random_string(16)
  725. pagination_handler._purges_by_id[purge_id] = PurgeStatus()
  726. self.get_success(
  727. pagination_handler._purge_history(
  728. purge_id=purge_id,
  729. room_id=self.room_id,
  730. token=second_token_str,
  731. delete_local_events=True,
  732. )
  733. )
  734. # Check that we only get the second message through /message now that the first
  735. # has been purged.
  736. channel = self.make_request(
  737. "GET",
  738. "/rooms/%s/messages?access_token=x&from=%s&dir=b&filter=%s"
  739. % (
  740. self.room_id,
  741. second_token_str,
  742. json.dumps({"types": [EventTypes.Message]}),
  743. ),
  744. )
  745. self.assertEqual(channel.code, 200, channel.json_body)
  746. chunk = channel.json_body["chunk"]
  747. self.assertEqual(len(chunk), 1, [event["content"] for event in chunk])
  748. # Check that we get no event, but also no error, when querying /messages with
  749. # the token that was pointing at the first event, because we don't have it
  750. # anymore.
  751. channel = self.make_request(
  752. "GET",
  753. "/rooms/%s/messages?access_token=x&from=%s&dir=b&filter=%s"
  754. % (
  755. self.room_id,
  756. first_token_str,
  757. json.dumps({"types": [EventTypes.Message]}),
  758. ),
  759. )
  760. self.assertEqual(channel.code, 200, channel.json_body)
  761. chunk = channel.json_body["chunk"]
  762. self.assertEqual(len(chunk), 0, [event["content"] for event in chunk])
  763. class RoomSearchTestCase(unittest.HomeserverTestCase):
  764. servlets = [
  765. synapse.rest.admin.register_servlets_for_client_rest_resource,
  766. room.register_servlets,
  767. login.register_servlets,
  768. ]
  769. user_id = True
  770. hijack_auth = False
  771. def prepare(self, reactor, clock, hs):
  772. # Register the user who does the searching
  773. self.user_id = self.register_user("user", "pass")
  774. self.access_token = self.login("user", "pass")
  775. # Register the user who sends the message
  776. self.other_user_id = self.register_user("otheruser", "pass")
  777. self.other_access_token = self.login("otheruser", "pass")
  778. # Create a room
  779. self.room = self.helper.create_room_as(self.user_id, tok=self.access_token)
  780. # Invite the other person
  781. self.helper.invite(
  782. room=self.room,
  783. src=self.user_id,
  784. tok=self.access_token,
  785. targ=self.other_user_id,
  786. )
  787. # The other user joins
  788. self.helper.join(
  789. room=self.room, user=self.other_user_id, tok=self.other_access_token
  790. )
  791. def test_finds_message(self):
  792. """
  793. The search functionality will search for content in messages if asked to
  794. do so.
  795. """
  796. # The other user sends some messages
  797. self.helper.send(self.room, body="Hi!", tok=self.other_access_token)
  798. self.helper.send(self.room, body="There!", tok=self.other_access_token)
  799. channel = self.make_request(
  800. "POST",
  801. "/search?access_token=%s" % (self.access_token,),
  802. {
  803. "search_categories": {
  804. "room_events": {"keys": ["content.body"], "search_term": "Hi"}
  805. }
  806. },
  807. )
  808. # Check we get the results we expect -- one search result, of the sent
  809. # messages
  810. self.assertEqual(channel.code, 200)
  811. results = channel.json_body["search_categories"]["room_events"]
  812. self.assertEqual(results["count"], 1)
  813. self.assertEqual(results["results"][0]["result"]["content"]["body"], "Hi!")
  814. # No context was requested, so we should get none.
  815. self.assertEqual(results["results"][0]["context"], {})
  816. def test_include_context(self):
  817. """
  818. When event_context includes include_profile, profile information will be
  819. included in the search response.
  820. """
  821. # The other user sends some messages
  822. self.helper.send(self.room, body="Hi!", tok=self.other_access_token)
  823. self.helper.send(self.room, body="There!", tok=self.other_access_token)
  824. channel = self.make_request(
  825. "POST",
  826. "/search?access_token=%s" % (self.access_token,),
  827. {
  828. "search_categories": {
  829. "room_events": {
  830. "keys": ["content.body"],
  831. "search_term": "Hi",
  832. "event_context": {"include_profile": True},
  833. }
  834. }
  835. },
  836. )
  837. # Check we get the results we expect -- one search result, of the sent
  838. # messages
  839. self.assertEqual(channel.code, 200)
  840. results = channel.json_body["search_categories"]["room_events"]
  841. self.assertEqual(results["count"], 1)
  842. self.assertEqual(results["results"][0]["result"]["content"]["body"], "Hi!")
  843. # We should get context info, like the two users, and the display names.
  844. context = results["results"][0]["context"]
  845. self.assertEqual(len(context["profile_info"].keys()), 2)
  846. self.assertEqual(
  847. context["profile_info"][self.other_user_id]["displayname"], "otheruser"
  848. )
  849. class PublicRoomsRestrictedTestCase(unittest.HomeserverTestCase):
  850. servlets = [
  851. synapse.rest.admin.register_servlets_for_client_rest_resource,
  852. room.register_servlets,
  853. login.register_servlets,
  854. ]
  855. def make_homeserver(self, reactor, clock):
  856. self.url = b"/_matrix/client/r0/publicRooms"
  857. config = self.default_config()
  858. config["allow_public_rooms_without_auth"] = False
  859. self.hs = self.setup_test_homeserver(config=config)
  860. return self.hs
  861. def test_restricted_no_auth(self):
  862. channel = self.make_request("GET", self.url)
  863. self.assertEqual(channel.code, 401, channel.result)
  864. def test_restricted_auth(self):
  865. self.register_user("user", "pass")
  866. tok = self.login("user", "pass")
  867. channel = self.make_request("GET", self.url, access_token=tok)
  868. self.assertEqual(channel.code, 200, channel.result)
  869. class PerRoomProfilesForbiddenTestCase(unittest.HomeserverTestCase):
  870. servlets = [
  871. synapse.rest.admin.register_servlets_for_client_rest_resource,
  872. room.register_servlets,
  873. login.register_servlets,
  874. profile.register_servlets,
  875. ]
  876. def make_homeserver(self, reactor, clock):
  877. config = self.default_config()
  878. config["allow_per_room_profiles"] = False
  879. self.hs = self.setup_test_homeserver(config=config)
  880. return self.hs
  881. def prepare(self, reactor, clock, homeserver):
  882. self.user_id = self.register_user("test", "test")
  883. self.tok = self.login("test", "test")
  884. # Set a profile for the test user
  885. self.displayname = "test user"
  886. data = {"displayname": self.displayname}
  887. request_data = json.dumps(data)
  888. channel = self.make_request(
  889. "PUT",
  890. "/_matrix/client/r0/profile/%s/displayname" % (self.user_id,),
  891. request_data,
  892. access_token=self.tok,
  893. )
  894. self.assertEqual(channel.code, 200, channel.result)
  895. self.room_id = self.helper.create_room_as(self.user_id, tok=self.tok)
  896. def test_per_room_profile_forbidden(self):
  897. data = {"membership": "join", "displayname": "other test user"}
  898. request_data = json.dumps(data)
  899. channel = self.make_request(
  900. "PUT",
  901. "/_matrix/client/r0/rooms/%s/state/m.room.member/%s"
  902. % (self.room_id, self.user_id),
  903. request_data,
  904. access_token=self.tok,
  905. )
  906. self.assertEqual(channel.code, 200, channel.result)
  907. event_id = channel.json_body["event_id"]
  908. channel = self.make_request(
  909. "GET",
  910. "/_matrix/client/r0/rooms/%s/event/%s" % (self.room_id, event_id),
  911. access_token=self.tok,
  912. )
  913. self.assertEqual(channel.code, 200, channel.result)
  914. res_displayname = channel.json_body["content"]["displayname"]
  915. self.assertEqual(res_displayname, self.displayname, channel.result)
  916. class RoomMembershipReasonTestCase(unittest.HomeserverTestCase):
  917. """Tests that clients can add a "reason" field to membership events and
  918. that they get correctly added to the generated events and propagated.
  919. """
  920. servlets = [
  921. synapse.rest.admin.register_servlets_for_client_rest_resource,
  922. room.register_servlets,
  923. login.register_servlets,
  924. ]
  925. def prepare(self, reactor, clock, homeserver):
  926. self.creator = self.register_user("creator", "test")
  927. self.creator_tok = self.login("creator", "test")
  928. self.second_user_id = self.register_user("second", "test")
  929. self.second_tok = self.login("second", "test")
  930. self.room_id = self.helper.create_room_as(self.creator, tok=self.creator_tok)
  931. def test_join_reason(self):
  932. reason = "hello"
  933. channel = self.make_request(
  934. "POST",
  935. "/_matrix/client/r0/rooms/{}/join".format(self.room_id),
  936. content={"reason": reason},
  937. access_token=self.second_tok,
  938. )
  939. self.assertEqual(channel.code, 200, channel.result)
  940. self._check_for_reason(reason)
  941. def test_leave_reason(self):
  942. self.helper.join(self.room_id, user=self.second_user_id, tok=self.second_tok)
  943. reason = "hello"
  944. channel = self.make_request(
  945. "POST",
  946. "/_matrix/client/r0/rooms/{}/leave".format(self.room_id),
  947. content={"reason": reason},
  948. access_token=self.second_tok,
  949. )
  950. self.assertEqual(channel.code, 200, channel.result)
  951. self._check_for_reason(reason)
  952. def test_kick_reason(self):
  953. self.helper.join(self.room_id, user=self.second_user_id, tok=self.second_tok)
  954. reason = "hello"
  955. channel = self.make_request(
  956. "POST",
  957. "/_matrix/client/r0/rooms/{}/kick".format(self.room_id),
  958. content={"reason": reason, "user_id": self.second_user_id},
  959. access_token=self.second_tok,
  960. )
  961. self.assertEqual(channel.code, 200, channel.result)
  962. self._check_for_reason(reason)
  963. def test_ban_reason(self):
  964. self.helper.join(self.room_id, user=self.second_user_id, tok=self.second_tok)
  965. reason = "hello"
  966. channel = self.make_request(
  967. "POST",
  968. "/_matrix/client/r0/rooms/{}/ban".format(self.room_id),
  969. content={"reason": reason, "user_id": self.second_user_id},
  970. access_token=self.creator_tok,
  971. )
  972. self.assertEqual(channel.code, 200, channel.result)
  973. self._check_for_reason(reason)
  974. def test_unban_reason(self):
  975. reason = "hello"
  976. channel = self.make_request(
  977. "POST",
  978. "/_matrix/client/r0/rooms/{}/unban".format(self.room_id),
  979. content={"reason": reason, "user_id": self.second_user_id},
  980. access_token=self.creator_tok,
  981. )
  982. self.assertEqual(channel.code, 200, channel.result)
  983. self._check_for_reason(reason)
  984. def test_invite_reason(self):
  985. reason = "hello"
  986. channel = self.make_request(
  987. "POST",
  988. "/_matrix/client/r0/rooms/{}/invite".format(self.room_id),
  989. content={"reason": reason, "user_id": self.second_user_id},
  990. access_token=self.creator_tok,
  991. )
  992. self.assertEqual(channel.code, 200, channel.result)
  993. self._check_for_reason(reason)
  994. def test_reject_invite_reason(self):
  995. self.helper.invite(
  996. self.room_id,
  997. src=self.creator,
  998. targ=self.second_user_id,
  999. tok=self.creator_tok,
  1000. )
  1001. reason = "hello"
  1002. channel = self.make_request(
  1003. "POST",
  1004. "/_matrix/client/r0/rooms/{}/leave".format(self.room_id),
  1005. content={"reason": reason},
  1006. access_token=self.second_tok,
  1007. )
  1008. self.assertEqual(channel.code, 200, channel.result)
  1009. self._check_for_reason(reason)
  1010. def _check_for_reason(self, reason):
  1011. channel = self.make_request(
  1012. "GET",
  1013. "/_matrix/client/r0/rooms/{}/state/m.room.member/{}".format(
  1014. self.room_id, self.second_user_id
  1015. ),
  1016. access_token=self.creator_tok,
  1017. )
  1018. self.assertEqual(channel.code, 200, channel.result)
  1019. event_content = channel.json_body
  1020. self.assertEqual(event_content.get("reason"), reason, channel.result)
  1021. class LabelsTestCase(unittest.HomeserverTestCase):
  1022. servlets = [
  1023. synapse.rest.admin.register_servlets_for_client_rest_resource,
  1024. room.register_servlets,
  1025. login.register_servlets,
  1026. profile.register_servlets,
  1027. ]
  1028. # Filter that should only catch messages with the label "#fun".
  1029. FILTER_LABELS = {
  1030. "types": [EventTypes.Message],
  1031. "org.matrix.labels": ["#fun"],
  1032. }
  1033. # Filter that should only catch messages without the label "#fun".
  1034. FILTER_NOT_LABELS = {
  1035. "types": [EventTypes.Message],
  1036. "org.matrix.not_labels": ["#fun"],
  1037. }
  1038. # Filter that should only catch messages with the label "#work" but without the label
  1039. # "#notfun".
  1040. FILTER_LABELS_NOT_LABELS = {
  1041. "types": [EventTypes.Message],
  1042. "org.matrix.labels": ["#work"],
  1043. "org.matrix.not_labels": ["#notfun"],
  1044. }
  1045. def prepare(self, reactor, clock, homeserver):
  1046. self.user_id = self.register_user("test", "test")
  1047. self.tok = self.login("test", "test")
  1048. self.room_id = self.helper.create_room_as(self.user_id, tok=self.tok)
  1049. def test_context_filter_labels(self):
  1050. """Test that we can filter by a label on a /context request."""
  1051. event_id = self._send_labelled_messages_in_room()
  1052. channel = self.make_request(
  1053. "GET",
  1054. "/rooms/%s/context/%s?filter=%s"
  1055. % (self.room_id, event_id, json.dumps(self.FILTER_LABELS)),
  1056. access_token=self.tok,
  1057. )
  1058. self.assertEqual(channel.code, 200, channel.result)
  1059. events_before = channel.json_body["events_before"]
  1060. self.assertEqual(
  1061. len(events_before), 1, [event["content"] for event in events_before]
  1062. )
  1063. self.assertEqual(
  1064. events_before[0]["content"]["body"], "with right label", events_before[0]
  1065. )
  1066. events_after = channel.json_body["events_before"]
  1067. self.assertEqual(
  1068. len(events_after), 1, [event["content"] for event in events_after]
  1069. )
  1070. self.assertEqual(
  1071. events_after[0]["content"]["body"], "with right label", events_after[0]
  1072. )
  1073. def test_context_filter_not_labels(self):
  1074. """Test that we can filter by the absence of a label on a /context request."""
  1075. event_id = self._send_labelled_messages_in_room()
  1076. channel = self.make_request(
  1077. "GET",
  1078. "/rooms/%s/context/%s?filter=%s"
  1079. % (self.room_id, event_id, json.dumps(self.FILTER_NOT_LABELS)),
  1080. access_token=self.tok,
  1081. )
  1082. self.assertEqual(channel.code, 200, channel.result)
  1083. events_before = channel.json_body["events_before"]
  1084. self.assertEqual(
  1085. len(events_before), 1, [event["content"] for event in events_before]
  1086. )
  1087. self.assertEqual(
  1088. events_before[0]["content"]["body"], "without label", events_before[0]
  1089. )
  1090. events_after = channel.json_body["events_after"]
  1091. self.assertEqual(
  1092. len(events_after), 2, [event["content"] for event in events_after]
  1093. )
  1094. self.assertEqual(
  1095. events_after[0]["content"]["body"], "with wrong label", events_after[0]
  1096. )
  1097. self.assertEqual(
  1098. events_after[1]["content"]["body"], "with two wrong labels", events_after[1]
  1099. )
  1100. def test_context_filter_labels_not_labels(self):
  1101. """Test that we can filter by both a label and the absence of another label on a
  1102. /context request.
  1103. """
  1104. event_id = self._send_labelled_messages_in_room()
  1105. channel = self.make_request(
  1106. "GET",
  1107. "/rooms/%s/context/%s?filter=%s"
  1108. % (self.room_id, event_id, json.dumps(self.FILTER_LABELS_NOT_LABELS)),
  1109. access_token=self.tok,
  1110. )
  1111. self.assertEqual(channel.code, 200, channel.result)
  1112. events_before = channel.json_body["events_before"]
  1113. self.assertEqual(
  1114. len(events_before), 0, [event["content"] for event in events_before]
  1115. )
  1116. events_after = channel.json_body["events_after"]
  1117. self.assertEqual(
  1118. len(events_after), 1, [event["content"] for event in events_after]
  1119. )
  1120. self.assertEqual(
  1121. events_after[0]["content"]["body"], "with wrong label", events_after[0]
  1122. )
  1123. def test_messages_filter_labels(self):
  1124. """Test that we can filter by a label on a /messages request."""
  1125. self._send_labelled_messages_in_room()
  1126. token = "s0_0_0_0_0_0_0_0_0"
  1127. channel = self.make_request(
  1128. "GET",
  1129. "/rooms/%s/messages?access_token=%s&from=%s&filter=%s"
  1130. % (self.room_id, self.tok, token, json.dumps(self.FILTER_LABELS)),
  1131. )
  1132. events = channel.json_body["chunk"]
  1133. self.assertEqual(len(events), 2, [event["content"] for event in events])
  1134. self.assertEqual(events[0]["content"]["body"], "with right label", events[0])
  1135. self.assertEqual(events[1]["content"]["body"], "with right label", events[1])
  1136. def test_messages_filter_not_labels(self):
  1137. """Test that we can filter by the absence of a label on a /messages request."""
  1138. self._send_labelled_messages_in_room()
  1139. token = "s0_0_0_0_0_0_0_0_0"
  1140. channel = self.make_request(
  1141. "GET",
  1142. "/rooms/%s/messages?access_token=%s&from=%s&filter=%s"
  1143. % (self.room_id, self.tok, token, json.dumps(self.FILTER_NOT_LABELS)),
  1144. )
  1145. events = channel.json_body["chunk"]
  1146. self.assertEqual(len(events), 4, [event["content"] for event in events])
  1147. self.assertEqual(events[0]["content"]["body"], "without label", events[0])
  1148. self.assertEqual(events[1]["content"]["body"], "without label", events[1])
  1149. self.assertEqual(events[2]["content"]["body"], "with wrong label", events[2])
  1150. self.assertEqual(
  1151. events[3]["content"]["body"], "with two wrong labels", events[3]
  1152. )
  1153. def test_messages_filter_labels_not_labels(self):
  1154. """Test that we can filter by both a label and the absence of another label on a
  1155. /messages request.
  1156. """
  1157. self._send_labelled_messages_in_room()
  1158. token = "s0_0_0_0_0_0_0_0_0"
  1159. channel = self.make_request(
  1160. "GET",
  1161. "/rooms/%s/messages?access_token=%s&from=%s&filter=%s"
  1162. % (
  1163. self.room_id,
  1164. self.tok,
  1165. token,
  1166. json.dumps(self.FILTER_LABELS_NOT_LABELS),
  1167. ),
  1168. )
  1169. events = channel.json_body["chunk"]
  1170. self.assertEqual(len(events), 1, [event["content"] for event in events])
  1171. self.assertEqual(events[0]["content"]["body"], "with wrong label", events[0])
  1172. def test_search_filter_labels(self):
  1173. """Test that we can filter by a label on a /search request."""
  1174. request_data = json.dumps(
  1175. {
  1176. "search_categories": {
  1177. "room_events": {
  1178. "search_term": "label",
  1179. "filter": self.FILTER_LABELS,
  1180. }
  1181. }
  1182. }
  1183. )
  1184. self._send_labelled_messages_in_room()
  1185. channel = self.make_request(
  1186. "POST", "/search?access_token=%s" % self.tok, request_data
  1187. )
  1188. results = channel.json_body["search_categories"]["room_events"]["results"]
  1189. self.assertEqual(
  1190. len(results), 2, [result["result"]["content"] for result in results],
  1191. )
  1192. self.assertEqual(
  1193. results[0]["result"]["content"]["body"],
  1194. "with right label",
  1195. results[0]["result"]["content"]["body"],
  1196. )
  1197. self.assertEqual(
  1198. results[1]["result"]["content"]["body"],
  1199. "with right label",
  1200. results[1]["result"]["content"]["body"],
  1201. )
  1202. def test_search_filter_not_labels(self):
  1203. """Test that we can filter by the absence of a label on a /search request."""
  1204. request_data = json.dumps(
  1205. {
  1206. "search_categories": {
  1207. "room_events": {
  1208. "search_term": "label",
  1209. "filter": self.FILTER_NOT_LABELS,
  1210. }
  1211. }
  1212. }
  1213. )
  1214. self._send_labelled_messages_in_room()
  1215. channel = self.make_request(
  1216. "POST", "/search?access_token=%s" % self.tok, request_data
  1217. )
  1218. results = channel.json_body["search_categories"]["room_events"]["results"]
  1219. self.assertEqual(
  1220. len(results), 4, [result["result"]["content"] for result in results],
  1221. )
  1222. self.assertEqual(
  1223. results[0]["result"]["content"]["body"],
  1224. "without label",
  1225. results[0]["result"]["content"]["body"],
  1226. )
  1227. self.assertEqual(
  1228. results[1]["result"]["content"]["body"],
  1229. "without label",
  1230. results[1]["result"]["content"]["body"],
  1231. )
  1232. self.assertEqual(
  1233. results[2]["result"]["content"]["body"],
  1234. "with wrong label",
  1235. results[2]["result"]["content"]["body"],
  1236. )
  1237. self.assertEqual(
  1238. results[3]["result"]["content"]["body"],
  1239. "with two wrong labels",
  1240. results[3]["result"]["content"]["body"],
  1241. )
  1242. def test_search_filter_labels_not_labels(self):
  1243. """Test that we can filter by both a label and the absence of another label on a
  1244. /search request.
  1245. """
  1246. request_data = json.dumps(
  1247. {
  1248. "search_categories": {
  1249. "room_events": {
  1250. "search_term": "label",
  1251. "filter": self.FILTER_LABELS_NOT_LABELS,
  1252. }
  1253. }
  1254. }
  1255. )
  1256. self._send_labelled_messages_in_room()
  1257. channel = self.make_request(
  1258. "POST", "/search?access_token=%s" % self.tok, request_data
  1259. )
  1260. results = channel.json_body["search_categories"]["room_events"]["results"]
  1261. self.assertEqual(
  1262. len(results), 1, [result["result"]["content"] for result in results],
  1263. )
  1264. self.assertEqual(
  1265. results[0]["result"]["content"]["body"],
  1266. "with wrong label",
  1267. results[0]["result"]["content"]["body"],
  1268. )
  1269. def _send_labelled_messages_in_room(self):
  1270. """Sends several messages to a room with different labels (or without any) to test
  1271. filtering by label.
  1272. Returns:
  1273. The ID of the event to use if we're testing filtering on /context.
  1274. """
  1275. self.helper.send_event(
  1276. room_id=self.room_id,
  1277. type=EventTypes.Message,
  1278. content={
  1279. "msgtype": "m.text",
  1280. "body": "with right label",
  1281. EventContentFields.LABELS: ["#fun"],
  1282. },
  1283. tok=self.tok,
  1284. )
  1285. self.helper.send_event(
  1286. room_id=self.room_id,
  1287. type=EventTypes.Message,
  1288. content={"msgtype": "m.text", "body": "without label"},
  1289. tok=self.tok,
  1290. )
  1291. res = self.helper.send_event(
  1292. room_id=self.room_id,
  1293. type=EventTypes.Message,
  1294. content={"msgtype": "m.text", "body": "without label"},
  1295. tok=self.tok,
  1296. )
  1297. # Return this event's ID when we test filtering in /context requests.
  1298. event_id = res["event_id"]
  1299. self.helper.send_event(
  1300. room_id=self.room_id,
  1301. type=EventTypes.Message,
  1302. content={
  1303. "msgtype": "m.text",
  1304. "body": "with wrong label",
  1305. EventContentFields.LABELS: ["#work"],
  1306. },
  1307. tok=self.tok,
  1308. )
  1309. self.helper.send_event(
  1310. room_id=self.room_id,
  1311. type=EventTypes.Message,
  1312. content={
  1313. "msgtype": "m.text",
  1314. "body": "with two wrong labels",
  1315. EventContentFields.LABELS: ["#work", "#notfun"],
  1316. },
  1317. tok=self.tok,
  1318. )
  1319. self.helper.send_event(
  1320. room_id=self.room_id,
  1321. type=EventTypes.Message,
  1322. content={
  1323. "msgtype": "m.text",
  1324. "body": "with right label",
  1325. EventContentFields.LABELS: ["#fun"],
  1326. },
  1327. tok=self.tok,
  1328. )
  1329. return event_id
  1330. class ContextTestCase(unittest.HomeserverTestCase):
  1331. servlets = [
  1332. synapse.rest.admin.register_servlets_for_client_rest_resource,
  1333. room.register_servlets,
  1334. login.register_servlets,
  1335. account.register_servlets,
  1336. ]
  1337. def prepare(self, reactor, clock, homeserver):
  1338. self.user_id = self.register_user("user", "password")
  1339. self.tok = self.login("user", "password")
  1340. self.room_id = self.helper.create_room_as(
  1341. self.user_id, tok=self.tok, is_public=False
  1342. )
  1343. self.other_user_id = self.register_user("user2", "password")
  1344. self.other_tok = self.login("user2", "password")
  1345. self.helper.invite(self.room_id, self.user_id, self.other_user_id, tok=self.tok)
  1346. self.helper.join(self.room_id, self.other_user_id, tok=self.other_tok)
  1347. def test_erased_sender(self):
  1348. """Test that an erasure request results in the requester's events being hidden
  1349. from any new member of the room.
  1350. """
  1351. # Send a bunch of events in the room.
  1352. self.helper.send(self.room_id, "message 1", tok=self.tok)
  1353. self.helper.send(self.room_id, "message 2", tok=self.tok)
  1354. event_id = self.helper.send(self.room_id, "message 3", tok=self.tok)["event_id"]
  1355. self.helper.send(self.room_id, "message 4", tok=self.tok)
  1356. self.helper.send(self.room_id, "message 5", tok=self.tok)
  1357. # Check that we can still see the messages before the erasure request.
  1358. channel = self.make_request(
  1359. "GET",
  1360. '/rooms/%s/context/%s?filter={"types":["m.room.message"]}'
  1361. % (self.room_id, event_id),
  1362. access_token=self.tok,
  1363. )
  1364. self.assertEqual(channel.code, 200, channel.result)
  1365. events_before = channel.json_body["events_before"]
  1366. self.assertEqual(len(events_before), 2, events_before)
  1367. self.assertEqual(
  1368. events_before[0].get("content", {}).get("body"),
  1369. "message 2",
  1370. events_before[0],
  1371. )
  1372. self.assertEqual(
  1373. events_before[1].get("content", {}).get("body"),
  1374. "message 1",
  1375. events_before[1],
  1376. )
  1377. self.assertEqual(
  1378. channel.json_body["event"].get("content", {}).get("body"),
  1379. "message 3",
  1380. channel.json_body["event"],
  1381. )
  1382. events_after = channel.json_body["events_after"]
  1383. self.assertEqual(len(events_after), 2, events_after)
  1384. self.assertEqual(
  1385. events_after[0].get("content", {}).get("body"),
  1386. "message 4",
  1387. events_after[0],
  1388. )
  1389. self.assertEqual(
  1390. events_after[1].get("content", {}).get("body"),
  1391. "message 5",
  1392. events_after[1],
  1393. )
  1394. # Deactivate the first account and erase the user's data.
  1395. deactivate_account_handler = self.hs.get_deactivate_account_handler()
  1396. self.get_success(
  1397. deactivate_account_handler.deactivate_account(
  1398. self.user_id, True, create_requester(self.user_id)
  1399. )
  1400. )
  1401. # Invite another user in the room. This is needed because messages will be
  1402. # pruned only if the user wasn't a member of the room when the messages were
  1403. # sent.
  1404. invited_user_id = self.register_user("user3", "password")
  1405. invited_tok = self.login("user3", "password")
  1406. self.helper.invite(
  1407. self.room_id, self.other_user_id, invited_user_id, tok=self.other_tok
  1408. )
  1409. self.helper.join(self.room_id, invited_user_id, tok=invited_tok)
  1410. # Check that a user that joined the room after the erasure request can't see
  1411. # the messages anymore.
  1412. channel = self.make_request(
  1413. "GET",
  1414. '/rooms/%s/context/%s?filter={"types":["m.room.message"]}'
  1415. % (self.room_id, event_id),
  1416. access_token=invited_tok,
  1417. )
  1418. self.assertEqual(channel.code, 200, channel.result)
  1419. events_before = channel.json_body["events_before"]
  1420. self.assertEqual(len(events_before), 2, events_before)
  1421. self.assertDictEqual(events_before[0].get("content"), {}, events_before[0])
  1422. self.assertDictEqual(events_before[1].get("content"), {}, events_before[1])
  1423. self.assertDictEqual(
  1424. channel.json_body["event"].get("content"), {}, channel.json_body["event"]
  1425. )
  1426. events_after = channel.json_body["events_after"]
  1427. self.assertEqual(len(events_after), 2, events_after)
  1428. self.assertDictEqual(events_after[0].get("content"), {}, events_after[0])
  1429. self.assertEqual(events_after[1].get("content"), {}, events_after[1])
  1430. class RoomAliasListTestCase(unittest.HomeserverTestCase):
  1431. servlets = [
  1432. synapse.rest.admin.register_servlets_for_client_rest_resource,
  1433. directory.register_servlets,
  1434. login.register_servlets,
  1435. room.register_servlets,
  1436. ]
  1437. def prepare(self, reactor, clock, homeserver):
  1438. self.room_owner = self.register_user("room_owner", "test")
  1439. self.room_owner_tok = self.login("room_owner", "test")
  1440. self.room_id = self.helper.create_room_as(
  1441. self.room_owner, tok=self.room_owner_tok
  1442. )
  1443. def test_no_aliases(self):
  1444. res = self._get_aliases(self.room_owner_tok)
  1445. self.assertEqual(res["aliases"], [])
  1446. def test_not_in_room(self):
  1447. self.register_user("user", "test")
  1448. user_tok = self.login("user", "test")
  1449. res = self._get_aliases(user_tok, expected_code=403)
  1450. self.assertEqual(res["errcode"], "M_FORBIDDEN")
  1451. def test_admin_user(self):
  1452. alias1 = self._random_alias()
  1453. self._set_alias_via_directory(alias1)
  1454. self.register_user("user", "test", admin=True)
  1455. user_tok = self.login("user", "test")
  1456. res = self._get_aliases(user_tok)
  1457. self.assertEqual(res["aliases"], [alias1])
  1458. def test_with_aliases(self):
  1459. alias1 = self._random_alias()
  1460. alias2 = self._random_alias()
  1461. self._set_alias_via_directory(alias1)
  1462. self._set_alias_via_directory(alias2)
  1463. res = self._get_aliases(self.room_owner_tok)
  1464. self.assertEqual(set(res["aliases"]), {alias1, alias2})
  1465. def test_peekable_room(self):
  1466. alias1 = self._random_alias()
  1467. self._set_alias_via_directory(alias1)
  1468. self.helper.send_state(
  1469. self.room_id,
  1470. EventTypes.RoomHistoryVisibility,
  1471. body={"history_visibility": "world_readable"},
  1472. tok=self.room_owner_tok,
  1473. )
  1474. self.register_user("user", "test")
  1475. user_tok = self.login("user", "test")
  1476. res = self._get_aliases(user_tok)
  1477. self.assertEqual(res["aliases"], [alias1])
  1478. def _get_aliases(self, access_token: str, expected_code: int = 200) -> JsonDict:
  1479. """Calls the endpoint under test. returns the json response object."""
  1480. channel = self.make_request(
  1481. "GET",
  1482. "/_matrix/client/unstable/org.matrix.msc2432/rooms/%s/aliases"
  1483. % (self.room_id,),
  1484. access_token=access_token,
  1485. )
  1486. self.assertEqual(channel.code, expected_code, channel.result)
  1487. res = channel.json_body
  1488. self.assertIsInstance(res, dict)
  1489. if expected_code == 200:
  1490. self.assertIsInstance(res["aliases"], list)
  1491. return res
  1492. def _random_alias(self) -> str:
  1493. return RoomAlias(random_string(5), self.hs.hostname).to_string()
  1494. def _set_alias_via_directory(self, alias: str, expected_code: int = 200):
  1495. url = "/_matrix/client/r0/directory/room/" + alias
  1496. data = {"room_id": self.room_id}
  1497. request_data = json.dumps(data)
  1498. channel = self.make_request(
  1499. "PUT", url, request_data, access_token=self.room_owner_tok
  1500. )
  1501. self.assertEqual(channel.code, expected_code, channel.result)
  1502. class RoomCanonicalAliasTestCase(unittest.HomeserverTestCase):
  1503. servlets = [
  1504. synapse.rest.admin.register_servlets_for_client_rest_resource,
  1505. directory.register_servlets,
  1506. login.register_servlets,
  1507. room.register_servlets,
  1508. ]
  1509. def prepare(self, reactor, clock, homeserver):
  1510. self.room_owner = self.register_user("room_owner", "test")
  1511. self.room_owner_tok = self.login("room_owner", "test")
  1512. self.room_id = self.helper.create_room_as(
  1513. self.room_owner, tok=self.room_owner_tok
  1514. )
  1515. self.alias = "#alias:test"
  1516. self._set_alias_via_directory(self.alias)
  1517. def _set_alias_via_directory(self, alias: str, expected_code: int = 200):
  1518. url = "/_matrix/client/r0/directory/room/" + alias
  1519. data = {"room_id": self.room_id}
  1520. request_data = json.dumps(data)
  1521. channel = self.make_request(
  1522. "PUT", url, request_data, access_token=self.room_owner_tok
  1523. )
  1524. self.assertEqual(channel.code, expected_code, channel.result)
  1525. def _get_canonical_alias(self, expected_code: int = 200) -> JsonDict:
  1526. """Calls the endpoint under test. returns the json response object."""
  1527. channel = self.make_request(
  1528. "GET",
  1529. "rooms/%s/state/m.room.canonical_alias" % (self.room_id,),
  1530. access_token=self.room_owner_tok,
  1531. )
  1532. self.assertEqual(channel.code, expected_code, channel.result)
  1533. res = channel.json_body
  1534. self.assertIsInstance(res, dict)
  1535. return res
  1536. def _set_canonical_alias(self, content: str, expected_code: int = 200) -> JsonDict:
  1537. """Calls the endpoint under test. returns the json response object."""
  1538. channel = self.make_request(
  1539. "PUT",
  1540. "rooms/%s/state/m.room.canonical_alias" % (self.room_id,),
  1541. json.dumps(content),
  1542. access_token=self.room_owner_tok,
  1543. )
  1544. self.assertEqual(channel.code, expected_code, channel.result)
  1545. res = channel.json_body
  1546. self.assertIsInstance(res, dict)
  1547. return res
  1548. def test_canonical_alias(self):
  1549. """Test a basic alias message."""
  1550. # There is no canonical alias to start with.
  1551. self._get_canonical_alias(expected_code=404)
  1552. # Create an alias.
  1553. self._set_canonical_alias({"alias": self.alias})
  1554. # Canonical alias now exists!
  1555. res = self._get_canonical_alias()
  1556. self.assertEqual(res, {"alias": self.alias})
  1557. # Now remove the alias.
  1558. self._set_canonical_alias({})
  1559. # There is an alias event, but it is empty.
  1560. res = self._get_canonical_alias()
  1561. self.assertEqual(res, {})
  1562. def test_alt_aliases(self):
  1563. """Test a canonical alias message with alt_aliases."""
  1564. # Create an alias.
  1565. self._set_canonical_alias({"alt_aliases": [self.alias]})
  1566. # Canonical alias now exists!
  1567. res = self._get_canonical_alias()
  1568. self.assertEqual(res, {"alt_aliases": [self.alias]})
  1569. # Now remove the alt_aliases.
  1570. self._set_canonical_alias({})
  1571. # There is an alias event, but it is empty.
  1572. res = self._get_canonical_alias()
  1573. self.assertEqual(res, {})
  1574. def test_alias_alt_aliases(self):
  1575. """Test a canonical alias message with an alias and alt_aliases."""
  1576. # Create an alias.
  1577. self._set_canonical_alias({"alias": self.alias, "alt_aliases": [self.alias]})
  1578. # Canonical alias now exists!
  1579. res = self._get_canonical_alias()
  1580. self.assertEqual(res, {"alias": self.alias, "alt_aliases": [self.alias]})
  1581. # Now remove the alias and alt_aliases.
  1582. self._set_canonical_alias({})
  1583. # There is an alias event, but it is empty.
  1584. res = self._get_canonical_alias()
  1585. self.assertEqual(res, {})
  1586. def test_partial_modify(self):
  1587. """Test removing only the alt_aliases."""
  1588. # Create an alias.
  1589. self._set_canonical_alias({"alias": self.alias, "alt_aliases": [self.alias]})
  1590. # Canonical alias now exists!
  1591. res = self._get_canonical_alias()
  1592. self.assertEqual(res, {"alias": self.alias, "alt_aliases": [self.alias]})
  1593. # Now remove the alt_aliases.
  1594. self._set_canonical_alias({"alias": self.alias})
  1595. # There is an alias event, but it is empty.
  1596. res = self._get_canonical_alias()
  1597. self.assertEqual(res, {"alias": self.alias})
  1598. def test_add_alias(self):
  1599. """Test removing only the alt_aliases."""
  1600. # Create an additional alias.
  1601. second_alias = "#second:test"
  1602. self._set_alias_via_directory(second_alias)
  1603. # Add the canonical alias.
  1604. self._set_canonical_alias({"alias": self.alias, "alt_aliases": [self.alias]})
  1605. # Then add the second alias.
  1606. self._set_canonical_alias(
  1607. {"alias": self.alias, "alt_aliases": [self.alias, second_alias]}
  1608. )
  1609. # Canonical alias now exists!
  1610. res = self._get_canonical_alias()
  1611. self.assertEqual(
  1612. res, {"alias": self.alias, "alt_aliases": [self.alias, second_alias]}
  1613. )
  1614. def test_bad_data(self):
  1615. """Invalid data for alt_aliases should cause errors."""
  1616. self._set_canonical_alias({"alt_aliases": "@bad:test"}, expected_code=400)
  1617. self._set_canonical_alias({"alt_aliases": None}, expected_code=400)
  1618. self._set_canonical_alias({"alt_aliases": 0}, expected_code=400)
  1619. self._set_canonical_alias({"alt_aliases": 1}, expected_code=400)
  1620. self._set_canonical_alias({"alt_aliases": False}, expected_code=400)
  1621. self._set_canonical_alias({"alt_aliases": True}, expected_code=400)
  1622. self._set_canonical_alias({"alt_aliases": {}}, expected_code=400)
  1623. def test_bad_alias(self):
  1624. """An alias which does not point to the room raises a SynapseError."""
  1625. self._set_canonical_alias({"alias": "@unknown:test"}, expected_code=400)
  1626. self._set_canonical_alias({"alt_aliases": ["@unknown:test"]}, expected_code=400)