test_rooms.py 94 KB

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