test_rooms.py 135 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654
  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 http import HTTPStatus
  20. from typing import Any, Dict, Iterable, List, Optional, Tuple, Union
  21. from unittest.mock import AsyncMock, Mock, call, patch
  22. from urllib import parse as urlparse
  23. from parameterized import param, parameterized
  24. from typing_extensions import Literal
  25. from twisted.test.proto_helpers import MemoryReactor
  26. import synapse.rest.admin
  27. from synapse.api.constants import (
  28. EduTypes,
  29. EventContentFields,
  30. EventTypes,
  31. Membership,
  32. PublicRoomsFilterFields,
  33. RoomTypes,
  34. )
  35. from synapse.api.errors import Codes, HttpResponseException
  36. from synapse.appservice import ApplicationService
  37. from synapse.events import EventBase
  38. from synapse.events.snapshot import EventContext
  39. from synapse.rest import admin
  40. from synapse.rest.client import account, directory, login, profile, register, room, sync
  41. from synapse.server import HomeServer
  42. from synapse.types import JsonDict, RoomAlias, UserID, create_requester
  43. from synapse.util import Clock
  44. from synapse.util.stringutils import random_string
  45. from tests import unittest
  46. from tests.http.server._base import make_request_with_cancellation_test
  47. from tests.storage.test_stream import PaginationTestCase
  48. from tests.test_utils.event_injection import create_event
  49. from tests.unittest import override_config
  50. PATH_PREFIX = b"/_matrix/client/api/v1"
  51. class RoomBase(unittest.HomeserverTestCase):
  52. rmcreator_id: Optional[str] = None
  53. servlets = [room.register_servlets, room.register_deprecated_servlets]
  54. def make_homeserver(self, reactor: MemoryReactor, clock: Clock) -> HomeServer:
  55. self.hs = self.setup_test_homeserver(
  56. "red",
  57. )
  58. self.hs.get_federation_handler = Mock() # type: ignore[method-assign]
  59. self.hs.get_federation_handler.return_value.maybe_backfill = AsyncMock(
  60. return_value=None
  61. )
  62. async def _insert_client_ip(*args: Any, **kwargs: Any) -> None:
  63. return None
  64. self.hs.get_datastores().main.insert_client_ip = _insert_client_ip # type: ignore[method-assign]
  65. return self.hs
  66. class RoomPermissionsTestCase(RoomBase):
  67. """Tests room permissions."""
  68. user_id = "@sid1:red"
  69. rmcreator_id = "@notme:red"
  70. def prepare(self, reactor: MemoryReactor, clock: Clock, hs: HomeServer) -> None:
  71. self.helper.auth_user_id = self.rmcreator_id
  72. # create some rooms under the name rmcreator_id
  73. self.uncreated_rmid = "!aa:test"
  74. self.created_rmid = self.helper.create_room_as(
  75. self.rmcreator_id, is_public=False
  76. )
  77. self.created_public_rmid = self.helper.create_room_as(
  78. self.rmcreator_id, is_public=True
  79. )
  80. # send a message in one of the rooms
  81. self.created_rmid_msg_path = (
  82. "rooms/%s/send/m.room.message/a1" % (self.created_rmid)
  83. ).encode("ascii")
  84. channel = self.make_request(
  85. "PUT", self.created_rmid_msg_path, b'{"msgtype":"m.text","body":"test msg"}'
  86. )
  87. self.assertEqual(HTTPStatus.OK, channel.code, channel.result)
  88. # set topic for public room
  89. channel = self.make_request(
  90. "PUT",
  91. ("rooms/%s/state/m.room.topic" % self.created_public_rmid).encode("ascii"),
  92. b'{"topic":"Public Room Topic"}',
  93. )
  94. self.assertEqual(HTTPStatus.OK, channel.code, channel.result)
  95. # auth as user_id now
  96. self.helper.auth_user_id = self.user_id
  97. def test_can_do_action(self) -> None:
  98. msg_content = b'{"msgtype":"m.text","body":"hello"}'
  99. seq = iter(range(100))
  100. def send_msg_path() -> str:
  101. return "/rooms/%s/send/m.room.message/mid%s" % (
  102. self.created_rmid,
  103. str(next(seq)),
  104. )
  105. # send message in uncreated room, expect 403
  106. channel = self.make_request(
  107. "PUT",
  108. "/rooms/%s/send/m.room.message/mid2" % (self.uncreated_rmid,),
  109. msg_content,
  110. )
  111. self.assertEqual(HTTPStatus.FORBIDDEN, channel.code, msg=channel.result["body"])
  112. # send message in created room not joined (no state), expect 403
  113. channel = self.make_request("PUT", send_msg_path(), msg_content)
  114. self.assertEqual(HTTPStatus.FORBIDDEN, channel.code, msg=channel.result["body"])
  115. # send message in created room and invited, expect 403
  116. self.helper.invite(
  117. room=self.created_rmid, src=self.rmcreator_id, targ=self.user_id
  118. )
  119. channel = self.make_request("PUT", send_msg_path(), msg_content)
  120. self.assertEqual(HTTPStatus.FORBIDDEN, channel.code, msg=channel.result["body"])
  121. # send message in created room and joined, expect 200
  122. self.helper.join(room=self.created_rmid, user=self.user_id)
  123. channel = self.make_request("PUT", send_msg_path(), msg_content)
  124. self.assertEqual(HTTPStatus.OK, channel.code, msg=channel.result["body"])
  125. # send message in created room and left, expect 403
  126. self.helper.leave(room=self.created_rmid, user=self.user_id)
  127. channel = self.make_request("PUT", send_msg_path(), msg_content)
  128. self.assertEqual(HTTPStatus.FORBIDDEN, channel.code, msg=channel.result["body"])
  129. def test_topic_perms(self) -> None:
  130. topic_content = b'{"topic":"My Topic Name"}'
  131. topic_path = "/rooms/%s/state/m.room.topic" % self.created_rmid
  132. # set/get topic in uncreated room, expect 403
  133. channel = self.make_request(
  134. "PUT", "/rooms/%s/state/m.room.topic" % self.uncreated_rmid, topic_content
  135. )
  136. self.assertEqual(HTTPStatus.FORBIDDEN, channel.code, msg=channel.result["body"])
  137. channel = self.make_request(
  138. "GET", "/rooms/%s/state/m.room.topic" % self.uncreated_rmid
  139. )
  140. self.assertEqual(HTTPStatus.FORBIDDEN, channel.code, msg=channel.result["body"])
  141. # set/get topic in created PRIVATE room not joined, expect 403
  142. channel = self.make_request("PUT", topic_path, topic_content)
  143. self.assertEqual(HTTPStatus.FORBIDDEN, channel.code, msg=channel.result["body"])
  144. channel = self.make_request("GET", topic_path)
  145. self.assertEqual(HTTPStatus.FORBIDDEN, channel.code, msg=channel.result["body"])
  146. # set topic in created PRIVATE room and invited, expect 403
  147. self.helper.invite(
  148. room=self.created_rmid, src=self.rmcreator_id, targ=self.user_id
  149. )
  150. channel = self.make_request("PUT", topic_path, topic_content)
  151. self.assertEqual(HTTPStatus.FORBIDDEN, channel.code, msg=channel.result["body"])
  152. # get topic in created PRIVATE room and invited, expect 403
  153. channel = self.make_request("GET", topic_path)
  154. self.assertEqual(HTTPStatus.FORBIDDEN, channel.code, msg=channel.result["body"])
  155. # set/get topic in created PRIVATE room and joined, expect 200
  156. self.helper.join(room=self.created_rmid, user=self.user_id)
  157. # Only room ops can set topic by default
  158. self.helper.auth_user_id = self.rmcreator_id
  159. channel = self.make_request("PUT", topic_path, topic_content)
  160. self.assertEqual(HTTPStatus.OK, channel.code, msg=channel.result["body"])
  161. self.helper.auth_user_id = self.user_id
  162. channel = self.make_request("GET", topic_path)
  163. self.assertEqual(HTTPStatus.OK, channel.code, msg=channel.result["body"])
  164. self.assert_dict(json.loads(topic_content.decode("utf8")), channel.json_body)
  165. # set/get topic in created PRIVATE room and left, expect 403
  166. self.helper.leave(room=self.created_rmid, user=self.user_id)
  167. channel = self.make_request("PUT", topic_path, topic_content)
  168. self.assertEqual(HTTPStatus.FORBIDDEN, channel.code, msg=channel.result["body"])
  169. channel = self.make_request("GET", topic_path)
  170. self.assertEqual(HTTPStatus.OK, channel.code, msg=channel.result["body"])
  171. # get topic in PUBLIC room, not joined, expect 403
  172. channel = self.make_request(
  173. "GET", "/rooms/%s/state/m.room.topic" % self.created_public_rmid
  174. )
  175. self.assertEqual(HTTPStatus.FORBIDDEN, channel.code, msg=channel.result["body"])
  176. # set topic in PUBLIC room, not joined, expect 403
  177. channel = self.make_request(
  178. "PUT",
  179. "/rooms/%s/state/m.room.topic" % self.created_public_rmid,
  180. topic_content,
  181. )
  182. self.assertEqual(HTTPStatus.FORBIDDEN, channel.code, msg=channel.result["body"])
  183. def _test_get_membership(
  184. self, room: str, members: Iterable = frozenset(), expect_code: int = 200
  185. ) -> None:
  186. for member in members:
  187. path = "/rooms/%s/state/m.room.member/%s" % (room, member)
  188. channel = self.make_request("GET", path)
  189. self.assertEqual(expect_code, channel.code)
  190. def test_membership_basic_room_perms(self) -> None:
  191. # === room does not exist ===
  192. room = self.uncreated_rmid
  193. # get membership of self, get membership of other, uncreated room
  194. # expect all 403s
  195. self._test_get_membership(
  196. members=[self.user_id, self.rmcreator_id], room=room, expect_code=403
  197. )
  198. # trying to invite people to this room should 403
  199. self.helper.invite(
  200. room=room, src=self.user_id, targ=self.rmcreator_id, expect_code=403
  201. )
  202. # set [invite/join/left] of self, set [invite/join/left] of other,
  203. # expect all 404s because room doesn't exist on any server
  204. for usr in [self.user_id, self.rmcreator_id]:
  205. self.helper.join(room=room, user=usr, expect_code=404)
  206. self.helper.leave(room=room, user=usr, expect_code=404)
  207. def test_membership_private_room_perms(self) -> None:
  208. room = self.created_rmid
  209. # get membership of self, get membership of other, private room + invite
  210. # expect all 403s
  211. self.helper.invite(room=room, src=self.rmcreator_id, targ=self.user_id)
  212. self._test_get_membership(
  213. members=[self.user_id, self.rmcreator_id], room=room, expect_code=403
  214. )
  215. # get membership of self, get membership of other, private room + joined
  216. # expect all 200s
  217. self.helper.join(room=room, user=self.user_id)
  218. self._test_get_membership(
  219. members=[self.user_id, self.rmcreator_id], room=room, expect_code=200
  220. )
  221. # get membership of self, get membership of other, private room + left
  222. # expect all 200s
  223. self.helper.leave(room=room, user=self.user_id)
  224. self._test_get_membership(
  225. members=[self.user_id, self.rmcreator_id], room=room, expect_code=200
  226. )
  227. def test_membership_public_room_perms(self) -> None:
  228. room = self.created_public_rmid
  229. # get membership of self, get membership of other, public room + invite
  230. # expect 403
  231. self.helper.invite(room=room, src=self.rmcreator_id, targ=self.user_id)
  232. self._test_get_membership(
  233. members=[self.user_id, self.rmcreator_id], room=room, expect_code=403
  234. )
  235. # get membership of self, get membership of other, public room + joined
  236. # expect all 200s
  237. self.helper.join(room=room, user=self.user_id)
  238. self._test_get_membership(
  239. members=[self.user_id, self.rmcreator_id], room=room, expect_code=200
  240. )
  241. # get membership of self, get membership of other, public room + left
  242. # expect 200.
  243. self.helper.leave(room=room, user=self.user_id)
  244. self._test_get_membership(
  245. members=[self.user_id, self.rmcreator_id], room=room, expect_code=200
  246. )
  247. def test_invited_permissions(self) -> None:
  248. room = self.created_rmid
  249. self.helper.invite(room=room, src=self.rmcreator_id, targ=self.user_id)
  250. # set [invite/join/left] of other user, expect 403s
  251. self.helper.invite(
  252. room=room, src=self.user_id, targ=self.rmcreator_id, expect_code=403
  253. )
  254. self.helper.change_membership(
  255. room=room,
  256. src=self.user_id,
  257. targ=self.rmcreator_id,
  258. membership=Membership.JOIN,
  259. expect_code=HTTPStatus.FORBIDDEN,
  260. )
  261. self.helper.change_membership(
  262. room=room,
  263. src=self.user_id,
  264. targ=self.rmcreator_id,
  265. membership=Membership.LEAVE,
  266. expect_code=HTTPStatus.FORBIDDEN,
  267. )
  268. def test_joined_permissions(self) -> None:
  269. room = self.created_rmid
  270. self.helper.invite(room=room, src=self.rmcreator_id, targ=self.user_id)
  271. self.helper.join(room=room, user=self.user_id)
  272. # set invited of self, expect 403
  273. self.helper.invite(
  274. room=room, src=self.user_id, targ=self.user_id, expect_code=403
  275. )
  276. # set joined of self, expect 200 (NOOP)
  277. self.helper.join(room=room, user=self.user_id)
  278. other = "@burgundy:red"
  279. # set invited of other, expect 200
  280. self.helper.invite(room=room, src=self.user_id, targ=other, expect_code=200)
  281. # set joined of other, expect 403
  282. self.helper.change_membership(
  283. room=room,
  284. src=self.user_id,
  285. targ=other,
  286. membership=Membership.JOIN,
  287. expect_code=HTTPStatus.FORBIDDEN,
  288. )
  289. # set left of other, expect 403
  290. self.helper.change_membership(
  291. room=room,
  292. src=self.user_id,
  293. targ=other,
  294. membership=Membership.LEAVE,
  295. expect_code=HTTPStatus.FORBIDDEN,
  296. )
  297. # set left of self, expect 200
  298. self.helper.leave(room=room, user=self.user_id)
  299. def test_leave_permissions(self) -> None:
  300. room = self.created_rmid
  301. self.helper.invite(room=room, src=self.rmcreator_id, targ=self.user_id)
  302. self.helper.join(room=room, user=self.user_id)
  303. self.helper.leave(room=room, user=self.user_id)
  304. # set [invite/join/left] of self, set [invite/join/left] of other,
  305. # expect all 403s
  306. for usr in [self.user_id, self.rmcreator_id]:
  307. self.helper.change_membership(
  308. room=room,
  309. src=self.user_id,
  310. targ=usr,
  311. membership=Membership.INVITE,
  312. expect_code=HTTPStatus.FORBIDDEN,
  313. )
  314. self.helper.change_membership(
  315. room=room,
  316. src=self.user_id,
  317. targ=usr,
  318. membership=Membership.JOIN,
  319. expect_code=HTTPStatus.FORBIDDEN,
  320. )
  321. # It is always valid to LEAVE if you've already left (currently.)
  322. self.helper.change_membership(
  323. room=room,
  324. src=self.user_id,
  325. targ=self.rmcreator_id,
  326. membership=Membership.LEAVE,
  327. expect_code=HTTPStatus.FORBIDDEN,
  328. )
  329. # tests the "from banned" line from the table in https://spec.matrix.org/unstable/client-server-api/#mroommember
  330. def test_member_event_from_ban(self) -> None:
  331. room = self.created_rmid
  332. self.helper.invite(room=room, src=self.rmcreator_id, targ=self.user_id)
  333. self.helper.join(room=room, user=self.user_id)
  334. other = "@burgundy:red"
  335. # User cannot ban other since they do not have required power level
  336. self.helper.change_membership(
  337. room=room,
  338. src=self.user_id,
  339. targ=other,
  340. membership=Membership.BAN,
  341. expect_code=HTTPStatus.FORBIDDEN, # expect failure
  342. expect_errcode=Codes.FORBIDDEN,
  343. )
  344. # Admin bans other
  345. self.helper.change_membership(
  346. room=room,
  347. src=self.rmcreator_id,
  348. targ=other,
  349. membership=Membership.BAN,
  350. expect_code=HTTPStatus.OK,
  351. )
  352. # from ban to invite: Must never happen.
  353. self.helper.change_membership(
  354. room=room,
  355. src=self.rmcreator_id,
  356. targ=other,
  357. membership=Membership.INVITE,
  358. expect_code=HTTPStatus.FORBIDDEN, # expect failure
  359. expect_errcode=Codes.BAD_STATE,
  360. )
  361. # from ban to join: Must never happen.
  362. self.helper.change_membership(
  363. room=room,
  364. src=other,
  365. targ=other,
  366. membership=Membership.JOIN,
  367. expect_code=HTTPStatus.FORBIDDEN, # expect failure
  368. expect_errcode=Codes.BAD_STATE,
  369. )
  370. # from ban to ban: No change.
  371. self.helper.change_membership(
  372. room=room,
  373. src=self.rmcreator_id,
  374. targ=other,
  375. membership=Membership.BAN,
  376. expect_code=HTTPStatus.OK,
  377. )
  378. # from ban to knock: Must never happen.
  379. self.helper.change_membership(
  380. room=room,
  381. src=self.rmcreator_id,
  382. targ=other,
  383. membership=Membership.KNOCK,
  384. expect_code=HTTPStatus.FORBIDDEN, # expect failure
  385. expect_errcode=Codes.BAD_STATE,
  386. )
  387. # User cannot unban other since they do not have required power level
  388. self.helper.change_membership(
  389. room=room,
  390. src=self.user_id,
  391. targ=other,
  392. membership=Membership.LEAVE,
  393. expect_code=HTTPStatus.FORBIDDEN, # expect failure
  394. expect_errcode=Codes.FORBIDDEN,
  395. )
  396. # from ban to leave: User was unbanned.
  397. self.helper.change_membership(
  398. room=room,
  399. src=self.rmcreator_id,
  400. targ=other,
  401. membership=Membership.LEAVE,
  402. expect_code=HTTPStatus.OK,
  403. )
  404. class RoomStateTestCase(RoomBase):
  405. """Tests /rooms/$room_id/state."""
  406. user_id = "@sid1:red"
  407. def test_get_state_cancellation(self) -> None:
  408. """Test cancellation of a `/rooms/$room_id/state` request."""
  409. room_id = self.helper.create_room_as(self.user_id)
  410. channel = make_request_with_cancellation_test(
  411. "test_state_cancellation",
  412. self.reactor,
  413. self.site,
  414. "GET",
  415. "/rooms/%s/state" % room_id,
  416. )
  417. self.assertEqual(HTTPStatus.OK, channel.code, msg=channel.result["body"])
  418. self.assertCountEqual(
  419. [state_event["type"] for state_event in channel.json_list],
  420. {
  421. "m.room.create",
  422. "m.room.power_levels",
  423. "m.room.join_rules",
  424. "m.room.member",
  425. "m.room.history_visibility",
  426. },
  427. )
  428. def test_get_state_event_cancellation(self) -> None:
  429. """Test cancellation of a `/rooms/$room_id/state/$event_type` request."""
  430. room_id = self.helper.create_room_as(self.user_id)
  431. channel = make_request_with_cancellation_test(
  432. "test_state_cancellation",
  433. self.reactor,
  434. self.site,
  435. "GET",
  436. "/rooms/%s/state/m.room.member/%s" % (room_id, self.user_id),
  437. )
  438. self.assertEqual(HTTPStatus.OK, channel.code, msg=channel.result["body"])
  439. self.assertEqual(channel.json_body, {"membership": "join"})
  440. class RoomsMemberListTestCase(RoomBase):
  441. """Tests /rooms/$room_id/members/list REST events."""
  442. servlets = RoomBase.servlets + [sync.register_servlets]
  443. user_id = "@sid1:red"
  444. def test_get_member_list(self) -> None:
  445. room_id = self.helper.create_room_as(self.user_id)
  446. channel = self.make_request("GET", "/rooms/%s/members" % room_id)
  447. self.assertEqual(HTTPStatus.OK, channel.code, msg=channel.result["body"])
  448. def test_get_member_list_no_room(self) -> None:
  449. channel = self.make_request("GET", "/rooms/roomdoesnotexist/members")
  450. self.assertEqual(HTTPStatus.FORBIDDEN, channel.code, msg=channel.result["body"])
  451. def test_get_member_list_no_permission(self) -> None:
  452. room_id = self.helper.create_room_as("@some_other_guy:red")
  453. channel = self.make_request("GET", "/rooms/%s/members" % room_id)
  454. self.assertEqual(HTTPStatus.FORBIDDEN, channel.code, msg=channel.result["body"])
  455. def test_get_member_list_no_permission_with_at_token(self) -> None:
  456. """
  457. Tests that a stranger to the room cannot get the member list
  458. (in the case that they use an at token).
  459. """
  460. room_id = self.helper.create_room_as("@someone.else:red")
  461. # first sync to get an at token
  462. channel = self.make_request("GET", "/sync")
  463. self.assertEqual(HTTPStatus.OK, channel.code)
  464. sync_token = channel.json_body["next_batch"]
  465. # check that permission is denied for @sid1:red to get the
  466. # memberships of @someone.else:red's room.
  467. channel = self.make_request(
  468. "GET",
  469. f"/rooms/{room_id}/members?at={sync_token}",
  470. )
  471. self.assertEqual(HTTPStatus.FORBIDDEN, channel.code, msg=channel.result["body"])
  472. def test_get_member_list_no_permission_former_member(self) -> None:
  473. """
  474. Tests that a former member of the room can not get the member list.
  475. """
  476. # create a room, invite the user and the user joins
  477. room_id = self.helper.create_room_as("@alice:red")
  478. self.helper.invite(room_id, "@alice:red", self.user_id)
  479. self.helper.join(room_id, self.user_id)
  480. # check that the user can see the member list to start with
  481. channel = self.make_request("GET", "/rooms/%s/members" % room_id)
  482. self.assertEqual(HTTPStatus.OK, channel.code, msg=channel.result["body"])
  483. # ban the user
  484. self.helper.change_membership(room_id, "@alice:red", self.user_id, "ban")
  485. # check the user can no longer see the member list
  486. channel = self.make_request("GET", "/rooms/%s/members" % room_id)
  487. self.assertEqual(HTTPStatus.FORBIDDEN, channel.code, msg=channel.result["body"])
  488. def test_get_member_list_no_permission_former_member_with_at_token(self) -> None:
  489. """
  490. Tests that a former member of the room can not get the member list
  491. (in the case that they use an at token).
  492. """
  493. # create a room, invite the user and the user joins
  494. room_id = self.helper.create_room_as("@alice:red")
  495. self.helper.invite(room_id, "@alice:red", self.user_id)
  496. self.helper.join(room_id, self.user_id)
  497. # sync to get an at token
  498. channel = self.make_request("GET", "/sync")
  499. self.assertEqual(HTTPStatus.OK, channel.code)
  500. sync_token = channel.json_body["next_batch"]
  501. # check that the user can see the member list to start with
  502. channel = self.make_request(
  503. "GET", "/rooms/%s/members?at=%s" % (room_id, sync_token)
  504. )
  505. self.assertEqual(HTTPStatus.OK, channel.code, msg=channel.result["body"])
  506. # ban the user (Note: the user is actually allowed to see this event and
  507. # state so that they know they're banned!)
  508. self.helper.change_membership(room_id, "@alice:red", self.user_id, "ban")
  509. # invite a third user and let them join
  510. self.helper.invite(room_id, "@alice:red", "@bob:red")
  511. self.helper.join(room_id, "@bob:red")
  512. # now, with the original user, sync again to get a new at token
  513. channel = self.make_request("GET", "/sync")
  514. self.assertEqual(HTTPStatus.OK, channel.code)
  515. sync_token = channel.json_body["next_batch"]
  516. # check the user can no longer see the updated member list
  517. channel = self.make_request(
  518. "GET", "/rooms/%s/members?at=%s" % (room_id, sync_token)
  519. )
  520. self.assertEqual(HTTPStatus.FORBIDDEN, channel.code, msg=channel.result["body"])
  521. def test_get_member_list_mixed_memberships(self) -> None:
  522. room_creator = "@some_other_guy:red"
  523. room_id = self.helper.create_room_as(room_creator)
  524. room_path = "/rooms/%s/members" % room_id
  525. self.helper.invite(room=room_id, src=room_creator, targ=self.user_id)
  526. # can't see list if you're just invited.
  527. channel = self.make_request("GET", room_path)
  528. self.assertEqual(HTTPStatus.FORBIDDEN, channel.code, msg=channel.result["body"])
  529. self.helper.join(room=room_id, user=self.user_id)
  530. # can see list now joined
  531. channel = self.make_request("GET", room_path)
  532. self.assertEqual(HTTPStatus.OK, channel.code, msg=channel.result["body"])
  533. self.helper.leave(room=room_id, user=self.user_id)
  534. # can see old list once left
  535. channel = self.make_request("GET", room_path)
  536. self.assertEqual(HTTPStatus.OK, channel.code, msg=channel.result["body"])
  537. def test_get_member_list_cancellation(self) -> None:
  538. """Test cancellation of a `/rooms/$room_id/members` request."""
  539. room_id = self.helper.create_room_as(self.user_id)
  540. channel = make_request_with_cancellation_test(
  541. "test_get_member_list_cancellation",
  542. self.reactor,
  543. self.site,
  544. "GET",
  545. "/rooms/%s/members" % room_id,
  546. )
  547. self.assertEqual(HTTPStatus.OK, channel.code, msg=channel.result["body"])
  548. self.assertEqual(len(channel.json_body["chunk"]), 1)
  549. self.assertLessEqual(
  550. {
  551. "content": {"membership": "join"},
  552. "room_id": room_id,
  553. "sender": self.user_id,
  554. "state_key": self.user_id,
  555. "type": "m.room.member",
  556. "user_id": self.user_id,
  557. }.items(),
  558. channel.json_body["chunk"][0].items(),
  559. )
  560. def test_get_member_list_with_at_token_cancellation(self) -> None:
  561. """Test cancellation of a `/rooms/$room_id/members?at=<sync token>` request."""
  562. room_id = self.helper.create_room_as(self.user_id)
  563. # first sync to get an at token
  564. channel = self.make_request("GET", "/sync")
  565. self.assertEqual(HTTPStatus.OK, channel.code)
  566. sync_token = channel.json_body["next_batch"]
  567. channel = make_request_with_cancellation_test(
  568. "test_get_member_list_with_at_token_cancellation",
  569. self.reactor,
  570. self.site,
  571. "GET",
  572. "/rooms/%s/members?at=%s" % (room_id, sync_token),
  573. )
  574. self.assertEqual(HTTPStatus.OK, channel.code, msg=channel.result["body"])
  575. self.assertEqual(len(channel.json_body["chunk"]), 1)
  576. self.assertLessEqual(
  577. {
  578. "content": {"membership": "join"},
  579. "room_id": room_id,
  580. "sender": self.user_id,
  581. "state_key": self.user_id,
  582. "type": "m.room.member",
  583. "user_id": self.user_id,
  584. }.items(),
  585. channel.json_body["chunk"][0].items(),
  586. )
  587. class RoomsCreateTestCase(RoomBase):
  588. """Tests /rooms and /rooms/$room_id REST events."""
  589. user_id = "@sid1:red"
  590. def test_post_room_no_keys(self) -> None:
  591. # POST with no config keys, expect new room id
  592. channel = self.make_request("POST", "/createRoom", "{}")
  593. self.assertEqual(HTTPStatus.OK, channel.code, channel.result)
  594. self.assertTrue("room_id" in channel.json_body)
  595. assert channel.resource_usage is not None
  596. self.assertEqual(32, channel.resource_usage.db_txn_count)
  597. def test_post_room_initial_state(self) -> None:
  598. # POST with initial_state config key, expect new room id
  599. channel = self.make_request(
  600. "POST",
  601. "/createRoom",
  602. b'{"initial_state":[{"type": "m.bridge", "content": {}}]}',
  603. )
  604. self.assertEqual(HTTPStatus.OK, channel.code, channel.result)
  605. self.assertTrue("room_id" in channel.json_body)
  606. assert channel.resource_usage is not None
  607. self.assertEqual(34, channel.resource_usage.db_txn_count)
  608. def test_post_room_visibility_key(self) -> None:
  609. # POST with visibility config key, expect new room id
  610. channel = self.make_request("POST", "/createRoom", b'{"visibility":"private"}')
  611. self.assertEqual(HTTPStatus.OK, channel.code)
  612. self.assertTrue("room_id" in channel.json_body)
  613. def test_post_room_custom_key(self) -> None:
  614. # POST with custom config keys, expect new room id
  615. channel = self.make_request("POST", "/createRoom", b'{"custom":"stuff"}')
  616. self.assertEqual(HTTPStatus.OK, channel.code)
  617. self.assertTrue("room_id" in channel.json_body)
  618. def test_post_room_known_and_unknown_keys(self) -> None:
  619. # POST with custom + known config keys, expect new room id
  620. channel = self.make_request(
  621. "POST", "/createRoom", b'{"visibility":"private","custom":"things"}'
  622. )
  623. self.assertEqual(HTTPStatus.OK, channel.code)
  624. self.assertTrue("room_id" in channel.json_body)
  625. def test_post_room_invalid_content(self) -> None:
  626. # POST with invalid content / paths, expect 400
  627. channel = self.make_request("POST", "/createRoom", b'{"visibili')
  628. self.assertEqual(HTTPStatus.BAD_REQUEST, channel.code)
  629. channel = self.make_request("POST", "/createRoom", b'["hello"]')
  630. self.assertEqual(HTTPStatus.BAD_REQUEST, channel.code)
  631. def test_post_room_invitees_invalid_mxid(self) -> None:
  632. # POST with invalid invitee, see https://github.com/matrix-org/synapse/issues/4088
  633. # Note the trailing space in the MXID here!
  634. channel = self.make_request(
  635. "POST", "/createRoom", b'{"invite":["@alice:example.com "]}'
  636. )
  637. self.assertEqual(HTTPStatus.BAD_REQUEST, channel.code)
  638. @unittest.override_config({"rc_invites": {"per_room": {"burst_count": 3}}})
  639. def test_post_room_invitees_ratelimit(self) -> None:
  640. """Test that invites sent when creating a room are ratelimited by a RateLimiter,
  641. which ratelimits them correctly, including by not limiting when the requester is
  642. exempt from ratelimiting.
  643. """
  644. # Build the request's content. We use local MXIDs because invites over federation
  645. # are more difficult to mock.
  646. content = {
  647. "invite": [
  648. "@alice1:red",
  649. "@alice2:red",
  650. "@alice3:red",
  651. "@alice4:red",
  652. ]
  653. }
  654. # Test that the invites are correctly ratelimited.
  655. channel = self.make_request("POST", "/createRoom", content)
  656. self.assertEqual(HTTPStatus.BAD_REQUEST, channel.code)
  657. self.assertEqual(
  658. "Cannot invite so many users at once",
  659. channel.json_body["error"],
  660. )
  661. # Add the current user to the ratelimit overrides, allowing them no ratelimiting.
  662. self.get_success(
  663. self.hs.get_datastores().main.set_ratelimit_for_user(self.user_id, 0, 0)
  664. )
  665. # Test that the invites aren't ratelimited anymore.
  666. channel = self.make_request("POST", "/createRoom", content)
  667. self.assertEqual(HTTPStatus.OK, channel.code)
  668. def test_spam_checker_may_join_room_deprecated(self) -> None:
  669. """Tests that the user_may_join_room spam checker callback is correctly bypassed
  670. when creating a new room.
  671. In this test, we use the deprecated API in which callbacks return a bool.
  672. """
  673. async def user_may_join_room(
  674. mxid: str,
  675. room_id: str,
  676. is_invite: bool,
  677. ) -> bool:
  678. return False
  679. join_mock = Mock(side_effect=user_may_join_room)
  680. self.hs.get_module_api_callbacks().spam_checker._user_may_join_room_callbacks.append(
  681. join_mock
  682. )
  683. channel = self.make_request(
  684. "POST",
  685. "/createRoom",
  686. {},
  687. )
  688. self.assertEqual(channel.code, HTTPStatus.OK, channel.json_body)
  689. self.assertEqual(join_mock.call_count, 0)
  690. def test_spam_checker_may_join_room(self) -> None:
  691. """Tests that the user_may_join_room spam checker callback is correctly bypassed
  692. when creating a new room.
  693. In this test, we use the more recent API in which callbacks return a `Union[Codes, Literal["NOT_SPAM"]]`.
  694. """
  695. async def user_may_join_room_codes(
  696. mxid: str,
  697. room_id: str,
  698. is_invite: bool,
  699. ) -> Codes:
  700. return Codes.CONSENT_NOT_GIVEN
  701. join_mock = Mock(side_effect=user_may_join_room_codes)
  702. self.hs.get_module_api_callbacks().spam_checker._user_may_join_room_callbacks.append(
  703. join_mock
  704. )
  705. channel = self.make_request(
  706. "POST",
  707. "/createRoom",
  708. {},
  709. )
  710. self.assertEqual(channel.code, HTTPStatus.OK, channel.json_body)
  711. self.assertEqual(join_mock.call_count, 0)
  712. # Now change the return value of the callback to deny any join. Since we're
  713. # creating the room, despite the return value, we should be able to join.
  714. async def user_may_join_room_tuple(
  715. mxid: str,
  716. room_id: str,
  717. is_invite: bool,
  718. ) -> Tuple[Codes, dict]:
  719. return Codes.INCOMPATIBLE_ROOM_VERSION, {}
  720. join_mock.side_effect = user_may_join_room_tuple
  721. channel = self.make_request(
  722. "POST",
  723. "/createRoom",
  724. {},
  725. )
  726. self.assertEqual(channel.code, HTTPStatus.OK, channel.json_body)
  727. self.assertEqual(join_mock.call_count, 0)
  728. def _create_basic_room(self) -> Tuple[int, object]:
  729. """
  730. Tries to create a basic room and returns the response code.
  731. """
  732. channel = self.make_request(
  733. "POST",
  734. "/createRoom",
  735. {},
  736. )
  737. return channel.code, channel.json_body
  738. @override_config(
  739. {
  740. "rc_message": {"per_second": 0.2, "burst_count": 10},
  741. }
  742. )
  743. def test_room_creation_ratelimiting(self) -> None:
  744. """
  745. Regression test for #14312, where ratelimiting was made too strict.
  746. Clients should be able to create 10 rooms in a row
  747. without hitting rate limits, using default rate limit config.
  748. (We override rate limiting config back to its default value.)
  749. To ensure we don't make ratelimiting too generous accidentally,
  750. also check that we can't create an 11th room.
  751. """
  752. for _ in range(10):
  753. code, json_body = self._create_basic_room()
  754. self.assertEqual(code, HTTPStatus.OK, json_body)
  755. # The 6th room hits the rate limit.
  756. code, json_body = self._create_basic_room()
  757. self.assertEqual(code, HTTPStatus.TOO_MANY_REQUESTS, json_body)
  758. class RoomTopicTestCase(RoomBase):
  759. """Tests /rooms/$room_id/topic REST events."""
  760. user_id = "@sid1:red"
  761. def prepare(self, reactor: MemoryReactor, clock: Clock, hs: HomeServer) -> None:
  762. # create the room
  763. self.room_id = self.helper.create_room_as(self.user_id)
  764. self.path = "/rooms/%s/state/m.room.topic" % (self.room_id,)
  765. def test_invalid_puts(self) -> None:
  766. # missing keys or invalid json
  767. channel = self.make_request("PUT", self.path, "{}")
  768. self.assertEqual(
  769. HTTPStatus.BAD_REQUEST, channel.code, msg=channel.result["body"]
  770. )
  771. channel = self.make_request("PUT", self.path, '{"_name":"bo"}')
  772. self.assertEqual(
  773. HTTPStatus.BAD_REQUEST, channel.code, msg=channel.result["body"]
  774. )
  775. channel = self.make_request("PUT", self.path, '{"nao')
  776. self.assertEqual(
  777. HTTPStatus.BAD_REQUEST, channel.code, msg=channel.result["body"]
  778. )
  779. channel = self.make_request(
  780. "PUT", self.path, '[{"_name":"bo"},{"_name":"jill"}]'
  781. )
  782. self.assertEqual(
  783. HTTPStatus.BAD_REQUEST, channel.code, msg=channel.result["body"]
  784. )
  785. channel = self.make_request("PUT", self.path, "text only")
  786. self.assertEqual(
  787. HTTPStatus.BAD_REQUEST, channel.code, msg=channel.result["body"]
  788. )
  789. channel = self.make_request("PUT", self.path, "")
  790. self.assertEqual(
  791. HTTPStatus.BAD_REQUEST, channel.code, msg=channel.result["body"]
  792. )
  793. # valid key, wrong type
  794. content = '{"topic":["Topic name"]}'
  795. channel = self.make_request("PUT", self.path, content)
  796. self.assertEqual(
  797. HTTPStatus.BAD_REQUEST, channel.code, msg=channel.result["body"]
  798. )
  799. def test_rooms_topic(self) -> None:
  800. # nothing should be there
  801. channel = self.make_request("GET", self.path)
  802. self.assertEqual(HTTPStatus.NOT_FOUND, channel.code, msg=channel.result["body"])
  803. # valid put
  804. content = '{"topic":"Topic name"}'
  805. channel = self.make_request("PUT", self.path, content)
  806. self.assertEqual(HTTPStatus.OK, channel.code, msg=channel.result["body"])
  807. # valid get
  808. channel = self.make_request("GET", self.path)
  809. self.assertEqual(HTTPStatus.OK, channel.code, msg=channel.result["body"])
  810. self.assert_dict(json.loads(content), channel.json_body)
  811. def test_rooms_topic_with_extra_keys(self) -> None:
  812. # valid put with extra keys
  813. content = '{"topic":"Seasons","subtopic":"Summer"}'
  814. channel = self.make_request("PUT", self.path, content)
  815. self.assertEqual(HTTPStatus.OK, channel.code, msg=channel.result["body"])
  816. # valid get
  817. channel = self.make_request("GET", self.path)
  818. self.assertEqual(HTTPStatus.OK, channel.code, msg=channel.result["body"])
  819. self.assert_dict(json.loads(content), channel.json_body)
  820. class RoomMemberStateTestCase(RoomBase):
  821. """Tests /rooms/$room_id/members/$user_id/state REST events."""
  822. user_id = "@sid1:red"
  823. def prepare(self, reactor: MemoryReactor, clock: Clock, hs: HomeServer) -> None:
  824. self.room_id = self.helper.create_room_as(self.user_id)
  825. def test_invalid_puts(self) -> None:
  826. path = "/rooms/%s/state/m.room.member/%s" % (self.room_id, self.user_id)
  827. # missing keys or invalid json
  828. channel = self.make_request("PUT", path, "{}")
  829. self.assertEqual(
  830. HTTPStatus.BAD_REQUEST, channel.code, msg=channel.result["body"]
  831. )
  832. channel = self.make_request("PUT", path, '{"_name":"bo"}')
  833. self.assertEqual(
  834. HTTPStatus.BAD_REQUEST, channel.code, msg=channel.result["body"]
  835. )
  836. channel = self.make_request("PUT", path, '{"nao')
  837. self.assertEqual(
  838. HTTPStatus.BAD_REQUEST, channel.code, msg=channel.result["body"]
  839. )
  840. channel = self.make_request("PUT", path, b'[{"_name":"bo"},{"_name":"jill"}]')
  841. self.assertEqual(
  842. HTTPStatus.BAD_REQUEST, channel.code, msg=channel.result["body"]
  843. )
  844. channel = self.make_request("PUT", path, "text only")
  845. self.assertEqual(
  846. HTTPStatus.BAD_REQUEST, channel.code, msg=channel.result["body"]
  847. )
  848. channel = self.make_request("PUT", path, "")
  849. self.assertEqual(
  850. HTTPStatus.BAD_REQUEST, channel.code, msg=channel.result["body"]
  851. )
  852. # valid keys, wrong types
  853. content = '{"membership":["%s","%s","%s"]}' % (
  854. Membership.INVITE,
  855. Membership.JOIN,
  856. Membership.LEAVE,
  857. )
  858. channel = self.make_request("PUT", path, content.encode("ascii"))
  859. self.assertEqual(
  860. HTTPStatus.BAD_REQUEST, channel.code, msg=channel.result["body"]
  861. )
  862. def test_rooms_members_self(self) -> None:
  863. path = "/rooms/%s/state/m.room.member/%s" % (
  864. urlparse.quote(self.room_id),
  865. self.user_id,
  866. )
  867. # valid join message (NOOP since we made the room)
  868. content = '{"membership":"%s"}' % Membership.JOIN
  869. channel = self.make_request("PUT", path, content.encode("ascii"))
  870. self.assertEqual(HTTPStatus.OK, channel.code, msg=channel.result["body"])
  871. channel = self.make_request("GET", path, content=b"")
  872. self.assertEqual(HTTPStatus.OK, channel.code, msg=channel.result["body"])
  873. expected_response = {"membership": Membership.JOIN}
  874. self.assertEqual(expected_response, channel.json_body)
  875. def test_rooms_members_other(self) -> None:
  876. self.other_id = "@zzsid1:red"
  877. path = "/rooms/%s/state/m.room.member/%s" % (
  878. urlparse.quote(self.room_id),
  879. self.other_id,
  880. )
  881. # valid invite message
  882. content = '{"membership":"%s"}' % Membership.INVITE
  883. channel = self.make_request("PUT", path, content)
  884. self.assertEqual(HTTPStatus.OK, channel.code, msg=channel.result["body"])
  885. channel = self.make_request("GET", path, content=b"")
  886. self.assertEqual(HTTPStatus.OK, channel.code, msg=channel.result["body"])
  887. self.assertEqual(json.loads(content), channel.json_body)
  888. def test_rooms_members_other_custom_keys(self) -> None:
  889. self.other_id = "@zzsid1:red"
  890. path = "/rooms/%s/state/m.room.member/%s" % (
  891. urlparse.quote(self.room_id),
  892. self.other_id,
  893. )
  894. # valid invite message with custom key
  895. content = '{"membership":"%s","invite_text":"%s"}' % (
  896. Membership.INVITE,
  897. "Join us!",
  898. )
  899. channel = self.make_request("PUT", path, content)
  900. self.assertEqual(HTTPStatus.OK, channel.code, msg=channel.result["body"])
  901. channel = self.make_request("GET", path, content=b"")
  902. self.assertEqual(HTTPStatus.OK, channel.code, msg=channel.result["body"])
  903. self.assertEqual(json.loads(content), channel.json_body)
  904. class RoomInviteRatelimitTestCase(RoomBase):
  905. user_id = "@sid1:red"
  906. servlets = [
  907. admin.register_servlets,
  908. profile.register_servlets,
  909. room.register_servlets,
  910. ]
  911. @unittest.override_config(
  912. {"rc_invites": {"per_room": {"per_second": 0.5, "burst_count": 3}}}
  913. )
  914. def test_invites_by_rooms_ratelimit(self) -> None:
  915. """Tests that invites in a room are actually rate-limited."""
  916. room_id = self.helper.create_room_as(self.user_id)
  917. for i in range(3):
  918. self.helper.invite(room_id, self.user_id, "@user-%s:red" % (i,))
  919. self.helper.invite(room_id, self.user_id, "@user-4:red", expect_code=429)
  920. @unittest.override_config(
  921. {"rc_invites": {"per_user": {"per_second": 0.5, "burst_count": 3}}}
  922. )
  923. def test_invites_by_users_ratelimit(self) -> None:
  924. """Tests that invites to a specific user are actually rate-limited."""
  925. for _ in range(3):
  926. room_id = self.helper.create_room_as(self.user_id)
  927. self.helper.invite(room_id, self.user_id, "@other-users:red")
  928. room_id = self.helper.create_room_as(self.user_id)
  929. self.helper.invite(room_id, self.user_id, "@other-users:red", expect_code=429)
  930. class RoomJoinTestCase(RoomBase):
  931. servlets = [
  932. admin.register_servlets,
  933. login.register_servlets,
  934. room.register_servlets,
  935. ]
  936. def prepare(self, reactor: MemoryReactor, clock: Clock, hs: HomeServer) -> None:
  937. self.user1 = self.register_user("thomas", "hackme")
  938. self.tok1 = self.login("thomas", "hackme")
  939. self.user2 = self.register_user("teresa", "hackme")
  940. self.tok2 = self.login("teresa", "hackme")
  941. self.room1 = self.helper.create_room_as(room_creator=self.user1, tok=self.tok1)
  942. self.room2 = self.helper.create_room_as(room_creator=self.user1, tok=self.tok1)
  943. self.room3 = self.helper.create_room_as(room_creator=self.user1, tok=self.tok1)
  944. def test_spam_checker_may_join_room_deprecated(self) -> None:
  945. """Tests that the user_may_join_room spam checker callback is correctly called
  946. and blocks room joins when needed.
  947. This test uses the deprecated API, in which callbacks return booleans.
  948. """
  949. # Register a dummy callback. Make it allow all room joins for now.
  950. return_value = True
  951. async def user_may_join_room(
  952. userid: str,
  953. room_id: str,
  954. is_invited: bool,
  955. ) -> bool:
  956. return return_value
  957. # `spec` argument is needed for this function mock to have `__qualname__`, which
  958. # is needed for `Measure` metrics buried in SpamChecker.
  959. callback_mock = Mock(side_effect=user_may_join_room, spec=lambda *x: None)
  960. self.hs.get_module_api_callbacks().spam_checker._user_may_join_room_callbacks.append(
  961. callback_mock
  962. )
  963. # Join a first room, without being invited to it.
  964. self.helper.join(self.room1, self.user2, tok=self.tok2)
  965. # Check that the callback was called with the right arguments.
  966. expected_call_args = (
  967. (
  968. self.user2,
  969. self.room1,
  970. False,
  971. ),
  972. )
  973. self.assertEqual(
  974. callback_mock.call_args,
  975. expected_call_args,
  976. callback_mock.call_args,
  977. )
  978. # Join a second room, this time with an invite for it.
  979. self.helper.invite(self.room2, self.user1, self.user2, tok=self.tok1)
  980. self.helper.join(self.room2, self.user2, tok=self.tok2)
  981. # Check that the callback was called with the right arguments.
  982. expected_call_args = (
  983. (
  984. self.user2,
  985. self.room2,
  986. True,
  987. ),
  988. )
  989. self.assertEqual(
  990. callback_mock.call_args,
  991. expected_call_args,
  992. callback_mock.call_args,
  993. )
  994. # Now make the callback deny all room joins, and check that a join actually fails.
  995. return_value = False
  996. self.helper.join(
  997. self.room3, self.user2, expect_code=HTTPStatus.FORBIDDEN, tok=self.tok2
  998. )
  999. def test_spam_checker_may_join_room(self) -> None:
  1000. """Tests that the user_may_join_room spam checker callback is correctly called
  1001. and blocks room joins when needed.
  1002. This test uses the latest API to this day, in which callbacks return `NOT_SPAM` or `Codes`.
  1003. """
  1004. # Register a dummy callback. Make it allow all room joins for now.
  1005. return_value: Union[
  1006. Literal["NOT_SPAM"], Tuple[Codes, dict], Codes
  1007. ] = synapse.module_api.NOT_SPAM
  1008. async def user_may_join_room(
  1009. userid: str,
  1010. room_id: str,
  1011. is_invited: bool,
  1012. ) -> Union[Literal["NOT_SPAM"], Tuple[Codes, dict], Codes]:
  1013. return return_value
  1014. # `spec` argument is needed for this function mock to have `__qualname__`, which
  1015. # is needed for `Measure` metrics buried in SpamChecker.
  1016. callback_mock = Mock(side_effect=user_may_join_room, spec=lambda *x: None)
  1017. self.hs.get_module_api_callbacks().spam_checker._user_may_join_room_callbacks.append(
  1018. callback_mock
  1019. )
  1020. # Join a first room, without being invited to it.
  1021. self.helper.join(self.room1, self.user2, tok=self.tok2)
  1022. # Check that the callback was called with the right arguments.
  1023. expected_call_args = (
  1024. (
  1025. self.user2,
  1026. self.room1,
  1027. False,
  1028. ),
  1029. )
  1030. self.assertEqual(
  1031. callback_mock.call_args,
  1032. expected_call_args,
  1033. callback_mock.call_args,
  1034. )
  1035. # Join a second room, this time with an invite for it.
  1036. self.helper.invite(self.room2, self.user1, self.user2, tok=self.tok1)
  1037. self.helper.join(self.room2, self.user2, tok=self.tok2)
  1038. # Check that the callback was called with the right arguments.
  1039. expected_call_args = (
  1040. (
  1041. self.user2,
  1042. self.room2,
  1043. True,
  1044. ),
  1045. )
  1046. self.assertEqual(
  1047. callback_mock.call_args,
  1048. expected_call_args,
  1049. callback_mock.call_args,
  1050. )
  1051. # Now make the callback deny all room joins, and check that a join actually fails.
  1052. # We pick an arbitrary Codes rather than the default `Codes.FORBIDDEN`.
  1053. return_value = Codes.CONSENT_NOT_GIVEN
  1054. self.helper.invite(self.room3, self.user1, self.user2, tok=self.tok1)
  1055. self.helper.join(
  1056. self.room3,
  1057. self.user2,
  1058. expect_code=HTTPStatus.FORBIDDEN,
  1059. expect_errcode=return_value,
  1060. tok=self.tok2,
  1061. )
  1062. # Now make the callback deny all room joins, and check that a join actually fails.
  1063. # As above, with the experimental extension that lets us return dictionaries.
  1064. return_value = (Codes.BAD_ALIAS, {"another_field": "12345"})
  1065. self.helper.join(
  1066. self.room3,
  1067. self.user2,
  1068. expect_code=HTTPStatus.FORBIDDEN,
  1069. expect_errcode=return_value[0],
  1070. tok=self.tok2,
  1071. expect_additional_fields=return_value[1],
  1072. )
  1073. class RoomAppserviceTsParamTestCase(unittest.HomeserverTestCase):
  1074. servlets = [
  1075. room.register_servlets,
  1076. synapse.rest.admin.register_servlets,
  1077. register.register_servlets,
  1078. ]
  1079. def prepare(self, reactor: MemoryReactor, clock: Clock, hs: HomeServer) -> None:
  1080. self.appservice_user, _ = self.register_appservice_user(
  1081. "as_user_potato", self.appservice.token
  1082. )
  1083. # Create a room as the appservice user.
  1084. args = {
  1085. "access_token": self.appservice.token,
  1086. "user_id": self.appservice_user,
  1087. }
  1088. channel = self.make_request(
  1089. "POST",
  1090. f"/_matrix/client/r0/createRoom?{urlparse.urlencode(args)}",
  1091. content={"visibility": "public"},
  1092. )
  1093. assert channel.code == 200
  1094. self.room = channel.json_body["room_id"]
  1095. self.main_store = self.hs.get_datastores().main
  1096. def make_homeserver(self, reactor: MemoryReactor, clock: Clock) -> HomeServer:
  1097. config = self.default_config()
  1098. self.appservice = ApplicationService(
  1099. token="i_am_an_app_service",
  1100. id="1234",
  1101. namespaces={"users": [{"regex": r"@as_user.*", "exclusive": True}]},
  1102. # Note: this user does not have to match the regex above
  1103. sender="@as_main:test",
  1104. )
  1105. mock_load_appservices = Mock(return_value=[self.appservice])
  1106. with patch(
  1107. "synapse.storage.databases.main.appservice.load_appservices",
  1108. mock_load_appservices,
  1109. ):
  1110. hs = self.setup_test_homeserver(config=config)
  1111. return hs
  1112. def test_send_event_ts(self) -> None:
  1113. """Test sending a non-state event with a custom timestamp."""
  1114. ts = 1
  1115. url_params = {
  1116. "user_id": self.appservice_user,
  1117. "ts": ts,
  1118. }
  1119. channel = self.make_request(
  1120. "PUT",
  1121. path=f"/_matrix/client/r0/rooms/{self.room}/send/m.room.message/1234?"
  1122. + urlparse.urlencode(url_params),
  1123. content={"body": "test", "msgtype": "m.text"},
  1124. access_token=self.appservice.token,
  1125. )
  1126. self.assertEqual(channel.code, 200, channel.json_body)
  1127. event_id = channel.json_body["event_id"]
  1128. # Ensure the event was persisted with the correct timestamp.
  1129. res = self.get_success(self.main_store.get_event(event_id))
  1130. self.assertEqual(ts, res.origin_server_ts)
  1131. def test_send_state_event_ts(self) -> None:
  1132. """Test sending a state event with a custom timestamp."""
  1133. ts = 1
  1134. url_params = {
  1135. "user_id": self.appservice_user,
  1136. "ts": ts,
  1137. }
  1138. channel = self.make_request(
  1139. "PUT",
  1140. path=f"/_matrix/client/r0/rooms/{self.room}/state/m.room.name?"
  1141. + urlparse.urlencode(url_params),
  1142. content={"name": "test"},
  1143. access_token=self.appservice.token,
  1144. )
  1145. self.assertEqual(channel.code, 200, channel.json_body)
  1146. event_id = channel.json_body["event_id"]
  1147. # Ensure the event was persisted with the correct timestamp.
  1148. res = self.get_success(self.main_store.get_event(event_id))
  1149. self.assertEqual(ts, res.origin_server_ts)
  1150. def test_send_membership_event_ts(self) -> None:
  1151. """Test sending a membership event with a custom timestamp."""
  1152. ts = 1
  1153. url_params = {
  1154. "user_id": self.appservice_user,
  1155. "ts": ts,
  1156. }
  1157. channel = self.make_request(
  1158. "PUT",
  1159. path=f"/_matrix/client/r0/rooms/{self.room}/state/m.room.member/{self.appservice_user}?"
  1160. + urlparse.urlencode(url_params),
  1161. content={"membership": "join", "display_name": "test"},
  1162. access_token=self.appservice.token,
  1163. )
  1164. self.assertEqual(channel.code, 200, channel.json_body)
  1165. event_id = channel.json_body["event_id"]
  1166. # Ensure the event was persisted with the correct timestamp.
  1167. res = self.get_success(self.main_store.get_event(event_id))
  1168. self.assertEqual(ts, res.origin_server_ts)
  1169. class RoomJoinRatelimitTestCase(RoomBase):
  1170. user_id = "@sid1:red"
  1171. servlets = [
  1172. admin.register_servlets,
  1173. profile.register_servlets,
  1174. room.register_servlets,
  1175. ]
  1176. def prepare(self, reactor: MemoryReactor, clock: Clock, hs: HomeServer) -> None:
  1177. super().prepare(reactor, clock, hs)
  1178. # profile changes expect that the user is actually registered
  1179. user = UserID.from_string(self.user_id)
  1180. self.register_user(user.localpart, "supersecretpassword")
  1181. @unittest.override_config(
  1182. {"rc_joins": {"local": {"per_second": 0.5, "burst_count": 3}}}
  1183. )
  1184. def test_join_local_ratelimit(self) -> None:
  1185. """Tests that local joins are actually rate-limited."""
  1186. # Create 4 rooms
  1187. room_ids = [
  1188. self.helper.create_room_as(self.user_id, is_public=True) for _ in range(4)
  1189. ]
  1190. joiner_user_id = self.register_user("joiner", "secret")
  1191. # Now make a new user try to join some of them.
  1192. # The user can join 3 rooms
  1193. for room_id in room_ids[0:3]:
  1194. self.helper.join(room_id, joiner_user_id)
  1195. # But the user cannot join a 4th room
  1196. self.helper.join(
  1197. room_ids[3], joiner_user_id, expect_code=HTTPStatus.TOO_MANY_REQUESTS
  1198. )
  1199. @unittest.override_config(
  1200. {"rc_joins": {"local": {"per_second": 0.5, "burst_count": 3}}}
  1201. )
  1202. def test_join_attempts_local_ratelimit(self) -> None:
  1203. """Tests that unsuccessful joins that end up being denied are rate-limited."""
  1204. # Create 4 rooms
  1205. room_ids = [
  1206. self.helper.create_room_as(self.user_id, is_public=True) for _ in range(4)
  1207. ]
  1208. # Pre-emptively ban the user who will attempt to join.
  1209. joiner_user_id = self.register_user("joiner", "secret")
  1210. for room_id in room_ids:
  1211. self.helper.ban(room_id, self.user_id, joiner_user_id)
  1212. # Now make a new user try to join some of them.
  1213. # The user can make 3 requests, each of which should be denied.
  1214. for room_id in room_ids[0:3]:
  1215. self.helper.join(room_id, joiner_user_id, expect_code=HTTPStatus.FORBIDDEN)
  1216. # The fourth attempt should be rate limited.
  1217. self.helper.join(
  1218. room_ids[3], joiner_user_id, expect_code=HTTPStatus.TOO_MANY_REQUESTS
  1219. )
  1220. @unittest.override_config(
  1221. {"rc_joins": {"local": {"per_second": 0.5, "burst_count": 3}}}
  1222. )
  1223. def test_join_local_ratelimit_profile_change(self) -> None:
  1224. """Tests that sending a profile update into all of the user's joined rooms isn't
  1225. rate-limited by the rate-limiter on joins."""
  1226. # Create and join as many rooms as the rate-limiting config allows in a second.
  1227. room_ids = [
  1228. self.helper.create_room_as(self.user_id),
  1229. self.helper.create_room_as(self.user_id),
  1230. self.helper.create_room_as(self.user_id),
  1231. ]
  1232. # Let some time for the rate-limiter to forget about our multi-join.
  1233. self.reactor.advance(2)
  1234. # Add one to make sure we're joined to more rooms than the config allows us to
  1235. # join in a second.
  1236. room_ids.append(self.helper.create_room_as(self.user_id))
  1237. # Update the display name for the user.
  1238. path = "/_matrix/client/r0/profile/%s/displayname" % self.user_id
  1239. channel = self.make_request("PUT", path, {"displayname": "John Doe"})
  1240. self.assertEqual(channel.code, HTTPStatus.OK, channel.json_body)
  1241. # Check that all the rooms have been sent a profile update into.
  1242. for room_id in room_ids:
  1243. path = "/_matrix/client/r0/rooms/%s/state/m.room.member/%s" % (
  1244. room_id,
  1245. self.user_id,
  1246. )
  1247. channel = self.make_request("GET", path)
  1248. self.assertEqual(channel.code, 200)
  1249. self.assertIn("displayname", channel.json_body)
  1250. self.assertEqual(channel.json_body["displayname"], "John Doe")
  1251. @unittest.override_config(
  1252. {"rc_joins": {"local": {"per_second": 0.5, "burst_count": 3}}}
  1253. )
  1254. def test_join_local_ratelimit_idempotent(self) -> None:
  1255. """Tests that the room join endpoints remain idempotent despite rate-limiting
  1256. on room joins."""
  1257. room_id = self.helper.create_room_as(self.user_id)
  1258. # Let's test both paths to be sure.
  1259. paths_to_test = [
  1260. "/_matrix/client/r0/rooms/%s/join",
  1261. "/_matrix/client/r0/join/%s",
  1262. ]
  1263. for path in paths_to_test:
  1264. # Make sure we send more requests than the rate-limiting config would allow
  1265. # if all of these requests ended up joining the user to a room.
  1266. for _ in range(4):
  1267. channel = self.make_request("POST", path % room_id, {})
  1268. self.assertEqual(channel.code, 200)
  1269. @unittest.override_config(
  1270. {
  1271. "rc_joins": {"local": {"per_second": 0.5, "burst_count": 3}},
  1272. "auto_join_rooms": ["#room:red", "#room2:red", "#room3:red", "#room4:red"],
  1273. "autocreate_auto_join_rooms": True,
  1274. },
  1275. )
  1276. def test_autojoin_rooms(self) -> None:
  1277. user_id = self.register_user("testuser", "password")
  1278. # Check that the new user successfully joined the four rooms
  1279. rooms = self.get_success(
  1280. self.hs.get_datastores().main.get_rooms_for_user(user_id)
  1281. )
  1282. self.assertEqual(len(rooms), 4)
  1283. class RoomMessagesTestCase(RoomBase):
  1284. """Tests /rooms/$room_id/messages/$user_id/$msg_id REST events."""
  1285. user_id = "@sid1:red"
  1286. def prepare(self, reactor: MemoryReactor, clock: Clock, hs: HomeServer) -> None:
  1287. self.room_id = self.helper.create_room_as(self.user_id)
  1288. def test_invalid_puts(self) -> None:
  1289. path = "/rooms/%s/send/m.room.message/mid1" % (urlparse.quote(self.room_id))
  1290. # missing keys or invalid json
  1291. channel = self.make_request("PUT", path, b"{}")
  1292. self.assertEqual(
  1293. HTTPStatus.BAD_REQUEST, channel.code, msg=channel.result["body"]
  1294. )
  1295. channel = self.make_request("PUT", path, b'{"_name":"bo"}')
  1296. self.assertEqual(
  1297. HTTPStatus.BAD_REQUEST, channel.code, msg=channel.result["body"]
  1298. )
  1299. channel = self.make_request("PUT", path, b'{"nao')
  1300. self.assertEqual(
  1301. HTTPStatus.BAD_REQUEST, channel.code, msg=channel.result["body"]
  1302. )
  1303. channel = self.make_request("PUT", path, b'[{"_name":"bo"},{"_name":"jill"}]')
  1304. self.assertEqual(
  1305. HTTPStatus.BAD_REQUEST, channel.code, msg=channel.result["body"]
  1306. )
  1307. channel = self.make_request("PUT", path, b"text only")
  1308. self.assertEqual(
  1309. HTTPStatus.BAD_REQUEST, channel.code, msg=channel.result["body"]
  1310. )
  1311. channel = self.make_request("PUT", path, b"")
  1312. self.assertEqual(
  1313. HTTPStatus.BAD_REQUEST, channel.code, msg=channel.result["body"]
  1314. )
  1315. def test_rooms_messages_sent(self) -> None:
  1316. path = "/rooms/%s/send/m.room.message/mid1" % (urlparse.quote(self.room_id))
  1317. content = b'{"body":"test","msgtype":{"type":"a"}}'
  1318. channel = self.make_request("PUT", path, content)
  1319. self.assertEqual(
  1320. HTTPStatus.BAD_REQUEST, channel.code, msg=channel.result["body"]
  1321. )
  1322. # custom message types
  1323. content = b'{"body":"test","msgtype":"test.custom.text"}'
  1324. channel = self.make_request("PUT", path, content)
  1325. self.assertEqual(HTTPStatus.OK, channel.code, msg=channel.result["body"])
  1326. # m.text message type
  1327. path = "/rooms/%s/send/m.room.message/mid2" % (urlparse.quote(self.room_id))
  1328. content = b'{"body":"test2","msgtype":"m.text"}'
  1329. channel = self.make_request("PUT", path, content)
  1330. self.assertEqual(HTTPStatus.OK, channel.code, msg=channel.result["body"])
  1331. @parameterized.expand(
  1332. [
  1333. # Allow
  1334. param(
  1335. name="NOT_SPAM",
  1336. value="NOT_SPAM",
  1337. expected_code=HTTPStatus.OK,
  1338. expected_fields={},
  1339. ),
  1340. param(
  1341. name="False",
  1342. value=False,
  1343. expected_code=HTTPStatus.OK,
  1344. expected_fields={},
  1345. ),
  1346. # Block
  1347. param(
  1348. name="scalene string",
  1349. value="ANY OTHER STRING",
  1350. expected_code=HTTPStatus.FORBIDDEN,
  1351. expected_fields={"errcode": "M_FORBIDDEN"},
  1352. ),
  1353. param(
  1354. name="True",
  1355. value=True,
  1356. expected_code=HTTPStatus.FORBIDDEN,
  1357. expected_fields={"errcode": "M_FORBIDDEN"},
  1358. ),
  1359. param(
  1360. name="Code",
  1361. value=Codes.LIMIT_EXCEEDED,
  1362. expected_code=HTTPStatus.FORBIDDEN,
  1363. expected_fields={"errcode": "M_LIMIT_EXCEEDED"},
  1364. ),
  1365. param(
  1366. name="Tuple",
  1367. value=(Codes.SERVER_NOT_TRUSTED, {"additional_field": "12345"}),
  1368. expected_code=HTTPStatus.FORBIDDEN,
  1369. expected_fields={
  1370. "errcode": "M_SERVER_NOT_TRUSTED",
  1371. "additional_field": "12345",
  1372. },
  1373. ),
  1374. ]
  1375. )
  1376. def test_spam_checker_check_event_for_spam(
  1377. self,
  1378. name: str,
  1379. value: Union[str, bool, Codes, Tuple[Codes, JsonDict]],
  1380. expected_code: int,
  1381. expected_fields: dict,
  1382. ) -> None:
  1383. class SpamCheck:
  1384. mock_return_value: Union[
  1385. str, bool, Codes, Tuple[Codes, JsonDict], bool
  1386. ] = "NOT_SPAM"
  1387. mock_content: Optional[JsonDict] = None
  1388. async def check_event_for_spam(
  1389. self,
  1390. event: synapse.events.EventBase,
  1391. ) -> Union[str, Codes, Tuple[Codes, JsonDict], bool]:
  1392. self.mock_content = event.content
  1393. return self.mock_return_value
  1394. spam_checker = SpamCheck()
  1395. self.hs.get_module_api_callbacks().spam_checker._check_event_for_spam_callbacks.append(
  1396. spam_checker.check_event_for_spam
  1397. )
  1398. # Inject `value` as mock_return_value
  1399. spam_checker.mock_return_value = value
  1400. path = "/rooms/%s/send/m.room.message/check_event_for_spam_%s" % (
  1401. urlparse.quote(self.room_id),
  1402. urlparse.quote(name),
  1403. )
  1404. body = "test-%s" % name
  1405. content = '{"body":"%s","msgtype":"m.text"}' % body
  1406. channel = self.make_request("PUT", path, content)
  1407. # Check that the callback has witnessed the correct event.
  1408. self.assertIsNotNone(spam_checker.mock_content)
  1409. if (
  1410. spam_checker.mock_content is not None
  1411. ): # Checked just above, but mypy doesn't know about that.
  1412. self.assertEqual(
  1413. spam_checker.mock_content["body"], body, spam_checker.mock_content
  1414. )
  1415. # Check that we have the correct result.
  1416. self.assertEqual(expected_code, channel.code, msg=channel.result["body"])
  1417. for expected_key, expected_value in expected_fields.items():
  1418. self.assertEqual(
  1419. channel.json_body.get(expected_key, None),
  1420. expected_value,
  1421. "Field %s absent or invalid " % expected_key,
  1422. )
  1423. class RoomPowerLevelOverridesTestCase(RoomBase):
  1424. """Tests that the power levels can be overridden with server config."""
  1425. user_id = "@sid1:red"
  1426. servlets = [
  1427. admin.register_servlets,
  1428. room.register_servlets,
  1429. login.register_servlets,
  1430. ]
  1431. def prepare(self, reactor: MemoryReactor, clock: Clock, hs: HomeServer) -> None:
  1432. self.admin_user_id = self.register_user("admin", "pass")
  1433. self.admin_access_token = self.login("admin", "pass")
  1434. def power_levels(self, room_id: str) -> Dict[str, Any]:
  1435. return self.helper.get_state(
  1436. room_id, "m.room.power_levels", self.admin_access_token
  1437. )
  1438. def test_default_power_levels_with_room_override(self) -> None:
  1439. """
  1440. Create a room, providing power level overrides.
  1441. Confirm that the room's power levels reflect the overrides.
  1442. See https://github.com/matrix-org/matrix-spec/issues/492
  1443. - currently we overwrite each key of power_level_content_override
  1444. completely.
  1445. """
  1446. room_id = self.helper.create_room_as(
  1447. self.user_id,
  1448. extra_content={
  1449. "power_level_content_override": {"events": {"custom.event": 0}}
  1450. },
  1451. )
  1452. self.assertEqual(
  1453. {
  1454. "custom.event": 0,
  1455. },
  1456. self.power_levels(room_id)["events"],
  1457. )
  1458. @unittest.override_config(
  1459. {
  1460. "default_power_level_content_override": {
  1461. "public_chat": {"events": {"custom.event": 0}},
  1462. }
  1463. },
  1464. )
  1465. def test_power_levels_with_server_override(self) -> None:
  1466. """
  1467. With a server configured to modify the room-level defaults,
  1468. Create a room, without providing any extra power level overrides.
  1469. Confirm that the room's power levels reflect the server-level overrides.
  1470. Similar to https://github.com/matrix-org/matrix-spec/issues/492,
  1471. we overwrite each key of power_level_content_override completely.
  1472. """
  1473. room_id = self.helper.create_room_as(self.user_id)
  1474. self.assertEqual(
  1475. {
  1476. "custom.event": 0,
  1477. },
  1478. self.power_levels(room_id)["events"],
  1479. )
  1480. @unittest.override_config(
  1481. {
  1482. "default_power_level_content_override": {
  1483. "public_chat": {
  1484. "events": {"server.event": 0},
  1485. "ban": 13,
  1486. },
  1487. }
  1488. },
  1489. )
  1490. def test_power_levels_with_server_and_room_overrides(self) -> None:
  1491. """
  1492. With a server configured to modify the room-level defaults,
  1493. create a room, providing different overrides.
  1494. Confirm that the room's power levels reflect both overrides, and
  1495. choose the room overrides where they clash.
  1496. """
  1497. room_id = self.helper.create_room_as(
  1498. self.user_id,
  1499. extra_content={
  1500. "power_level_content_override": {"events": {"room.event": 0}}
  1501. },
  1502. )
  1503. # Room override wins over server config
  1504. self.assertEqual(
  1505. {"room.event": 0},
  1506. self.power_levels(room_id)["events"],
  1507. )
  1508. # But where there is no room override, server config wins
  1509. self.assertEqual(13, self.power_levels(room_id)["ban"])
  1510. class RoomPowerLevelOverridesInPracticeTestCase(RoomBase):
  1511. """
  1512. Tests that we can really do various otherwise-prohibited actions
  1513. based on overriding the power levels in config.
  1514. """
  1515. user_id = "@sid1:red"
  1516. def test_creator_can_post_state_event(self) -> None:
  1517. # Given I am the creator of a room
  1518. room_id = self.helper.create_room_as(self.user_id)
  1519. # When I send a state event
  1520. path = "/rooms/{room_id}/state/custom.event/my_state_key".format(
  1521. room_id=urlparse.quote(room_id),
  1522. )
  1523. channel = self.make_request("PUT", path, "{}")
  1524. # Then I am allowed
  1525. self.assertEqual(HTTPStatus.OK, channel.code, msg=channel.result["body"])
  1526. def test_normal_user_can_not_post_state_event(self) -> None:
  1527. # Given I am a normal member of a room
  1528. room_id = self.helper.create_room_as("@some_other_guy:red")
  1529. self.helper.join(room=room_id, user=self.user_id)
  1530. # When I send a state event
  1531. path = "/rooms/{room_id}/state/custom.event/my_state_key".format(
  1532. room_id=urlparse.quote(room_id),
  1533. )
  1534. channel = self.make_request("PUT", path, "{}")
  1535. # Then I am not allowed because state events require PL>=50
  1536. self.assertEqual(HTTPStatus.FORBIDDEN, channel.code, msg=channel.result["body"])
  1537. self.assertEqual(
  1538. "You don't have permission to post that to the room. "
  1539. "user_level (0) < send_level (50)",
  1540. channel.json_body["error"],
  1541. )
  1542. @unittest.override_config(
  1543. {
  1544. "default_power_level_content_override": {
  1545. "public_chat": {"events": {"custom.event": 0}},
  1546. }
  1547. },
  1548. )
  1549. def test_with_config_override_normal_user_can_post_state_event(self) -> None:
  1550. # Given the server has config allowing normal users to post my event type,
  1551. # and I am a normal member of a room
  1552. room_id = self.helper.create_room_as("@some_other_guy:red")
  1553. self.helper.join(room=room_id, user=self.user_id)
  1554. # When I send a state event
  1555. path = "/rooms/{room_id}/state/custom.event/my_state_key".format(
  1556. room_id=urlparse.quote(room_id),
  1557. )
  1558. channel = self.make_request("PUT", path, "{}")
  1559. # Then I am allowed
  1560. self.assertEqual(HTTPStatus.OK, channel.code, msg=channel.result["body"])
  1561. @unittest.override_config(
  1562. {
  1563. "default_power_level_content_override": {
  1564. "public_chat": {"events": {"custom.event": 0}},
  1565. }
  1566. },
  1567. )
  1568. def test_any_room_override_defeats_config_override(self) -> None:
  1569. # Given the server has config allowing normal users to post my event type
  1570. # And I am a normal member of a room
  1571. # But the room was created with special permissions
  1572. extra_content: Dict[str, Any] = {
  1573. "power_level_content_override": {"events": {}},
  1574. }
  1575. room_id = self.helper.create_room_as(
  1576. "@some_other_guy:red", extra_content=extra_content
  1577. )
  1578. self.helper.join(room=room_id, user=self.user_id)
  1579. # When I send a state event
  1580. path = "/rooms/{room_id}/state/custom.event/my_state_key".format(
  1581. room_id=urlparse.quote(room_id),
  1582. )
  1583. channel = self.make_request("PUT", path, "{}")
  1584. # Then I am not allowed
  1585. self.assertEqual(HTTPStatus.FORBIDDEN, channel.code, msg=channel.result["body"])
  1586. @unittest.override_config(
  1587. {
  1588. "default_power_level_content_override": {
  1589. "public_chat": {"events": {"custom.event": 0}},
  1590. }
  1591. },
  1592. )
  1593. def test_specific_room_override_defeats_config_override(self) -> None:
  1594. # Given the server has config allowing normal users to post my event type,
  1595. # and I am a normal member of a room,
  1596. # but the room was created with special permissions for this event type
  1597. extra_content = {
  1598. "power_level_content_override": {"events": {"custom.event": 1}},
  1599. }
  1600. room_id = self.helper.create_room_as(
  1601. "@some_other_guy:red", extra_content=extra_content
  1602. )
  1603. self.helper.join(room=room_id, user=self.user_id)
  1604. # When I send a state event
  1605. path = "/rooms/{room_id}/state/custom.event/my_state_key".format(
  1606. room_id=urlparse.quote(room_id),
  1607. )
  1608. channel = self.make_request("PUT", path, "{}")
  1609. # Then I am not allowed
  1610. self.assertEqual(HTTPStatus.FORBIDDEN, channel.code, msg=channel.result["body"])
  1611. self.assertEqual(
  1612. "You don't have permission to post that to the room. "
  1613. + "user_level (0) < send_level (1)",
  1614. channel.json_body["error"],
  1615. )
  1616. @unittest.override_config(
  1617. {
  1618. "default_power_level_content_override": {
  1619. "public_chat": {"events": {"custom.event": 0}},
  1620. "private_chat": None,
  1621. "trusted_private_chat": None,
  1622. }
  1623. },
  1624. )
  1625. def test_config_override_applies_only_to_specific_preset(self) -> None:
  1626. # Given the server has config for public_chats,
  1627. # and I am a normal member of a private_chat room
  1628. room_id = self.helper.create_room_as("@some_other_guy:red", is_public=False)
  1629. self.helper.invite(room=room_id, src="@some_other_guy:red", targ=self.user_id)
  1630. self.helper.join(room=room_id, user=self.user_id)
  1631. # When I send a state event
  1632. path = "/rooms/{room_id}/state/custom.event/my_state_key".format(
  1633. room_id=urlparse.quote(room_id),
  1634. )
  1635. channel = self.make_request("PUT", path, "{}")
  1636. # Then I am not allowed because the public_chat config does not
  1637. # affect this room, because this room is a private_chat
  1638. self.assertEqual(HTTPStatus.FORBIDDEN, channel.code, msg=channel.result["body"])
  1639. self.assertEqual(
  1640. "You don't have permission to post that to the room. "
  1641. + "user_level (0) < send_level (50)",
  1642. channel.json_body["error"],
  1643. )
  1644. @unittest.override_config(
  1645. {
  1646. "default_power_level_content_override": {
  1647. "private_chat": {
  1648. "events": {
  1649. "m.room.avatar": 50,
  1650. "m.room.canonical_alias": 50,
  1651. "m.room.encryption": 999,
  1652. "m.room.history_visibility": 100,
  1653. "m.room.name": 50,
  1654. "m.room.power_levels": 100,
  1655. "m.room.server_acl": 100,
  1656. "m.room.tombstone": 100,
  1657. },
  1658. "events_default": 0,
  1659. },
  1660. }
  1661. },
  1662. )
  1663. def test_config_override_blocks_encrypted_room(self) -> None:
  1664. # Given the server has config for private_chats,
  1665. # When I attempt to create an encrypted private_chat room
  1666. channel = self.make_request(
  1667. "POST",
  1668. "/createRoom",
  1669. '{"creation_content": {"m.federate": false},"name": "Secret Private Room","preset": "private_chat","initial_state": [{"type": "m.room.encryption","state_key": "","content": {"algorithm": "m.megolm.v1.aes-sha2"}}]}',
  1670. )
  1671. # Then I am not allowed because the required power level is unattainable
  1672. self.assertEqual(HTTPStatus.FORBIDDEN, channel.code, msg=channel.result["body"])
  1673. self.assertEqual(
  1674. "You cannot create an encrypted room. "
  1675. + "user_level (100) < send_level (999)",
  1676. channel.json_body["error"],
  1677. )
  1678. class RoomInitialSyncTestCase(RoomBase):
  1679. """Tests /rooms/$room_id/initialSync."""
  1680. user_id = "@sid1:red"
  1681. def prepare(self, reactor: MemoryReactor, clock: Clock, hs: HomeServer) -> None:
  1682. # create the room
  1683. self.room_id = self.helper.create_room_as(self.user_id)
  1684. def test_initial_sync(self) -> None:
  1685. channel = self.make_request("GET", "/rooms/%s/initialSync" % self.room_id)
  1686. self.assertEqual(HTTPStatus.OK, channel.code)
  1687. self.assertEqual(self.room_id, channel.json_body["room_id"])
  1688. self.assertEqual("join", channel.json_body["membership"])
  1689. # Room state is easier to assert on if we unpack it into a dict
  1690. state: JsonDict = {}
  1691. for event in channel.json_body["state"]:
  1692. if "state_key" not in event:
  1693. continue
  1694. t = event["type"]
  1695. if t not in state:
  1696. state[t] = []
  1697. state[t].append(event)
  1698. self.assertTrue("m.room.create" in state)
  1699. self.assertTrue("messages" in channel.json_body)
  1700. self.assertTrue("chunk" in channel.json_body["messages"])
  1701. self.assertTrue("end" in channel.json_body["messages"])
  1702. self.assertTrue("presence" in channel.json_body)
  1703. presence_by_user = {
  1704. e["content"]["user_id"]: e for e in channel.json_body["presence"]
  1705. }
  1706. self.assertTrue(self.user_id in presence_by_user)
  1707. self.assertEqual(EduTypes.PRESENCE, presence_by_user[self.user_id]["type"])
  1708. class RoomMessageListTestCase(RoomBase):
  1709. """Tests /rooms/$room_id/messages REST events."""
  1710. user_id = "@sid1:red"
  1711. def prepare(self, reactor: MemoryReactor, clock: Clock, hs: HomeServer) -> None:
  1712. self.room_id = self.helper.create_room_as(self.user_id)
  1713. def test_topo_token_is_accepted(self) -> None:
  1714. token = "t1-0_0_0_0_0_0_0_0_0_0"
  1715. channel = self.make_request(
  1716. "GET", "/rooms/%s/messages?access_token=x&from=%s" % (self.room_id, token)
  1717. )
  1718. self.assertEqual(HTTPStatus.OK, channel.code)
  1719. self.assertTrue("start" in channel.json_body)
  1720. self.assertEqual(token, channel.json_body["start"])
  1721. self.assertTrue("chunk" in channel.json_body)
  1722. self.assertTrue("end" in channel.json_body)
  1723. def test_stream_token_is_accepted_for_fwd_pagianation(self) -> None:
  1724. token = "s0_0_0_0_0_0_0_0_0_0"
  1725. channel = self.make_request(
  1726. "GET", "/rooms/%s/messages?access_token=x&from=%s" % (self.room_id, token)
  1727. )
  1728. self.assertEqual(HTTPStatus.OK, channel.code)
  1729. self.assertTrue("start" in channel.json_body)
  1730. self.assertEqual(token, channel.json_body["start"])
  1731. self.assertTrue("chunk" in channel.json_body)
  1732. self.assertTrue("end" in channel.json_body)
  1733. def test_room_messages_purge(self) -> None:
  1734. store = self.hs.get_datastores().main
  1735. pagination_handler = self.hs.get_pagination_handler()
  1736. # Send a first message in the room, which will be removed by the purge.
  1737. first_event_id = self.helper.send(self.room_id, "message 1")["event_id"]
  1738. first_token = self.get_success(
  1739. store.get_topological_token_for_event(first_event_id)
  1740. )
  1741. first_token_str = self.get_success(first_token.to_string(store))
  1742. # Send a second message in the room, which won't be removed, and which we'll
  1743. # use as the marker to purge events before.
  1744. second_event_id = self.helper.send(self.room_id, "message 2")["event_id"]
  1745. second_token = self.get_success(
  1746. store.get_topological_token_for_event(second_event_id)
  1747. )
  1748. second_token_str = self.get_success(second_token.to_string(store))
  1749. # Send a third event in the room to ensure we don't fall under any edge case
  1750. # due to our marker being the latest forward extremity in the room.
  1751. self.helper.send(self.room_id, "message 3")
  1752. # Check that we get the first and second message when querying /messages.
  1753. channel = self.make_request(
  1754. "GET",
  1755. "/rooms/%s/messages?access_token=x&from=%s&dir=b&filter=%s"
  1756. % (
  1757. self.room_id,
  1758. second_token_str,
  1759. json.dumps({"types": [EventTypes.Message]}),
  1760. ),
  1761. )
  1762. self.assertEqual(channel.code, HTTPStatus.OK, channel.json_body)
  1763. chunk = channel.json_body["chunk"]
  1764. self.assertEqual(len(chunk), 2, [event["content"] for event in chunk])
  1765. # Purge every event before the second event.
  1766. self.get_success(
  1767. pagination_handler.purge_history(
  1768. room_id=self.room_id,
  1769. token=second_token_str,
  1770. delete_local_events=True,
  1771. )
  1772. )
  1773. # Check that we only get the second message through /message now that the first
  1774. # has been purged.
  1775. channel = self.make_request(
  1776. "GET",
  1777. "/rooms/%s/messages?access_token=x&from=%s&dir=b&filter=%s"
  1778. % (
  1779. self.room_id,
  1780. second_token_str,
  1781. json.dumps({"types": [EventTypes.Message]}),
  1782. ),
  1783. )
  1784. self.assertEqual(channel.code, HTTPStatus.OK, channel.json_body)
  1785. chunk = channel.json_body["chunk"]
  1786. self.assertEqual(len(chunk), 1, [event["content"] for event in chunk])
  1787. # Check that we get no event, but also no error, when querying /messages with
  1788. # the token that was pointing at the first event, because we don't have it
  1789. # anymore.
  1790. channel = self.make_request(
  1791. "GET",
  1792. "/rooms/%s/messages?access_token=x&from=%s&dir=b&filter=%s"
  1793. % (
  1794. self.room_id,
  1795. first_token_str,
  1796. json.dumps({"types": [EventTypes.Message]}),
  1797. ),
  1798. )
  1799. self.assertEqual(channel.code, HTTPStatus.OK, channel.json_body)
  1800. chunk = channel.json_body["chunk"]
  1801. self.assertEqual(len(chunk), 0, [event["content"] for event in chunk])
  1802. class RoomSearchTestCase(unittest.HomeserverTestCase):
  1803. servlets = [
  1804. synapse.rest.admin.register_servlets_for_client_rest_resource,
  1805. room.register_servlets,
  1806. login.register_servlets,
  1807. ]
  1808. user_id = True
  1809. hijack_auth = False
  1810. def prepare(self, reactor: MemoryReactor, clock: Clock, hs: HomeServer) -> None:
  1811. # Register the user who does the searching
  1812. self.user_id2 = self.register_user("user", "pass")
  1813. self.access_token = self.login("user", "pass")
  1814. # Register the user who sends the message
  1815. self.other_user_id = self.register_user("otheruser", "pass")
  1816. self.other_access_token = self.login("otheruser", "pass")
  1817. # Create a room
  1818. self.room = self.helper.create_room_as(self.user_id2, tok=self.access_token)
  1819. # Invite the other person
  1820. self.helper.invite(
  1821. room=self.room,
  1822. src=self.user_id2,
  1823. tok=self.access_token,
  1824. targ=self.other_user_id,
  1825. )
  1826. # The other user joins
  1827. self.helper.join(
  1828. room=self.room, user=self.other_user_id, tok=self.other_access_token
  1829. )
  1830. def test_finds_message(self) -> None:
  1831. """
  1832. The search functionality will search for content in messages if asked to
  1833. do so.
  1834. """
  1835. # The other user sends some messages
  1836. self.helper.send(self.room, body="Hi!", tok=self.other_access_token)
  1837. self.helper.send(self.room, body="There!", tok=self.other_access_token)
  1838. channel = self.make_request(
  1839. "POST",
  1840. "/search?access_token=%s" % (self.access_token,),
  1841. {
  1842. "search_categories": {
  1843. "room_events": {"keys": ["content.body"], "search_term": "Hi"}
  1844. }
  1845. },
  1846. )
  1847. # Check we get the results we expect -- one search result, of the sent
  1848. # messages
  1849. self.assertEqual(channel.code, 200)
  1850. results = channel.json_body["search_categories"]["room_events"]
  1851. self.assertEqual(results["count"], 1)
  1852. self.assertEqual(results["results"][0]["result"]["content"]["body"], "Hi!")
  1853. # No context was requested, so we should get none.
  1854. self.assertEqual(results["results"][0]["context"], {})
  1855. def test_include_context(self) -> None:
  1856. """
  1857. When event_context includes include_profile, profile information will be
  1858. included in the search response.
  1859. """
  1860. # The other user sends some messages
  1861. self.helper.send(self.room, body="Hi!", tok=self.other_access_token)
  1862. self.helper.send(self.room, body="There!", tok=self.other_access_token)
  1863. channel = self.make_request(
  1864. "POST",
  1865. "/search?access_token=%s" % (self.access_token,),
  1866. {
  1867. "search_categories": {
  1868. "room_events": {
  1869. "keys": ["content.body"],
  1870. "search_term": "Hi",
  1871. "event_context": {"include_profile": True},
  1872. }
  1873. }
  1874. },
  1875. )
  1876. # Check we get the results we expect -- one search result, of the sent
  1877. # messages
  1878. self.assertEqual(channel.code, 200)
  1879. results = channel.json_body["search_categories"]["room_events"]
  1880. self.assertEqual(results["count"], 1)
  1881. self.assertEqual(results["results"][0]["result"]["content"]["body"], "Hi!")
  1882. # We should get context info, like the two users, and the display names.
  1883. context = results["results"][0]["context"]
  1884. self.assertEqual(len(context["profile_info"].keys()), 2)
  1885. self.assertEqual(
  1886. context["profile_info"][self.other_user_id]["displayname"], "otheruser"
  1887. )
  1888. class PublicRoomsRestrictedTestCase(unittest.HomeserverTestCase):
  1889. servlets = [
  1890. synapse.rest.admin.register_servlets_for_client_rest_resource,
  1891. room.register_servlets,
  1892. login.register_servlets,
  1893. ]
  1894. def make_homeserver(self, reactor: MemoryReactor, clock: Clock) -> HomeServer:
  1895. self.url = b"/_matrix/client/r0/publicRooms"
  1896. config = self.default_config()
  1897. config["allow_public_rooms_without_auth"] = False
  1898. self.hs = self.setup_test_homeserver(config=config)
  1899. return self.hs
  1900. def test_restricted_no_auth(self) -> None:
  1901. channel = self.make_request("GET", self.url)
  1902. self.assertEqual(channel.code, HTTPStatus.UNAUTHORIZED, channel.result)
  1903. def test_restricted_auth(self) -> None:
  1904. self.register_user("user", "pass")
  1905. tok = self.login("user", "pass")
  1906. channel = self.make_request("GET", self.url, access_token=tok)
  1907. self.assertEqual(channel.code, HTTPStatus.OK, channel.result)
  1908. class PublicRoomsRoomTypeFilterTestCase(unittest.HomeserverTestCase):
  1909. servlets = [
  1910. synapse.rest.admin.register_servlets_for_client_rest_resource,
  1911. room.register_servlets,
  1912. login.register_servlets,
  1913. ]
  1914. def make_homeserver(self, reactor: MemoryReactor, clock: Clock) -> HomeServer:
  1915. config = self.default_config()
  1916. config["allow_public_rooms_without_auth"] = True
  1917. self.hs = self.setup_test_homeserver(config=config)
  1918. self.url = b"/_matrix/client/r0/publicRooms"
  1919. return self.hs
  1920. def prepare(self, reactor: MemoryReactor, clock: Clock, hs: HomeServer) -> None:
  1921. user = self.register_user("alice", "pass")
  1922. self.token = self.login(user, "pass")
  1923. # Create a room
  1924. self.helper.create_room_as(
  1925. user,
  1926. is_public=True,
  1927. extra_content={"visibility": "public"},
  1928. tok=self.token,
  1929. )
  1930. # Create a space
  1931. self.helper.create_room_as(
  1932. user,
  1933. is_public=True,
  1934. extra_content={
  1935. "visibility": "public",
  1936. "creation_content": {EventContentFields.ROOM_TYPE: RoomTypes.SPACE},
  1937. },
  1938. tok=self.token,
  1939. )
  1940. def make_public_rooms_request(
  1941. self,
  1942. room_types: Optional[List[Union[str, None]]],
  1943. instance_id: Optional[str] = None,
  1944. ) -> Tuple[List[Dict[str, Any]], int]:
  1945. body: JsonDict = {"filter": {PublicRoomsFilterFields.ROOM_TYPES: room_types}}
  1946. if instance_id:
  1947. body["third_party_instance_id"] = "test|test"
  1948. channel = self.make_request("POST", self.url, body, self.token)
  1949. self.assertEqual(channel.code, 200)
  1950. chunk = channel.json_body["chunk"]
  1951. count = channel.json_body["total_room_count_estimate"]
  1952. self.assertEqual(len(chunk), count)
  1953. return chunk, count
  1954. def test_returns_both_rooms_and_spaces_if_no_filter(self) -> None:
  1955. chunk, count = self.make_public_rooms_request(None)
  1956. self.assertEqual(count, 2)
  1957. # Also check if there's no filter property at all in the body.
  1958. channel = self.make_request("POST", self.url, {}, self.token)
  1959. self.assertEqual(channel.code, 200)
  1960. self.assertEqual(len(channel.json_body["chunk"]), 2)
  1961. self.assertEqual(channel.json_body["total_room_count_estimate"], 2)
  1962. chunk, count = self.make_public_rooms_request(None, "test|test")
  1963. self.assertEqual(count, 0)
  1964. def test_returns_only_rooms_based_on_filter(self) -> None:
  1965. chunk, count = self.make_public_rooms_request([None])
  1966. self.assertEqual(count, 1)
  1967. self.assertEqual(chunk[0].get("room_type", None), None)
  1968. chunk, count = self.make_public_rooms_request([None], "test|test")
  1969. self.assertEqual(count, 0)
  1970. def test_returns_only_space_based_on_filter(self) -> None:
  1971. chunk, count = self.make_public_rooms_request(["m.space"])
  1972. self.assertEqual(count, 1)
  1973. self.assertEqual(chunk[0].get("room_type", None), "m.space")
  1974. chunk, count = self.make_public_rooms_request(["m.space"], "test|test")
  1975. self.assertEqual(count, 0)
  1976. def test_returns_both_rooms_and_space_based_on_filter(self) -> None:
  1977. chunk, count = self.make_public_rooms_request(["m.space", None])
  1978. self.assertEqual(count, 2)
  1979. chunk, count = self.make_public_rooms_request(["m.space", None], "test|test")
  1980. self.assertEqual(count, 0)
  1981. def test_returns_both_rooms_and_spaces_if_array_is_empty(self) -> None:
  1982. chunk, count = self.make_public_rooms_request([])
  1983. self.assertEqual(count, 2)
  1984. chunk, count = self.make_public_rooms_request([], "test|test")
  1985. self.assertEqual(count, 0)
  1986. class PublicRoomsTestRemoteSearchFallbackTestCase(unittest.HomeserverTestCase):
  1987. """Test that we correctly fallback to local filtering if a remote server
  1988. doesn't support search.
  1989. """
  1990. servlets = [
  1991. synapse.rest.admin.register_servlets_for_client_rest_resource,
  1992. room.register_servlets,
  1993. login.register_servlets,
  1994. ]
  1995. def make_homeserver(self, reactor: MemoryReactor, clock: Clock) -> HomeServer:
  1996. return self.setup_test_homeserver(federation_client=AsyncMock())
  1997. def prepare(self, reactor: MemoryReactor, clock: Clock, hs: HomeServer) -> None:
  1998. self.register_user("user", "pass")
  1999. self.token = self.login("user", "pass")
  2000. self.federation_client = hs.get_federation_client()
  2001. def test_simple(self) -> None:
  2002. "Simple test for searching rooms over federation"
  2003. self.federation_client.get_public_rooms.return_value = {} # type: ignore[attr-defined]
  2004. search_filter = {PublicRoomsFilterFields.GENERIC_SEARCH_TERM: "foobar"}
  2005. channel = self.make_request(
  2006. "POST",
  2007. b"/_matrix/client/r0/publicRooms?server=testserv",
  2008. content={"filter": search_filter},
  2009. access_token=self.token,
  2010. )
  2011. self.assertEqual(channel.code, HTTPStatus.OK, channel.result)
  2012. self.federation_client.get_public_rooms.assert_called_once_with( # type: ignore[attr-defined]
  2013. "testserv",
  2014. limit=100,
  2015. since_token=None,
  2016. search_filter=search_filter,
  2017. include_all_networks=False,
  2018. third_party_instance_id=None,
  2019. )
  2020. def test_fallback(self) -> None:
  2021. "Test that searching public rooms over federation falls back if it gets a 404"
  2022. # The `get_public_rooms` should be called again if the first call fails
  2023. # with a 404, when using search filters.
  2024. self.federation_client.get_public_rooms.side_effect = ( # type: ignore[attr-defined]
  2025. HttpResponseException(HTTPStatus.NOT_FOUND, "Not Found", b""),
  2026. {},
  2027. )
  2028. search_filter = {PublicRoomsFilterFields.GENERIC_SEARCH_TERM: "foobar"}
  2029. channel = self.make_request(
  2030. "POST",
  2031. b"/_matrix/client/r0/publicRooms?server=testserv",
  2032. content={"filter": search_filter},
  2033. access_token=self.token,
  2034. )
  2035. self.assertEqual(channel.code, HTTPStatus.OK, channel.result)
  2036. self.federation_client.get_public_rooms.assert_has_calls( # type: ignore[attr-defined]
  2037. [
  2038. call(
  2039. "testserv",
  2040. limit=100,
  2041. since_token=None,
  2042. search_filter=search_filter,
  2043. include_all_networks=False,
  2044. third_party_instance_id=None,
  2045. ),
  2046. call(
  2047. "testserv",
  2048. limit=None,
  2049. since_token=None,
  2050. search_filter=None,
  2051. include_all_networks=False,
  2052. third_party_instance_id=None,
  2053. ),
  2054. ]
  2055. )
  2056. class PerRoomProfilesForbiddenTestCase(unittest.HomeserverTestCase):
  2057. servlets = [
  2058. synapse.rest.admin.register_servlets_for_client_rest_resource,
  2059. room.register_servlets,
  2060. login.register_servlets,
  2061. profile.register_servlets,
  2062. ]
  2063. def make_homeserver(self, reactor: MemoryReactor, clock: Clock) -> HomeServer:
  2064. config = self.default_config()
  2065. config["allow_per_room_profiles"] = False
  2066. self.hs = self.setup_test_homeserver(config=config)
  2067. return self.hs
  2068. def prepare(self, reactor: MemoryReactor, clock: Clock, hs: HomeServer) -> None:
  2069. self.user_id = self.register_user("test", "test")
  2070. self.tok = self.login("test", "test")
  2071. # Set a profile for the test user
  2072. self.displayname = "test user"
  2073. request_data = {"displayname": self.displayname}
  2074. channel = self.make_request(
  2075. "PUT",
  2076. "/_matrix/client/r0/profile/%s/displayname" % (self.user_id,),
  2077. request_data,
  2078. access_token=self.tok,
  2079. )
  2080. self.assertEqual(channel.code, HTTPStatus.OK, channel.result)
  2081. self.room_id = self.helper.create_room_as(self.user_id, tok=self.tok)
  2082. def test_per_room_profile_forbidden(self) -> None:
  2083. request_data = {"membership": "join", "displayname": "other test user"}
  2084. channel = self.make_request(
  2085. "PUT",
  2086. "/_matrix/client/r0/rooms/%s/state/m.room.member/%s"
  2087. % (self.room_id, self.user_id),
  2088. request_data,
  2089. access_token=self.tok,
  2090. )
  2091. self.assertEqual(channel.code, HTTPStatus.OK, channel.result)
  2092. event_id = channel.json_body["event_id"]
  2093. channel = self.make_request(
  2094. "GET",
  2095. "/_matrix/client/r0/rooms/%s/event/%s" % (self.room_id, event_id),
  2096. access_token=self.tok,
  2097. )
  2098. self.assertEqual(channel.code, HTTPStatus.OK, channel.result)
  2099. res_displayname = channel.json_body["content"]["displayname"]
  2100. self.assertEqual(res_displayname, self.displayname, channel.result)
  2101. class RoomMembershipReasonTestCase(unittest.HomeserverTestCase):
  2102. """Tests that clients can add a "reason" field to membership events and
  2103. that they get correctly added to the generated events and propagated.
  2104. """
  2105. servlets = [
  2106. synapse.rest.admin.register_servlets_for_client_rest_resource,
  2107. room.register_servlets,
  2108. login.register_servlets,
  2109. ]
  2110. def prepare(self, reactor: MemoryReactor, clock: Clock, hs: HomeServer) -> None:
  2111. self.creator = self.register_user("creator", "test")
  2112. self.creator_tok = self.login("creator", "test")
  2113. self.second_user_id = self.register_user("second", "test")
  2114. self.second_tok = self.login("second", "test")
  2115. self.room_id = self.helper.create_room_as(self.creator, tok=self.creator_tok)
  2116. def test_join_reason(self) -> None:
  2117. reason = "hello"
  2118. channel = self.make_request(
  2119. "POST",
  2120. f"/_matrix/client/r0/rooms/{self.room_id}/join",
  2121. content={"reason": reason},
  2122. access_token=self.second_tok,
  2123. )
  2124. self.assertEqual(channel.code, HTTPStatus.OK, channel.result)
  2125. self._check_for_reason(reason)
  2126. def test_leave_reason(self) -> None:
  2127. self.helper.join(self.room_id, user=self.second_user_id, tok=self.second_tok)
  2128. reason = "hello"
  2129. channel = self.make_request(
  2130. "POST",
  2131. f"/_matrix/client/r0/rooms/{self.room_id}/leave",
  2132. content={"reason": reason},
  2133. access_token=self.second_tok,
  2134. )
  2135. self.assertEqual(channel.code, HTTPStatus.OK, channel.result)
  2136. self._check_for_reason(reason)
  2137. def test_kick_reason(self) -> None:
  2138. self.helper.join(self.room_id, user=self.second_user_id, tok=self.second_tok)
  2139. reason = "hello"
  2140. channel = self.make_request(
  2141. "POST",
  2142. f"/_matrix/client/r0/rooms/{self.room_id}/kick",
  2143. content={"reason": reason, "user_id": self.second_user_id},
  2144. access_token=self.second_tok,
  2145. )
  2146. self.assertEqual(channel.code, HTTPStatus.OK, channel.result)
  2147. self._check_for_reason(reason)
  2148. def test_ban_reason(self) -> None:
  2149. self.helper.join(self.room_id, user=self.second_user_id, tok=self.second_tok)
  2150. reason = "hello"
  2151. channel = self.make_request(
  2152. "POST",
  2153. f"/_matrix/client/r0/rooms/{self.room_id}/ban",
  2154. content={"reason": reason, "user_id": self.second_user_id},
  2155. access_token=self.creator_tok,
  2156. )
  2157. self.assertEqual(channel.code, HTTPStatus.OK, channel.result)
  2158. self._check_for_reason(reason)
  2159. def test_unban_reason(self) -> None:
  2160. reason = "hello"
  2161. channel = self.make_request(
  2162. "POST",
  2163. f"/_matrix/client/r0/rooms/{self.room_id}/unban",
  2164. content={"reason": reason, "user_id": self.second_user_id},
  2165. access_token=self.creator_tok,
  2166. )
  2167. self.assertEqual(channel.code, HTTPStatus.OK, channel.result)
  2168. self._check_for_reason(reason)
  2169. def test_invite_reason(self) -> None:
  2170. reason = "hello"
  2171. channel = self.make_request(
  2172. "POST",
  2173. f"/_matrix/client/r0/rooms/{self.room_id}/invite",
  2174. content={"reason": reason, "user_id": self.second_user_id},
  2175. access_token=self.creator_tok,
  2176. )
  2177. self.assertEqual(channel.code, HTTPStatus.OK, channel.result)
  2178. self._check_for_reason(reason)
  2179. def test_reject_invite_reason(self) -> None:
  2180. self.helper.invite(
  2181. self.room_id,
  2182. src=self.creator,
  2183. targ=self.second_user_id,
  2184. tok=self.creator_tok,
  2185. )
  2186. reason = "hello"
  2187. channel = self.make_request(
  2188. "POST",
  2189. f"/_matrix/client/r0/rooms/{self.room_id}/leave",
  2190. content={"reason": reason},
  2191. access_token=self.second_tok,
  2192. )
  2193. self.assertEqual(channel.code, HTTPStatus.OK, channel.result)
  2194. self._check_for_reason(reason)
  2195. def _check_for_reason(self, reason: str) -> None:
  2196. channel = self.make_request(
  2197. "GET",
  2198. "/_matrix/client/r0/rooms/{}/state/m.room.member/{}".format(
  2199. self.room_id, self.second_user_id
  2200. ),
  2201. access_token=self.creator_tok,
  2202. )
  2203. self.assertEqual(channel.code, HTTPStatus.OK, channel.result)
  2204. event_content = channel.json_body
  2205. self.assertEqual(event_content.get("reason"), reason, channel.result)
  2206. class LabelsTestCase(unittest.HomeserverTestCase):
  2207. servlets = [
  2208. synapse.rest.admin.register_servlets_for_client_rest_resource,
  2209. room.register_servlets,
  2210. login.register_servlets,
  2211. profile.register_servlets,
  2212. ]
  2213. # Filter that should only catch messages with the label "#fun".
  2214. FILTER_LABELS = {
  2215. "types": [EventTypes.Message],
  2216. "org.matrix.labels": ["#fun"],
  2217. }
  2218. # Filter that should only catch messages without the label "#fun".
  2219. FILTER_NOT_LABELS = {
  2220. "types": [EventTypes.Message],
  2221. "org.matrix.not_labels": ["#fun"],
  2222. }
  2223. # Filter that should only catch messages with the label "#work" but without the label
  2224. # "#notfun".
  2225. FILTER_LABELS_NOT_LABELS = {
  2226. "types": [EventTypes.Message],
  2227. "org.matrix.labels": ["#work"],
  2228. "org.matrix.not_labels": ["#notfun"],
  2229. }
  2230. def prepare(self, reactor: MemoryReactor, clock: Clock, hs: HomeServer) -> None:
  2231. self.user_id = self.register_user("test", "test")
  2232. self.tok = self.login("test", "test")
  2233. self.room_id = self.helper.create_room_as(self.user_id, tok=self.tok)
  2234. def test_context_filter_labels(self) -> None:
  2235. """Test that we can filter by a label on a /context request."""
  2236. event_id = self._send_labelled_messages_in_room()
  2237. channel = self.make_request(
  2238. "GET",
  2239. "/rooms/%s/context/%s?filter=%s"
  2240. % (self.room_id, event_id, json.dumps(self.FILTER_LABELS)),
  2241. access_token=self.tok,
  2242. )
  2243. self.assertEqual(channel.code, HTTPStatus.OK, channel.result)
  2244. events_before = channel.json_body["events_before"]
  2245. self.assertEqual(
  2246. len(events_before), 1, [event["content"] for event in events_before]
  2247. )
  2248. self.assertEqual(
  2249. events_before[0]["content"]["body"], "with right label", events_before[0]
  2250. )
  2251. events_after = channel.json_body["events_before"]
  2252. self.assertEqual(
  2253. len(events_after), 1, [event["content"] for event in events_after]
  2254. )
  2255. self.assertEqual(
  2256. events_after[0]["content"]["body"], "with right label", events_after[0]
  2257. )
  2258. def test_context_filter_not_labels(self) -> None:
  2259. """Test that we can filter by the absence of a label on a /context request."""
  2260. event_id = self._send_labelled_messages_in_room()
  2261. channel = self.make_request(
  2262. "GET",
  2263. "/rooms/%s/context/%s?filter=%s"
  2264. % (self.room_id, event_id, json.dumps(self.FILTER_NOT_LABELS)),
  2265. access_token=self.tok,
  2266. )
  2267. self.assertEqual(channel.code, HTTPStatus.OK, channel.result)
  2268. events_before = channel.json_body["events_before"]
  2269. self.assertEqual(
  2270. len(events_before), 1, [event["content"] for event in events_before]
  2271. )
  2272. self.assertEqual(
  2273. events_before[0]["content"]["body"], "without label", events_before[0]
  2274. )
  2275. events_after = channel.json_body["events_after"]
  2276. self.assertEqual(
  2277. len(events_after), 2, [event["content"] for event in events_after]
  2278. )
  2279. self.assertEqual(
  2280. events_after[0]["content"]["body"], "with wrong label", events_after[0]
  2281. )
  2282. self.assertEqual(
  2283. events_after[1]["content"]["body"], "with two wrong labels", events_after[1]
  2284. )
  2285. def test_context_filter_labels_not_labels(self) -> None:
  2286. """Test that we can filter by both a label and the absence of another label on a
  2287. /context request.
  2288. """
  2289. event_id = self._send_labelled_messages_in_room()
  2290. channel = self.make_request(
  2291. "GET",
  2292. "/rooms/%s/context/%s?filter=%s"
  2293. % (self.room_id, event_id, json.dumps(self.FILTER_LABELS_NOT_LABELS)),
  2294. access_token=self.tok,
  2295. )
  2296. self.assertEqual(channel.code, HTTPStatus.OK, channel.result)
  2297. events_before = channel.json_body["events_before"]
  2298. self.assertEqual(
  2299. len(events_before), 0, [event["content"] for event in events_before]
  2300. )
  2301. events_after = channel.json_body["events_after"]
  2302. self.assertEqual(
  2303. len(events_after), 1, [event["content"] for event in events_after]
  2304. )
  2305. self.assertEqual(
  2306. events_after[0]["content"]["body"], "with wrong label", events_after[0]
  2307. )
  2308. def test_messages_filter_labels(self) -> None:
  2309. """Test that we can filter by a label on a /messages request."""
  2310. self._send_labelled_messages_in_room()
  2311. token = "s0_0_0_0_0_0_0_0_0_0"
  2312. channel = self.make_request(
  2313. "GET",
  2314. "/rooms/%s/messages?access_token=%s&from=%s&filter=%s"
  2315. % (self.room_id, self.tok, token, json.dumps(self.FILTER_LABELS)),
  2316. )
  2317. events = channel.json_body["chunk"]
  2318. self.assertEqual(len(events), 2, [event["content"] for event in events])
  2319. self.assertEqual(events[0]["content"]["body"], "with right label", events[0])
  2320. self.assertEqual(events[1]["content"]["body"], "with right label", events[1])
  2321. def test_messages_filter_not_labels(self) -> None:
  2322. """Test that we can filter by the absence of a label on a /messages request."""
  2323. self._send_labelled_messages_in_room()
  2324. token = "s0_0_0_0_0_0_0_0_0_0"
  2325. channel = self.make_request(
  2326. "GET",
  2327. "/rooms/%s/messages?access_token=%s&from=%s&filter=%s"
  2328. % (self.room_id, self.tok, token, json.dumps(self.FILTER_NOT_LABELS)),
  2329. )
  2330. events = channel.json_body["chunk"]
  2331. self.assertEqual(len(events), 4, [event["content"] for event in events])
  2332. self.assertEqual(events[0]["content"]["body"], "without label", events[0])
  2333. self.assertEqual(events[1]["content"]["body"], "without label", events[1])
  2334. self.assertEqual(events[2]["content"]["body"], "with wrong label", events[2])
  2335. self.assertEqual(
  2336. events[3]["content"]["body"], "with two wrong labels", events[3]
  2337. )
  2338. def test_messages_filter_labels_not_labels(self) -> None:
  2339. """Test that we can filter by both a label and the absence of another label on a
  2340. /messages request.
  2341. """
  2342. self._send_labelled_messages_in_room()
  2343. token = "s0_0_0_0_0_0_0_0_0_0"
  2344. channel = self.make_request(
  2345. "GET",
  2346. "/rooms/%s/messages?access_token=%s&from=%s&filter=%s"
  2347. % (
  2348. self.room_id,
  2349. self.tok,
  2350. token,
  2351. json.dumps(self.FILTER_LABELS_NOT_LABELS),
  2352. ),
  2353. )
  2354. events = channel.json_body["chunk"]
  2355. self.assertEqual(len(events), 1, [event["content"] for event in events])
  2356. self.assertEqual(events[0]["content"]["body"], "with wrong label", events[0])
  2357. def test_search_filter_labels(self) -> None:
  2358. """Test that we can filter by a label on a /search request."""
  2359. request_data = {
  2360. "search_categories": {
  2361. "room_events": {
  2362. "search_term": "label",
  2363. "filter": self.FILTER_LABELS,
  2364. }
  2365. }
  2366. }
  2367. self._send_labelled_messages_in_room()
  2368. channel = self.make_request(
  2369. "POST", "/search?access_token=%s" % self.tok, request_data
  2370. )
  2371. results = channel.json_body["search_categories"]["room_events"]["results"]
  2372. self.assertEqual(
  2373. len(results),
  2374. 2,
  2375. [result["result"]["content"] for result in results],
  2376. )
  2377. self.assertEqual(
  2378. results[0]["result"]["content"]["body"],
  2379. "with right label",
  2380. results[0]["result"]["content"]["body"],
  2381. )
  2382. self.assertEqual(
  2383. results[1]["result"]["content"]["body"],
  2384. "with right label",
  2385. results[1]["result"]["content"]["body"],
  2386. )
  2387. def test_search_filter_not_labels(self) -> None:
  2388. """Test that we can filter by the absence of a label on a /search request."""
  2389. request_data = {
  2390. "search_categories": {
  2391. "room_events": {
  2392. "search_term": "label",
  2393. "filter": self.FILTER_NOT_LABELS,
  2394. }
  2395. }
  2396. }
  2397. self._send_labelled_messages_in_room()
  2398. channel = self.make_request(
  2399. "POST", "/search?access_token=%s" % self.tok, request_data
  2400. )
  2401. results = channel.json_body["search_categories"]["room_events"]["results"]
  2402. self.assertEqual(
  2403. len(results),
  2404. 4,
  2405. [result["result"]["content"] for result in results],
  2406. )
  2407. self.assertEqual(
  2408. results[0]["result"]["content"]["body"],
  2409. "without label",
  2410. results[0]["result"]["content"]["body"],
  2411. )
  2412. self.assertEqual(
  2413. results[1]["result"]["content"]["body"],
  2414. "without label",
  2415. results[1]["result"]["content"]["body"],
  2416. )
  2417. self.assertEqual(
  2418. results[2]["result"]["content"]["body"],
  2419. "with wrong label",
  2420. results[2]["result"]["content"]["body"],
  2421. )
  2422. self.assertEqual(
  2423. results[3]["result"]["content"]["body"],
  2424. "with two wrong labels",
  2425. results[3]["result"]["content"]["body"],
  2426. )
  2427. def test_search_filter_labels_not_labels(self) -> None:
  2428. """Test that we can filter by both a label and the absence of another label on a
  2429. /search request.
  2430. """
  2431. request_data = {
  2432. "search_categories": {
  2433. "room_events": {
  2434. "search_term": "label",
  2435. "filter": self.FILTER_LABELS_NOT_LABELS,
  2436. }
  2437. }
  2438. }
  2439. self._send_labelled_messages_in_room()
  2440. channel = self.make_request(
  2441. "POST", "/search?access_token=%s" % self.tok, request_data
  2442. )
  2443. results = channel.json_body["search_categories"]["room_events"]["results"]
  2444. self.assertEqual(
  2445. len(results),
  2446. 1,
  2447. [result["result"]["content"] for result in results],
  2448. )
  2449. self.assertEqual(
  2450. results[0]["result"]["content"]["body"],
  2451. "with wrong label",
  2452. results[0]["result"]["content"]["body"],
  2453. )
  2454. def _send_labelled_messages_in_room(self) -> str:
  2455. """Sends several messages to a room with different labels (or without any) to test
  2456. filtering by label.
  2457. Returns:
  2458. The ID of the event to use if we're testing filtering on /context.
  2459. """
  2460. self.helper.send_event(
  2461. room_id=self.room_id,
  2462. type=EventTypes.Message,
  2463. content={
  2464. "msgtype": "m.text",
  2465. "body": "with right label",
  2466. EventContentFields.LABELS: ["#fun"],
  2467. },
  2468. tok=self.tok,
  2469. )
  2470. self.helper.send_event(
  2471. room_id=self.room_id,
  2472. type=EventTypes.Message,
  2473. content={"msgtype": "m.text", "body": "without label"},
  2474. tok=self.tok,
  2475. )
  2476. res = self.helper.send_event(
  2477. room_id=self.room_id,
  2478. type=EventTypes.Message,
  2479. content={"msgtype": "m.text", "body": "without label"},
  2480. tok=self.tok,
  2481. )
  2482. # Return this event's ID when we test filtering in /context requests.
  2483. event_id = res["event_id"]
  2484. self.helper.send_event(
  2485. room_id=self.room_id,
  2486. type=EventTypes.Message,
  2487. content={
  2488. "msgtype": "m.text",
  2489. "body": "with wrong label",
  2490. EventContentFields.LABELS: ["#work"],
  2491. },
  2492. tok=self.tok,
  2493. )
  2494. self.helper.send_event(
  2495. room_id=self.room_id,
  2496. type=EventTypes.Message,
  2497. content={
  2498. "msgtype": "m.text",
  2499. "body": "with two wrong labels",
  2500. EventContentFields.LABELS: ["#work", "#notfun"],
  2501. },
  2502. tok=self.tok,
  2503. )
  2504. self.helper.send_event(
  2505. room_id=self.room_id,
  2506. type=EventTypes.Message,
  2507. content={
  2508. "msgtype": "m.text",
  2509. "body": "with right label",
  2510. EventContentFields.LABELS: ["#fun"],
  2511. },
  2512. tok=self.tok,
  2513. )
  2514. return event_id
  2515. class RelationsTestCase(PaginationTestCase):
  2516. def _filter_messages(self, filter: JsonDict) -> List[str]:
  2517. """Make a request to /messages with a filter, returns the chunk of events."""
  2518. from_token = self.get_success(
  2519. self.from_token.to_string(self.hs.get_datastores().main)
  2520. )
  2521. channel = self.make_request(
  2522. "GET",
  2523. f"/rooms/{self.room_id}/messages?filter={json.dumps(filter)}&dir=f&from={from_token}",
  2524. access_token=self.tok,
  2525. )
  2526. self.assertEqual(channel.code, HTTPStatus.OK, channel.result)
  2527. return [ev["event_id"] for ev in channel.json_body["chunk"]]
  2528. class ContextTestCase(unittest.HomeserverTestCase):
  2529. servlets = [
  2530. synapse.rest.admin.register_servlets_for_client_rest_resource,
  2531. room.register_servlets,
  2532. login.register_servlets,
  2533. account.register_servlets,
  2534. ]
  2535. def prepare(self, reactor: MemoryReactor, clock: Clock, hs: HomeServer) -> None:
  2536. self.user_id = self.register_user("user", "password")
  2537. self.tok = self.login("user", "password")
  2538. self.room_id = self.helper.create_room_as(
  2539. self.user_id, tok=self.tok, is_public=False
  2540. )
  2541. self.other_user_id = self.register_user("user2", "password")
  2542. self.other_tok = self.login("user2", "password")
  2543. self.helper.invite(self.room_id, self.user_id, self.other_user_id, tok=self.tok)
  2544. self.helper.join(self.room_id, self.other_user_id, tok=self.other_tok)
  2545. def test_erased_sender(self) -> None:
  2546. """Test that an erasure request results in the requester's events being hidden
  2547. from any new member of the room.
  2548. """
  2549. # Send a bunch of events in the room.
  2550. self.helper.send(self.room_id, "message 1", tok=self.tok)
  2551. self.helper.send(self.room_id, "message 2", tok=self.tok)
  2552. event_id = self.helper.send(self.room_id, "message 3", tok=self.tok)["event_id"]
  2553. self.helper.send(self.room_id, "message 4", tok=self.tok)
  2554. self.helper.send(self.room_id, "message 5", tok=self.tok)
  2555. # Check that we can still see the messages before the erasure request.
  2556. channel = self.make_request(
  2557. "GET",
  2558. '/rooms/%s/context/%s?filter={"types":["m.room.message"]}'
  2559. % (self.room_id, event_id),
  2560. access_token=self.tok,
  2561. )
  2562. self.assertEqual(channel.code, HTTPStatus.OK, channel.result)
  2563. events_before = channel.json_body["events_before"]
  2564. self.assertEqual(len(events_before), 2, events_before)
  2565. self.assertEqual(
  2566. events_before[0].get("content", {}).get("body"),
  2567. "message 2",
  2568. events_before[0],
  2569. )
  2570. self.assertEqual(
  2571. events_before[1].get("content", {}).get("body"),
  2572. "message 1",
  2573. events_before[1],
  2574. )
  2575. self.assertEqual(
  2576. channel.json_body["event"].get("content", {}).get("body"),
  2577. "message 3",
  2578. channel.json_body["event"],
  2579. )
  2580. events_after = channel.json_body["events_after"]
  2581. self.assertEqual(len(events_after), 2, events_after)
  2582. self.assertEqual(
  2583. events_after[0].get("content", {}).get("body"),
  2584. "message 4",
  2585. events_after[0],
  2586. )
  2587. self.assertEqual(
  2588. events_after[1].get("content", {}).get("body"),
  2589. "message 5",
  2590. events_after[1],
  2591. )
  2592. # Deactivate the first account and erase the user's data.
  2593. deactivate_account_handler = self.hs.get_deactivate_account_handler()
  2594. self.get_success(
  2595. deactivate_account_handler.deactivate_account(
  2596. self.user_id, True, create_requester(self.user_id)
  2597. )
  2598. )
  2599. # Invite another user in the room. This is needed because messages will be
  2600. # pruned only if the user wasn't a member of the room when the messages were
  2601. # sent.
  2602. invited_user_id = self.register_user("user3", "password")
  2603. invited_tok = self.login("user3", "password")
  2604. self.helper.invite(
  2605. self.room_id, self.other_user_id, invited_user_id, tok=self.other_tok
  2606. )
  2607. self.helper.join(self.room_id, invited_user_id, tok=invited_tok)
  2608. # Check that a user that joined the room after the erasure request can't see
  2609. # the messages anymore.
  2610. channel = self.make_request(
  2611. "GET",
  2612. '/rooms/%s/context/%s?filter={"types":["m.room.message"]}'
  2613. % (self.room_id, event_id),
  2614. access_token=invited_tok,
  2615. )
  2616. self.assertEqual(channel.code, HTTPStatus.OK, channel.result)
  2617. events_before = channel.json_body["events_before"]
  2618. self.assertEqual(len(events_before), 2, events_before)
  2619. self.assertDictEqual(events_before[0].get("content"), {}, events_before[0])
  2620. self.assertDictEqual(events_before[1].get("content"), {}, events_before[1])
  2621. self.assertDictEqual(
  2622. channel.json_body["event"].get("content"), {}, channel.json_body["event"]
  2623. )
  2624. events_after = channel.json_body["events_after"]
  2625. self.assertEqual(len(events_after), 2, events_after)
  2626. self.assertDictEqual(events_after[0].get("content"), {}, events_after[0])
  2627. self.assertEqual(events_after[1].get("content"), {}, events_after[1])
  2628. class RoomAliasListTestCase(unittest.HomeserverTestCase):
  2629. servlets = [
  2630. synapse.rest.admin.register_servlets_for_client_rest_resource,
  2631. directory.register_servlets,
  2632. login.register_servlets,
  2633. room.register_servlets,
  2634. ]
  2635. def prepare(self, reactor: MemoryReactor, clock: Clock, hs: HomeServer) -> None:
  2636. self.room_owner = self.register_user("room_owner", "test")
  2637. self.room_owner_tok = self.login("room_owner", "test")
  2638. self.room_id = self.helper.create_room_as(
  2639. self.room_owner, tok=self.room_owner_tok
  2640. )
  2641. def test_no_aliases(self) -> None:
  2642. res = self._get_aliases(self.room_owner_tok)
  2643. self.assertEqual(res["aliases"], [])
  2644. def test_not_in_room(self) -> None:
  2645. self.register_user("user", "test")
  2646. user_tok = self.login("user", "test")
  2647. res = self._get_aliases(user_tok, expected_code=403)
  2648. self.assertEqual(res["errcode"], "M_FORBIDDEN")
  2649. def test_admin_user(self) -> None:
  2650. alias1 = self._random_alias()
  2651. self._set_alias_via_directory(alias1)
  2652. self.register_user("user", "test", admin=True)
  2653. user_tok = self.login("user", "test")
  2654. res = self._get_aliases(user_tok)
  2655. self.assertEqual(res["aliases"], [alias1])
  2656. def test_with_aliases(self) -> None:
  2657. alias1 = self._random_alias()
  2658. alias2 = self._random_alias()
  2659. self._set_alias_via_directory(alias1)
  2660. self._set_alias_via_directory(alias2)
  2661. res = self._get_aliases(self.room_owner_tok)
  2662. self.assertEqual(set(res["aliases"]), {alias1, alias2})
  2663. def test_peekable_room(self) -> None:
  2664. alias1 = self._random_alias()
  2665. self._set_alias_via_directory(alias1)
  2666. self.helper.send_state(
  2667. self.room_id,
  2668. EventTypes.RoomHistoryVisibility,
  2669. body={"history_visibility": "world_readable"},
  2670. tok=self.room_owner_tok,
  2671. )
  2672. self.register_user("user", "test")
  2673. user_tok = self.login("user", "test")
  2674. res = self._get_aliases(user_tok)
  2675. self.assertEqual(res["aliases"], [alias1])
  2676. def _get_aliases(self, access_token: str, expected_code: int = 200) -> JsonDict:
  2677. """Calls the endpoint under test. returns the json response object."""
  2678. channel = self.make_request(
  2679. "GET",
  2680. "/_matrix/client/r0/rooms/%s/aliases" % (self.room_id,),
  2681. access_token=access_token,
  2682. )
  2683. self.assertEqual(channel.code, expected_code, channel.result)
  2684. res = channel.json_body
  2685. self.assertIsInstance(res, dict)
  2686. if expected_code == 200:
  2687. self.assertIsInstance(res["aliases"], list)
  2688. return res
  2689. def _random_alias(self) -> str:
  2690. return RoomAlias(random_string(5), self.hs.hostname).to_string()
  2691. def _set_alias_via_directory(self, alias: str, expected_code: int = 200) -> None:
  2692. url = "/_matrix/client/r0/directory/room/" + alias
  2693. request_data = {"room_id": self.room_id}
  2694. channel = self.make_request(
  2695. "PUT", url, request_data, access_token=self.room_owner_tok
  2696. )
  2697. self.assertEqual(channel.code, expected_code, channel.result)
  2698. class RoomCanonicalAliasTestCase(unittest.HomeserverTestCase):
  2699. servlets = [
  2700. synapse.rest.admin.register_servlets_for_client_rest_resource,
  2701. directory.register_servlets,
  2702. login.register_servlets,
  2703. room.register_servlets,
  2704. ]
  2705. def prepare(self, reactor: MemoryReactor, clock: Clock, hs: HomeServer) -> None:
  2706. self.room_owner = self.register_user("room_owner", "test")
  2707. self.room_owner_tok = self.login("room_owner", "test")
  2708. self.room_id = self.helper.create_room_as(
  2709. self.room_owner, tok=self.room_owner_tok
  2710. )
  2711. self.alias = "#alias:test"
  2712. self._set_alias_via_directory(self.alias)
  2713. def _set_alias_via_directory(self, alias: str, expected_code: int = 200) -> None:
  2714. url = "/_matrix/client/r0/directory/room/" + alias
  2715. request_data = {"room_id": self.room_id}
  2716. channel = self.make_request(
  2717. "PUT", url, request_data, access_token=self.room_owner_tok
  2718. )
  2719. self.assertEqual(channel.code, expected_code, channel.result)
  2720. def _get_canonical_alias(self, expected_code: int = 200) -> JsonDict:
  2721. """Calls the endpoint under test. returns the json response object."""
  2722. channel = self.make_request(
  2723. "GET",
  2724. "rooms/%s/state/m.room.canonical_alias" % (self.room_id,),
  2725. access_token=self.room_owner_tok,
  2726. )
  2727. self.assertEqual(channel.code, expected_code, channel.result)
  2728. res = channel.json_body
  2729. self.assertIsInstance(res, dict)
  2730. return res
  2731. def _set_canonical_alias(
  2732. self, content: JsonDict, expected_code: int = 200
  2733. ) -> JsonDict:
  2734. """Calls the endpoint under test. returns the json response object."""
  2735. channel = self.make_request(
  2736. "PUT",
  2737. "rooms/%s/state/m.room.canonical_alias" % (self.room_id,),
  2738. content,
  2739. access_token=self.room_owner_tok,
  2740. )
  2741. self.assertEqual(channel.code, expected_code, channel.result)
  2742. res = channel.json_body
  2743. self.assertIsInstance(res, dict)
  2744. return res
  2745. def test_canonical_alias(self) -> None:
  2746. """Test a basic alias message."""
  2747. # There is no canonical alias to start with.
  2748. self._get_canonical_alias(expected_code=404)
  2749. # Create an alias.
  2750. self._set_canonical_alias({"alias": self.alias})
  2751. # Canonical alias now exists!
  2752. res = self._get_canonical_alias()
  2753. self.assertEqual(res, {"alias": self.alias})
  2754. # Now remove the alias.
  2755. self._set_canonical_alias({})
  2756. # There is an alias event, but it is empty.
  2757. res = self._get_canonical_alias()
  2758. self.assertEqual(res, {})
  2759. def test_alt_aliases(self) -> None:
  2760. """Test a canonical alias message with alt_aliases."""
  2761. # Create an alias.
  2762. self._set_canonical_alias({"alt_aliases": [self.alias]})
  2763. # Canonical alias now exists!
  2764. res = self._get_canonical_alias()
  2765. self.assertEqual(res, {"alt_aliases": [self.alias]})
  2766. # Now remove the alt_aliases.
  2767. self._set_canonical_alias({})
  2768. # There is an alias event, but it is empty.
  2769. res = self._get_canonical_alias()
  2770. self.assertEqual(res, {})
  2771. def test_alias_alt_aliases(self) -> None:
  2772. """Test a canonical alias message with an alias and alt_aliases."""
  2773. # Create an alias.
  2774. self._set_canonical_alias({"alias": self.alias, "alt_aliases": [self.alias]})
  2775. # Canonical alias now exists!
  2776. res = self._get_canonical_alias()
  2777. self.assertEqual(res, {"alias": self.alias, "alt_aliases": [self.alias]})
  2778. # Now remove the alias and alt_aliases.
  2779. self._set_canonical_alias({})
  2780. # There is an alias event, but it is empty.
  2781. res = self._get_canonical_alias()
  2782. self.assertEqual(res, {})
  2783. def test_partial_modify(self) -> None:
  2784. """Test removing only the alt_aliases."""
  2785. # Create an alias.
  2786. self._set_canonical_alias({"alias": self.alias, "alt_aliases": [self.alias]})
  2787. # Canonical alias now exists!
  2788. res = self._get_canonical_alias()
  2789. self.assertEqual(res, {"alias": self.alias, "alt_aliases": [self.alias]})
  2790. # Now remove the alt_aliases.
  2791. self._set_canonical_alias({"alias": self.alias})
  2792. # There is an alias event, but it is empty.
  2793. res = self._get_canonical_alias()
  2794. self.assertEqual(res, {"alias": self.alias})
  2795. def test_add_alias(self) -> None:
  2796. """Test removing only the alt_aliases."""
  2797. # Create an additional alias.
  2798. second_alias = "#second:test"
  2799. self._set_alias_via_directory(second_alias)
  2800. # Add the canonical alias.
  2801. self._set_canonical_alias({"alias": self.alias, "alt_aliases": [self.alias]})
  2802. # Then add the second alias.
  2803. self._set_canonical_alias(
  2804. {"alias": self.alias, "alt_aliases": [self.alias, second_alias]}
  2805. )
  2806. # Canonical alias now exists!
  2807. res = self._get_canonical_alias()
  2808. self.assertEqual(
  2809. res, {"alias": self.alias, "alt_aliases": [self.alias, second_alias]}
  2810. )
  2811. def test_bad_data(self) -> None:
  2812. """Invalid data for alt_aliases should cause errors."""
  2813. self._set_canonical_alias({"alt_aliases": "@bad:test"}, expected_code=400)
  2814. self._set_canonical_alias({"alt_aliases": None}, expected_code=400)
  2815. self._set_canonical_alias({"alt_aliases": 0}, expected_code=400)
  2816. self._set_canonical_alias({"alt_aliases": 1}, expected_code=400)
  2817. self._set_canonical_alias({"alt_aliases": False}, expected_code=400)
  2818. self._set_canonical_alias({"alt_aliases": True}, expected_code=400)
  2819. self._set_canonical_alias({"alt_aliases": {}}, expected_code=400)
  2820. def test_bad_alias(self) -> None:
  2821. """An alias which does not point to the room raises a SynapseError."""
  2822. self._set_canonical_alias({"alias": "@unknown:test"}, expected_code=400)
  2823. self._set_canonical_alias({"alt_aliases": ["@unknown:test"]}, expected_code=400)
  2824. class ThreepidInviteTestCase(unittest.HomeserverTestCase):
  2825. servlets = [
  2826. admin.register_servlets,
  2827. login.register_servlets,
  2828. room.register_servlets,
  2829. ]
  2830. def prepare(self, reactor: MemoryReactor, clock: Clock, hs: HomeServer) -> None:
  2831. self.user_id = self.register_user("thomas", "hackme")
  2832. self.tok = self.login("thomas", "hackme")
  2833. self.room_id = self.helper.create_room_as(self.user_id, tok=self.tok)
  2834. def test_threepid_invite_spamcheck_deprecated(self) -> None:
  2835. """
  2836. Test allowing/blocking threepid invites with a spam-check module.
  2837. In this test, we use the deprecated API in which callbacks return a bool.
  2838. """
  2839. # Mock a few functions to prevent the test from failing due to failing to talk to
  2840. # a remote IS. We keep the mock for make_and_store_3pid_invite around so we
  2841. # can check its call_count later on during the test.
  2842. make_invite_mock = AsyncMock(return_value=(Mock(event_id="abc"), 0))
  2843. self.hs.get_room_member_handler()._make_and_store_3pid_invite = make_invite_mock # type: ignore[method-assign]
  2844. self.hs.get_identity_handler().lookup_3pid = AsyncMock( # type: ignore[method-assign]
  2845. return_value=None,
  2846. )
  2847. # Add a mock to the spamchecker callbacks for user_may_send_3pid_invite. Make it
  2848. # allow everything for now.
  2849. # `spec` argument is needed for this function mock to have `__qualname__`, which
  2850. # is needed for `Measure` metrics buried in SpamChecker.
  2851. mock = AsyncMock(return_value=True, spec=lambda *x: None)
  2852. self.hs.get_module_api_callbacks().spam_checker._user_may_send_3pid_invite_callbacks.append(
  2853. mock
  2854. )
  2855. # Send a 3PID invite into the room and check that it succeeded.
  2856. email_to_invite = "teresa@example.com"
  2857. channel = self.make_request(
  2858. method="POST",
  2859. path="/rooms/" + self.room_id + "/invite",
  2860. content={
  2861. "id_server": "example.com",
  2862. "id_access_token": "sometoken",
  2863. "medium": "email",
  2864. "address": email_to_invite,
  2865. },
  2866. access_token=self.tok,
  2867. )
  2868. self.assertEqual(channel.code, 200)
  2869. # Check that the callback was called with the right params.
  2870. mock.assert_called_with(self.user_id, "email", email_to_invite, self.room_id)
  2871. # Check that the call to send the invite was made.
  2872. make_invite_mock.assert_called_once()
  2873. # Now change the return value of the callback to deny any invite and test that
  2874. # we can't send the invite.
  2875. mock.return_value = False
  2876. channel = self.make_request(
  2877. method="POST",
  2878. path="/rooms/" + self.room_id + "/invite",
  2879. content={
  2880. "id_server": "example.com",
  2881. "id_access_token": "sometoken",
  2882. "medium": "email",
  2883. "address": email_to_invite,
  2884. },
  2885. access_token=self.tok,
  2886. )
  2887. self.assertEqual(channel.code, 403)
  2888. # Also check that it stopped before calling _make_and_store_3pid_invite.
  2889. make_invite_mock.assert_called_once()
  2890. def test_threepid_invite_spamcheck(self) -> None:
  2891. """
  2892. Test allowing/blocking threepid invites with a spam-check module.
  2893. In this test, we use the more recent API in which callbacks return a `Union[Codes, Literal["NOT_SPAM"]]`.
  2894. """
  2895. # Mock a few functions to prevent the test from failing due to failing to talk to
  2896. # a remote IS. We keep the mock for make_and_store_3pid_invite around so we
  2897. # can check its call_count later on during the test.
  2898. make_invite_mock = AsyncMock(return_value=(Mock(event_id="abc"), 0))
  2899. self.hs.get_room_member_handler()._make_and_store_3pid_invite = make_invite_mock # type: ignore[method-assign]
  2900. self.hs.get_identity_handler().lookup_3pid = AsyncMock( # type: ignore[method-assign]
  2901. return_value=None,
  2902. )
  2903. # Add a mock to the spamchecker callbacks for user_may_send_3pid_invite. Make it
  2904. # allow everything for now.
  2905. # `spec` argument is needed for this function mock to have `__qualname__`, which
  2906. # is needed for `Measure` metrics buried in SpamChecker.
  2907. mock = AsyncMock(
  2908. return_value=synapse.module_api.NOT_SPAM,
  2909. spec=lambda *x: None,
  2910. )
  2911. self.hs.get_module_api_callbacks().spam_checker._user_may_send_3pid_invite_callbacks.append(
  2912. mock
  2913. )
  2914. # Send a 3PID invite into the room and check that it succeeded.
  2915. email_to_invite = "teresa@example.com"
  2916. channel = self.make_request(
  2917. method="POST",
  2918. path="/rooms/" + self.room_id + "/invite",
  2919. content={
  2920. "id_server": "example.com",
  2921. "id_access_token": "sometoken",
  2922. "medium": "email",
  2923. "address": email_to_invite,
  2924. },
  2925. access_token=self.tok,
  2926. )
  2927. self.assertEqual(channel.code, 200)
  2928. # Check that the callback was called with the right params.
  2929. mock.assert_called_with(self.user_id, "email", email_to_invite, self.room_id)
  2930. # Check that the call to send the invite was made.
  2931. make_invite_mock.assert_called_once()
  2932. # Now change the return value of the callback to deny any invite and test that
  2933. # we can't send the invite. We pick an arbitrary error code to be able to check
  2934. # that the same code has been returned
  2935. mock.return_value = Codes.CONSENT_NOT_GIVEN
  2936. channel = self.make_request(
  2937. method="POST",
  2938. path="/rooms/" + self.room_id + "/invite",
  2939. content={
  2940. "id_server": "example.com",
  2941. "id_access_token": "sometoken",
  2942. "medium": "email",
  2943. "address": email_to_invite,
  2944. },
  2945. access_token=self.tok,
  2946. )
  2947. self.assertEqual(channel.code, 403)
  2948. self.assertEqual(channel.json_body["errcode"], Codes.CONSENT_NOT_GIVEN)
  2949. # Also check that it stopped before calling _make_and_store_3pid_invite.
  2950. make_invite_mock.assert_called_once()
  2951. # Run variant with `Tuple[Codes, dict]`.
  2952. mock.return_value = (Codes.EXPIRED_ACCOUNT, {"field": "value"})
  2953. channel = self.make_request(
  2954. method="POST",
  2955. path="/rooms/" + self.room_id + "/invite",
  2956. content={
  2957. "id_server": "example.com",
  2958. "id_access_token": "sometoken",
  2959. "medium": "email",
  2960. "address": email_to_invite,
  2961. },
  2962. access_token=self.tok,
  2963. )
  2964. self.assertEqual(channel.code, 403)
  2965. self.assertEqual(channel.json_body["errcode"], Codes.EXPIRED_ACCOUNT)
  2966. self.assertEqual(channel.json_body["field"], "value")
  2967. # Also check that it stopped before calling _make_and_store_3pid_invite.
  2968. make_invite_mock.assert_called_once()
  2969. def test_400_missing_param_without_id_access_token(self) -> None:
  2970. """
  2971. Test that a 3pid invite request returns 400 M_MISSING_PARAM
  2972. if we do not include id_access_token.
  2973. """
  2974. channel = self.make_request(
  2975. method="POST",
  2976. path="/rooms/" + self.room_id + "/invite",
  2977. content={
  2978. "id_server": "example.com",
  2979. "medium": "email",
  2980. "address": "teresa@example.com",
  2981. },
  2982. access_token=self.tok,
  2983. )
  2984. self.assertEqual(channel.code, 400)
  2985. self.assertEqual(channel.json_body["errcode"], "M_MISSING_PARAM")
  2986. class TimestampLookupTestCase(unittest.HomeserverTestCase):
  2987. servlets = [
  2988. admin.register_servlets,
  2989. room.register_servlets,
  2990. login.register_servlets,
  2991. ]
  2992. def prepare(self, reactor: MemoryReactor, clock: Clock, hs: HomeServer) -> None:
  2993. self._storage_controllers = self.hs.get_storage_controllers()
  2994. self.room_owner = self.register_user("room_owner", "test")
  2995. self.room_owner_tok = self.login("room_owner", "test")
  2996. def _inject_outlier(self, room_id: str) -> EventBase:
  2997. event, _context = self.get_success(
  2998. create_event(
  2999. self.hs,
  3000. room_id=room_id,
  3001. type="m.test",
  3002. sender="@test_remote_user:remote",
  3003. )
  3004. )
  3005. event.internal_metadata.outlier = True
  3006. persistence = self._storage_controllers.persistence
  3007. assert persistence is not None
  3008. self.get_success(
  3009. persistence.persist_event(
  3010. event, EventContext.for_outlier(self._storage_controllers)
  3011. )
  3012. )
  3013. return event
  3014. def test_no_outliers(self) -> None:
  3015. """
  3016. Test to make sure `/timestamp_to_event` does not return `outlier` events.
  3017. We're unable to determine whether an `outlier` is next to a gap so we
  3018. don't know whether it's actually the closest event. Instead, let's just
  3019. ignore `outliers` with this endpoint.
  3020. This test is really seeing that we choose the non-`outlier` event behind the
  3021. `outlier`. Since the gap checking logic considers the latest message in the room
  3022. as *not* next to a gap, asking over federation does not come into play here.
  3023. """
  3024. room_id = self.helper.create_room_as(self.room_owner, tok=self.room_owner_tok)
  3025. outlier_event = self._inject_outlier(room_id)
  3026. channel = self.make_request(
  3027. "GET",
  3028. f"/_matrix/client/v1/rooms/{room_id}/timestamp_to_event?dir=b&ts={outlier_event.origin_server_ts}",
  3029. access_token=self.room_owner_tok,
  3030. )
  3031. self.assertEqual(HTTPStatus.OK, channel.code, msg=channel.json_body)
  3032. # Make sure the outlier event is not returned
  3033. self.assertNotEqual(channel.json_body["event_id"], outlier_event.event_id)