test_rooms.py 133 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600
  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_module_api_callbacks().spam_checker._user_may_join_room_callbacks.append(
  685. join_mock
  686. )
  687. channel = self.make_request(
  688. "POST",
  689. "/createRoom",
  690. {},
  691. )
  692. self.assertEqual(channel.code, HTTPStatus.OK, channel.json_body)
  693. self.assertEqual(join_mock.call_count, 0)
  694. def test_spam_checker_may_join_room(self) -> None:
  695. """Tests that the user_may_join_room spam checker callback is correctly bypassed
  696. when creating a new room.
  697. In this test, we use the more recent API in which callbacks return a `Union[Codes, Literal["NOT_SPAM"]]`.
  698. """
  699. async def user_may_join_room_codes(
  700. mxid: str,
  701. room_id: str,
  702. is_invite: bool,
  703. ) -> Codes:
  704. return Codes.CONSENT_NOT_GIVEN
  705. join_mock = Mock(side_effect=user_may_join_room_codes)
  706. self.hs.get_module_api_callbacks().spam_checker._user_may_join_room_callbacks.append(
  707. join_mock
  708. )
  709. channel = self.make_request(
  710. "POST",
  711. "/createRoom",
  712. {},
  713. )
  714. self.assertEqual(channel.code, HTTPStatus.OK, channel.json_body)
  715. self.assertEqual(join_mock.call_count, 0)
  716. # Now change the return value of the callback to deny any join. Since we're
  717. # creating the room, despite the return value, we should be able to join.
  718. async def user_may_join_room_tuple(
  719. mxid: str,
  720. room_id: str,
  721. is_invite: bool,
  722. ) -> Tuple[Codes, dict]:
  723. return Codes.INCOMPATIBLE_ROOM_VERSION, {}
  724. join_mock.side_effect = user_may_join_room_tuple
  725. channel = self.make_request(
  726. "POST",
  727. "/createRoom",
  728. {},
  729. )
  730. self.assertEqual(channel.code, HTTPStatus.OK, channel.json_body)
  731. self.assertEqual(join_mock.call_count, 0)
  732. def _create_basic_room(self) -> Tuple[int, object]:
  733. """
  734. Tries to create a basic room and returns the response code.
  735. """
  736. channel = self.make_request(
  737. "POST",
  738. "/createRoom",
  739. {},
  740. )
  741. return channel.code, channel.json_body
  742. @override_config(
  743. {
  744. "rc_message": {"per_second": 0.2, "burst_count": 10},
  745. }
  746. )
  747. def test_room_creation_ratelimiting(self) -> None:
  748. """
  749. Regression test for #14312, where ratelimiting was made too strict.
  750. Clients should be able to create 10 rooms in a row
  751. without hitting rate limits, using default rate limit config.
  752. (We override rate limiting config back to its default value.)
  753. To ensure we don't make ratelimiting too generous accidentally,
  754. also check that we can't create an 11th room.
  755. """
  756. for _ in range(10):
  757. code, json_body = self._create_basic_room()
  758. self.assertEqual(code, HTTPStatus.OK, json_body)
  759. # The 6th room hits the rate limit.
  760. code, json_body = self._create_basic_room()
  761. self.assertEqual(code, HTTPStatus.TOO_MANY_REQUESTS, json_body)
  762. class RoomTopicTestCase(RoomBase):
  763. """Tests /rooms/$room_id/topic REST events."""
  764. user_id = "@sid1:red"
  765. def prepare(self, reactor: MemoryReactor, clock: Clock, hs: HomeServer) -> None:
  766. # create the room
  767. self.room_id = self.helper.create_room_as(self.user_id)
  768. self.path = "/rooms/%s/state/m.room.topic" % (self.room_id,)
  769. def test_invalid_puts(self) -> None:
  770. # missing keys or invalid json
  771. channel = self.make_request("PUT", self.path, "{}")
  772. self.assertEqual(
  773. HTTPStatus.BAD_REQUEST, channel.code, msg=channel.result["body"]
  774. )
  775. channel = self.make_request("PUT", self.path, '{"_name":"bo"}')
  776. self.assertEqual(
  777. HTTPStatus.BAD_REQUEST, channel.code, msg=channel.result["body"]
  778. )
  779. channel = self.make_request("PUT", self.path, '{"nao')
  780. self.assertEqual(
  781. HTTPStatus.BAD_REQUEST, channel.code, msg=channel.result["body"]
  782. )
  783. channel = self.make_request(
  784. "PUT", self.path, '[{"_name":"bo"},{"_name":"jill"}]'
  785. )
  786. self.assertEqual(
  787. HTTPStatus.BAD_REQUEST, channel.code, msg=channel.result["body"]
  788. )
  789. channel = self.make_request("PUT", self.path, "text only")
  790. self.assertEqual(
  791. HTTPStatus.BAD_REQUEST, channel.code, msg=channel.result["body"]
  792. )
  793. channel = self.make_request("PUT", self.path, "")
  794. self.assertEqual(
  795. HTTPStatus.BAD_REQUEST, channel.code, msg=channel.result["body"]
  796. )
  797. # valid key, wrong type
  798. content = '{"topic":["Topic name"]}'
  799. channel = self.make_request("PUT", self.path, content)
  800. self.assertEqual(
  801. HTTPStatus.BAD_REQUEST, channel.code, msg=channel.result["body"]
  802. )
  803. def test_rooms_topic(self) -> None:
  804. # nothing should be there
  805. channel = self.make_request("GET", self.path)
  806. self.assertEqual(HTTPStatus.NOT_FOUND, channel.code, msg=channel.result["body"])
  807. # valid put
  808. content = '{"topic":"Topic name"}'
  809. channel = self.make_request("PUT", self.path, content)
  810. self.assertEqual(HTTPStatus.OK, channel.code, msg=channel.result["body"])
  811. # valid get
  812. channel = self.make_request("GET", self.path)
  813. self.assertEqual(HTTPStatus.OK, channel.code, msg=channel.result["body"])
  814. self.assert_dict(json.loads(content), channel.json_body)
  815. def test_rooms_topic_with_extra_keys(self) -> None:
  816. # valid put with extra keys
  817. content = '{"topic":"Seasons","subtopic":"Summer"}'
  818. channel = self.make_request("PUT", self.path, content)
  819. self.assertEqual(HTTPStatus.OK, channel.code, msg=channel.result["body"])
  820. # valid get
  821. channel = self.make_request("GET", self.path)
  822. self.assertEqual(HTTPStatus.OK, channel.code, msg=channel.result["body"])
  823. self.assert_dict(json.loads(content), channel.json_body)
  824. class RoomMemberStateTestCase(RoomBase):
  825. """Tests /rooms/$room_id/members/$user_id/state REST events."""
  826. user_id = "@sid1:red"
  827. def prepare(self, reactor: MemoryReactor, clock: Clock, hs: HomeServer) -> None:
  828. self.room_id = self.helper.create_room_as(self.user_id)
  829. def test_invalid_puts(self) -> None:
  830. path = "/rooms/%s/state/m.room.member/%s" % (self.room_id, self.user_id)
  831. # missing keys or invalid json
  832. channel = self.make_request("PUT", path, "{}")
  833. self.assertEqual(
  834. HTTPStatus.BAD_REQUEST, channel.code, msg=channel.result["body"]
  835. )
  836. channel = self.make_request("PUT", path, '{"_name":"bo"}')
  837. self.assertEqual(
  838. HTTPStatus.BAD_REQUEST, channel.code, msg=channel.result["body"]
  839. )
  840. channel = self.make_request("PUT", path, '{"nao')
  841. self.assertEqual(
  842. HTTPStatus.BAD_REQUEST, channel.code, msg=channel.result["body"]
  843. )
  844. channel = self.make_request("PUT", path, b'[{"_name":"bo"},{"_name":"jill"}]')
  845. self.assertEqual(
  846. HTTPStatus.BAD_REQUEST, channel.code, msg=channel.result["body"]
  847. )
  848. channel = self.make_request("PUT", path, "text only")
  849. self.assertEqual(
  850. HTTPStatus.BAD_REQUEST, channel.code, msg=channel.result["body"]
  851. )
  852. channel = self.make_request("PUT", path, "")
  853. self.assertEqual(
  854. HTTPStatus.BAD_REQUEST, channel.code, msg=channel.result["body"]
  855. )
  856. # valid keys, wrong types
  857. content = '{"membership":["%s","%s","%s"]}' % (
  858. Membership.INVITE,
  859. Membership.JOIN,
  860. Membership.LEAVE,
  861. )
  862. channel = self.make_request("PUT", path, content.encode("ascii"))
  863. self.assertEqual(
  864. HTTPStatus.BAD_REQUEST, channel.code, msg=channel.result["body"]
  865. )
  866. def test_rooms_members_self(self) -> None:
  867. path = "/rooms/%s/state/m.room.member/%s" % (
  868. urlparse.quote(self.room_id),
  869. self.user_id,
  870. )
  871. # valid join message (NOOP since we made the room)
  872. content = '{"membership":"%s"}' % Membership.JOIN
  873. channel = self.make_request("PUT", path, content.encode("ascii"))
  874. self.assertEqual(HTTPStatus.OK, channel.code, msg=channel.result["body"])
  875. channel = self.make_request("GET", path, content=b"")
  876. self.assertEqual(HTTPStatus.OK, channel.code, msg=channel.result["body"])
  877. expected_response = {"membership": Membership.JOIN}
  878. self.assertEqual(expected_response, channel.json_body)
  879. def test_rooms_members_other(self) -> None:
  880. self.other_id = "@zzsid1:red"
  881. path = "/rooms/%s/state/m.room.member/%s" % (
  882. urlparse.quote(self.room_id),
  883. self.other_id,
  884. )
  885. # valid invite message
  886. content = '{"membership":"%s"}' % Membership.INVITE
  887. channel = self.make_request("PUT", path, content)
  888. self.assertEqual(HTTPStatus.OK, channel.code, msg=channel.result["body"])
  889. channel = self.make_request("GET", path, content=b"")
  890. self.assertEqual(HTTPStatus.OK, channel.code, msg=channel.result["body"])
  891. self.assertEqual(json.loads(content), channel.json_body)
  892. def test_rooms_members_other_custom_keys(self) -> None:
  893. self.other_id = "@zzsid1:red"
  894. path = "/rooms/%s/state/m.room.member/%s" % (
  895. urlparse.quote(self.room_id),
  896. self.other_id,
  897. )
  898. # valid invite message with custom key
  899. content = '{"membership":"%s","invite_text":"%s"}' % (
  900. Membership.INVITE,
  901. "Join us!",
  902. )
  903. channel = self.make_request("PUT", path, content)
  904. self.assertEqual(HTTPStatus.OK, channel.code, msg=channel.result["body"])
  905. channel = self.make_request("GET", path, content=b"")
  906. self.assertEqual(HTTPStatus.OK, channel.code, msg=channel.result["body"])
  907. self.assertEqual(json.loads(content), channel.json_body)
  908. class RoomInviteRatelimitTestCase(RoomBase):
  909. user_id = "@sid1:red"
  910. servlets = [
  911. admin.register_servlets,
  912. profile.register_servlets,
  913. room.register_servlets,
  914. ]
  915. @unittest.override_config(
  916. {"rc_invites": {"per_room": {"per_second": 0.5, "burst_count": 3}}}
  917. )
  918. def test_invites_by_rooms_ratelimit(self) -> None:
  919. """Tests that invites in a room are actually rate-limited."""
  920. room_id = self.helper.create_room_as(self.user_id)
  921. for i in range(3):
  922. self.helper.invite(room_id, self.user_id, "@user-%s:red" % (i,))
  923. self.helper.invite(room_id, self.user_id, "@user-4:red", expect_code=429)
  924. @unittest.override_config(
  925. {"rc_invites": {"per_user": {"per_second": 0.5, "burst_count": 3}}}
  926. )
  927. def test_invites_by_users_ratelimit(self) -> None:
  928. """Tests that invites to a specific user are actually rate-limited."""
  929. for _ in range(3):
  930. room_id = self.helper.create_room_as(self.user_id)
  931. self.helper.invite(room_id, self.user_id, "@other-users:red")
  932. room_id = self.helper.create_room_as(self.user_id)
  933. self.helper.invite(room_id, self.user_id, "@other-users:red", expect_code=429)
  934. class RoomJoinTestCase(RoomBase):
  935. servlets = [
  936. admin.register_servlets,
  937. login.register_servlets,
  938. room.register_servlets,
  939. ]
  940. def prepare(self, reactor: MemoryReactor, clock: Clock, hs: HomeServer) -> None:
  941. self.user1 = self.register_user("thomas", "hackme")
  942. self.tok1 = self.login("thomas", "hackme")
  943. self.user2 = self.register_user("teresa", "hackme")
  944. self.tok2 = self.login("teresa", "hackme")
  945. self.room1 = self.helper.create_room_as(room_creator=self.user1, tok=self.tok1)
  946. self.room2 = self.helper.create_room_as(room_creator=self.user1, tok=self.tok1)
  947. self.room3 = self.helper.create_room_as(room_creator=self.user1, tok=self.tok1)
  948. def test_spam_checker_may_join_room_deprecated(self) -> None:
  949. """Tests that the user_may_join_room spam checker callback is correctly called
  950. and blocks room joins when needed.
  951. This test uses the deprecated API, in which callbacks return booleans.
  952. """
  953. # Register a dummy callback. Make it allow all room joins for now.
  954. return_value = True
  955. async def user_may_join_room(
  956. userid: str,
  957. room_id: str,
  958. is_invited: bool,
  959. ) -> bool:
  960. return return_value
  961. # `spec` argument is needed for this function mock to have `__qualname__`, which
  962. # is needed for `Measure` metrics buried in SpamChecker.
  963. callback_mock = Mock(side_effect=user_may_join_room, spec=lambda *x: None)
  964. self.hs.get_module_api_callbacks().spam_checker._user_may_join_room_callbacks.append(
  965. callback_mock
  966. )
  967. # Join a first room, without being invited to it.
  968. self.helper.join(self.room1, self.user2, tok=self.tok2)
  969. # Check that the callback was called with the right arguments.
  970. expected_call_args = (
  971. (
  972. self.user2,
  973. self.room1,
  974. False,
  975. ),
  976. )
  977. self.assertEqual(
  978. callback_mock.call_args,
  979. expected_call_args,
  980. callback_mock.call_args,
  981. )
  982. # Join a second room, this time with an invite for it.
  983. self.helper.invite(self.room2, self.user1, self.user2, tok=self.tok1)
  984. self.helper.join(self.room2, self.user2, tok=self.tok2)
  985. # Check that the callback was called with the right arguments.
  986. expected_call_args = (
  987. (
  988. self.user2,
  989. self.room2,
  990. True,
  991. ),
  992. )
  993. self.assertEqual(
  994. callback_mock.call_args,
  995. expected_call_args,
  996. callback_mock.call_args,
  997. )
  998. # Now make the callback deny all room joins, and check that a join actually fails.
  999. return_value = False
  1000. self.helper.join(
  1001. self.room3, self.user2, expect_code=HTTPStatus.FORBIDDEN, tok=self.tok2
  1002. )
  1003. def test_spam_checker_may_join_room(self) -> None:
  1004. """Tests that the user_may_join_room spam checker callback is correctly called
  1005. and blocks room joins when needed.
  1006. This test uses the latest API to this day, in which callbacks return `NOT_SPAM` or `Codes`.
  1007. """
  1008. # Register a dummy callback. Make it allow all room joins for now.
  1009. return_value: Union[
  1010. Literal["NOT_SPAM"], Tuple[Codes, dict], Codes
  1011. ] = synapse.module_api.NOT_SPAM
  1012. async def user_may_join_room(
  1013. userid: str,
  1014. room_id: str,
  1015. is_invited: bool,
  1016. ) -> Union[Literal["NOT_SPAM"], Tuple[Codes, dict], Codes]:
  1017. return return_value
  1018. # `spec` argument is needed for this function mock to have `__qualname__`, which
  1019. # is needed for `Measure` metrics buried in SpamChecker.
  1020. callback_mock = Mock(side_effect=user_may_join_room, spec=lambda *x: None)
  1021. self.hs.get_module_api_callbacks().spam_checker._user_may_join_room_callbacks.append(
  1022. callback_mock
  1023. )
  1024. # Join a first room, without being invited to it.
  1025. self.helper.join(self.room1, self.user2, tok=self.tok2)
  1026. # Check that the callback was called with the right arguments.
  1027. expected_call_args = (
  1028. (
  1029. self.user2,
  1030. self.room1,
  1031. False,
  1032. ),
  1033. )
  1034. self.assertEqual(
  1035. callback_mock.call_args,
  1036. expected_call_args,
  1037. callback_mock.call_args,
  1038. )
  1039. # Join a second room, this time with an invite for it.
  1040. self.helper.invite(self.room2, self.user1, self.user2, tok=self.tok1)
  1041. self.helper.join(self.room2, self.user2, tok=self.tok2)
  1042. # Check that the callback was called with the right arguments.
  1043. expected_call_args = (
  1044. (
  1045. self.user2,
  1046. self.room2,
  1047. True,
  1048. ),
  1049. )
  1050. self.assertEqual(
  1051. callback_mock.call_args,
  1052. expected_call_args,
  1053. callback_mock.call_args,
  1054. )
  1055. # Now make the callback deny all room joins, and check that a join actually fails.
  1056. # We pick an arbitrary Codes rather than the default `Codes.FORBIDDEN`.
  1057. return_value = Codes.CONSENT_NOT_GIVEN
  1058. self.helper.invite(self.room3, self.user1, self.user2, tok=self.tok1)
  1059. self.helper.join(
  1060. self.room3,
  1061. self.user2,
  1062. expect_code=HTTPStatus.FORBIDDEN,
  1063. expect_errcode=return_value,
  1064. tok=self.tok2,
  1065. )
  1066. # Now make the callback deny all room joins, and check that a join actually fails.
  1067. # As above, with the experimental extension that lets us return dictionaries.
  1068. return_value = (Codes.BAD_ALIAS, {"another_field": "12345"})
  1069. self.helper.join(
  1070. self.room3,
  1071. self.user2,
  1072. expect_code=HTTPStatus.FORBIDDEN,
  1073. expect_errcode=return_value[0],
  1074. tok=self.tok2,
  1075. expect_additional_fields=return_value[1],
  1076. )
  1077. class RoomAppserviceTsParamTestCase(unittest.HomeserverTestCase):
  1078. servlets = [
  1079. room.register_servlets,
  1080. synapse.rest.admin.register_servlets,
  1081. register.register_servlets,
  1082. ]
  1083. def prepare(self, reactor: MemoryReactor, clock: Clock, hs: HomeServer) -> None:
  1084. self.appservice_user, _ = self.register_appservice_user(
  1085. "as_user_potato", self.appservice.token
  1086. )
  1087. # Create a room as the appservice user.
  1088. args = {
  1089. "access_token": self.appservice.token,
  1090. "user_id": self.appservice_user,
  1091. }
  1092. channel = self.make_request(
  1093. "POST",
  1094. f"/_matrix/client/r0/createRoom?{urlparse.urlencode(args)}",
  1095. content={"visibility": "public"},
  1096. )
  1097. assert channel.code == 200
  1098. self.room = channel.json_body["room_id"]
  1099. self.main_store = self.hs.get_datastores().main
  1100. def make_homeserver(self, reactor: MemoryReactor, clock: Clock) -> HomeServer:
  1101. config = self.default_config()
  1102. self.appservice = ApplicationService(
  1103. token="i_am_an_app_service",
  1104. id="1234",
  1105. namespaces={"users": [{"regex": r"@as_user.*", "exclusive": True}]},
  1106. # Note: this user does not have to match the regex above
  1107. sender="@as_main:test",
  1108. )
  1109. mock_load_appservices = Mock(return_value=[self.appservice])
  1110. with patch(
  1111. "synapse.storage.databases.main.appservice.load_appservices",
  1112. mock_load_appservices,
  1113. ):
  1114. hs = self.setup_test_homeserver(config=config)
  1115. return hs
  1116. def test_send_event_ts(self) -> None:
  1117. """Test sending a non-state event with a custom timestamp."""
  1118. ts = 1
  1119. url_params = {
  1120. "user_id": self.appservice_user,
  1121. "ts": ts,
  1122. }
  1123. channel = self.make_request(
  1124. "PUT",
  1125. path=f"/_matrix/client/r0/rooms/{self.room}/send/m.room.message/1234?"
  1126. + urlparse.urlencode(url_params),
  1127. content={"body": "test", "msgtype": "m.text"},
  1128. access_token=self.appservice.token,
  1129. )
  1130. self.assertEqual(channel.code, 200, channel.json_body)
  1131. event_id = channel.json_body["event_id"]
  1132. # Ensure the event was persisted with the correct timestamp.
  1133. res = self.get_success(self.main_store.get_event(event_id))
  1134. self.assertEquals(ts, res.origin_server_ts)
  1135. def test_send_state_event_ts(self) -> None:
  1136. """Test sending a state event with a custom timestamp."""
  1137. ts = 1
  1138. url_params = {
  1139. "user_id": self.appservice_user,
  1140. "ts": ts,
  1141. }
  1142. channel = self.make_request(
  1143. "PUT",
  1144. path=f"/_matrix/client/r0/rooms/{self.room}/state/m.room.name?"
  1145. + urlparse.urlencode(url_params),
  1146. content={"name": "test"},
  1147. access_token=self.appservice.token,
  1148. )
  1149. self.assertEqual(channel.code, 200, channel.json_body)
  1150. event_id = channel.json_body["event_id"]
  1151. # Ensure the event was persisted with the correct timestamp.
  1152. res = self.get_success(self.main_store.get_event(event_id))
  1153. self.assertEquals(ts, res.origin_server_ts)
  1154. def test_send_membership_event_ts(self) -> None:
  1155. """Test sending a membership event with a custom timestamp."""
  1156. ts = 1
  1157. url_params = {
  1158. "user_id": self.appservice_user,
  1159. "ts": ts,
  1160. }
  1161. channel = self.make_request(
  1162. "PUT",
  1163. path=f"/_matrix/client/r0/rooms/{self.room}/state/m.room.member/{self.appservice_user}?"
  1164. + urlparse.urlencode(url_params),
  1165. content={"membership": "join", "display_name": "test"},
  1166. access_token=self.appservice.token,
  1167. )
  1168. self.assertEqual(channel.code, 200, channel.json_body)
  1169. event_id = channel.json_body["event_id"]
  1170. # Ensure the event was persisted with the correct timestamp.
  1171. res = self.get_success(self.main_store.get_event(event_id))
  1172. self.assertEquals(ts, res.origin_server_ts)
  1173. class RoomJoinRatelimitTestCase(RoomBase):
  1174. user_id = "@sid1:red"
  1175. servlets = [
  1176. admin.register_servlets,
  1177. profile.register_servlets,
  1178. room.register_servlets,
  1179. ]
  1180. def prepare(self, reactor: MemoryReactor, clock: Clock, hs: HomeServer) -> None:
  1181. super().prepare(reactor, clock, hs)
  1182. # profile changes expect that the user is actually registered
  1183. user = UserID.from_string(self.user_id)
  1184. self.register_user(user.localpart, "supersecretpassword")
  1185. @unittest.override_config(
  1186. {"rc_joins": {"local": {"per_second": 0.5, "burst_count": 3}}}
  1187. )
  1188. def test_join_local_ratelimit(self) -> None:
  1189. """Tests that local joins are actually rate-limited."""
  1190. # Create 4 rooms
  1191. room_ids = [
  1192. self.helper.create_room_as(self.user_id, is_public=True) for _ in range(4)
  1193. ]
  1194. joiner_user_id = self.register_user("joiner", "secret")
  1195. # Now make a new user try to join some of them.
  1196. # The user can join 3 rooms
  1197. for room_id in room_ids[0:3]:
  1198. self.helper.join(room_id, joiner_user_id)
  1199. # But the user cannot join a 4th room
  1200. self.helper.join(
  1201. room_ids[3], joiner_user_id, expect_code=HTTPStatus.TOO_MANY_REQUESTS
  1202. )
  1203. @unittest.override_config(
  1204. {"rc_joins": {"local": {"per_second": 0.5, "burst_count": 3}}}
  1205. )
  1206. def test_join_local_ratelimit_profile_change(self) -> None:
  1207. """Tests that sending a profile update into all of the user's joined rooms isn't
  1208. rate-limited by the rate-limiter on joins."""
  1209. # Create and join as many rooms as the rate-limiting config allows in a second.
  1210. room_ids = [
  1211. self.helper.create_room_as(self.user_id),
  1212. self.helper.create_room_as(self.user_id),
  1213. self.helper.create_room_as(self.user_id),
  1214. ]
  1215. # Let some time for the rate-limiter to forget about our multi-join.
  1216. self.reactor.advance(2)
  1217. # Add one to make sure we're joined to more rooms than the config allows us to
  1218. # join in a second.
  1219. room_ids.append(self.helper.create_room_as(self.user_id))
  1220. # Update the display name for the user.
  1221. path = "/_matrix/client/r0/profile/%s/displayname" % self.user_id
  1222. channel = self.make_request("PUT", path, {"displayname": "John Doe"})
  1223. self.assertEqual(channel.code, HTTPStatus.OK, channel.json_body)
  1224. # Check that all the rooms have been sent a profile update into.
  1225. for room_id in room_ids:
  1226. path = "/_matrix/client/r0/rooms/%s/state/m.room.member/%s" % (
  1227. room_id,
  1228. self.user_id,
  1229. )
  1230. channel = self.make_request("GET", path)
  1231. self.assertEqual(channel.code, 200)
  1232. self.assertIn("displayname", channel.json_body)
  1233. self.assertEqual(channel.json_body["displayname"], "John Doe")
  1234. @unittest.override_config(
  1235. {"rc_joins": {"local": {"per_second": 0.5, "burst_count": 3}}}
  1236. )
  1237. def test_join_local_ratelimit_idempotent(self) -> None:
  1238. """Tests that the room join endpoints remain idempotent despite rate-limiting
  1239. on room joins."""
  1240. room_id = self.helper.create_room_as(self.user_id)
  1241. # Let's test both paths to be sure.
  1242. paths_to_test = [
  1243. "/_matrix/client/r0/rooms/%s/join",
  1244. "/_matrix/client/r0/join/%s",
  1245. ]
  1246. for path in paths_to_test:
  1247. # Make sure we send more requests than the rate-limiting config would allow
  1248. # if all of these requests ended up joining the user to a room.
  1249. for _ in range(4):
  1250. channel = self.make_request("POST", path % room_id, {})
  1251. self.assertEqual(channel.code, 200)
  1252. @unittest.override_config(
  1253. {
  1254. "rc_joins": {"local": {"per_second": 0.5, "burst_count": 3}},
  1255. "auto_join_rooms": ["#room:red", "#room2:red", "#room3:red", "#room4:red"],
  1256. "autocreate_auto_join_rooms": True,
  1257. },
  1258. )
  1259. def test_autojoin_rooms(self) -> None:
  1260. user_id = self.register_user("testuser", "password")
  1261. # Check that the new user successfully joined the four rooms
  1262. rooms = self.get_success(
  1263. self.hs.get_datastores().main.get_rooms_for_user(user_id)
  1264. )
  1265. self.assertEqual(len(rooms), 4)
  1266. class RoomMessagesTestCase(RoomBase):
  1267. """Tests /rooms/$room_id/messages/$user_id/$msg_id REST events."""
  1268. user_id = "@sid1:red"
  1269. def prepare(self, reactor: MemoryReactor, clock: Clock, hs: HomeServer) -> None:
  1270. self.room_id = self.helper.create_room_as(self.user_id)
  1271. def test_invalid_puts(self) -> None:
  1272. path = "/rooms/%s/send/m.room.message/mid1" % (urlparse.quote(self.room_id))
  1273. # missing keys or invalid json
  1274. channel = self.make_request("PUT", path, b"{}")
  1275. self.assertEqual(
  1276. HTTPStatus.BAD_REQUEST, channel.code, msg=channel.result["body"]
  1277. )
  1278. channel = self.make_request("PUT", path, b'{"_name":"bo"}')
  1279. self.assertEqual(
  1280. HTTPStatus.BAD_REQUEST, channel.code, msg=channel.result["body"]
  1281. )
  1282. channel = self.make_request("PUT", path, b'{"nao')
  1283. self.assertEqual(
  1284. HTTPStatus.BAD_REQUEST, channel.code, msg=channel.result["body"]
  1285. )
  1286. channel = self.make_request("PUT", path, b'[{"_name":"bo"},{"_name":"jill"}]')
  1287. self.assertEqual(
  1288. HTTPStatus.BAD_REQUEST, channel.code, msg=channel.result["body"]
  1289. )
  1290. channel = self.make_request("PUT", path, b"text only")
  1291. self.assertEqual(
  1292. HTTPStatus.BAD_REQUEST, channel.code, msg=channel.result["body"]
  1293. )
  1294. channel = self.make_request("PUT", path, b"")
  1295. self.assertEqual(
  1296. HTTPStatus.BAD_REQUEST, channel.code, msg=channel.result["body"]
  1297. )
  1298. def test_rooms_messages_sent(self) -> None:
  1299. path = "/rooms/%s/send/m.room.message/mid1" % (urlparse.quote(self.room_id))
  1300. content = b'{"body":"test","msgtype":{"type":"a"}}'
  1301. channel = self.make_request("PUT", path, content)
  1302. self.assertEqual(
  1303. HTTPStatus.BAD_REQUEST, channel.code, msg=channel.result["body"]
  1304. )
  1305. # custom message types
  1306. content = b'{"body":"test","msgtype":"test.custom.text"}'
  1307. channel = self.make_request("PUT", path, content)
  1308. self.assertEqual(HTTPStatus.OK, channel.code, msg=channel.result["body"])
  1309. # m.text message type
  1310. path = "/rooms/%s/send/m.room.message/mid2" % (urlparse.quote(self.room_id))
  1311. content = b'{"body":"test2","msgtype":"m.text"}'
  1312. channel = self.make_request("PUT", path, content)
  1313. self.assertEqual(HTTPStatus.OK, channel.code, msg=channel.result["body"])
  1314. @parameterized.expand(
  1315. [
  1316. # Allow
  1317. param(
  1318. name="NOT_SPAM",
  1319. value="NOT_SPAM",
  1320. expected_code=HTTPStatus.OK,
  1321. expected_fields={},
  1322. ),
  1323. param(
  1324. name="False",
  1325. value=False,
  1326. expected_code=HTTPStatus.OK,
  1327. expected_fields={},
  1328. ),
  1329. # Block
  1330. param(
  1331. name="scalene string",
  1332. value="ANY OTHER STRING",
  1333. expected_code=HTTPStatus.FORBIDDEN,
  1334. expected_fields={"errcode": "M_FORBIDDEN"},
  1335. ),
  1336. param(
  1337. name="True",
  1338. value=True,
  1339. expected_code=HTTPStatus.FORBIDDEN,
  1340. expected_fields={"errcode": "M_FORBIDDEN"},
  1341. ),
  1342. param(
  1343. name="Code",
  1344. value=Codes.LIMIT_EXCEEDED,
  1345. expected_code=HTTPStatus.FORBIDDEN,
  1346. expected_fields={"errcode": "M_LIMIT_EXCEEDED"},
  1347. ),
  1348. param(
  1349. name="Tuple",
  1350. value=(Codes.SERVER_NOT_TRUSTED, {"additional_field": "12345"}),
  1351. expected_code=HTTPStatus.FORBIDDEN,
  1352. expected_fields={
  1353. "errcode": "M_SERVER_NOT_TRUSTED",
  1354. "additional_field": "12345",
  1355. },
  1356. ),
  1357. ]
  1358. )
  1359. def test_spam_checker_check_event_for_spam(
  1360. self,
  1361. name: str,
  1362. value: Union[str, bool, Codes, Tuple[Codes, JsonDict]],
  1363. expected_code: int,
  1364. expected_fields: dict,
  1365. ) -> None:
  1366. class SpamCheck:
  1367. mock_return_value: Union[
  1368. str, bool, Codes, Tuple[Codes, JsonDict], bool
  1369. ] = "NOT_SPAM"
  1370. mock_content: Optional[JsonDict] = None
  1371. async def check_event_for_spam(
  1372. self,
  1373. event: synapse.events.EventBase,
  1374. ) -> Union[str, Codes, Tuple[Codes, JsonDict], bool]:
  1375. self.mock_content = event.content
  1376. return self.mock_return_value
  1377. spam_checker = SpamCheck()
  1378. self.hs.get_module_api_callbacks().spam_checker._check_event_for_spam_callbacks.append(
  1379. spam_checker.check_event_for_spam
  1380. )
  1381. # Inject `value` as mock_return_value
  1382. spam_checker.mock_return_value = value
  1383. path = "/rooms/%s/send/m.room.message/check_event_for_spam_%s" % (
  1384. urlparse.quote(self.room_id),
  1385. urlparse.quote(name),
  1386. )
  1387. body = "test-%s" % name
  1388. content = '{"body":"%s","msgtype":"m.text"}' % body
  1389. channel = self.make_request("PUT", path, content)
  1390. # Check that the callback has witnessed the correct event.
  1391. self.assertIsNotNone(spam_checker.mock_content)
  1392. if (
  1393. spam_checker.mock_content is not None
  1394. ): # Checked just above, but mypy doesn't know about that.
  1395. self.assertEqual(
  1396. spam_checker.mock_content["body"], body, spam_checker.mock_content
  1397. )
  1398. # Check that we have the correct result.
  1399. self.assertEqual(expected_code, channel.code, msg=channel.result["body"])
  1400. for expected_key, expected_value in expected_fields.items():
  1401. self.assertEqual(
  1402. channel.json_body.get(expected_key, None),
  1403. expected_value,
  1404. "Field %s absent or invalid " % expected_key,
  1405. )
  1406. class RoomPowerLevelOverridesTestCase(RoomBase):
  1407. """Tests that the power levels can be overridden with server config."""
  1408. user_id = "@sid1:red"
  1409. servlets = [
  1410. admin.register_servlets,
  1411. room.register_servlets,
  1412. login.register_servlets,
  1413. ]
  1414. def prepare(self, reactor: MemoryReactor, clock: Clock, hs: HomeServer) -> None:
  1415. self.admin_user_id = self.register_user("admin", "pass")
  1416. self.admin_access_token = self.login("admin", "pass")
  1417. def power_levels(self, room_id: str) -> Dict[str, Any]:
  1418. return self.helper.get_state(
  1419. room_id, "m.room.power_levels", self.admin_access_token
  1420. )
  1421. def test_default_power_levels_with_room_override(self) -> None:
  1422. """
  1423. Create a room, providing power level overrides.
  1424. Confirm that the room's power levels reflect the overrides.
  1425. See https://github.com/matrix-org/matrix-spec/issues/492
  1426. - currently we overwrite each key of power_level_content_override
  1427. completely.
  1428. """
  1429. room_id = self.helper.create_room_as(
  1430. self.user_id,
  1431. extra_content={
  1432. "power_level_content_override": {"events": {"custom.event": 0}}
  1433. },
  1434. )
  1435. self.assertEqual(
  1436. {
  1437. "custom.event": 0,
  1438. },
  1439. self.power_levels(room_id)["events"],
  1440. )
  1441. @unittest.override_config(
  1442. {
  1443. "default_power_level_content_override": {
  1444. "public_chat": {"events": {"custom.event": 0}},
  1445. }
  1446. },
  1447. )
  1448. def test_power_levels_with_server_override(self) -> None:
  1449. """
  1450. With a server configured to modify the room-level defaults,
  1451. Create a room, without providing any extra power level overrides.
  1452. Confirm that the room's power levels reflect the server-level overrides.
  1453. Similar to https://github.com/matrix-org/matrix-spec/issues/492,
  1454. we overwrite each key of power_level_content_override completely.
  1455. """
  1456. room_id = self.helper.create_room_as(self.user_id)
  1457. self.assertEqual(
  1458. {
  1459. "custom.event": 0,
  1460. },
  1461. self.power_levels(room_id)["events"],
  1462. )
  1463. @unittest.override_config(
  1464. {
  1465. "default_power_level_content_override": {
  1466. "public_chat": {
  1467. "events": {"server.event": 0},
  1468. "ban": 13,
  1469. },
  1470. }
  1471. },
  1472. )
  1473. def test_power_levels_with_server_and_room_overrides(self) -> None:
  1474. """
  1475. With a server configured to modify the room-level defaults,
  1476. create a room, providing different overrides.
  1477. Confirm that the room's power levels reflect both overrides, and
  1478. choose the room overrides where they clash.
  1479. """
  1480. room_id = self.helper.create_room_as(
  1481. self.user_id,
  1482. extra_content={
  1483. "power_level_content_override": {"events": {"room.event": 0}}
  1484. },
  1485. )
  1486. # Room override wins over server config
  1487. self.assertEqual(
  1488. {"room.event": 0},
  1489. self.power_levels(room_id)["events"],
  1490. )
  1491. # But where there is no room override, server config wins
  1492. self.assertEqual(13, self.power_levels(room_id)["ban"])
  1493. class RoomPowerLevelOverridesInPracticeTestCase(RoomBase):
  1494. """
  1495. Tests that we can really do various otherwise-prohibited actions
  1496. based on overriding the power levels in config.
  1497. """
  1498. user_id = "@sid1:red"
  1499. def test_creator_can_post_state_event(self) -> None:
  1500. # Given I am the creator of a room
  1501. room_id = self.helper.create_room_as(self.user_id)
  1502. # When I send a state event
  1503. path = "/rooms/{room_id}/state/custom.event/my_state_key".format(
  1504. room_id=urlparse.quote(room_id),
  1505. )
  1506. channel = self.make_request("PUT", path, "{}")
  1507. # Then I am allowed
  1508. self.assertEqual(HTTPStatus.OK, channel.code, msg=channel.result["body"])
  1509. def test_normal_user_can_not_post_state_event(self) -> None:
  1510. # Given I am a normal member of a room
  1511. room_id = self.helper.create_room_as("@some_other_guy:red")
  1512. self.helper.join(room=room_id, user=self.user_id)
  1513. # When I send a state event
  1514. path = "/rooms/{room_id}/state/custom.event/my_state_key".format(
  1515. room_id=urlparse.quote(room_id),
  1516. )
  1517. channel = self.make_request("PUT", path, "{}")
  1518. # Then I am not allowed because state events require PL>=50
  1519. self.assertEqual(HTTPStatus.FORBIDDEN, channel.code, msg=channel.result["body"])
  1520. self.assertEqual(
  1521. "You don't have permission to post that to the room. "
  1522. "user_level (0) < send_level (50)",
  1523. channel.json_body["error"],
  1524. )
  1525. @unittest.override_config(
  1526. {
  1527. "default_power_level_content_override": {
  1528. "public_chat": {"events": {"custom.event": 0}},
  1529. }
  1530. },
  1531. )
  1532. def test_with_config_override_normal_user_can_post_state_event(self) -> None:
  1533. # Given the server has config allowing normal users to post my event type,
  1534. # and I am a normal member of a room
  1535. room_id = self.helper.create_room_as("@some_other_guy:red")
  1536. self.helper.join(room=room_id, user=self.user_id)
  1537. # When I send a state event
  1538. path = "/rooms/{room_id}/state/custom.event/my_state_key".format(
  1539. room_id=urlparse.quote(room_id),
  1540. )
  1541. channel = self.make_request("PUT", path, "{}")
  1542. # Then I am allowed
  1543. self.assertEqual(HTTPStatus.OK, channel.code, msg=channel.result["body"])
  1544. @unittest.override_config(
  1545. {
  1546. "default_power_level_content_override": {
  1547. "public_chat": {"events": {"custom.event": 0}},
  1548. }
  1549. },
  1550. )
  1551. def test_any_room_override_defeats_config_override(self) -> None:
  1552. # Given the server has config allowing normal users to post my event type
  1553. # And I am a normal member of a room
  1554. # But the room was created with special permissions
  1555. extra_content: Dict[str, Any] = {
  1556. "power_level_content_override": {"events": {}},
  1557. }
  1558. room_id = self.helper.create_room_as(
  1559. "@some_other_guy:red", extra_content=extra_content
  1560. )
  1561. self.helper.join(room=room_id, user=self.user_id)
  1562. # When I send a state event
  1563. path = "/rooms/{room_id}/state/custom.event/my_state_key".format(
  1564. room_id=urlparse.quote(room_id),
  1565. )
  1566. channel = self.make_request("PUT", path, "{}")
  1567. # Then I am not allowed
  1568. self.assertEqual(HTTPStatus.FORBIDDEN, channel.code, msg=channel.result["body"])
  1569. @unittest.override_config(
  1570. {
  1571. "default_power_level_content_override": {
  1572. "public_chat": {"events": {"custom.event": 0}},
  1573. }
  1574. },
  1575. )
  1576. def test_specific_room_override_defeats_config_override(self) -> None:
  1577. # Given the server has config allowing normal users to post my event type,
  1578. # and I am a normal member of a room,
  1579. # but the room was created with special permissions for this event type
  1580. extra_content = {
  1581. "power_level_content_override": {"events": {"custom.event": 1}},
  1582. }
  1583. room_id = self.helper.create_room_as(
  1584. "@some_other_guy:red", extra_content=extra_content
  1585. )
  1586. self.helper.join(room=room_id, user=self.user_id)
  1587. # When I send a state event
  1588. path = "/rooms/{room_id}/state/custom.event/my_state_key".format(
  1589. room_id=urlparse.quote(room_id),
  1590. )
  1591. channel = self.make_request("PUT", path, "{}")
  1592. # Then I am not allowed
  1593. self.assertEqual(HTTPStatus.FORBIDDEN, channel.code, msg=channel.result["body"])
  1594. self.assertEqual(
  1595. "You don't have permission to post that to the room. "
  1596. + "user_level (0) < send_level (1)",
  1597. channel.json_body["error"],
  1598. )
  1599. @unittest.override_config(
  1600. {
  1601. "default_power_level_content_override": {
  1602. "public_chat": {"events": {"custom.event": 0}},
  1603. "private_chat": None,
  1604. "trusted_private_chat": None,
  1605. }
  1606. },
  1607. )
  1608. def test_config_override_applies_only_to_specific_preset(self) -> None:
  1609. # Given the server has config for public_chats,
  1610. # and I am a normal member of a private_chat room
  1611. room_id = self.helper.create_room_as("@some_other_guy:red", is_public=False)
  1612. self.helper.invite(room=room_id, src="@some_other_guy:red", targ=self.user_id)
  1613. self.helper.join(room=room_id, user=self.user_id)
  1614. # When I send a state event
  1615. path = "/rooms/{room_id}/state/custom.event/my_state_key".format(
  1616. room_id=urlparse.quote(room_id),
  1617. )
  1618. channel = self.make_request("PUT", path, "{}")
  1619. # Then I am not allowed because the public_chat config does not
  1620. # affect this room, because this room is a private_chat
  1621. self.assertEqual(HTTPStatus.FORBIDDEN, channel.code, msg=channel.result["body"])
  1622. self.assertEqual(
  1623. "You don't have permission to post that to the room. "
  1624. + "user_level (0) < send_level (50)",
  1625. channel.json_body["error"],
  1626. )
  1627. class RoomInitialSyncTestCase(RoomBase):
  1628. """Tests /rooms/$room_id/initialSync."""
  1629. user_id = "@sid1:red"
  1630. def prepare(self, reactor: MemoryReactor, clock: Clock, hs: HomeServer) -> None:
  1631. # create the room
  1632. self.room_id = self.helper.create_room_as(self.user_id)
  1633. def test_initial_sync(self) -> None:
  1634. channel = self.make_request("GET", "/rooms/%s/initialSync" % self.room_id)
  1635. self.assertEqual(HTTPStatus.OK, channel.code)
  1636. self.assertEqual(self.room_id, channel.json_body["room_id"])
  1637. self.assertEqual("join", channel.json_body["membership"])
  1638. # Room state is easier to assert on if we unpack it into a dict
  1639. state: JsonDict = {}
  1640. for event in channel.json_body["state"]:
  1641. if "state_key" not in event:
  1642. continue
  1643. t = event["type"]
  1644. if t not in state:
  1645. state[t] = []
  1646. state[t].append(event)
  1647. self.assertTrue("m.room.create" in state)
  1648. self.assertTrue("messages" in channel.json_body)
  1649. self.assertTrue("chunk" in channel.json_body["messages"])
  1650. self.assertTrue("end" in channel.json_body["messages"])
  1651. self.assertTrue("presence" in channel.json_body)
  1652. presence_by_user = {
  1653. e["content"]["user_id"]: e for e in channel.json_body["presence"]
  1654. }
  1655. self.assertTrue(self.user_id in presence_by_user)
  1656. self.assertEqual(EduTypes.PRESENCE, presence_by_user[self.user_id]["type"])
  1657. class RoomMessageListTestCase(RoomBase):
  1658. """Tests /rooms/$room_id/messages REST events."""
  1659. user_id = "@sid1:red"
  1660. def prepare(self, reactor: MemoryReactor, clock: Clock, hs: HomeServer) -> None:
  1661. self.room_id = self.helper.create_room_as(self.user_id)
  1662. def test_topo_token_is_accepted(self) -> None:
  1663. token = "t1-0_0_0_0_0_0_0_0_0_0"
  1664. channel = self.make_request(
  1665. "GET", "/rooms/%s/messages?access_token=x&from=%s" % (self.room_id, token)
  1666. )
  1667. self.assertEqual(HTTPStatus.OK, channel.code)
  1668. self.assertTrue("start" in channel.json_body)
  1669. self.assertEqual(token, channel.json_body["start"])
  1670. self.assertTrue("chunk" in channel.json_body)
  1671. self.assertTrue("end" in channel.json_body)
  1672. def test_stream_token_is_accepted_for_fwd_pagianation(self) -> None:
  1673. token = "s0_0_0_0_0_0_0_0_0_0"
  1674. channel = self.make_request(
  1675. "GET", "/rooms/%s/messages?access_token=x&from=%s" % (self.room_id, token)
  1676. )
  1677. self.assertEqual(HTTPStatus.OK, channel.code)
  1678. self.assertTrue("start" in channel.json_body)
  1679. self.assertEqual(token, channel.json_body["start"])
  1680. self.assertTrue("chunk" in channel.json_body)
  1681. self.assertTrue("end" in channel.json_body)
  1682. def test_room_messages_purge(self) -> None:
  1683. store = self.hs.get_datastores().main
  1684. pagination_handler = self.hs.get_pagination_handler()
  1685. # Send a first message in the room, which will be removed by the purge.
  1686. first_event_id = self.helper.send(self.room_id, "message 1")["event_id"]
  1687. first_token = self.get_success(
  1688. store.get_topological_token_for_event(first_event_id)
  1689. )
  1690. first_token_str = self.get_success(first_token.to_string(store))
  1691. # Send a second message in the room, which won't be removed, and which we'll
  1692. # use as the marker to purge events before.
  1693. second_event_id = self.helper.send(self.room_id, "message 2")["event_id"]
  1694. second_token = self.get_success(
  1695. store.get_topological_token_for_event(second_event_id)
  1696. )
  1697. second_token_str = self.get_success(second_token.to_string(store))
  1698. # Send a third event in the room to ensure we don't fall under any edge case
  1699. # due to our marker being the latest forward extremity in the room.
  1700. self.helper.send(self.room_id, "message 3")
  1701. # Check that we get the first and second message when querying /messages.
  1702. channel = self.make_request(
  1703. "GET",
  1704. "/rooms/%s/messages?access_token=x&from=%s&dir=b&filter=%s"
  1705. % (
  1706. self.room_id,
  1707. second_token_str,
  1708. json.dumps({"types": [EventTypes.Message]}),
  1709. ),
  1710. )
  1711. self.assertEqual(channel.code, HTTPStatus.OK, channel.json_body)
  1712. chunk = channel.json_body["chunk"]
  1713. self.assertEqual(len(chunk), 2, [event["content"] for event in chunk])
  1714. # Purge every event before the second event.
  1715. purge_id = random_string(16)
  1716. pagination_handler._purges_by_id[purge_id] = PurgeStatus()
  1717. self.get_success(
  1718. pagination_handler._purge_history(
  1719. purge_id=purge_id,
  1720. room_id=self.room_id,
  1721. token=second_token_str,
  1722. delete_local_events=True,
  1723. )
  1724. )
  1725. # Check that we only get the second message through /message now that the first
  1726. # has been purged.
  1727. channel = self.make_request(
  1728. "GET",
  1729. "/rooms/%s/messages?access_token=x&from=%s&dir=b&filter=%s"
  1730. % (
  1731. self.room_id,
  1732. second_token_str,
  1733. json.dumps({"types": [EventTypes.Message]}),
  1734. ),
  1735. )
  1736. self.assertEqual(channel.code, HTTPStatus.OK, channel.json_body)
  1737. chunk = channel.json_body["chunk"]
  1738. self.assertEqual(len(chunk), 1, [event["content"] for event in chunk])
  1739. # Check that we get no event, but also no error, when querying /messages with
  1740. # the token that was pointing at the first event, because we don't have it
  1741. # anymore.
  1742. channel = self.make_request(
  1743. "GET",
  1744. "/rooms/%s/messages?access_token=x&from=%s&dir=b&filter=%s"
  1745. % (
  1746. self.room_id,
  1747. first_token_str,
  1748. json.dumps({"types": [EventTypes.Message]}),
  1749. ),
  1750. )
  1751. self.assertEqual(channel.code, HTTPStatus.OK, channel.json_body)
  1752. chunk = channel.json_body["chunk"]
  1753. self.assertEqual(len(chunk), 0, [event["content"] for event in chunk])
  1754. class RoomSearchTestCase(unittest.HomeserverTestCase):
  1755. servlets = [
  1756. synapse.rest.admin.register_servlets_for_client_rest_resource,
  1757. room.register_servlets,
  1758. login.register_servlets,
  1759. ]
  1760. user_id = True
  1761. hijack_auth = False
  1762. def prepare(self, reactor: MemoryReactor, clock: Clock, hs: HomeServer) -> None:
  1763. # Register the user who does the searching
  1764. self.user_id2 = self.register_user("user", "pass")
  1765. self.access_token = self.login("user", "pass")
  1766. # Register the user who sends the message
  1767. self.other_user_id = self.register_user("otheruser", "pass")
  1768. self.other_access_token = self.login("otheruser", "pass")
  1769. # Create a room
  1770. self.room = self.helper.create_room_as(self.user_id2, tok=self.access_token)
  1771. # Invite the other person
  1772. self.helper.invite(
  1773. room=self.room,
  1774. src=self.user_id2,
  1775. tok=self.access_token,
  1776. targ=self.other_user_id,
  1777. )
  1778. # The other user joins
  1779. self.helper.join(
  1780. room=self.room, user=self.other_user_id, tok=self.other_access_token
  1781. )
  1782. def test_finds_message(self) -> None:
  1783. """
  1784. The search functionality will search for content in messages if asked to
  1785. do so.
  1786. """
  1787. # The other user sends some messages
  1788. self.helper.send(self.room, body="Hi!", tok=self.other_access_token)
  1789. self.helper.send(self.room, body="There!", tok=self.other_access_token)
  1790. channel = self.make_request(
  1791. "POST",
  1792. "/search?access_token=%s" % (self.access_token,),
  1793. {
  1794. "search_categories": {
  1795. "room_events": {"keys": ["content.body"], "search_term": "Hi"}
  1796. }
  1797. },
  1798. )
  1799. # Check we get the results we expect -- one search result, of the sent
  1800. # messages
  1801. self.assertEqual(channel.code, 200)
  1802. results = channel.json_body["search_categories"]["room_events"]
  1803. self.assertEqual(results["count"], 1)
  1804. self.assertEqual(results["results"][0]["result"]["content"]["body"], "Hi!")
  1805. # No context was requested, so we should get none.
  1806. self.assertEqual(results["results"][0]["context"], {})
  1807. def test_include_context(self) -> None:
  1808. """
  1809. When event_context includes include_profile, profile information will be
  1810. included in the search response.
  1811. """
  1812. # The other user sends some messages
  1813. self.helper.send(self.room, body="Hi!", tok=self.other_access_token)
  1814. self.helper.send(self.room, body="There!", tok=self.other_access_token)
  1815. channel = self.make_request(
  1816. "POST",
  1817. "/search?access_token=%s" % (self.access_token,),
  1818. {
  1819. "search_categories": {
  1820. "room_events": {
  1821. "keys": ["content.body"],
  1822. "search_term": "Hi",
  1823. "event_context": {"include_profile": True},
  1824. }
  1825. }
  1826. },
  1827. )
  1828. # Check we get the results we expect -- one search result, of the sent
  1829. # messages
  1830. self.assertEqual(channel.code, 200)
  1831. results = channel.json_body["search_categories"]["room_events"]
  1832. self.assertEqual(results["count"], 1)
  1833. self.assertEqual(results["results"][0]["result"]["content"]["body"], "Hi!")
  1834. # We should get context info, like the two users, and the display names.
  1835. context = results["results"][0]["context"]
  1836. self.assertEqual(len(context["profile_info"].keys()), 2)
  1837. self.assertEqual(
  1838. context["profile_info"][self.other_user_id]["displayname"], "otheruser"
  1839. )
  1840. class PublicRoomsRestrictedTestCase(unittest.HomeserverTestCase):
  1841. servlets = [
  1842. synapse.rest.admin.register_servlets_for_client_rest_resource,
  1843. room.register_servlets,
  1844. login.register_servlets,
  1845. ]
  1846. def make_homeserver(self, reactor: MemoryReactor, clock: Clock) -> HomeServer:
  1847. self.url = b"/_matrix/client/r0/publicRooms"
  1848. config = self.default_config()
  1849. config["allow_public_rooms_without_auth"] = False
  1850. self.hs = self.setup_test_homeserver(config=config)
  1851. return self.hs
  1852. def test_restricted_no_auth(self) -> None:
  1853. channel = self.make_request("GET", self.url)
  1854. self.assertEqual(channel.code, HTTPStatus.UNAUTHORIZED, channel.result)
  1855. def test_restricted_auth(self) -> None:
  1856. self.register_user("user", "pass")
  1857. tok = self.login("user", "pass")
  1858. channel = self.make_request("GET", self.url, access_token=tok)
  1859. self.assertEqual(channel.code, HTTPStatus.OK, channel.result)
  1860. class PublicRoomsRoomTypeFilterTestCase(unittest.HomeserverTestCase):
  1861. servlets = [
  1862. synapse.rest.admin.register_servlets_for_client_rest_resource,
  1863. room.register_servlets,
  1864. login.register_servlets,
  1865. ]
  1866. def make_homeserver(self, reactor: MemoryReactor, clock: Clock) -> HomeServer:
  1867. config = self.default_config()
  1868. config["allow_public_rooms_without_auth"] = True
  1869. self.hs = self.setup_test_homeserver(config=config)
  1870. self.url = b"/_matrix/client/r0/publicRooms"
  1871. return self.hs
  1872. def prepare(self, reactor: MemoryReactor, clock: Clock, hs: HomeServer) -> None:
  1873. user = self.register_user("alice", "pass")
  1874. self.token = self.login(user, "pass")
  1875. # Create a room
  1876. self.helper.create_room_as(
  1877. user,
  1878. is_public=True,
  1879. extra_content={"visibility": "public"},
  1880. tok=self.token,
  1881. )
  1882. # Create a space
  1883. self.helper.create_room_as(
  1884. user,
  1885. is_public=True,
  1886. extra_content={
  1887. "visibility": "public",
  1888. "creation_content": {EventContentFields.ROOM_TYPE: RoomTypes.SPACE},
  1889. },
  1890. tok=self.token,
  1891. )
  1892. def make_public_rooms_request(
  1893. self,
  1894. room_types: Optional[List[Union[str, None]]],
  1895. instance_id: Optional[str] = None,
  1896. ) -> Tuple[List[Dict[str, Any]], int]:
  1897. body: JsonDict = {"filter": {PublicRoomsFilterFields.ROOM_TYPES: room_types}}
  1898. if instance_id:
  1899. body["third_party_instance_id"] = "test|test"
  1900. channel = self.make_request("POST", self.url, body, self.token)
  1901. self.assertEqual(channel.code, 200)
  1902. chunk = channel.json_body["chunk"]
  1903. count = channel.json_body["total_room_count_estimate"]
  1904. self.assertEqual(len(chunk), count)
  1905. return chunk, count
  1906. def test_returns_both_rooms_and_spaces_if_no_filter(self) -> None:
  1907. chunk, count = self.make_public_rooms_request(None)
  1908. self.assertEqual(count, 2)
  1909. # Also check if there's no filter property at all in the body.
  1910. channel = self.make_request("POST", self.url, {}, self.token)
  1911. self.assertEqual(channel.code, 200)
  1912. self.assertEqual(len(channel.json_body["chunk"]), 2)
  1913. self.assertEqual(channel.json_body["total_room_count_estimate"], 2)
  1914. chunk, count = self.make_public_rooms_request(None, "test|test")
  1915. self.assertEqual(count, 0)
  1916. def test_returns_only_rooms_based_on_filter(self) -> None:
  1917. chunk, count = self.make_public_rooms_request([None])
  1918. self.assertEqual(count, 1)
  1919. self.assertEqual(chunk[0].get("room_type", None), None)
  1920. chunk, count = self.make_public_rooms_request([None], "test|test")
  1921. self.assertEqual(count, 0)
  1922. def test_returns_only_space_based_on_filter(self) -> None:
  1923. chunk, count = self.make_public_rooms_request(["m.space"])
  1924. self.assertEqual(count, 1)
  1925. self.assertEqual(chunk[0].get("room_type", None), "m.space")
  1926. chunk, count = self.make_public_rooms_request(["m.space"], "test|test")
  1927. self.assertEqual(count, 0)
  1928. def test_returns_both_rooms_and_space_based_on_filter(self) -> None:
  1929. chunk, count = self.make_public_rooms_request(["m.space", None])
  1930. self.assertEqual(count, 2)
  1931. chunk, count = self.make_public_rooms_request(["m.space", None], "test|test")
  1932. self.assertEqual(count, 0)
  1933. def test_returns_both_rooms_and_spaces_if_array_is_empty(self) -> None:
  1934. chunk, count = self.make_public_rooms_request([])
  1935. self.assertEqual(count, 2)
  1936. chunk, count = self.make_public_rooms_request([], "test|test")
  1937. self.assertEqual(count, 0)
  1938. class PublicRoomsTestRemoteSearchFallbackTestCase(unittest.HomeserverTestCase):
  1939. """Test that we correctly fallback to local filtering if a remote server
  1940. doesn't support search.
  1941. """
  1942. servlets = [
  1943. synapse.rest.admin.register_servlets_for_client_rest_resource,
  1944. room.register_servlets,
  1945. login.register_servlets,
  1946. ]
  1947. def make_homeserver(self, reactor: MemoryReactor, clock: Clock) -> HomeServer:
  1948. return self.setup_test_homeserver(federation_client=Mock())
  1949. def prepare(self, reactor: MemoryReactor, clock: Clock, hs: HomeServer) -> None:
  1950. self.register_user("user", "pass")
  1951. self.token = self.login("user", "pass")
  1952. self.federation_client = hs.get_federation_client()
  1953. def test_simple(self) -> None:
  1954. "Simple test for searching rooms over federation"
  1955. self.federation_client.get_public_rooms.return_value = make_awaitable({}) # type: ignore[attr-defined]
  1956. search_filter = {PublicRoomsFilterFields.GENERIC_SEARCH_TERM: "foobar"}
  1957. channel = self.make_request(
  1958. "POST",
  1959. b"/_matrix/client/r0/publicRooms?server=testserv",
  1960. content={"filter": search_filter},
  1961. access_token=self.token,
  1962. )
  1963. self.assertEqual(channel.code, HTTPStatus.OK, channel.result)
  1964. self.federation_client.get_public_rooms.assert_called_once_with( # type: ignore[attr-defined]
  1965. "testserv",
  1966. limit=100,
  1967. since_token=None,
  1968. search_filter=search_filter,
  1969. include_all_networks=False,
  1970. third_party_instance_id=None,
  1971. )
  1972. def test_fallback(self) -> None:
  1973. "Test that searching public rooms over federation falls back if it gets a 404"
  1974. # The `get_public_rooms` should be called again if the first call fails
  1975. # with a 404, when using search filters.
  1976. self.federation_client.get_public_rooms.side_effect = ( # type: ignore[attr-defined]
  1977. HttpResponseException(HTTPStatus.NOT_FOUND, "Not Found", b""),
  1978. make_awaitable({}),
  1979. )
  1980. search_filter = {PublicRoomsFilterFields.GENERIC_SEARCH_TERM: "foobar"}
  1981. channel = self.make_request(
  1982. "POST",
  1983. b"/_matrix/client/r0/publicRooms?server=testserv",
  1984. content={"filter": search_filter},
  1985. access_token=self.token,
  1986. )
  1987. self.assertEqual(channel.code, HTTPStatus.OK, channel.result)
  1988. self.federation_client.get_public_rooms.assert_has_calls( # type: ignore[attr-defined]
  1989. [
  1990. call(
  1991. "testserv",
  1992. limit=100,
  1993. since_token=None,
  1994. search_filter=search_filter,
  1995. include_all_networks=False,
  1996. third_party_instance_id=None,
  1997. ),
  1998. call(
  1999. "testserv",
  2000. limit=None,
  2001. since_token=None,
  2002. search_filter=None,
  2003. include_all_networks=False,
  2004. third_party_instance_id=None,
  2005. ),
  2006. ]
  2007. )
  2008. class PerRoomProfilesForbiddenTestCase(unittest.HomeserverTestCase):
  2009. servlets = [
  2010. synapse.rest.admin.register_servlets_for_client_rest_resource,
  2011. room.register_servlets,
  2012. login.register_servlets,
  2013. profile.register_servlets,
  2014. ]
  2015. def make_homeserver(self, reactor: MemoryReactor, clock: Clock) -> HomeServer:
  2016. config = self.default_config()
  2017. config["allow_per_room_profiles"] = False
  2018. self.hs = self.setup_test_homeserver(config=config)
  2019. return self.hs
  2020. def prepare(self, reactor: MemoryReactor, clock: Clock, hs: HomeServer) -> None:
  2021. self.user_id = self.register_user("test", "test")
  2022. self.tok = self.login("test", "test")
  2023. # Set a profile for the test user
  2024. self.displayname = "test user"
  2025. request_data = {"displayname": self.displayname}
  2026. channel = self.make_request(
  2027. "PUT",
  2028. "/_matrix/client/r0/profile/%s/displayname" % (self.user_id,),
  2029. request_data,
  2030. access_token=self.tok,
  2031. )
  2032. self.assertEqual(channel.code, HTTPStatus.OK, channel.result)
  2033. self.room_id = self.helper.create_room_as(self.user_id, tok=self.tok)
  2034. def test_per_room_profile_forbidden(self) -> None:
  2035. request_data = {"membership": "join", "displayname": "other test user"}
  2036. channel = self.make_request(
  2037. "PUT",
  2038. "/_matrix/client/r0/rooms/%s/state/m.room.member/%s"
  2039. % (self.room_id, self.user_id),
  2040. request_data,
  2041. access_token=self.tok,
  2042. )
  2043. self.assertEqual(channel.code, HTTPStatus.OK, channel.result)
  2044. event_id = channel.json_body["event_id"]
  2045. channel = self.make_request(
  2046. "GET",
  2047. "/_matrix/client/r0/rooms/%s/event/%s" % (self.room_id, event_id),
  2048. access_token=self.tok,
  2049. )
  2050. self.assertEqual(channel.code, HTTPStatus.OK, channel.result)
  2051. res_displayname = channel.json_body["content"]["displayname"]
  2052. self.assertEqual(res_displayname, self.displayname, channel.result)
  2053. class RoomMembershipReasonTestCase(unittest.HomeserverTestCase):
  2054. """Tests that clients can add a "reason" field to membership events and
  2055. that they get correctly added to the generated events and propagated.
  2056. """
  2057. servlets = [
  2058. synapse.rest.admin.register_servlets_for_client_rest_resource,
  2059. room.register_servlets,
  2060. login.register_servlets,
  2061. ]
  2062. def prepare(self, reactor: MemoryReactor, clock: Clock, hs: HomeServer) -> None:
  2063. self.creator = self.register_user("creator", "test")
  2064. self.creator_tok = self.login("creator", "test")
  2065. self.second_user_id = self.register_user("second", "test")
  2066. self.second_tok = self.login("second", "test")
  2067. self.room_id = self.helper.create_room_as(self.creator, tok=self.creator_tok)
  2068. def test_join_reason(self) -> None:
  2069. reason = "hello"
  2070. channel = self.make_request(
  2071. "POST",
  2072. f"/_matrix/client/r0/rooms/{self.room_id}/join",
  2073. content={"reason": reason},
  2074. access_token=self.second_tok,
  2075. )
  2076. self.assertEqual(channel.code, HTTPStatus.OK, channel.result)
  2077. self._check_for_reason(reason)
  2078. def test_leave_reason(self) -> None:
  2079. self.helper.join(self.room_id, user=self.second_user_id, tok=self.second_tok)
  2080. reason = "hello"
  2081. channel = self.make_request(
  2082. "POST",
  2083. f"/_matrix/client/r0/rooms/{self.room_id}/leave",
  2084. content={"reason": reason},
  2085. access_token=self.second_tok,
  2086. )
  2087. self.assertEqual(channel.code, HTTPStatus.OK, channel.result)
  2088. self._check_for_reason(reason)
  2089. def test_kick_reason(self) -> None:
  2090. self.helper.join(self.room_id, user=self.second_user_id, tok=self.second_tok)
  2091. reason = "hello"
  2092. channel = self.make_request(
  2093. "POST",
  2094. f"/_matrix/client/r0/rooms/{self.room_id}/kick",
  2095. content={"reason": reason, "user_id": self.second_user_id},
  2096. access_token=self.second_tok,
  2097. )
  2098. self.assertEqual(channel.code, HTTPStatus.OK, channel.result)
  2099. self._check_for_reason(reason)
  2100. def test_ban_reason(self) -> None:
  2101. self.helper.join(self.room_id, user=self.second_user_id, tok=self.second_tok)
  2102. reason = "hello"
  2103. channel = self.make_request(
  2104. "POST",
  2105. f"/_matrix/client/r0/rooms/{self.room_id}/ban",
  2106. content={"reason": reason, "user_id": self.second_user_id},
  2107. access_token=self.creator_tok,
  2108. )
  2109. self.assertEqual(channel.code, HTTPStatus.OK, channel.result)
  2110. self._check_for_reason(reason)
  2111. def test_unban_reason(self) -> None:
  2112. reason = "hello"
  2113. channel = self.make_request(
  2114. "POST",
  2115. f"/_matrix/client/r0/rooms/{self.room_id}/unban",
  2116. content={"reason": reason, "user_id": self.second_user_id},
  2117. access_token=self.creator_tok,
  2118. )
  2119. self.assertEqual(channel.code, HTTPStatus.OK, channel.result)
  2120. self._check_for_reason(reason)
  2121. def test_invite_reason(self) -> None:
  2122. reason = "hello"
  2123. channel = self.make_request(
  2124. "POST",
  2125. f"/_matrix/client/r0/rooms/{self.room_id}/invite",
  2126. content={"reason": reason, "user_id": self.second_user_id},
  2127. access_token=self.creator_tok,
  2128. )
  2129. self.assertEqual(channel.code, HTTPStatus.OK, channel.result)
  2130. self._check_for_reason(reason)
  2131. def test_reject_invite_reason(self) -> None:
  2132. self.helper.invite(
  2133. self.room_id,
  2134. src=self.creator,
  2135. targ=self.second_user_id,
  2136. tok=self.creator_tok,
  2137. )
  2138. reason = "hello"
  2139. channel = self.make_request(
  2140. "POST",
  2141. f"/_matrix/client/r0/rooms/{self.room_id}/leave",
  2142. content={"reason": reason},
  2143. access_token=self.second_tok,
  2144. )
  2145. self.assertEqual(channel.code, HTTPStatus.OK, channel.result)
  2146. self._check_for_reason(reason)
  2147. def _check_for_reason(self, reason: str) -> None:
  2148. channel = self.make_request(
  2149. "GET",
  2150. "/_matrix/client/r0/rooms/{}/state/m.room.member/{}".format(
  2151. self.room_id, self.second_user_id
  2152. ),
  2153. access_token=self.creator_tok,
  2154. )
  2155. self.assertEqual(channel.code, HTTPStatus.OK, channel.result)
  2156. event_content = channel.json_body
  2157. self.assertEqual(event_content.get("reason"), reason, channel.result)
  2158. class LabelsTestCase(unittest.HomeserverTestCase):
  2159. servlets = [
  2160. synapse.rest.admin.register_servlets_for_client_rest_resource,
  2161. room.register_servlets,
  2162. login.register_servlets,
  2163. profile.register_servlets,
  2164. ]
  2165. # Filter that should only catch messages with the label "#fun".
  2166. FILTER_LABELS = {
  2167. "types": [EventTypes.Message],
  2168. "org.matrix.labels": ["#fun"],
  2169. }
  2170. # Filter that should only catch messages without the label "#fun".
  2171. FILTER_NOT_LABELS = {
  2172. "types": [EventTypes.Message],
  2173. "org.matrix.not_labels": ["#fun"],
  2174. }
  2175. # Filter that should only catch messages with the label "#work" but without the label
  2176. # "#notfun".
  2177. FILTER_LABELS_NOT_LABELS = {
  2178. "types": [EventTypes.Message],
  2179. "org.matrix.labels": ["#work"],
  2180. "org.matrix.not_labels": ["#notfun"],
  2181. }
  2182. def prepare(self, reactor: MemoryReactor, clock: Clock, hs: HomeServer) -> None:
  2183. self.user_id = self.register_user("test", "test")
  2184. self.tok = self.login("test", "test")
  2185. self.room_id = self.helper.create_room_as(self.user_id, tok=self.tok)
  2186. def test_context_filter_labels(self) -> None:
  2187. """Test that we can filter by a label on a /context request."""
  2188. event_id = self._send_labelled_messages_in_room()
  2189. channel = self.make_request(
  2190. "GET",
  2191. "/rooms/%s/context/%s?filter=%s"
  2192. % (self.room_id, event_id, json.dumps(self.FILTER_LABELS)),
  2193. access_token=self.tok,
  2194. )
  2195. self.assertEqual(channel.code, HTTPStatus.OK, channel.result)
  2196. events_before = channel.json_body["events_before"]
  2197. self.assertEqual(
  2198. len(events_before), 1, [event["content"] for event in events_before]
  2199. )
  2200. self.assertEqual(
  2201. events_before[0]["content"]["body"], "with right label", events_before[0]
  2202. )
  2203. events_after = channel.json_body["events_before"]
  2204. self.assertEqual(
  2205. len(events_after), 1, [event["content"] for event in events_after]
  2206. )
  2207. self.assertEqual(
  2208. events_after[0]["content"]["body"], "with right label", events_after[0]
  2209. )
  2210. def test_context_filter_not_labels(self) -> None:
  2211. """Test that we can filter by the absence of a label on a /context request."""
  2212. event_id = self._send_labelled_messages_in_room()
  2213. channel = self.make_request(
  2214. "GET",
  2215. "/rooms/%s/context/%s?filter=%s"
  2216. % (self.room_id, event_id, json.dumps(self.FILTER_NOT_LABELS)),
  2217. access_token=self.tok,
  2218. )
  2219. self.assertEqual(channel.code, HTTPStatus.OK, channel.result)
  2220. events_before = channel.json_body["events_before"]
  2221. self.assertEqual(
  2222. len(events_before), 1, [event["content"] for event in events_before]
  2223. )
  2224. self.assertEqual(
  2225. events_before[0]["content"]["body"], "without label", events_before[0]
  2226. )
  2227. events_after = channel.json_body["events_after"]
  2228. self.assertEqual(
  2229. len(events_after), 2, [event["content"] for event in events_after]
  2230. )
  2231. self.assertEqual(
  2232. events_after[0]["content"]["body"], "with wrong label", events_after[0]
  2233. )
  2234. self.assertEqual(
  2235. events_after[1]["content"]["body"], "with two wrong labels", events_after[1]
  2236. )
  2237. def test_context_filter_labels_not_labels(self) -> None:
  2238. """Test that we can filter by both a label and the absence of another label on a
  2239. /context request.
  2240. """
  2241. event_id = self._send_labelled_messages_in_room()
  2242. channel = self.make_request(
  2243. "GET",
  2244. "/rooms/%s/context/%s?filter=%s"
  2245. % (self.room_id, event_id, json.dumps(self.FILTER_LABELS_NOT_LABELS)),
  2246. access_token=self.tok,
  2247. )
  2248. self.assertEqual(channel.code, HTTPStatus.OK, channel.result)
  2249. events_before = channel.json_body["events_before"]
  2250. self.assertEqual(
  2251. len(events_before), 0, [event["content"] for event in events_before]
  2252. )
  2253. events_after = channel.json_body["events_after"]
  2254. self.assertEqual(
  2255. len(events_after), 1, [event["content"] for event in events_after]
  2256. )
  2257. self.assertEqual(
  2258. events_after[0]["content"]["body"], "with wrong label", events_after[0]
  2259. )
  2260. def test_messages_filter_labels(self) -> None:
  2261. """Test that we can filter by a label on a /messages request."""
  2262. self._send_labelled_messages_in_room()
  2263. token = "s0_0_0_0_0_0_0_0_0_0"
  2264. channel = self.make_request(
  2265. "GET",
  2266. "/rooms/%s/messages?access_token=%s&from=%s&filter=%s"
  2267. % (self.room_id, self.tok, token, json.dumps(self.FILTER_LABELS)),
  2268. )
  2269. events = channel.json_body["chunk"]
  2270. self.assertEqual(len(events), 2, [event["content"] for event in events])
  2271. self.assertEqual(events[0]["content"]["body"], "with right label", events[0])
  2272. self.assertEqual(events[1]["content"]["body"], "with right label", events[1])
  2273. def test_messages_filter_not_labels(self) -> None:
  2274. """Test that we can filter by the absence of a label on a /messages request."""
  2275. self._send_labelled_messages_in_room()
  2276. token = "s0_0_0_0_0_0_0_0_0_0"
  2277. channel = self.make_request(
  2278. "GET",
  2279. "/rooms/%s/messages?access_token=%s&from=%s&filter=%s"
  2280. % (self.room_id, self.tok, token, json.dumps(self.FILTER_NOT_LABELS)),
  2281. )
  2282. events = channel.json_body["chunk"]
  2283. self.assertEqual(len(events), 4, [event["content"] for event in events])
  2284. self.assertEqual(events[0]["content"]["body"], "without label", events[0])
  2285. self.assertEqual(events[1]["content"]["body"], "without label", events[1])
  2286. self.assertEqual(events[2]["content"]["body"], "with wrong label", events[2])
  2287. self.assertEqual(
  2288. events[3]["content"]["body"], "with two wrong labels", events[3]
  2289. )
  2290. def test_messages_filter_labels_not_labels(self) -> None:
  2291. """Test that we can filter by both a label and the absence of another label on a
  2292. /messages request.
  2293. """
  2294. self._send_labelled_messages_in_room()
  2295. token = "s0_0_0_0_0_0_0_0_0_0"
  2296. channel = self.make_request(
  2297. "GET",
  2298. "/rooms/%s/messages?access_token=%s&from=%s&filter=%s"
  2299. % (
  2300. self.room_id,
  2301. self.tok,
  2302. token,
  2303. json.dumps(self.FILTER_LABELS_NOT_LABELS),
  2304. ),
  2305. )
  2306. events = channel.json_body["chunk"]
  2307. self.assertEqual(len(events), 1, [event["content"] for event in events])
  2308. self.assertEqual(events[0]["content"]["body"], "with wrong label", events[0])
  2309. def test_search_filter_labels(self) -> None:
  2310. """Test that we can filter by a label on a /search request."""
  2311. request_data = {
  2312. "search_categories": {
  2313. "room_events": {
  2314. "search_term": "label",
  2315. "filter": self.FILTER_LABELS,
  2316. }
  2317. }
  2318. }
  2319. self._send_labelled_messages_in_room()
  2320. channel = self.make_request(
  2321. "POST", "/search?access_token=%s" % self.tok, request_data
  2322. )
  2323. results = channel.json_body["search_categories"]["room_events"]["results"]
  2324. self.assertEqual(
  2325. len(results),
  2326. 2,
  2327. [result["result"]["content"] for result in results],
  2328. )
  2329. self.assertEqual(
  2330. results[0]["result"]["content"]["body"],
  2331. "with right label",
  2332. results[0]["result"]["content"]["body"],
  2333. )
  2334. self.assertEqual(
  2335. results[1]["result"]["content"]["body"],
  2336. "with right label",
  2337. results[1]["result"]["content"]["body"],
  2338. )
  2339. def test_search_filter_not_labels(self) -> None:
  2340. """Test that we can filter by the absence of a label on a /search request."""
  2341. request_data = {
  2342. "search_categories": {
  2343. "room_events": {
  2344. "search_term": "label",
  2345. "filter": self.FILTER_NOT_LABELS,
  2346. }
  2347. }
  2348. }
  2349. self._send_labelled_messages_in_room()
  2350. channel = self.make_request(
  2351. "POST", "/search?access_token=%s" % self.tok, request_data
  2352. )
  2353. results = channel.json_body["search_categories"]["room_events"]["results"]
  2354. self.assertEqual(
  2355. len(results),
  2356. 4,
  2357. [result["result"]["content"] for result in results],
  2358. )
  2359. self.assertEqual(
  2360. results[0]["result"]["content"]["body"],
  2361. "without label",
  2362. results[0]["result"]["content"]["body"],
  2363. )
  2364. self.assertEqual(
  2365. results[1]["result"]["content"]["body"],
  2366. "without label",
  2367. results[1]["result"]["content"]["body"],
  2368. )
  2369. self.assertEqual(
  2370. results[2]["result"]["content"]["body"],
  2371. "with wrong label",
  2372. results[2]["result"]["content"]["body"],
  2373. )
  2374. self.assertEqual(
  2375. results[3]["result"]["content"]["body"],
  2376. "with two wrong labels",
  2377. results[3]["result"]["content"]["body"],
  2378. )
  2379. def test_search_filter_labels_not_labels(self) -> None:
  2380. """Test that we can filter by both a label and the absence of another label on a
  2381. /search request.
  2382. """
  2383. request_data = {
  2384. "search_categories": {
  2385. "room_events": {
  2386. "search_term": "label",
  2387. "filter": self.FILTER_LABELS_NOT_LABELS,
  2388. }
  2389. }
  2390. }
  2391. self._send_labelled_messages_in_room()
  2392. channel = self.make_request(
  2393. "POST", "/search?access_token=%s" % self.tok, request_data
  2394. )
  2395. results = channel.json_body["search_categories"]["room_events"]["results"]
  2396. self.assertEqual(
  2397. len(results),
  2398. 1,
  2399. [result["result"]["content"] for result in results],
  2400. )
  2401. self.assertEqual(
  2402. results[0]["result"]["content"]["body"],
  2403. "with wrong label",
  2404. results[0]["result"]["content"]["body"],
  2405. )
  2406. def _send_labelled_messages_in_room(self) -> str:
  2407. """Sends several messages to a room with different labels (or without any) to test
  2408. filtering by label.
  2409. Returns:
  2410. The ID of the event to use if we're testing filtering on /context.
  2411. """
  2412. self.helper.send_event(
  2413. room_id=self.room_id,
  2414. type=EventTypes.Message,
  2415. content={
  2416. "msgtype": "m.text",
  2417. "body": "with right label",
  2418. EventContentFields.LABELS: ["#fun"],
  2419. },
  2420. tok=self.tok,
  2421. )
  2422. self.helper.send_event(
  2423. room_id=self.room_id,
  2424. type=EventTypes.Message,
  2425. content={"msgtype": "m.text", "body": "without label"},
  2426. tok=self.tok,
  2427. )
  2428. res = self.helper.send_event(
  2429. room_id=self.room_id,
  2430. type=EventTypes.Message,
  2431. content={"msgtype": "m.text", "body": "without label"},
  2432. tok=self.tok,
  2433. )
  2434. # Return this event's ID when we test filtering in /context requests.
  2435. event_id = res["event_id"]
  2436. self.helper.send_event(
  2437. room_id=self.room_id,
  2438. type=EventTypes.Message,
  2439. content={
  2440. "msgtype": "m.text",
  2441. "body": "with wrong label",
  2442. EventContentFields.LABELS: ["#work"],
  2443. },
  2444. tok=self.tok,
  2445. )
  2446. self.helper.send_event(
  2447. room_id=self.room_id,
  2448. type=EventTypes.Message,
  2449. content={
  2450. "msgtype": "m.text",
  2451. "body": "with two wrong labels",
  2452. EventContentFields.LABELS: ["#work", "#notfun"],
  2453. },
  2454. tok=self.tok,
  2455. )
  2456. self.helper.send_event(
  2457. room_id=self.room_id,
  2458. type=EventTypes.Message,
  2459. content={
  2460. "msgtype": "m.text",
  2461. "body": "with right label",
  2462. EventContentFields.LABELS: ["#fun"],
  2463. },
  2464. tok=self.tok,
  2465. )
  2466. return event_id
  2467. class RelationsTestCase(PaginationTestCase):
  2468. def _filter_messages(self, filter: JsonDict) -> List[str]:
  2469. """Make a request to /messages with a filter, returns the chunk of events."""
  2470. from_token = self.get_success(
  2471. self.from_token.to_string(self.hs.get_datastores().main)
  2472. )
  2473. channel = self.make_request(
  2474. "GET",
  2475. f"/rooms/{self.room_id}/messages?filter={json.dumps(filter)}&dir=f&from={from_token}",
  2476. access_token=self.tok,
  2477. )
  2478. self.assertEqual(channel.code, HTTPStatus.OK, channel.result)
  2479. return [ev["event_id"] for ev in channel.json_body["chunk"]]
  2480. class ContextTestCase(unittest.HomeserverTestCase):
  2481. servlets = [
  2482. synapse.rest.admin.register_servlets_for_client_rest_resource,
  2483. room.register_servlets,
  2484. login.register_servlets,
  2485. account.register_servlets,
  2486. ]
  2487. def prepare(self, reactor: MemoryReactor, clock: Clock, hs: HomeServer) -> None:
  2488. self.user_id = self.register_user("user", "password")
  2489. self.tok = self.login("user", "password")
  2490. self.room_id = self.helper.create_room_as(
  2491. self.user_id, tok=self.tok, is_public=False
  2492. )
  2493. self.other_user_id = self.register_user("user2", "password")
  2494. self.other_tok = self.login("user2", "password")
  2495. self.helper.invite(self.room_id, self.user_id, self.other_user_id, tok=self.tok)
  2496. self.helper.join(self.room_id, self.other_user_id, tok=self.other_tok)
  2497. def test_erased_sender(self) -> None:
  2498. """Test that an erasure request results in the requester's events being hidden
  2499. from any new member of the room.
  2500. """
  2501. # Send a bunch of events in the room.
  2502. self.helper.send(self.room_id, "message 1", tok=self.tok)
  2503. self.helper.send(self.room_id, "message 2", tok=self.tok)
  2504. event_id = self.helper.send(self.room_id, "message 3", tok=self.tok)["event_id"]
  2505. self.helper.send(self.room_id, "message 4", tok=self.tok)
  2506. self.helper.send(self.room_id, "message 5", tok=self.tok)
  2507. # Check that we can still see the messages before the erasure request.
  2508. channel = self.make_request(
  2509. "GET",
  2510. '/rooms/%s/context/%s?filter={"types":["m.room.message"]}'
  2511. % (self.room_id, event_id),
  2512. access_token=self.tok,
  2513. )
  2514. self.assertEqual(channel.code, HTTPStatus.OK, channel.result)
  2515. events_before = channel.json_body["events_before"]
  2516. self.assertEqual(len(events_before), 2, events_before)
  2517. self.assertEqual(
  2518. events_before[0].get("content", {}).get("body"),
  2519. "message 2",
  2520. events_before[0],
  2521. )
  2522. self.assertEqual(
  2523. events_before[1].get("content", {}).get("body"),
  2524. "message 1",
  2525. events_before[1],
  2526. )
  2527. self.assertEqual(
  2528. channel.json_body["event"].get("content", {}).get("body"),
  2529. "message 3",
  2530. channel.json_body["event"],
  2531. )
  2532. events_after = channel.json_body["events_after"]
  2533. self.assertEqual(len(events_after), 2, events_after)
  2534. self.assertEqual(
  2535. events_after[0].get("content", {}).get("body"),
  2536. "message 4",
  2537. events_after[0],
  2538. )
  2539. self.assertEqual(
  2540. events_after[1].get("content", {}).get("body"),
  2541. "message 5",
  2542. events_after[1],
  2543. )
  2544. # Deactivate the first account and erase the user's data.
  2545. deactivate_account_handler = self.hs.get_deactivate_account_handler()
  2546. self.get_success(
  2547. deactivate_account_handler.deactivate_account(
  2548. self.user_id, True, create_requester(self.user_id)
  2549. )
  2550. )
  2551. # Invite another user in the room. This is needed because messages will be
  2552. # pruned only if the user wasn't a member of the room when the messages were
  2553. # sent.
  2554. invited_user_id = self.register_user("user3", "password")
  2555. invited_tok = self.login("user3", "password")
  2556. self.helper.invite(
  2557. self.room_id, self.other_user_id, invited_user_id, tok=self.other_tok
  2558. )
  2559. self.helper.join(self.room_id, invited_user_id, tok=invited_tok)
  2560. # Check that a user that joined the room after the erasure request can't see
  2561. # the messages anymore.
  2562. channel = self.make_request(
  2563. "GET",
  2564. '/rooms/%s/context/%s?filter={"types":["m.room.message"]}'
  2565. % (self.room_id, event_id),
  2566. access_token=invited_tok,
  2567. )
  2568. self.assertEqual(channel.code, HTTPStatus.OK, channel.result)
  2569. events_before = channel.json_body["events_before"]
  2570. self.assertEqual(len(events_before), 2, events_before)
  2571. self.assertDictEqual(events_before[0].get("content"), {}, events_before[0])
  2572. self.assertDictEqual(events_before[1].get("content"), {}, events_before[1])
  2573. self.assertDictEqual(
  2574. channel.json_body["event"].get("content"), {}, channel.json_body["event"]
  2575. )
  2576. events_after = channel.json_body["events_after"]
  2577. self.assertEqual(len(events_after), 2, events_after)
  2578. self.assertDictEqual(events_after[0].get("content"), {}, events_after[0])
  2579. self.assertEqual(events_after[1].get("content"), {}, events_after[1])
  2580. class RoomAliasListTestCase(unittest.HomeserverTestCase):
  2581. servlets = [
  2582. synapse.rest.admin.register_servlets_for_client_rest_resource,
  2583. directory.register_servlets,
  2584. login.register_servlets,
  2585. room.register_servlets,
  2586. ]
  2587. def prepare(self, reactor: MemoryReactor, clock: Clock, hs: HomeServer) -> None:
  2588. self.room_owner = self.register_user("room_owner", "test")
  2589. self.room_owner_tok = self.login("room_owner", "test")
  2590. self.room_id = self.helper.create_room_as(
  2591. self.room_owner, tok=self.room_owner_tok
  2592. )
  2593. def test_no_aliases(self) -> None:
  2594. res = self._get_aliases(self.room_owner_tok)
  2595. self.assertEqual(res["aliases"], [])
  2596. def test_not_in_room(self) -> None:
  2597. self.register_user("user", "test")
  2598. user_tok = self.login("user", "test")
  2599. res = self._get_aliases(user_tok, expected_code=403)
  2600. self.assertEqual(res["errcode"], "M_FORBIDDEN")
  2601. def test_admin_user(self) -> None:
  2602. alias1 = self._random_alias()
  2603. self._set_alias_via_directory(alias1)
  2604. self.register_user("user", "test", admin=True)
  2605. user_tok = self.login("user", "test")
  2606. res = self._get_aliases(user_tok)
  2607. self.assertEqual(res["aliases"], [alias1])
  2608. def test_with_aliases(self) -> None:
  2609. alias1 = self._random_alias()
  2610. alias2 = self._random_alias()
  2611. self._set_alias_via_directory(alias1)
  2612. self._set_alias_via_directory(alias2)
  2613. res = self._get_aliases(self.room_owner_tok)
  2614. self.assertEqual(set(res["aliases"]), {alias1, alias2})
  2615. def test_peekable_room(self) -> None:
  2616. alias1 = self._random_alias()
  2617. self._set_alias_via_directory(alias1)
  2618. self.helper.send_state(
  2619. self.room_id,
  2620. EventTypes.RoomHistoryVisibility,
  2621. body={"history_visibility": "world_readable"},
  2622. tok=self.room_owner_tok,
  2623. )
  2624. self.register_user("user", "test")
  2625. user_tok = self.login("user", "test")
  2626. res = self._get_aliases(user_tok)
  2627. self.assertEqual(res["aliases"], [alias1])
  2628. def _get_aliases(self, access_token: str, expected_code: int = 200) -> JsonDict:
  2629. """Calls the endpoint under test. returns the json response object."""
  2630. channel = self.make_request(
  2631. "GET",
  2632. "/_matrix/client/r0/rooms/%s/aliases" % (self.room_id,),
  2633. access_token=access_token,
  2634. )
  2635. self.assertEqual(channel.code, expected_code, channel.result)
  2636. res = channel.json_body
  2637. self.assertIsInstance(res, dict)
  2638. if expected_code == 200:
  2639. self.assertIsInstance(res["aliases"], list)
  2640. return res
  2641. def _random_alias(self) -> str:
  2642. return RoomAlias(random_string(5), self.hs.hostname).to_string()
  2643. def _set_alias_via_directory(self, alias: str, expected_code: int = 200) -> None:
  2644. url = "/_matrix/client/r0/directory/room/" + alias
  2645. request_data = {"room_id": self.room_id}
  2646. channel = self.make_request(
  2647. "PUT", url, request_data, access_token=self.room_owner_tok
  2648. )
  2649. self.assertEqual(channel.code, expected_code, channel.result)
  2650. class RoomCanonicalAliasTestCase(unittest.HomeserverTestCase):
  2651. servlets = [
  2652. synapse.rest.admin.register_servlets_for_client_rest_resource,
  2653. directory.register_servlets,
  2654. login.register_servlets,
  2655. room.register_servlets,
  2656. ]
  2657. def prepare(self, reactor: MemoryReactor, clock: Clock, hs: HomeServer) -> None:
  2658. self.room_owner = self.register_user("room_owner", "test")
  2659. self.room_owner_tok = self.login("room_owner", "test")
  2660. self.room_id = self.helper.create_room_as(
  2661. self.room_owner, tok=self.room_owner_tok
  2662. )
  2663. self.alias = "#alias:test"
  2664. self._set_alias_via_directory(self.alias)
  2665. def _set_alias_via_directory(self, alias: str, expected_code: int = 200) -> None:
  2666. url = "/_matrix/client/r0/directory/room/" + alias
  2667. request_data = {"room_id": self.room_id}
  2668. channel = self.make_request(
  2669. "PUT", url, request_data, access_token=self.room_owner_tok
  2670. )
  2671. self.assertEqual(channel.code, expected_code, channel.result)
  2672. def _get_canonical_alias(self, expected_code: int = 200) -> JsonDict:
  2673. """Calls the endpoint under test. returns the json response object."""
  2674. channel = self.make_request(
  2675. "GET",
  2676. "rooms/%s/state/m.room.canonical_alias" % (self.room_id,),
  2677. access_token=self.room_owner_tok,
  2678. )
  2679. self.assertEqual(channel.code, expected_code, channel.result)
  2680. res = channel.json_body
  2681. self.assertIsInstance(res, dict)
  2682. return res
  2683. def _set_canonical_alias(
  2684. self, content: JsonDict, expected_code: int = 200
  2685. ) -> JsonDict:
  2686. """Calls the endpoint under test. returns the json response object."""
  2687. channel = self.make_request(
  2688. "PUT",
  2689. "rooms/%s/state/m.room.canonical_alias" % (self.room_id,),
  2690. content,
  2691. access_token=self.room_owner_tok,
  2692. )
  2693. self.assertEqual(channel.code, expected_code, channel.result)
  2694. res = channel.json_body
  2695. self.assertIsInstance(res, dict)
  2696. return res
  2697. def test_canonical_alias(self) -> None:
  2698. """Test a basic alias message."""
  2699. # There is no canonical alias to start with.
  2700. self._get_canonical_alias(expected_code=404)
  2701. # Create an alias.
  2702. self._set_canonical_alias({"alias": self.alias})
  2703. # Canonical alias now exists!
  2704. res = self._get_canonical_alias()
  2705. self.assertEqual(res, {"alias": self.alias})
  2706. # Now remove the alias.
  2707. self._set_canonical_alias({})
  2708. # There is an alias event, but it is empty.
  2709. res = self._get_canonical_alias()
  2710. self.assertEqual(res, {})
  2711. def test_alt_aliases(self) -> None:
  2712. """Test a canonical alias message with alt_aliases."""
  2713. # Create an alias.
  2714. self._set_canonical_alias({"alt_aliases": [self.alias]})
  2715. # Canonical alias now exists!
  2716. res = self._get_canonical_alias()
  2717. self.assertEqual(res, {"alt_aliases": [self.alias]})
  2718. # Now remove the alt_aliases.
  2719. self._set_canonical_alias({})
  2720. # There is an alias event, but it is empty.
  2721. res = self._get_canonical_alias()
  2722. self.assertEqual(res, {})
  2723. def test_alias_alt_aliases(self) -> None:
  2724. """Test a canonical alias message with an alias and alt_aliases."""
  2725. # Create an alias.
  2726. self._set_canonical_alias({"alias": self.alias, "alt_aliases": [self.alias]})
  2727. # Canonical alias now exists!
  2728. res = self._get_canonical_alias()
  2729. self.assertEqual(res, {"alias": self.alias, "alt_aliases": [self.alias]})
  2730. # Now remove the alias and alt_aliases.
  2731. self._set_canonical_alias({})
  2732. # There is an alias event, but it is empty.
  2733. res = self._get_canonical_alias()
  2734. self.assertEqual(res, {})
  2735. def test_partial_modify(self) -> None:
  2736. """Test removing only the alt_aliases."""
  2737. # Create an alias.
  2738. self._set_canonical_alias({"alias": self.alias, "alt_aliases": [self.alias]})
  2739. # Canonical alias now exists!
  2740. res = self._get_canonical_alias()
  2741. self.assertEqual(res, {"alias": self.alias, "alt_aliases": [self.alias]})
  2742. # Now remove the alt_aliases.
  2743. self._set_canonical_alias({"alias": self.alias})
  2744. # There is an alias event, but it is empty.
  2745. res = self._get_canonical_alias()
  2746. self.assertEqual(res, {"alias": self.alias})
  2747. def test_add_alias(self) -> None:
  2748. """Test removing only the alt_aliases."""
  2749. # Create an additional alias.
  2750. second_alias = "#second:test"
  2751. self._set_alias_via_directory(second_alias)
  2752. # Add the canonical alias.
  2753. self._set_canonical_alias({"alias": self.alias, "alt_aliases": [self.alias]})
  2754. # Then add the second alias.
  2755. self._set_canonical_alias(
  2756. {"alias": self.alias, "alt_aliases": [self.alias, second_alias]}
  2757. )
  2758. # Canonical alias now exists!
  2759. res = self._get_canonical_alias()
  2760. self.assertEqual(
  2761. res, {"alias": self.alias, "alt_aliases": [self.alias, second_alias]}
  2762. )
  2763. def test_bad_data(self) -> None:
  2764. """Invalid data for alt_aliases should cause errors."""
  2765. self._set_canonical_alias({"alt_aliases": "@bad:test"}, expected_code=400)
  2766. self._set_canonical_alias({"alt_aliases": None}, expected_code=400)
  2767. self._set_canonical_alias({"alt_aliases": 0}, expected_code=400)
  2768. self._set_canonical_alias({"alt_aliases": 1}, expected_code=400)
  2769. self._set_canonical_alias({"alt_aliases": False}, expected_code=400)
  2770. self._set_canonical_alias({"alt_aliases": True}, expected_code=400)
  2771. self._set_canonical_alias({"alt_aliases": {}}, expected_code=400)
  2772. def test_bad_alias(self) -> None:
  2773. """An alias which does not point to the room raises a SynapseError."""
  2774. self._set_canonical_alias({"alias": "@unknown:test"}, expected_code=400)
  2775. self._set_canonical_alias({"alt_aliases": ["@unknown:test"]}, expected_code=400)
  2776. class ThreepidInviteTestCase(unittest.HomeserverTestCase):
  2777. servlets = [
  2778. admin.register_servlets,
  2779. login.register_servlets,
  2780. room.register_servlets,
  2781. ]
  2782. def prepare(self, reactor: MemoryReactor, clock: Clock, hs: HomeServer) -> None:
  2783. self.user_id = self.register_user("thomas", "hackme")
  2784. self.tok = self.login("thomas", "hackme")
  2785. self.room_id = self.helper.create_room_as(self.user_id, tok=self.tok)
  2786. def test_threepid_invite_spamcheck_deprecated(self) -> None:
  2787. """
  2788. Test allowing/blocking threepid invites with a spam-check module.
  2789. In this test, we use the deprecated API in which callbacks return a bool.
  2790. """
  2791. # Mock a few functions to prevent the test from failing due to failing to talk to
  2792. # a remote IS. We keep the mock for make_and_store_3pid_invite around so we
  2793. # can check its call_count later on during the test.
  2794. make_invite_mock = Mock(return_value=make_awaitable((Mock(event_id="abc"), 0)))
  2795. self.hs.get_room_member_handler()._make_and_store_3pid_invite = make_invite_mock # type: ignore[assignment]
  2796. self.hs.get_identity_handler().lookup_3pid = Mock( # type: ignore[assignment]
  2797. return_value=make_awaitable(None),
  2798. )
  2799. # Add a mock to the spamchecker callbacks for user_may_send_3pid_invite. Make it
  2800. # allow everything for now.
  2801. # `spec` argument is needed for this function mock to have `__qualname__`, which
  2802. # is needed for `Measure` metrics buried in SpamChecker.
  2803. mock = Mock(return_value=make_awaitable(True), spec=lambda *x: None)
  2804. self.hs.get_module_api_callbacks().spam_checker._user_may_send_3pid_invite_callbacks.append(
  2805. mock
  2806. )
  2807. # Send a 3PID invite into the room and check that it succeeded.
  2808. email_to_invite = "teresa@example.com"
  2809. channel = self.make_request(
  2810. method="POST",
  2811. path="/rooms/" + self.room_id + "/invite",
  2812. content={
  2813. "id_server": "example.com",
  2814. "id_access_token": "sometoken",
  2815. "medium": "email",
  2816. "address": email_to_invite,
  2817. },
  2818. access_token=self.tok,
  2819. )
  2820. self.assertEqual(channel.code, 200)
  2821. # Check that the callback was called with the right params.
  2822. mock.assert_called_with(self.user_id, "email", email_to_invite, self.room_id)
  2823. # Check that the call to send the invite was made.
  2824. make_invite_mock.assert_called_once()
  2825. # Now change the return value of the callback to deny any invite and test that
  2826. # we can't send the invite.
  2827. mock.return_value = make_awaitable(False)
  2828. channel = self.make_request(
  2829. method="POST",
  2830. path="/rooms/" + self.room_id + "/invite",
  2831. content={
  2832. "id_server": "example.com",
  2833. "id_access_token": "sometoken",
  2834. "medium": "email",
  2835. "address": email_to_invite,
  2836. },
  2837. access_token=self.tok,
  2838. )
  2839. self.assertEqual(channel.code, 403)
  2840. # Also check that it stopped before calling _make_and_store_3pid_invite.
  2841. make_invite_mock.assert_called_once()
  2842. def test_threepid_invite_spamcheck(self) -> None:
  2843. """
  2844. Test allowing/blocking threepid invites with a spam-check module.
  2845. In this test, we use the more recent API in which callbacks return a `Union[Codes, Literal["NOT_SPAM"]]`.
  2846. """
  2847. # Mock a few functions to prevent the test from failing due to failing to talk to
  2848. # a remote IS. We keep the mock for make_and_store_3pid_invite around so we
  2849. # can check its call_count later on during the test.
  2850. make_invite_mock = Mock(return_value=make_awaitable((Mock(event_id="abc"), 0)))
  2851. self.hs.get_room_member_handler()._make_and_store_3pid_invite = make_invite_mock # type: ignore[assignment]
  2852. self.hs.get_identity_handler().lookup_3pid = Mock( # type: ignore[assignment]
  2853. return_value=make_awaitable(None),
  2854. )
  2855. # Add a mock to the spamchecker callbacks for user_may_send_3pid_invite. Make it
  2856. # allow everything for now.
  2857. # `spec` argument is needed for this function mock to have `__qualname__`, which
  2858. # is needed for `Measure` metrics buried in SpamChecker.
  2859. mock = Mock(
  2860. return_value=make_awaitable(synapse.module_api.NOT_SPAM),
  2861. spec=lambda *x: None,
  2862. )
  2863. self.hs.get_module_api_callbacks().spam_checker._user_may_send_3pid_invite_callbacks.append(
  2864. mock
  2865. )
  2866. # Send a 3PID invite into the room and check that it succeeded.
  2867. email_to_invite = "teresa@example.com"
  2868. channel = self.make_request(
  2869. method="POST",
  2870. path="/rooms/" + self.room_id + "/invite",
  2871. content={
  2872. "id_server": "example.com",
  2873. "id_access_token": "sometoken",
  2874. "medium": "email",
  2875. "address": email_to_invite,
  2876. },
  2877. access_token=self.tok,
  2878. )
  2879. self.assertEqual(channel.code, 200)
  2880. # Check that the callback was called with the right params.
  2881. mock.assert_called_with(self.user_id, "email", email_to_invite, self.room_id)
  2882. # Check that the call to send the invite was made.
  2883. make_invite_mock.assert_called_once()
  2884. # Now change the return value of the callback to deny any invite and test that
  2885. # we can't send the invite. We pick an arbitrary error code to be able to check
  2886. # that the same code has been returned
  2887. mock.return_value = make_awaitable(Codes.CONSENT_NOT_GIVEN)
  2888. channel = self.make_request(
  2889. method="POST",
  2890. path="/rooms/" + self.room_id + "/invite",
  2891. content={
  2892. "id_server": "example.com",
  2893. "id_access_token": "sometoken",
  2894. "medium": "email",
  2895. "address": email_to_invite,
  2896. },
  2897. access_token=self.tok,
  2898. )
  2899. self.assertEqual(channel.code, 403)
  2900. self.assertEqual(channel.json_body["errcode"], Codes.CONSENT_NOT_GIVEN)
  2901. # Also check that it stopped before calling _make_and_store_3pid_invite.
  2902. make_invite_mock.assert_called_once()
  2903. # Run variant with `Tuple[Codes, dict]`.
  2904. mock.return_value = make_awaitable((Codes.EXPIRED_ACCOUNT, {"field": "value"}))
  2905. channel = self.make_request(
  2906. method="POST",
  2907. path="/rooms/" + self.room_id + "/invite",
  2908. content={
  2909. "id_server": "example.com",
  2910. "id_access_token": "sometoken",
  2911. "medium": "email",
  2912. "address": email_to_invite,
  2913. },
  2914. access_token=self.tok,
  2915. )
  2916. self.assertEqual(channel.code, 403)
  2917. self.assertEqual(channel.json_body["errcode"], Codes.EXPIRED_ACCOUNT)
  2918. self.assertEqual(channel.json_body["field"], "value")
  2919. # Also check that it stopped before calling _make_and_store_3pid_invite.
  2920. make_invite_mock.assert_called_once()
  2921. def test_400_missing_param_without_id_access_token(self) -> None:
  2922. """
  2923. Test that a 3pid invite request returns 400 M_MISSING_PARAM
  2924. if we do not include id_access_token.
  2925. """
  2926. channel = self.make_request(
  2927. method="POST",
  2928. path="/rooms/" + self.room_id + "/invite",
  2929. content={
  2930. "id_server": "example.com",
  2931. "medium": "email",
  2932. "address": "teresa@example.com",
  2933. },
  2934. access_token=self.tok,
  2935. )
  2936. self.assertEqual(channel.code, 400)
  2937. self.assertEqual(channel.json_body["errcode"], "M_MISSING_PARAM")
  2938. class TimestampLookupTestCase(unittest.HomeserverTestCase):
  2939. servlets = [
  2940. admin.register_servlets,
  2941. room.register_servlets,
  2942. login.register_servlets,
  2943. ]
  2944. def prepare(self, reactor: MemoryReactor, clock: Clock, hs: HomeServer) -> None:
  2945. self._storage_controllers = self.hs.get_storage_controllers()
  2946. self.room_owner = self.register_user("room_owner", "test")
  2947. self.room_owner_tok = self.login("room_owner", "test")
  2948. def _inject_outlier(self, room_id: str) -> EventBase:
  2949. event, _context = self.get_success(
  2950. create_event(
  2951. self.hs,
  2952. room_id=room_id,
  2953. type="m.test",
  2954. sender="@test_remote_user:remote",
  2955. )
  2956. )
  2957. event.internal_metadata.outlier = True
  2958. persistence = self._storage_controllers.persistence
  2959. assert persistence is not None
  2960. self.get_success(
  2961. persistence.persist_event(
  2962. event, EventContext.for_outlier(self._storage_controllers)
  2963. )
  2964. )
  2965. return event
  2966. def test_no_outliers(self) -> None:
  2967. """
  2968. Test to make sure `/timestamp_to_event` does not return `outlier` events.
  2969. We're unable to determine whether an `outlier` is next to a gap so we
  2970. don't know whether it's actually the closest event. Instead, let's just
  2971. ignore `outliers` with this endpoint.
  2972. This test is really seeing that we choose the non-`outlier` event behind the
  2973. `outlier`. Since the gap checking logic considers the latest message in the room
  2974. as *not* next to a gap, asking over federation does not come into play here.
  2975. """
  2976. room_id = self.helper.create_room_as(self.room_owner, tok=self.room_owner_tok)
  2977. outlier_event = self._inject_outlier(room_id)
  2978. channel = self.make_request(
  2979. "GET",
  2980. f"/_matrix/client/v1/rooms/{room_id}/timestamp_to_event?dir=b&ts={outlier_event.origin_server_ts}",
  2981. access_token=self.room_owner_tok,
  2982. )
  2983. self.assertEqual(HTTPStatus.OK, channel.code, msg=channel.json_body)
  2984. # Make sure the outlier event is not returned
  2985. self.assertNotEqual(channel.json_body["event_id"], outlier_event.event_id)