test_rooms.py 99 KB

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