test_rooms.py 133 KB

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