test_rooms.py 133 KB

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