test_rooms.py 75 KB

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