test_rooms.py 134 KB

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