test_room.py 104 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911
  1. # Copyright 2020 Dirk Klimpel
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. import json
  15. import time
  16. import urllib.parse
  17. from typing import List, Optional
  18. from unittest.mock import AsyncMock, Mock
  19. from parameterized import parameterized
  20. from twisted.internet.task import deferLater
  21. from twisted.test.proto_helpers import MemoryReactor
  22. import synapse.rest.admin
  23. from synapse.api.constants import EventTypes, Membership, RoomTypes
  24. from synapse.api.errors import Codes
  25. from synapse.handlers.pagination import (
  26. PURGE_ROOM_ACTION_NAME,
  27. SHUTDOWN_AND_PURGE_ROOM_ACTION_NAME,
  28. )
  29. from synapse.rest.client import directory, events, knock, login, room, sync
  30. from synapse.server import HomeServer
  31. from synapse.types import UserID
  32. from synapse.util import Clock
  33. from synapse.util.task_scheduler import TaskScheduler
  34. from tests import unittest
  35. """Tests admin REST events for /rooms paths."""
  36. ONE_HOUR_IN_S = 3600
  37. class DeleteRoomTestCase(unittest.HomeserverTestCase):
  38. servlets = [
  39. synapse.rest.admin.register_servlets,
  40. login.register_servlets,
  41. events.register_servlets,
  42. room.register_servlets,
  43. knock.register_servlets,
  44. sync.register_servlets,
  45. room.register_deprecated_servlets,
  46. ]
  47. def prepare(self, reactor: MemoryReactor, clock: Clock, hs: HomeServer) -> None:
  48. self.event_creation_handler = hs.get_event_creation_handler()
  49. self.task_scheduler = hs.get_task_scheduler()
  50. hs.config.consent.user_consent_version = "1"
  51. consent_uri_builder = Mock()
  52. consent_uri_builder.build_user_consent_uri.return_value = "http://example.com"
  53. self.event_creation_handler._consent_uri_builder = consent_uri_builder
  54. self.store = hs.get_datastores().main
  55. self.admin_user = self.register_user("admin", "pass", admin=True)
  56. self.admin_user_tok = self.login("admin", "pass")
  57. self.other_user = self.register_user("user", "pass")
  58. self.other_user_tok = self.login("user", "pass")
  59. # Mark the admin user as having consented
  60. self.get_success(self.store.user_set_consent_version(self.admin_user, "1"))
  61. self.room_id = self.helper.create_room_as(
  62. self.other_user, tok=self.other_user_tok
  63. )
  64. self.url = "/_synapse/admin/v1/rooms/%s" % self.room_id
  65. def test_requester_is_no_admin(self) -> None:
  66. """
  67. If the user is not a server admin, an error 403 is returned.
  68. """
  69. channel = self.make_request(
  70. "DELETE",
  71. self.url,
  72. {},
  73. access_token=self.other_user_tok,
  74. )
  75. self.assertEqual(403, channel.code, msg=channel.json_body)
  76. self.assertEqual(Codes.FORBIDDEN, channel.json_body["errcode"])
  77. def test_room_does_not_exist(self) -> None:
  78. """
  79. Check that unknown rooms/server return 200
  80. """
  81. url = "/_synapse/admin/v1/rooms/%s" % "!unknown:test"
  82. channel = self.make_request(
  83. "DELETE",
  84. url,
  85. {},
  86. access_token=self.admin_user_tok,
  87. )
  88. self.assertEqual(200, channel.code, msg=channel.json_body)
  89. def test_room_is_not_valid(self) -> None:
  90. """
  91. Check that invalid room names, return an error 400.
  92. """
  93. url = "/_synapse/admin/v1/rooms/%s" % "invalidroom"
  94. channel = self.make_request(
  95. "DELETE",
  96. url,
  97. {},
  98. access_token=self.admin_user_tok,
  99. )
  100. self.assertEqual(400, channel.code, msg=channel.json_body)
  101. self.assertEqual(
  102. "invalidroom is not a legal room ID",
  103. channel.json_body["error"],
  104. )
  105. def test_new_room_user_does_not_exist(self) -> None:
  106. """
  107. Tests that the user ID must be from local server but it does not have to exist.
  108. """
  109. channel = self.make_request(
  110. "DELETE",
  111. self.url,
  112. content={"new_room_user_id": "@unknown:test"},
  113. access_token=self.admin_user_tok,
  114. )
  115. self.assertEqual(200, channel.code, msg=channel.json_body)
  116. self.assertIn("new_room_id", channel.json_body)
  117. self.assertIn("kicked_users", channel.json_body)
  118. self.assertIn("failed_to_kick_users", channel.json_body)
  119. self.assertIn("local_aliases", channel.json_body)
  120. def test_new_room_user_is_not_local(self) -> None:
  121. """
  122. Check that only local users can create new room to move members.
  123. """
  124. channel = self.make_request(
  125. "DELETE",
  126. self.url,
  127. content={"new_room_user_id": "@not:exist.bla"},
  128. access_token=self.admin_user_tok,
  129. )
  130. self.assertEqual(400, channel.code, msg=channel.json_body)
  131. self.assertEqual(
  132. "User must be our own: @not:exist.bla",
  133. channel.json_body["error"],
  134. )
  135. def test_block_is_not_bool(self) -> None:
  136. """
  137. If parameter `block` is not boolean, return an error
  138. """
  139. channel = self.make_request(
  140. "DELETE",
  141. self.url,
  142. content={"block": "NotBool"},
  143. access_token=self.admin_user_tok,
  144. )
  145. self.assertEqual(400, channel.code, msg=channel.json_body)
  146. self.assertEqual(Codes.BAD_JSON, channel.json_body["errcode"])
  147. def test_purge_is_not_bool(self) -> None:
  148. """
  149. If parameter `purge` is not boolean, return an error
  150. """
  151. channel = self.make_request(
  152. "DELETE",
  153. self.url,
  154. content={"purge": "NotBool"},
  155. access_token=self.admin_user_tok,
  156. )
  157. self.assertEqual(400, channel.code, msg=channel.json_body)
  158. self.assertEqual(Codes.BAD_JSON, channel.json_body["errcode"])
  159. def test_purge_room_and_block(self) -> None:
  160. """Test to purge a room and block it.
  161. Members will not be moved to a new room and will not receive a message.
  162. """
  163. # Test that room is not purged
  164. with self.assertRaises(AssertionError):
  165. self._is_purged(self.room_id)
  166. # Test that room is not blocked
  167. self._is_blocked(self.room_id, expect=False)
  168. # Assert one user in room
  169. self._is_member(room_id=self.room_id, user_id=self.other_user)
  170. channel = self.make_request(
  171. "DELETE",
  172. self.url.encode("ascii"),
  173. content={"block": True, "purge": True},
  174. access_token=self.admin_user_tok,
  175. )
  176. self.assertEqual(200, channel.code, msg=channel.json_body)
  177. self.assertEqual(None, channel.json_body["new_room_id"])
  178. self.assertEqual(self.other_user, channel.json_body["kicked_users"][0])
  179. self.assertIn("failed_to_kick_users", channel.json_body)
  180. self.assertIn("local_aliases", channel.json_body)
  181. self._is_purged(self.room_id)
  182. self._is_blocked(self.room_id, expect=True)
  183. self._has_no_members(self.room_id)
  184. def test_purge_room_and_not_block(self) -> None:
  185. """Test to purge a room and do not block it.
  186. Members will not be moved to a new room and will not receive a message.
  187. """
  188. # Test that room is not purged
  189. with self.assertRaises(AssertionError):
  190. self._is_purged(self.room_id)
  191. # Test that room is not blocked
  192. self._is_blocked(self.room_id, expect=False)
  193. # Assert one user in room
  194. self._is_member(room_id=self.room_id, user_id=self.other_user)
  195. channel = self.make_request(
  196. "DELETE",
  197. self.url.encode("ascii"),
  198. content={"block": False, "purge": True},
  199. access_token=self.admin_user_tok,
  200. )
  201. self.assertEqual(200, channel.code, msg=channel.json_body)
  202. self.assertEqual(None, channel.json_body["new_room_id"])
  203. self.assertEqual(self.other_user, channel.json_body["kicked_users"][0])
  204. self.assertIn("failed_to_kick_users", channel.json_body)
  205. self.assertIn("local_aliases", channel.json_body)
  206. self._is_purged(self.room_id)
  207. self._is_blocked(self.room_id, expect=False)
  208. self._has_no_members(self.room_id)
  209. def test_purge_room_unjoined(self) -> None:
  210. """Test to purge a room when there are invited or knocked users."""
  211. # Test that room is not purged
  212. with self.assertRaises(AssertionError):
  213. self._is_purged(self.room_id)
  214. # Test that room is not blocked
  215. self._is_blocked(self.room_id, expect=False)
  216. # Assert one user in room
  217. self._is_member(room_id=self.room_id, user_id=self.other_user)
  218. self.helper.send_state(
  219. self.room_id,
  220. EventTypes.JoinRules,
  221. {"join_rule": "knock"},
  222. tok=self.other_user_tok,
  223. )
  224. # Invite a user.
  225. invited_user = self.register_user("invited", "pass")
  226. self.helper.invite(
  227. self.room_id, self.other_user, invited_user, tok=self.other_user_tok
  228. )
  229. # Have a user knock.
  230. knocked_user = self.register_user("knocked", "pass")
  231. knocked_user_tok = self.login("knocked", "pass")
  232. self.helper.knock(self.room_id, knocked_user, tok=knocked_user_tok)
  233. channel = self.make_request(
  234. "DELETE",
  235. self.url.encode("ascii"),
  236. content={"block": False, "purge": True},
  237. access_token=self.admin_user_tok,
  238. )
  239. self.assertEqual(200, channel.code, msg=channel.json_body)
  240. self.assertEqual(None, channel.json_body["new_room_id"])
  241. self.assertCountEqual(
  242. [self.other_user, invited_user, knocked_user],
  243. channel.json_body["kicked_users"],
  244. )
  245. self.assertIn("failed_to_kick_users", channel.json_body)
  246. self.assertIn("local_aliases", channel.json_body)
  247. self._is_purged(self.room_id)
  248. self._is_blocked(self.room_id, expect=False)
  249. self._has_no_members(self.room_id)
  250. def test_block_room_and_not_purge(self) -> None:
  251. """Test to block a room without purging it.
  252. Members will not be moved to a new room and will not receive a message.
  253. The room will not be purged.
  254. """
  255. # Test that room is not purged
  256. with self.assertRaises(AssertionError):
  257. self._is_purged(self.room_id)
  258. # Test that room is not blocked
  259. self._is_blocked(self.room_id, expect=False)
  260. # Assert one user in room
  261. self._is_member(room_id=self.room_id, user_id=self.other_user)
  262. channel = self.make_request(
  263. "DELETE",
  264. self.url.encode("ascii"),
  265. content={"block": True, "purge": False},
  266. access_token=self.admin_user_tok,
  267. )
  268. self.assertEqual(200, channel.code, msg=channel.json_body)
  269. self.assertEqual(None, channel.json_body["new_room_id"])
  270. self.assertEqual(self.other_user, channel.json_body["kicked_users"][0])
  271. self.assertIn("failed_to_kick_users", channel.json_body)
  272. self.assertIn("local_aliases", channel.json_body)
  273. with self.assertRaises(AssertionError):
  274. self._is_purged(self.room_id)
  275. self._is_blocked(self.room_id, expect=True)
  276. self._has_no_members(self.room_id)
  277. @parameterized.expand([(True,), (False,)])
  278. def test_block_unknown_room(self, purge: bool) -> None:
  279. """
  280. We can block an unknown room. In this case, the `purge` argument
  281. should be ignored.
  282. """
  283. room_id = "!unknown:test"
  284. # The room isn't already in the blocked rooms table
  285. self._is_blocked(room_id, expect=False)
  286. # Request the room be blocked.
  287. channel = self.make_request(
  288. "DELETE",
  289. f"/_synapse/admin/v1/rooms/{room_id}",
  290. {"block": True, "purge": purge},
  291. access_token=self.admin_user_tok,
  292. )
  293. # The room is now blocked.
  294. self.assertEqual(200, channel.code, msg=channel.json_body)
  295. self._is_blocked(room_id)
  296. def test_shutdown_room_consent(self) -> None:
  297. """Test that we can shutdown rooms with local users who have not
  298. yet accepted the privacy policy. This used to fail when we tried to
  299. force part the user from the old room.
  300. Members will be moved to a new room and will receive a message.
  301. """
  302. self.event_creation_handler._block_events_without_consent_error = None
  303. # Assert one user in room
  304. users_in_room = self.get_success(self.store.get_users_in_room(self.room_id))
  305. self.assertEqual([self.other_user], users_in_room)
  306. # Enable require consent to send events
  307. self.event_creation_handler._block_events_without_consent_error = "Error"
  308. # Assert that the user is getting consent error
  309. self.helper.send(
  310. self.room_id,
  311. body="foo",
  312. tok=self.other_user_tok,
  313. expect_code=403,
  314. )
  315. # Test that room is not purged
  316. with self.assertRaises(AssertionError):
  317. self._is_purged(self.room_id)
  318. # Assert one user in room
  319. self._is_member(room_id=self.room_id, user_id=self.other_user)
  320. # Test that the admin can still send shutdown
  321. channel = self.make_request(
  322. "DELETE",
  323. self.url,
  324. {"new_room_user_id": self.admin_user},
  325. access_token=self.admin_user_tok,
  326. )
  327. self.assertEqual(200, channel.code, msg=channel.json_body)
  328. self.assertEqual(self.other_user, channel.json_body["kicked_users"][0])
  329. self.assertIn("new_room_id", channel.json_body)
  330. self.assertIn("failed_to_kick_users", channel.json_body)
  331. self.assertIn("local_aliases", channel.json_body)
  332. # Test that member has moved to new room
  333. self._is_member(
  334. room_id=channel.json_body["new_room_id"], user_id=self.other_user
  335. )
  336. self._is_purged(self.room_id)
  337. self._has_no_members(self.room_id)
  338. def test_shutdown_room_block_peek(self) -> None:
  339. """Test that a world_readable room can no longer be peeked into after
  340. it has been shut down.
  341. Members will be moved to a new room and will receive a message.
  342. """
  343. self.event_creation_handler._block_events_without_consent_error = None
  344. # Enable world readable
  345. url = "rooms/%s/state/m.room.history_visibility" % (self.room_id,)
  346. channel = self.make_request(
  347. "PUT",
  348. url.encode("ascii"),
  349. {"history_visibility": "world_readable"},
  350. access_token=self.other_user_tok,
  351. )
  352. self.assertEqual(200, channel.code, msg=channel.json_body)
  353. # Test that room is not purged
  354. with self.assertRaises(AssertionError):
  355. self._is_purged(self.room_id)
  356. # Assert one user in room
  357. self._is_member(room_id=self.room_id, user_id=self.other_user)
  358. # Test that the admin can still send shutdown
  359. channel = self.make_request(
  360. "DELETE",
  361. self.url,
  362. {"new_room_user_id": self.admin_user},
  363. access_token=self.admin_user_tok,
  364. )
  365. self.assertEqual(200, channel.code, msg=channel.json_body)
  366. self.assertEqual(self.other_user, channel.json_body["kicked_users"][0])
  367. self.assertIn("new_room_id", channel.json_body)
  368. self.assertIn("failed_to_kick_users", channel.json_body)
  369. self.assertIn("local_aliases", channel.json_body)
  370. # Test that member has moved to new room
  371. self._is_member(
  372. room_id=channel.json_body["new_room_id"], user_id=self.other_user
  373. )
  374. self._is_purged(self.room_id)
  375. self._has_no_members(self.room_id)
  376. # Assert we can no longer peek into the room
  377. self._assert_peek(self.room_id, expect_code=403)
  378. def test_room_delete_send(self) -> None:
  379. """Test that sending into a deleted room returns a 403"""
  380. channel = self.make_request(
  381. "DELETE",
  382. self.url,
  383. content={},
  384. access_token=self.admin_user_tok,
  385. )
  386. self.assertEqual(200, channel.code, msg=channel.json_body)
  387. self.helper.send(
  388. self.room_id, "test message", expect_code=403, tok=self.other_user_tok
  389. )
  390. def _is_blocked(self, room_id: str, expect: bool = True) -> None:
  391. """Assert that the room is blocked or not"""
  392. d = self.store.is_room_blocked(room_id)
  393. if expect:
  394. self.assertTrue(self.get_success(d))
  395. else:
  396. self.assertIsNone(self.get_success(d))
  397. def _has_no_members(self, room_id: str) -> None:
  398. """Assert there is now no longer anyone in the room"""
  399. users_in_room = self.get_success(self.store.get_users_in_room(room_id))
  400. self.assertEqual([], users_in_room)
  401. def _is_member(self, room_id: str, user_id: str) -> None:
  402. """Test that user is member of the room"""
  403. users_in_room = self.get_success(self.store.get_users_in_room(room_id))
  404. self.assertIn(user_id, users_in_room)
  405. def _is_purged(self, room_id: str) -> None:
  406. """Test that the following tables have been purged of all rows related to the room."""
  407. for table in PURGE_TABLES:
  408. count = self.get_success(
  409. self.store.db_pool.simple_select_one_onecol(
  410. table=table,
  411. keyvalues={"room_id": room_id},
  412. retcol="COUNT(*)",
  413. desc="test_purge_room",
  414. )
  415. )
  416. self.assertEqual(count, 0, msg=f"Rows not purged in {table}")
  417. def _assert_peek(self, room_id: str, expect_code: int) -> None:
  418. """Assert that the admin user can (or cannot) peek into the room."""
  419. url = "rooms/%s/initialSync" % (room_id,)
  420. channel = self.make_request(
  421. "GET", url.encode("ascii"), access_token=self.admin_user_tok
  422. )
  423. self.assertEqual(expect_code, channel.code, msg=channel.json_body)
  424. url = "events?timeout=0&room_id=" + room_id
  425. channel = self.make_request(
  426. "GET", url.encode("ascii"), access_token=self.admin_user_tok
  427. )
  428. self.assertEqual(expect_code, channel.code, msg=channel.json_body)
  429. class DeleteRoomV2TestCase(unittest.HomeserverTestCase):
  430. servlets = [
  431. synapse.rest.admin.register_servlets,
  432. login.register_servlets,
  433. events.register_servlets,
  434. room.register_servlets,
  435. room.register_deprecated_servlets,
  436. ]
  437. def prepare(self, reactor: MemoryReactor, clock: Clock, hs: HomeServer) -> None:
  438. self.event_creation_handler = hs.get_event_creation_handler()
  439. self.task_scheduler = hs.get_task_scheduler()
  440. hs.config.consent.user_consent_version = "1"
  441. consent_uri_builder = Mock()
  442. consent_uri_builder.build_user_consent_uri.return_value = "http://example.com"
  443. self.event_creation_handler._consent_uri_builder = consent_uri_builder
  444. self.store = hs.get_datastores().main
  445. self.admin_user = self.register_user("admin", "pass", admin=True)
  446. self.admin_user_tok = self.login("admin", "pass")
  447. self.other_user = self.register_user("user", "pass")
  448. self.other_user_tok = self.login("user", "pass")
  449. # Mark the admin user as having consented
  450. self.get_success(self.store.user_set_consent_version(self.admin_user, "1"))
  451. self.room_id = self.helper.create_room_as(
  452. self.other_user, tok=self.other_user_tok
  453. )
  454. self.url = f"/_synapse/admin/v2/rooms/{self.room_id}"
  455. self.url_status_by_room_id = (
  456. f"/_synapse/admin/v2/rooms/{self.room_id}/delete_status"
  457. )
  458. self.url_status_by_delete_id = "/_synapse/admin/v2/rooms/delete_status/"
  459. self.room_member_handler = hs.get_room_member_handler()
  460. self.pagination_handler = hs.get_pagination_handler()
  461. @parameterized.expand(
  462. [
  463. ("DELETE", "/_synapse/admin/v2/rooms/%s"),
  464. ("GET", "/_synapse/admin/v2/rooms/%s/delete_status"),
  465. ("GET", "/_synapse/admin/v2/rooms/delete_status/%s"),
  466. ]
  467. )
  468. def test_requester_is_no_admin(self, method: str, url: str) -> None:
  469. """
  470. If the user is not a server admin, an error 403 is returned.
  471. """
  472. channel = self.make_request(
  473. method,
  474. url % self.room_id,
  475. content={},
  476. access_token=self.other_user_tok,
  477. )
  478. self.assertEqual(403, channel.code, msg=channel.json_body)
  479. self.assertEqual(Codes.FORBIDDEN, channel.json_body["errcode"])
  480. def test_room_does_not_exist(self) -> None:
  481. """
  482. Check that unknown rooms/server return 200
  483. This is important, as it allows incomplete vestiges of rooms to be cleared up
  484. even if the create event/etc is missing.
  485. """
  486. room_id = "!unknown:test"
  487. channel = self.make_request(
  488. "DELETE",
  489. f"/_synapse/admin/v2/rooms/{room_id}",
  490. content={},
  491. access_token=self.admin_user_tok,
  492. )
  493. self.assertEqual(200, channel.code, msg=channel.json_body)
  494. self.assertIn("delete_id", channel.json_body)
  495. delete_id = channel.json_body["delete_id"]
  496. # get status
  497. channel = self.make_request(
  498. "GET",
  499. f"/_synapse/admin/v2/rooms/{room_id}/delete_status",
  500. access_token=self.admin_user_tok,
  501. )
  502. self.assertEqual(200, channel.code, msg=channel.json_body)
  503. self.assertEqual(1, len(channel.json_body["results"]))
  504. self.assertEqual("complete", channel.json_body["results"][0]["status"])
  505. self.assertEqual(delete_id, channel.json_body["results"][0]["delete_id"])
  506. @parameterized.expand(
  507. [
  508. ("DELETE", "/_synapse/admin/v2/rooms/%s"),
  509. ("GET", "/_synapse/admin/v2/rooms/%s/delete_status"),
  510. ]
  511. )
  512. def test_room_is_not_valid(self, method: str, url: str) -> None:
  513. """
  514. Check that invalid room names, return an error 400.
  515. """
  516. channel = self.make_request(
  517. method,
  518. url % "invalidroom",
  519. content={},
  520. access_token=self.admin_user_tok,
  521. )
  522. self.assertEqual(400, channel.code, msg=channel.json_body)
  523. self.assertEqual(
  524. "invalidroom is not a legal room ID",
  525. channel.json_body["error"],
  526. )
  527. def test_new_room_user_does_not_exist(self) -> None:
  528. """
  529. Tests that the user ID must be from local server but it does not have to exist.
  530. """
  531. channel = self.make_request(
  532. "DELETE",
  533. self.url,
  534. content={"new_room_user_id": "@unknown:test"},
  535. access_token=self.admin_user_tok,
  536. )
  537. self.assertEqual(200, channel.code, msg=channel.json_body)
  538. self.assertIn("delete_id", channel.json_body)
  539. delete_id = channel.json_body["delete_id"]
  540. self._test_result(delete_id, self.other_user, expect_new_room=True)
  541. def test_new_room_user_is_not_local(self) -> None:
  542. """
  543. Check that only local users can create new room to move members.
  544. """
  545. channel = self.make_request(
  546. "DELETE",
  547. self.url,
  548. content={"new_room_user_id": "@not:exist.bla"},
  549. access_token=self.admin_user_tok,
  550. )
  551. self.assertEqual(400, channel.code, msg=channel.json_body)
  552. self.assertEqual(
  553. "User must be our own: @not:exist.bla",
  554. channel.json_body["error"],
  555. )
  556. def test_block_is_not_bool(self) -> None:
  557. """
  558. If parameter `block` is not boolean, return an error
  559. """
  560. channel = self.make_request(
  561. "DELETE",
  562. self.url,
  563. content={"block": "NotBool"},
  564. access_token=self.admin_user_tok,
  565. )
  566. self.assertEqual(400, channel.code, msg=channel.json_body)
  567. self.assertEqual(Codes.BAD_JSON, channel.json_body["errcode"])
  568. def test_purge_is_not_bool(self) -> None:
  569. """
  570. If parameter `purge` is not boolean, return an error
  571. """
  572. channel = self.make_request(
  573. "DELETE",
  574. self.url,
  575. content={"purge": "NotBool"},
  576. access_token=self.admin_user_tok,
  577. )
  578. self.assertEqual(400, channel.code, msg=channel.json_body)
  579. self.assertEqual(Codes.BAD_JSON, channel.json_body["errcode"])
  580. def test_delete_expired_status(self) -> None:
  581. """Test that the task status is removed after expiration."""
  582. # first task, do not purge, that we can create a second task
  583. channel = self.make_request(
  584. "DELETE",
  585. self.url.encode("ascii"),
  586. content={"purge": False},
  587. access_token=self.admin_user_tok,
  588. )
  589. self.assertEqual(200, channel.code, msg=channel.json_body)
  590. self.assertIn("delete_id", channel.json_body)
  591. delete_id1 = channel.json_body["delete_id"]
  592. # go ahead
  593. self.reactor.advance(TaskScheduler.KEEP_TASKS_FOR_MS / 1000 / 2)
  594. # second task
  595. channel = self.make_request(
  596. "DELETE",
  597. self.url.encode("ascii"),
  598. content={"purge": True},
  599. access_token=self.admin_user_tok,
  600. )
  601. self.assertEqual(200, channel.code, msg=channel.json_body)
  602. self.assertIn("delete_id", channel.json_body)
  603. delete_id2 = channel.json_body["delete_id"]
  604. # get status
  605. channel = self.make_request(
  606. "GET",
  607. self.url_status_by_room_id,
  608. access_token=self.admin_user_tok,
  609. )
  610. self.assertEqual(200, channel.code, msg=channel.json_body)
  611. self.assertEqual(2, len(channel.json_body["results"]))
  612. self.assertEqual("complete", channel.json_body["results"][0]["status"])
  613. self.assertEqual("complete", channel.json_body["results"][1]["status"])
  614. delete_ids = {delete_id1, delete_id2}
  615. self.assertTrue(channel.json_body["results"][0]["delete_id"] in delete_ids)
  616. delete_ids.remove(channel.json_body["results"][0]["delete_id"])
  617. self.assertTrue(channel.json_body["results"][1]["delete_id"] in delete_ids)
  618. # get status after more than clearing time for first task
  619. # second task is not cleared
  620. self.reactor.advance(TaskScheduler.KEEP_TASKS_FOR_MS / 1000 / 2)
  621. channel = self.make_request(
  622. "GET",
  623. self.url_status_by_room_id,
  624. access_token=self.admin_user_tok,
  625. )
  626. self.assertEqual(200, channel.code, msg=channel.json_body)
  627. self.assertEqual(1, len(channel.json_body["results"]))
  628. self.assertEqual("complete", channel.json_body["results"][0]["status"])
  629. self.assertEqual(delete_id2, channel.json_body["results"][0]["delete_id"])
  630. # get status after more than clearing time for all tasks
  631. self.reactor.advance(TaskScheduler.KEEP_TASKS_FOR_MS / 1000 / 2)
  632. channel = self.make_request(
  633. "GET",
  634. self.url_status_by_room_id,
  635. access_token=self.admin_user_tok,
  636. )
  637. self.assertEqual(404, channel.code, msg=channel.json_body)
  638. self.assertEqual(Codes.NOT_FOUND, channel.json_body["errcode"])
  639. def test_delete_same_room_twice(self) -> None:
  640. """Test that the call for delete a room at second time gives an exception."""
  641. body = {"new_room_user_id": self.admin_user}
  642. # Mock PaginationHandler.purge_room to sleep for 100s, so we have time to do a second call
  643. # before the purge is over. Note that it doesn't purge anymore, but we don't care.
  644. async def purge_room(room_id: str, force: bool) -> None:
  645. await deferLater(self.hs.get_reactor(), 100, lambda: None)
  646. self.pagination_handler.purge_room = AsyncMock(side_effect=purge_room) # type: ignore[method-assign]
  647. # first call to delete room
  648. # and do not wait for finish the task
  649. first_channel = self.make_request(
  650. "DELETE",
  651. self.url.encode("ascii"),
  652. content=body,
  653. access_token=self.admin_user_tok,
  654. )
  655. # second call to delete room
  656. second_channel = self.make_request(
  657. "DELETE",
  658. self.url.encode("ascii"),
  659. content=body,
  660. access_token=self.admin_user_tok,
  661. )
  662. self.assertEqual(400, second_channel.code, msg=second_channel.json_body)
  663. self.assertEqual(Codes.UNKNOWN, second_channel.json_body["errcode"])
  664. self.assertEqual(
  665. f"Purge already in progress for {self.room_id}",
  666. second_channel.json_body["error"],
  667. )
  668. # get result of first call
  669. first_channel.await_result()
  670. self.assertEqual(200, first_channel.code, msg=first_channel.json_body)
  671. self.assertIn("delete_id", first_channel.json_body)
  672. # wait for purge_room to finish
  673. self.pump(1)
  674. # check status after finish the task
  675. self._test_result(
  676. first_channel.json_body["delete_id"],
  677. self.other_user,
  678. expect_new_room=True,
  679. )
  680. def test_purge_room_and_block(self) -> None:
  681. """Test to purge a room and block it.
  682. Members will not be moved to a new room and will not receive a message.
  683. """
  684. # Test that room is not purged
  685. with self.assertRaises(AssertionError):
  686. self._is_purged(self.room_id)
  687. # Test that room is not blocked
  688. self._is_blocked(self.room_id, expect=False)
  689. # Assert one user in room
  690. self._is_member(room_id=self.room_id, user_id=self.other_user)
  691. channel = self.make_request(
  692. "DELETE",
  693. self.url.encode("ascii"),
  694. content={"block": True, "purge": True},
  695. access_token=self.admin_user_tok,
  696. )
  697. self.assertEqual(200, channel.code, msg=channel.json_body)
  698. self.assertIn("delete_id", channel.json_body)
  699. delete_id = channel.json_body["delete_id"]
  700. self._test_result(delete_id, self.other_user)
  701. self._is_purged(self.room_id)
  702. self._is_blocked(self.room_id, expect=True)
  703. self._has_no_members(self.room_id)
  704. def test_purge_room_and_not_block(self) -> None:
  705. """Test to purge a room and do not block it.
  706. Members will not be moved to a new room and will not receive a message.
  707. """
  708. # Test that room is not purged
  709. with self.assertRaises(AssertionError):
  710. self._is_purged(self.room_id)
  711. # Test that room is not blocked
  712. self._is_blocked(self.room_id, expect=False)
  713. # Assert one user in room
  714. self._is_member(room_id=self.room_id, user_id=self.other_user)
  715. channel = self.make_request(
  716. "DELETE",
  717. self.url.encode("ascii"),
  718. content={"block": False, "purge": True},
  719. access_token=self.admin_user_tok,
  720. )
  721. self.assertEqual(200, channel.code, msg=channel.json_body)
  722. self.assertIn("delete_id", channel.json_body)
  723. delete_id = channel.json_body["delete_id"]
  724. self._test_result(delete_id, self.other_user)
  725. self._is_purged(self.room_id)
  726. self._is_blocked(self.room_id, expect=False)
  727. self._has_no_members(self.room_id)
  728. def test_block_room_and_not_purge(self) -> None:
  729. """Test to block a room without purging it.
  730. Members will not be moved to a new room and will not receive a message.
  731. The room will not be purged.
  732. """
  733. # Test that room is not purged
  734. with self.assertRaises(AssertionError):
  735. self._is_purged(self.room_id)
  736. # Test that room is not blocked
  737. self._is_blocked(self.room_id, expect=False)
  738. # Assert one user in room
  739. self._is_member(room_id=self.room_id, user_id=self.other_user)
  740. channel = self.make_request(
  741. "DELETE",
  742. self.url.encode("ascii"),
  743. content={"block": True, "purge": False},
  744. access_token=self.admin_user_tok,
  745. )
  746. self.assertEqual(200, channel.code, msg=channel.json_body)
  747. self.assertIn("delete_id", channel.json_body)
  748. delete_id = channel.json_body["delete_id"]
  749. self._test_result(delete_id, self.other_user)
  750. with self.assertRaises(AssertionError):
  751. self._is_purged(self.room_id)
  752. self._is_blocked(self.room_id, expect=True)
  753. self._has_no_members(self.room_id)
  754. def test_shutdown_room_consent(self) -> None:
  755. """Test that we can shutdown rooms with local users who have not
  756. yet accepted the privacy policy. This used to fail when we tried to
  757. force part the user from the old room.
  758. Members will be moved to a new room and will receive a message.
  759. """
  760. self.event_creation_handler._block_events_without_consent_error = None
  761. # Assert one user in room
  762. users_in_room = self.get_success(self.store.get_users_in_room(self.room_id))
  763. self.assertEqual([self.other_user], users_in_room)
  764. # Enable require consent to send events
  765. self.event_creation_handler._block_events_without_consent_error = "Error"
  766. # Assert that the user is getting consent error
  767. self.helper.send(
  768. self.room_id,
  769. body="foo",
  770. tok=self.other_user_tok,
  771. expect_code=403,
  772. )
  773. # Test that room is not purged
  774. with self.assertRaises(AssertionError):
  775. self._is_purged(self.room_id)
  776. # Assert one user in room
  777. self._is_member(room_id=self.room_id, user_id=self.other_user)
  778. # Test that the admin can still send shutdown
  779. channel = self.make_request(
  780. "DELETE",
  781. self.url,
  782. content={"new_room_user_id": self.admin_user},
  783. access_token=self.admin_user_tok,
  784. )
  785. self.assertEqual(200, channel.code, msg=channel.json_body)
  786. self.assertIn("delete_id", channel.json_body)
  787. delete_id = channel.json_body["delete_id"]
  788. self._test_result(delete_id, self.other_user, expect_new_room=True)
  789. channel = self.make_request(
  790. "GET",
  791. self.url_status_by_room_id,
  792. access_token=self.admin_user_tok,
  793. )
  794. self.assertEqual(200, channel.code, msg=channel.json_body)
  795. self.assertEqual(1, len(channel.json_body["results"]))
  796. # Test that member has moved to new room
  797. self._is_member(
  798. room_id=channel.json_body["results"][0]["shutdown_room"]["new_room_id"],
  799. user_id=self.other_user,
  800. )
  801. self._is_purged(self.room_id)
  802. self._has_no_members(self.room_id)
  803. def test_shutdown_room_block_peek(self) -> None:
  804. """Test that a world_readable room can no longer be peeked into after
  805. it has been shut down.
  806. Members will be moved to a new room and will receive a message.
  807. """
  808. self.event_creation_handler._block_events_without_consent_error = None
  809. # Enable world readable
  810. url = "rooms/%s/state/m.room.history_visibility" % (self.room_id,)
  811. channel = self.make_request(
  812. "PUT",
  813. url.encode("ascii"),
  814. content={"history_visibility": "world_readable"},
  815. access_token=self.other_user_tok,
  816. )
  817. self.assertEqual(200, channel.code, msg=channel.json_body)
  818. # Test that room is not purged
  819. with self.assertRaises(AssertionError):
  820. self._is_purged(self.room_id)
  821. # Assert one user in room
  822. self._is_member(room_id=self.room_id, user_id=self.other_user)
  823. # Test that the admin can still send shutdown
  824. channel = self.make_request(
  825. "DELETE",
  826. self.url,
  827. content={"new_room_user_id": self.admin_user},
  828. access_token=self.admin_user_tok,
  829. )
  830. self.assertEqual(200, channel.code, msg=channel.json_body)
  831. self.assertIn("delete_id", channel.json_body)
  832. delete_id = channel.json_body["delete_id"]
  833. self._test_result(delete_id, self.other_user, expect_new_room=True)
  834. channel = self.make_request(
  835. "GET",
  836. self.url_status_by_room_id,
  837. access_token=self.admin_user_tok,
  838. )
  839. self.assertEqual(200, channel.code, msg=channel.json_body)
  840. self.assertEqual(1, len(channel.json_body["results"]))
  841. # Test that member has moved to new room
  842. self._is_member(
  843. room_id=channel.json_body["results"][0]["shutdown_room"]["new_room_id"],
  844. user_id=self.other_user,
  845. )
  846. self._is_purged(self.room_id)
  847. self._has_no_members(self.room_id)
  848. # Assert we can no longer peek into the room
  849. self._assert_peek(self.room_id, expect_code=403)
  850. @unittest.override_config({"forgotten_room_retention_period": "1d"})
  851. def test_purge_forgotten_room(self) -> None:
  852. # Create a test room
  853. room_id = self.helper.create_room_as(
  854. self.admin_user,
  855. tok=self.admin_user_tok,
  856. )
  857. self.helper.leave(room_id, user=self.admin_user, tok=self.admin_user_tok)
  858. self.get_success(
  859. self.room_member_handler.forget(
  860. UserID.from_string(self.admin_user), room_id
  861. )
  862. )
  863. # Test that room is not yet purged
  864. with self.assertRaises(AssertionError):
  865. self._is_purged(room_id)
  866. # Advance 24 hours in the future, past the `forgotten_room_retention_period`
  867. self.reactor.advance(24 * ONE_HOUR_IN_S)
  868. self._is_purged(room_id)
  869. def test_scheduled_purge_room(self) -> None:
  870. # Create a test room
  871. room_id = self.helper.create_room_as(
  872. self.admin_user,
  873. tok=self.admin_user_tok,
  874. )
  875. self.helper.leave(room_id, user=self.admin_user, tok=self.admin_user_tok)
  876. # Schedule a purge 10 seconds in the future
  877. self.get_success(
  878. self.task_scheduler.schedule_task(
  879. PURGE_ROOM_ACTION_NAME,
  880. resource_id=room_id,
  881. timestamp=self.clock.time_msec() + 10 * 1000,
  882. )
  883. )
  884. # Test that room is not yet purged
  885. with self.assertRaises(AssertionError):
  886. self._is_purged(room_id)
  887. # Wait for next scheduler run
  888. self.reactor.advance(TaskScheduler.SCHEDULE_INTERVAL_MS)
  889. self._is_purged(room_id)
  890. def test_schedule_shutdown_room(self) -> None:
  891. # Create a test room
  892. room_id = self.helper.create_room_as(
  893. self.other_user,
  894. tok=self.other_user_tok,
  895. )
  896. # Schedule a shutdown 10 seconds in the future
  897. delete_id = self.get_success(
  898. self.task_scheduler.schedule_task(
  899. SHUTDOWN_AND_PURGE_ROOM_ACTION_NAME,
  900. resource_id=room_id,
  901. params={
  902. "requester_user_id": self.admin_user,
  903. "new_room_user_id": self.admin_user,
  904. "new_room_name": None,
  905. "message": None,
  906. "block": False,
  907. "purge": True,
  908. "force_purge": True,
  909. },
  910. timestamp=self.clock.time_msec() + 10 * 1000,
  911. )
  912. )
  913. # Test that room is not yet shutdown
  914. self._is_member(room_id, self.other_user)
  915. # Test that room is not yet purged
  916. with self.assertRaises(AssertionError):
  917. self._is_purged(room_id)
  918. # Wait for next scheduler run
  919. self.reactor.advance(TaskScheduler.SCHEDULE_INTERVAL_MS)
  920. # Test that all users has been kicked (room is shutdown)
  921. self._has_no_members(room_id)
  922. self._is_purged(room_id)
  923. # Retrieve delete results
  924. result = self.make_request(
  925. "GET",
  926. self.url_status_by_delete_id + delete_id,
  927. access_token=self.admin_user_tok,
  928. )
  929. self.assertEqual(200, result.code, msg=result.json_body)
  930. # Check that the user is in kicked_users
  931. self.assertIn(
  932. self.other_user, result.json_body["shutdown_room"]["kicked_users"]
  933. )
  934. new_room_id = result.json_body["shutdown_room"]["new_room_id"]
  935. self.assertTrue(new_room_id)
  936. # Check that the user is actually in the new room
  937. self._is_member(new_room_id, self.other_user)
  938. def _is_blocked(self, room_id: str, expect: bool = True) -> None:
  939. """Assert that the room is blocked or not"""
  940. d = self.store.is_room_blocked(room_id)
  941. if expect:
  942. self.assertTrue(self.get_success(d))
  943. else:
  944. self.assertIsNone(self.get_success(d))
  945. def _has_no_members(self, room_id: str) -> None:
  946. """Assert there is now no longer anyone in the room"""
  947. users_in_room = self.get_success(self.store.get_users_in_room(room_id))
  948. self.assertEqual([], users_in_room)
  949. def _is_member(self, room_id: str, user_id: str) -> None:
  950. """Test that user is member of the room"""
  951. users_in_room = self.get_success(self.store.get_users_in_room(room_id))
  952. self.assertIn(user_id, users_in_room)
  953. def _is_purged(self, room_id: str) -> None:
  954. """Test that the following tables have been purged of all rows related to the room."""
  955. for table in PURGE_TABLES:
  956. count = self.get_success(
  957. self.store.db_pool.simple_select_one_onecol(
  958. table=table,
  959. keyvalues={"room_id": room_id},
  960. retcol="COUNT(*)",
  961. desc="test_purge_room",
  962. )
  963. )
  964. self.assertEqual(count, 0, msg=f"Rows not purged in {table}")
  965. def _assert_peek(self, room_id: str, expect_code: int) -> None:
  966. """Assert that the admin user can (or cannot) peek into the room."""
  967. url = f"rooms/{room_id}/initialSync"
  968. channel = self.make_request(
  969. "GET", url.encode("ascii"), access_token=self.admin_user_tok
  970. )
  971. self.assertEqual(expect_code, channel.code, msg=channel.json_body)
  972. url = "events?timeout=0&room_id=" + room_id
  973. channel = self.make_request(
  974. "GET", url.encode("ascii"), access_token=self.admin_user_tok
  975. )
  976. self.assertEqual(expect_code, channel.code, msg=channel.json_body)
  977. def _test_result(
  978. self,
  979. delete_id: str,
  980. kicked_user: str,
  981. expect_new_room: bool = False,
  982. ) -> None:
  983. """
  984. Test that the result is the expected.
  985. Uses both APIs (status by room_id and delete_id)
  986. Args:
  987. delete_id: id of this purge
  988. kicked_user: a user_id which is kicked from the room
  989. expect_new_room: if we expect that a new room was created
  990. """
  991. # get information by room_id
  992. channel_room_id = self.make_request(
  993. "GET",
  994. self.url_status_by_room_id,
  995. access_token=self.admin_user_tok,
  996. )
  997. self.assertEqual(200, channel_room_id.code, msg=channel_room_id.json_body)
  998. self.assertEqual(1, len(channel_room_id.json_body["results"]))
  999. self.assertEqual(
  1000. delete_id, channel_room_id.json_body["results"][0]["delete_id"]
  1001. )
  1002. # get information by delete_id
  1003. channel_delete_id = self.make_request(
  1004. "GET",
  1005. self.url_status_by_delete_id + delete_id,
  1006. access_token=self.admin_user_tok,
  1007. )
  1008. self.assertEqual(
  1009. 200,
  1010. channel_delete_id.code,
  1011. msg=channel_delete_id.json_body,
  1012. )
  1013. # test values that are the same in both responses
  1014. for content in [
  1015. channel_room_id.json_body["results"][0],
  1016. channel_delete_id.json_body,
  1017. ]:
  1018. self.assertEqual("complete", content["status"])
  1019. self.assertEqual(kicked_user, content["shutdown_room"]["kicked_users"][0])
  1020. self.assertIn("failed_to_kick_users", content["shutdown_room"])
  1021. self.assertIn("local_aliases", content["shutdown_room"])
  1022. self.assertNotIn("error", content)
  1023. if expect_new_room:
  1024. self.assertIsNotNone(content["shutdown_room"]["new_room_id"])
  1025. else:
  1026. self.assertIsNone(content["shutdown_room"]["new_room_id"])
  1027. class RoomTestCase(unittest.HomeserverTestCase):
  1028. """Test /room admin API."""
  1029. servlets = [
  1030. synapse.rest.admin.register_servlets,
  1031. login.register_servlets,
  1032. room.register_servlets,
  1033. directory.register_servlets,
  1034. ]
  1035. def prepare(self, reactor: MemoryReactor, clock: Clock, hs: HomeServer) -> None:
  1036. # Create user
  1037. self.admin_user = self.register_user("admin", "pass", admin=True)
  1038. self.admin_user_tok = self.login("admin", "pass")
  1039. def test_list_rooms(self) -> None:
  1040. """Test that we can list rooms"""
  1041. # Create 3 test rooms
  1042. total_rooms = 3
  1043. room_ids = []
  1044. for _ in range(total_rooms):
  1045. room_id = self.helper.create_room_as(
  1046. self.admin_user,
  1047. tok=self.admin_user_tok,
  1048. is_public=True,
  1049. )
  1050. room_ids.append(room_id)
  1051. room_ids.sort()
  1052. # Request the list of rooms
  1053. url = "/_synapse/admin/v1/rooms"
  1054. channel = self.make_request(
  1055. "GET",
  1056. url.encode("ascii"),
  1057. access_token=self.admin_user_tok,
  1058. )
  1059. # Check request completed successfully
  1060. self.assertEqual(200, channel.code, msg=channel.json_body)
  1061. # Check that response json body contains a "rooms" key
  1062. self.assertTrue(
  1063. "rooms" in channel.json_body,
  1064. msg="Response body does not " "contain a 'rooms' key",
  1065. )
  1066. # Check that 3 rooms were returned
  1067. self.assertEqual(3, len(channel.json_body["rooms"]), msg=channel.json_body)
  1068. # Check their room_ids match
  1069. returned_room_ids = [room["room_id"] for room in channel.json_body["rooms"]]
  1070. self.assertEqual(room_ids, returned_room_ids)
  1071. # Check that all fields are available
  1072. for r in channel.json_body["rooms"]:
  1073. self.assertIn("name", r)
  1074. self.assertIn("canonical_alias", r)
  1075. self.assertIn("joined_members", r)
  1076. self.assertIn("joined_local_members", r)
  1077. self.assertIn("version", r)
  1078. self.assertIn("creator", r)
  1079. self.assertIn("encryption", r)
  1080. self.assertIs(r["federatable"], True)
  1081. self.assertIs(r["public"], True)
  1082. self.assertIn("join_rules", r)
  1083. self.assertIn("guest_access", r)
  1084. self.assertIn("history_visibility", r)
  1085. self.assertIn("state_events", r)
  1086. self.assertIn("room_type", r)
  1087. self.assertIsNone(r["room_type"])
  1088. # Check that the correct number of total rooms was returned
  1089. self.assertEqual(channel.json_body["total_rooms"], total_rooms)
  1090. # Check that the offset is correct
  1091. # Should be 0 as we aren't paginating
  1092. self.assertEqual(channel.json_body["offset"], 0)
  1093. # Check that the prev_batch parameter is not present
  1094. self.assertNotIn("prev_batch", channel.json_body)
  1095. # We shouldn't receive a next token here as there's no further rooms to show
  1096. self.assertNotIn("next_batch", channel.json_body)
  1097. def test_list_rooms_pagination(self) -> None:
  1098. """Test that we can get a full list of rooms through pagination"""
  1099. # Create 5 test rooms
  1100. total_rooms = 5
  1101. room_ids = []
  1102. for _ in range(total_rooms):
  1103. room_id = self.helper.create_room_as(
  1104. self.admin_user, tok=self.admin_user_tok
  1105. )
  1106. room_ids.append(room_id)
  1107. # Set the name of the rooms so we get a consistent returned ordering
  1108. for idx, room_id in enumerate(room_ids):
  1109. self.helper.send_state(
  1110. room_id,
  1111. "m.room.name",
  1112. {"name": str(idx)},
  1113. tok=self.admin_user_tok,
  1114. )
  1115. # Request the list of rooms
  1116. returned_room_ids = []
  1117. start = 0
  1118. limit = 2
  1119. run_count = 0
  1120. should_repeat = True
  1121. while should_repeat:
  1122. run_count += 1
  1123. url = "/_synapse/admin/v1/rooms?from=%d&limit=%d&order_by=%s" % (
  1124. start,
  1125. limit,
  1126. "name",
  1127. )
  1128. channel = self.make_request(
  1129. "GET",
  1130. url.encode("ascii"),
  1131. access_token=self.admin_user_tok,
  1132. )
  1133. self.assertEqual(200, channel.code, msg=channel.json_body)
  1134. self.assertTrue("rooms" in channel.json_body)
  1135. for r in channel.json_body["rooms"]:
  1136. returned_room_ids.append(r["room_id"])
  1137. # Check that the correct number of total rooms was returned
  1138. self.assertEqual(channel.json_body["total_rooms"], total_rooms)
  1139. # Check that the offset is correct
  1140. # We're only getting 2 rooms each page, so should be 2 * last run_count
  1141. self.assertEqual(channel.json_body["offset"], 2 * (run_count - 1))
  1142. if run_count > 1:
  1143. # Check the value of prev_batch is correct
  1144. self.assertEqual(channel.json_body["prev_batch"], 2 * (run_count - 2))
  1145. if "next_batch" not in channel.json_body:
  1146. # We have reached the end of the list
  1147. should_repeat = False
  1148. else:
  1149. # Make another query with an updated start value
  1150. start = channel.json_body["next_batch"]
  1151. # We should've queried the endpoint 3 times
  1152. self.assertEqual(
  1153. run_count,
  1154. 3,
  1155. msg="Should've queried 3 times for 5 rooms with limit 2 per query",
  1156. )
  1157. # Check that we received all of the room ids
  1158. self.assertEqual(room_ids, returned_room_ids)
  1159. url = "/_synapse/admin/v1/rooms?from=%d&limit=%d" % (start, limit)
  1160. channel = self.make_request(
  1161. "GET",
  1162. url.encode("ascii"),
  1163. access_token=self.admin_user_tok,
  1164. )
  1165. self.assertEqual(200, channel.code, msg=channel.json_body)
  1166. def test_correct_room_attributes(self) -> None:
  1167. """Test the correct attributes for a room are returned"""
  1168. # Create a test room
  1169. room_id = self.helper.create_room_as(
  1170. self.admin_user,
  1171. tok=self.admin_user_tok,
  1172. extra_content={"creation_content": {"type": RoomTypes.SPACE}},
  1173. )
  1174. test_alias = "#test:test"
  1175. test_room_name = "something"
  1176. # Have another user join the room
  1177. user_2 = self.register_user("user4", "pass")
  1178. user_tok_2 = self.login("user4", "pass")
  1179. self.helper.join(room_id, user_2, tok=user_tok_2)
  1180. # Create a new alias to this room
  1181. url = "/_matrix/client/r0/directory/room/%s" % (urllib.parse.quote(test_alias),)
  1182. channel = self.make_request(
  1183. "PUT",
  1184. url.encode("ascii"),
  1185. {"room_id": room_id},
  1186. access_token=self.admin_user_tok,
  1187. )
  1188. self.assertEqual(200, channel.code, msg=channel.json_body)
  1189. # Set this new alias as the canonical alias for this room
  1190. self.helper.send_state(
  1191. room_id,
  1192. "m.room.aliases",
  1193. {"aliases": [test_alias]},
  1194. tok=self.admin_user_tok,
  1195. state_key="test",
  1196. )
  1197. self.helper.send_state(
  1198. room_id,
  1199. "m.room.canonical_alias",
  1200. {"alias": test_alias},
  1201. tok=self.admin_user_tok,
  1202. )
  1203. # Set a name for the room
  1204. self.helper.send_state(
  1205. room_id,
  1206. "m.room.name",
  1207. {"name": test_room_name},
  1208. tok=self.admin_user_tok,
  1209. )
  1210. # Request the list of rooms
  1211. url = "/_synapse/admin/v1/rooms"
  1212. channel = self.make_request(
  1213. "GET",
  1214. url.encode("ascii"),
  1215. access_token=self.admin_user_tok,
  1216. )
  1217. self.assertEqual(200, channel.code, msg=channel.json_body)
  1218. # Check that rooms were returned
  1219. self.assertTrue("rooms" in channel.json_body)
  1220. rooms = channel.json_body["rooms"]
  1221. # Check that only one room was returned
  1222. self.assertEqual(len(rooms), 1)
  1223. # And that the value of the total_rooms key was correct
  1224. self.assertEqual(channel.json_body["total_rooms"], 1)
  1225. # Check that the offset is correct
  1226. # We're not paginating, so should be 0
  1227. self.assertEqual(channel.json_body["offset"], 0)
  1228. # Check that there is no `prev_batch`
  1229. self.assertNotIn("prev_batch", channel.json_body)
  1230. # Check that there is no `next_batch`
  1231. self.assertNotIn("next_batch", channel.json_body)
  1232. # Check that all provided attributes are set
  1233. r = rooms[0]
  1234. self.assertEqual(room_id, r["room_id"])
  1235. self.assertEqual(test_room_name, r["name"])
  1236. self.assertEqual(test_alias, r["canonical_alias"])
  1237. self.assertEqual(RoomTypes.SPACE, r["room_type"])
  1238. def test_room_list_sort_order(self) -> None:
  1239. """Test room list sort ordering. alphabetical name versus number of members,
  1240. reversing the order, etc.
  1241. """
  1242. def _order_test(
  1243. order_type: str,
  1244. expected_room_list: List[str],
  1245. reverse: bool = False,
  1246. ) -> None:
  1247. """Request the list of rooms in a certain order. Assert that order is what
  1248. we expect
  1249. Args:
  1250. order_type: The type of ordering to give the server
  1251. expected_room_list: The list of room_ids in the order we expect to get
  1252. back from the server
  1253. """
  1254. # Request the list of rooms in the given order
  1255. url = "/_synapse/admin/v1/rooms?order_by=%s" % (order_type,)
  1256. if reverse:
  1257. url += "&dir=b"
  1258. channel = self.make_request(
  1259. "GET",
  1260. url.encode("ascii"),
  1261. access_token=self.admin_user_tok,
  1262. )
  1263. self.assertEqual(200, channel.code, msg=channel.json_body)
  1264. # Check that rooms were returned
  1265. self.assertTrue("rooms" in channel.json_body)
  1266. rooms = channel.json_body["rooms"]
  1267. # Check for the correct total_rooms value
  1268. self.assertEqual(channel.json_body["total_rooms"], 3)
  1269. # Check that the offset is correct
  1270. # We're not paginating, so should be 0
  1271. self.assertEqual(channel.json_body["offset"], 0)
  1272. # Check that there is no `prev_batch`
  1273. self.assertNotIn("prev_batch", channel.json_body)
  1274. # Check that there is no `next_batch`
  1275. self.assertNotIn("next_batch", channel.json_body)
  1276. # Check that rooms were returned in alphabetical order
  1277. returned_order = [r["room_id"] for r in rooms]
  1278. self.assertListEqual(expected_room_list, returned_order) # order is checked
  1279. # Create 3 test rooms
  1280. room_id_1 = self.helper.create_room_as(self.admin_user, tok=self.admin_user_tok)
  1281. room_id_2 = self.helper.create_room_as(self.admin_user, tok=self.admin_user_tok)
  1282. room_id_3 = self.helper.create_room_as(self.admin_user, tok=self.admin_user_tok)
  1283. # Also create a list sorted by IDs for properties that are equal (and thus sorted by room_id)
  1284. sorted_by_room_id_asc = [room_id_1, room_id_2, room_id_3]
  1285. sorted_by_room_id_asc.sort()
  1286. sorted_by_room_id_desc = sorted_by_room_id_asc.copy()
  1287. sorted_by_room_id_desc.reverse()
  1288. # Set room names in alphabetical order. room 1 -> A, 2 -> B, 3 -> C
  1289. self.helper.send_state(
  1290. room_id_1,
  1291. "m.room.name",
  1292. {"name": "A"},
  1293. tok=self.admin_user_tok,
  1294. )
  1295. self.helper.send_state(
  1296. room_id_2,
  1297. "m.room.name",
  1298. {"name": "B"},
  1299. tok=self.admin_user_tok,
  1300. )
  1301. self.helper.send_state(
  1302. room_id_3,
  1303. "m.room.name",
  1304. {"name": "C"},
  1305. tok=self.admin_user_tok,
  1306. )
  1307. # Set room canonical room aliases
  1308. self._set_canonical_alias(room_id_1, "#A_alias:test", self.admin_user_tok)
  1309. self._set_canonical_alias(room_id_2, "#B_alias:test", self.admin_user_tok)
  1310. self._set_canonical_alias(room_id_3, "#C_alias:test", self.admin_user_tok)
  1311. # Set room member size in the reverse order. room 1 -> 1 member, 2 -> 2, 3 -> 3
  1312. user_1 = self.register_user("bob1", "pass")
  1313. user_1_tok = self.login("bob1", "pass")
  1314. self.helper.join(room_id_2, user_1, tok=user_1_tok)
  1315. user_2 = self.register_user("bob2", "pass")
  1316. user_2_tok = self.login("bob2", "pass")
  1317. self.helper.join(room_id_3, user_2, tok=user_2_tok)
  1318. user_3 = self.register_user("bob3", "pass")
  1319. user_3_tok = self.login("bob3", "pass")
  1320. self.helper.join(room_id_3, user_3, tok=user_3_tok)
  1321. # Test different sort orders, with forward and reverse directions
  1322. _order_test("name", [room_id_1, room_id_2, room_id_3])
  1323. _order_test("name", [room_id_3, room_id_2, room_id_1], reverse=True)
  1324. _order_test("canonical_alias", [room_id_1, room_id_2, room_id_3])
  1325. _order_test("canonical_alias", [room_id_3, room_id_2, room_id_1], reverse=True)
  1326. # Note: joined_member counts are sorted in descending order when dir=f
  1327. _order_test("joined_members", [room_id_3, room_id_2, room_id_1])
  1328. _order_test("joined_members", [room_id_1, room_id_2, room_id_3], reverse=True)
  1329. # Note: joined_local_member counts are sorted in descending order when dir=f
  1330. _order_test("joined_local_members", [room_id_3, room_id_2, room_id_1])
  1331. _order_test(
  1332. "joined_local_members", [room_id_1, room_id_2, room_id_3], reverse=True
  1333. )
  1334. # Note: versions are sorted in descending order when dir=f
  1335. _order_test("version", sorted_by_room_id_asc, reverse=True)
  1336. _order_test("version", sorted_by_room_id_desc)
  1337. _order_test("creator", sorted_by_room_id_asc)
  1338. _order_test("creator", sorted_by_room_id_desc, reverse=True)
  1339. _order_test("encryption", sorted_by_room_id_asc)
  1340. _order_test("encryption", sorted_by_room_id_desc, reverse=True)
  1341. _order_test("federatable", sorted_by_room_id_asc)
  1342. _order_test("federatable", sorted_by_room_id_desc, reverse=True)
  1343. _order_test("public", sorted_by_room_id_asc)
  1344. _order_test("public", sorted_by_room_id_desc, reverse=True)
  1345. _order_test("join_rules", sorted_by_room_id_asc)
  1346. _order_test("join_rules", sorted_by_room_id_desc, reverse=True)
  1347. _order_test("guest_access", sorted_by_room_id_asc)
  1348. _order_test("guest_access", sorted_by_room_id_desc, reverse=True)
  1349. _order_test("history_visibility", sorted_by_room_id_asc)
  1350. _order_test("history_visibility", sorted_by_room_id_desc, reverse=True)
  1351. # Note: state_event counts are sorted in descending order when dir=f
  1352. _order_test("state_events", [room_id_3, room_id_2, room_id_1])
  1353. _order_test("state_events", [room_id_1, room_id_2, room_id_3], reverse=True)
  1354. def test_search_term(self) -> None:
  1355. """Test that searching for a room works correctly"""
  1356. # Create two test rooms
  1357. room_id_1 = self.helper.create_room_as(self.admin_user, tok=self.admin_user_tok)
  1358. room_id_2 = self.helper.create_room_as(self.admin_user, tok=self.admin_user_tok)
  1359. room_name_1 = "something"
  1360. room_name_2 = "LoremIpsum"
  1361. # Set the name for each room
  1362. self.helper.send_state(
  1363. room_id_1,
  1364. "m.room.name",
  1365. {"name": room_name_1},
  1366. tok=self.admin_user_tok,
  1367. )
  1368. self.helper.send_state(
  1369. room_id_2,
  1370. "m.room.name",
  1371. {"name": room_name_2},
  1372. tok=self.admin_user_tok,
  1373. )
  1374. self._set_canonical_alias(room_id_1, "#Room_Alias1:test", self.admin_user_tok)
  1375. def _search_test(
  1376. expected_room_id: Optional[str],
  1377. search_term: str,
  1378. expected_http_code: int = 200,
  1379. ) -> None:
  1380. """Search for a room and check that the returned room's id is a match
  1381. Args:
  1382. expected_room_id: The room_id expected to be returned by the API. Set
  1383. to None to expect zero results for the search
  1384. search_term: The term to search for room names with
  1385. expected_http_code: The expected http code for the request
  1386. """
  1387. url = "/_synapse/admin/v1/rooms?search_term=%s" % (search_term,)
  1388. channel = self.make_request(
  1389. "GET",
  1390. url.encode("ascii"),
  1391. access_token=self.admin_user_tok,
  1392. )
  1393. self.assertEqual(expected_http_code, channel.code, msg=channel.json_body)
  1394. if expected_http_code != 200:
  1395. return
  1396. # Check that rooms were returned
  1397. self.assertTrue("rooms" in channel.json_body)
  1398. rooms = channel.json_body["rooms"]
  1399. # Check that the expected number of rooms were returned
  1400. expected_room_count = 1 if expected_room_id else 0
  1401. self.assertEqual(len(rooms), expected_room_count)
  1402. self.assertEqual(channel.json_body["total_rooms"], expected_room_count)
  1403. # Check that the offset is correct
  1404. # We're not paginating, so should be 0
  1405. self.assertEqual(channel.json_body["offset"], 0)
  1406. # Check that there is no `prev_batch`
  1407. self.assertNotIn("prev_batch", channel.json_body)
  1408. # Check that there is no `next_batch`
  1409. self.assertNotIn("next_batch", channel.json_body)
  1410. if expected_room_id:
  1411. # Check that the first returned room id is correct
  1412. r = rooms[0]
  1413. self.assertEqual(expected_room_id, r["room_id"])
  1414. # Test searching by room name
  1415. _search_test(room_id_1, "something")
  1416. _search_test(room_id_1, "thing")
  1417. _search_test(room_id_2, "LoremIpsum")
  1418. _search_test(room_id_2, "lorem")
  1419. # Test case insensitive
  1420. _search_test(room_id_1, "SOMETHING")
  1421. _search_test(room_id_1, "THING")
  1422. _search_test(room_id_2, "LOREMIPSUM")
  1423. _search_test(room_id_2, "LOREM")
  1424. _search_test(None, "foo")
  1425. _search_test(None, "bar")
  1426. _search_test(None, "", expected_http_code=400)
  1427. # Test that the whole room id returns the room
  1428. _search_test(room_id_1, room_id_1)
  1429. # Test that the search by room_id is case sensitive
  1430. _search_test(None, room_id_1.lower())
  1431. # Test search part of local part of room id do not match
  1432. _search_test(None, room_id_1[1:10])
  1433. # Test that whole room alias return no result, because of domain
  1434. _search_test(None, "#Room_Alias1:test")
  1435. # Test search local part of alias
  1436. _search_test(room_id_1, "alias1")
  1437. def test_search_term_non_ascii(self) -> None:
  1438. """Test that searching for a room with non-ASCII characters works correctly"""
  1439. # Create test room
  1440. room_id = self.helper.create_room_as(self.admin_user, tok=self.admin_user_tok)
  1441. room_name = "ж"
  1442. # Set the name for the room
  1443. self.helper.send_state(
  1444. room_id,
  1445. "m.room.name",
  1446. {"name": room_name},
  1447. tok=self.admin_user_tok,
  1448. )
  1449. # make the request and test that the response is what we wanted
  1450. search_term = urllib.parse.quote("ж", "utf-8")
  1451. url = "/_synapse/admin/v1/rooms?search_term=%s" % (search_term,)
  1452. channel = self.make_request(
  1453. "GET",
  1454. url.encode("ascii"),
  1455. access_token=self.admin_user_tok,
  1456. )
  1457. self.assertEqual(200, channel.code, msg=channel.json_body)
  1458. self.assertEqual(room_id, channel.json_body["rooms"][0].get("room_id"))
  1459. self.assertEqual("ж", channel.json_body["rooms"][0].get("name"))
  1460. def test_single_room(self) -> None:
  1461. """Test that a single room can be requested correctly"""
  1462. # Create two test rooms
  1463. room_id_1 = self.helper.create_room_as(
  1464. self.admin_user, tok=self.admin_user_tok, is_public=True
  1465. )
  1466. room_id_2 = self.helper.create_room_as(
  1467. self.admin_user, tok=self.admin_user_tok, is_public=False
  1468. )
  1469. room_name_1 = "something"
  1470. room_name_2 = "else"
  1471. # Set the name for each room
  1472. self.helper.send_state(
  1473. room_id_1,
  1474. "m.room.name",
  1475. {"name": room_name_1},
  1476. tok=self.admin_user_tok,
  1477. )
  1478. self.helper.send_state(
  1479. room_id_2,
  1480. "m.room.name",
  1481. {"name": room_name_2},
  1482. tok=self.admin_user_tok,
  1483. )
  1484. url = "/_synapse/admin/v1/rooms/%s" % (room_id_1,)
  1485. channel = self.make_request(
  1486. "GET",
  1487. url.encode("ascii"),
  1488. access_token=self.admin_user_tok,
  1489. )
  1490. self.assertEqual(200, channel.code, msg=channel.json_body)
  1491. self.assertIn("room_id", channel.json_body)
  1492. self.assertIn("name", channel.json_body)
  1493. self.assertIn("topic", channel.json_body)
  1494. self.assertIn("avatar", channel.json_body)
  1495. self.assertIn("canonical_alias", channel.json_body)
  1496. self.assertIn("joined_members", channel.json_body)
  1497. self.assertIn("joined_local_members", channel.json_body)
  1498. self.assertIn("joined_local_devices", channel.json_body)
  1499. self.assertIn("version", channel.json_body)
  1500. self.assertIn("creator", channel.json_body)
  1501. self.assertIn("encryption", channel.json_body)
  1502. self.assertIn("federatable", channel.json_body)
  1503. self.assertIn("public", channel.json_body)
  1504. self.assertIn("join_rules", channel.json_body)
  1505. self.assertIn("guest_access", channel.json_body)
  1506. self.assertIn("history_visibility", channel.json_body)
  1507. self.assertIn("state_events", channel.json_body)
  1508. self.assertIn("room_type", channel.json_body)
  1509. self.assertIn("forgotten", channel.json_body)
  1510. self.assertEqual(room_id_1, channel.json_body["room_id"])
  1511. self.assertIs(True, channel.json_body["federatable"])
  1512. self.assertIs(True, channel.json_body["public"])
  1513. def test_single_room_devices(self) -> None:
  1514. """Test that `joined_local_devices` can be requested correctly"""
  1515. room_id_1 = self.helper.create_room_as(self.admin_user, tok=self.admin_user_tok)
  1516. url = "/_synapse/admin/v1/rooms/%s" % (room_id_1,)
  1517. channel = self.make_request(
  1518. "GET",
  1519. url.encode("ascii"),
  1520. access_token=self.admin_user_tok,
  1521. )
  1522. self.assertEqual(200, channel.code, msg=channel.json_body)
  1523. self.assertEqual(1, channel.json_body["joined_local_devices"])
  1524. # Have another user join the room
  1525. user_1 = self.register_user("foo", "pass")
  1526. user_tok_1 = self.login("foo", "pass")
  1527. self.helper.join(room_id_1, user_1, tok=user_tok_1)
  1528. url = "/_synapse/admin/v1/rooms/%s" % (room_id_1,)
  1529. channel = self.make_request(
  1530. "GET",
  1531. url.encode("ascii"),
  1532. access_token=self.admin_user_tok,
  1533. )
  1534. self.assertEqual(200, channel.code, msg=channel.json_body)
  1535. self.assertEqual(2, channel.json_body["joined_local_devices"])
  1536. # leave room
  1537. self.helper.leave(room_id_1, self.admin_user, tok=self.admin_user_tok)
  1538. self.helper.leave(room_id_1, user_1, tok=user_tok_1)
  1539. url = "/_synapse/admin/v1/rooms/%s" % (room_id_1,)
  1540. channel = self.make_request(
  1541. "GET",
  1542. url.encode("ascii"),
  1543. access_token=self.admin_user_tok,
  1544. )
  1545. self.assertEqual(200, channel.code, msg=channel.json_body)
  1546. self.assertEqual(0, channel.json_body["joined_local_devices"])
  1547. def test_room_members(self) -> None:
  1548. """Test that room members can be requested correctly"""
  1549. # Create two test rooms
  1550. room_id_1 = self.helper.create_room_as(self.admin_user, tok=self.admin_user_tok)
  1551. room_id_2 = self.helper.create_room_as(self.admin_user, tok=self.admin_user_tok)
  1552. # Have another user join the room
  1553. user_1 = self.register_user("foo", "pass")
  1554. user_tok_1 = self.login("foo", "pass")
  1555. self.helper.join(room_id_1, user_1, tok=user_tok_1)
  1556. # Have another user join the room
  1557. user_2 = self.register_user("bar", "pass")
  1558. user_tok_2 = self.login("bar", "pass")
  1559. self.helper.join(room_id_1, user_2, tok=user_tok_2)
  1560. self.helper.join(room_id_2, user_2, tok=user_tok_2)
  1561. # Have another user join the room
  1562. user_3 = self.register_user("foobar", "pass")
  1563. user_tok_3 = self.login("foobar", "pass")
  1564. self.helper.join(room_id_2, user_3, tok=user_tok_3)
  1565. url = "/_synapse/admin/v1/rooms/%s/members" % (room_id_1,)
  1566. channel = self.make_request(
  1567. "GET",
  1568. url.encode("ascii"),
  1569. access_token=self.admin_user_tok,
  1570. )
  1571. self.assertEqual(200, channel.code, msg=channel.json_body)
  1572. self.assertCountEqual(
  1573. ["@admin:test", "@foo:test", "@bar:test"], channel.json_body["members"]
  1574. )
  1575. self.assertEqual(channel.json_body["total"], 3)
  1576. url = "/_synapse/admin/v1/rooms/%s/members" % (room_id_2,)
  1577. channel = self.make_request(
  1578. "GET",
  1579. url.encode("ascii"),
  1580. access_token=self.admin_user_tok,
  1581. )
  1582. self.assertEqual(200, channel.code, msg=channel.json_body)
  1583. self.assertCountEqual(
  1584. ["@admin:test", "@bar:test", "@foobar:test"], channel.json_body["members"]
  1585. )
  1586. self.assertEqual(channel.json_body["total"], 3)
  1587. def test_room_state(self) -> None:
  1588. """Test that room state can be requested correctly"""
  1589. # Create two test rooms
  1590. room_id = self.helper.create_room_as(self.admin_user, tok=self.admin_user_tok)
  1591. url = "/_synapse/admin/v1/rooms/%s/state" % (room_id,)
  1592. channel = self.make_request(
  1593. "GET",
  1594. url.encode("ascii"),
  1595. access_token=self.admin_user_tok,
  1596. )
  1597. self.assertEqual(200, channel.code, msg=channel.json_body)
  1598. self.assertIn("state", channel.json_body)
  1599. # testing that the state events match is painful and not done here. We assume that
  1600. # the create_room already does the right thing, so no need to verify that we got
  1601. # the state events it created.
  1602. def _set_canonical_alias(
  1603. self, room_id: str, test_alias: str, admin_user_tok: str
  1604. ) -> None:
  1605. # Create a new alias to this room
  1606. url = "/_matrix/client/r0/directory/room/%s" % (urllib.parse.quote(test_alias),)
  1607. channel = self.make_request(
  1608. "PUT",
  1609. url.encode("ascii"),
  1610. {"room_id": room_id},
  1611. access_token=admin_user_tok,
  1612. )
  1613. self.assertEqual(200, channel.code, msg=channel.json_body)
  1614. # Set this new alias as the canonical alias for this room
  1615. self.helper.send_state(
  1616. room_id,
  1617. "m.room.aliases",
  1618. {"aliases": [test_alias]},
  1619. tok=admin_user_tok,
  1620. state_key="test",
  1621. )
  1622. self.helper.send_state(
  1623. room_id,
  1624. "m.room.canonical_alias",
  1625. {"alias": test_alias},
  1626. tok=admin_user_tok,
  1627. )
  1628. def test_get_joined_members_after_leave_room(self) -> None:
  1629. """Test that requesting room members after leaving the room raises a 403 error."""
  1630. # create the room
  1631. user = self.register_user("foo", "pass")
  1632. user_tok = self.login("foo", "pass")
  1633. room_id = self.helper.create_room_as(user, tok=user_tok)
  1634. self.helper.leave(room_id, user, tok=user_tok)
  1635. # delete the rooms and get joined roomed membership
  1636. url = f"/_matrix/client/r0/rooms/{room_id}/joined_members"
  1637. channel = self.make_request("GET", url.encode("ascii"), access_token=user_tok)
  1638. self.assertEqual(403, channel.code, msg=channel.json_body)
  1639. self.assertEqual(Codes.FORBIDDEN, channel.json_body["errcode"])
  1640. class RoomMessagesTestCase(unittest.HomeserverTestCase):
  1641. servlets = [
  1642. synapse.rest.admin.register_servlets,
  1643. login.register_servlets,
  1644. room.register_servlets,
  1645. ]
  1646. def prepare(self, reactor: MemoryReactor, clock: Clock, hs: HomeServer) -> None:
  1647. self.admin_user = self.register_user("admin", "pass", admin=True)
  1648. self.admin_user_tok = self.login("admin", "pass")
  1649. self.user = self.register_user("foo", "pass")
  1650. self.user_tok = self.login("foo", "pass")
  1651. self.room_id = self.helper.create_room_as(self.user, tok=self.user_tok)
  1652. def test_timestamp_to_event(self) -> None:
  1653. """Test that providing the current timestamp can get the last event."""
  1654. self.helper.send(self.room_id, body="message 1", tok=self.user_tok)
  1655. second_event_id = self.helper.send(
  1656. self.room_id, body="message 2", tok=self.user_tok
  1657. )["event_id"]
  1658. ts = str(round(time.time() * 1000))
  1659. channel = self.make_request(
  1660. "GET",
  1661. "/_synapse/admin/v1/rooms/%s/timestamp_to_event?dir=b&ts=%s"
  1662. % (self.room_id, ts),
  1663. access_token=self.admin_user_tok,
  1664. )
  1665. self.assertEqual(200, channel.code)
  1666. self.assertIn("event_id", channel.json_body)
  1667. self.assertEqual(second_event_id, channel.json_body["event_id"])
  1668. def test_topo_token_is_accepted(self) -> None:
  1669. """Test Topo Token is accepted."""
  1670. token = "t1-0_0_0_0_0_0_0_0_0_0"
  1671. channel = self.make_request(
  1672. "GET",
  1673. "/_synapse/admin/v1/rooms/%s/messages?from=%s" % (self.room_id, token),
  1674. access_token=self.admin_user_tok,
  1675. )
  1676. self.assertEqual(200, channel.code)
  1677. self.assertIn("start", channel.json_body)
  1678. self.assertEqual(token, channel.json_body["start"])
  1679. self.assertIn("chunk", channel.json_body)
  1680. self.assertIn("end", channel.json_body)
  1681. def test_stream_token_is_accepted_for_fwd_pagianation(self) -> None:
  1682. """Test that stream token is accepted for forward pagination."""
  1683. token = "s0_0_0_0_0_0_0_0_0_0"
  1684. channel = self.make_request(
  1685. "GET",
  1686. "/_synapse/admin/v1/rooms/%s/messages?from=%s" % (self.room_id, token),
  1687. access_token=self.admin_user_tok,
  1688. )
  1689. self.assertEqual(200, channel.code)
  1690. self.assertIn("start", channel.json_body)
  1691. self.assertEqual(token, channel.json_body["start"])
  1692. self.assertIn("chunk", channel.json_body)
  1693. self.assertIn("end", channel.json_body)
  1694. def test_room_messages_backward(self) -> None:
  1695. """Test room messages can be retrieved by an admin that isn't in the room."""
  1696. latest_event_id = self.helper.send(
  1697. self.room_id, body="message 1", tok=self.user_tok
  1698. )["event_id"]
  1699. # Check that we get the first and second message when querying /messages.
  1700. channel = self.make_request(
  1701. "GET",
  1702. "/_synapse/admin/v1/rooms/%s/messages?dir=b" % (self.room_id,),
  1703. access_token=self.admin_user_tok,
  1704. )
  1705. self.assertEqual(channel.code, 200, channel.json_body)
  1706. chunk = channel.json_body["chunk"]
  1707. self.assertEqual(len(chunk), 6, [event["content"] for event in chunk])
  1708. # in backwards, this is the first event
  1709. self.assertEqual(chunk[0]["event_id"], latest_event_id)
  1710. def test_room_messages_forward(self) -> None:
  1711. """Test room messages can be retrieved by an admin that isn't in the room."""
  1712. latest_event_id = self.helper.send(
  1713. self.room_id, body="message 1", tok=self.user_tok
  1714. )["event_id"]
  1715. # Check that we get the first and second message when querying /messages.
  1716. channel = self.make_request(
  1717. "GET",
  1718. "/_synapse/admin/v1/rooms/%s/messages?dir=f" % (self.room_id,),
  1719. access_token=self.admin_user_tok,
  1720. )
  1721. self.assertEqual(channel.code, 200, channel.json_body)
  1722. chunk = channel.json_body["chunk"]
  1723. self.assertEqual(len(chunk), 6, [event["content"] for event in chunk])
  1724. # in forward, this is the last event
  1725. self.assertEqual(chunk[5]["event_id"], latest_event_id)
  1726. def test_room_messages_purge(self) -> None:
  1727. """Test room messages can be retrieved by an admin that isn't in the room."""
  1728. store = self.hs.get_datastores().main
  1729. pagination_handler = self.hs.get_pagination_handler()
  1730. # Send a first message in the room, which will be removed by the purge.
  1731. first_event_id = self.helper.send(
  1732. self.room_id, body="message 1", tok=self.user_tok
  1733. )["event_id"]
  1734. first_token = self.get_success(
  1735. store.get_topological_token_for_event(first_event_id)
  1736. )
  1737. first_token_str = self.get_success(first_token.to_string(store))
  1738. # Send a second message in the room, which won't be removed, and which we'll
  1739. # use as the marker to purge events before.
  1740. second_event_id = self.helper.send(
  1741. self.room_id, body="message 2", tok=self.user_tok
  1742. )["event_id"]
  1743. second_token = self.get_success(
  1744. store.get_topological_token_for_event(second_event_id)
  1745. )
  1746. second_token_str = self.get_success(second_token.to_string(store))
  1747. # Send a third event in the room to ensure we don't fall under any edge case
  1748. # due to our marker being the latest forward extremity in the room.
  1749. self.helper.send(self.room_id, body="message 3", tok=self.user_tok)
  1750. # Check that we get the first and second message when querying /messages.
  1751. channel = self.make_request(
  1752. "GET",
  1753. "/_synapse/admin/v1/rooms/%s/messages?from=%s&dir=b&filter=%s"
  1754. % (
  1755. self.room_id,
  1756. second_token_str,
  1757. json.dumps({"types": [EventTypes.Message]}),
  1758. ),
  1759. access_token=self.admin_user_tok,
  1760. )
  1761. self.assertEqual(channel.code, 200, channel.json_body)
  1762. chunk = channel.json_body["chunk"]
  1763. self.assertEqual(len(chunk), 2, [event["content"] for event in chunk])
  1764. # Purge every event before the second event.
  1765. self.get_success(
  1766. pagination_handler.purge_history(
  1767. room_id=self.room_id,
  1768. token=second_token_str,
  1769. delete_local_events=True,
  1770. )
  1771. )
  1772. # Check that we only get the second message through /message now that the first
  1773. # has been purged.
  1774. channel = self.make_request(
  1775. "GET",
  1776. "/_synapse/admin/v1/rooms/%s/messages?from=%s&dir=b&filter=%s"
  1777. % (
  1778. self.room_id,
  1779. second_token_str,
  1780. json.dumps({"types": [EventTypes.Message]}),
  1781. ),
  1782. access_token=self.admin_user_tok,
  1783. )
  1784. self.assertEqual(channel.code, 200, channel.json_body)
  1785. chunk = channel.json_body["chunk"]
  1786. self.assertEqual(len(chunk), 1, [event["content"] for event in chunk])
  1787. # Check that we get no event, but also no error, when querying /messages with
  1788. # the token that was pointing at the first event, because we don't have it
  1789. # anymore.
  1790. channel = self.make_request(
  1791. "GET",
  1792. "/_synapse/admin/v1/rooms/%s/messages?from=%s&dir=b&filter=%s"
  1793. % (
  1794. self.room_id,
  1795. first_token_str,
  1796. json.dumps({"types": [EventTypes.Message]}),
  1797. ),
  1798. access_token=self.admin_user_tok,
  1799. )
  1800. self.assertEqual(channel.code, 200, channel.json_body)
  1801. chunk = channel.json_body["chunk"]
  1802. self.assertEqual(len(chunk), 0, [event["content"] for event in chunk])
  1803. class JoinAliasRoomTestCase(unittest.HomeserverTestCase):
  1804. servlets = [
  1805. synapse.rest.admin.register_servlets,
  1806. room.register_servlets,
  1807. login.register_servlets,
  1808. ]
  1809. def prepare(self, reactor: MemoryReactor, clock: Clock, hs: HomeServer) -> None:
  1810. self.admin_user = self.register_user("admin", "pass", admin=True)
  1811. self.admin_user_tok = self.login("admin", "pass")
  1812. self.creator = self.register_user("creator", "test")
  1813. self.creator_tok = self.login("creator", "test")
  1814. self.second_user_id = self.register_user("second", "test")
  1815. self.second_tok = self.login("second", "test")
  1816. self.public_room_id = self.helper.create_room_as(
  1817. self.creator, tok=self.creator_tok, is_public=True
  1818. )
  1819. self.url = f"/_synapse/admin/v1/join/{self.public_room_id}"
  1820. def test_requester_is_no_admin(self) -> None:
  1821. """
  1822. If the user is not a server admin, an error 403 is returned.
  1823. """
  1824. channel = self.make_request(
  1825. "POST",
  1826. self.url,
  1827. content={"user_id": self.second_user_id},
  1828. access_token=self.second_tok,
  1829. )
  1830. self.assertEqual(403, channel.code, msg=channel.json_body)
  1831. self.assertEqual(Codes.FORBIDDEN, channel.json_body["errcode"])
  1832. def test_invalid_parameter(self) -> None:
  1833. """
  1834. If a parameter is missing, return an error
  1835. """
  1836. channel = self.make_request(
  1837. "POST",
  1838. self.url,
  1839. content={"unknown_parameter": "@unknown:test"},
  1840. access_token=self.admin_user_tok,
  1841. )
  1842. self.assertEqual(400, channel.code, msg=channel.json_body)
  1843. self.assertEqual(Codes.MISSING_PARAM, channel.json_body["errcode"])
  1844. def test_local_user_does_not_exist(self) -> None:
  1845. """
  1846. Tests that a lookup for a user that does not exist returns a 404
  1847. """
  1848. channel = self.make_request(
  1849. "POST",
  1850. self.url,
  1851. content={"user_id": "@unknown:test"},
  1852. access_token=self.admin_user_tok,
  1853. )
  1854. self.assertEqual(404, channel.code, msg=channel.json_body)
  1855. self.assertEqual(Codes.NOT_FOUND, channel.json_body["errcode"])
  1856. def test_remote_user(self) -> None:
  1857. """
  1858. Check that only local user can join rooms.
  1859. """
  1860. channel = self.make_request(
  1861. "POST",
  1862. self.url,
  1863. content={"user_id": "@not:exist.bla"},
  1864. access_token=self.admin_user_tok,
  1865. )
  1866. self.assertEqual(400, channel.code, msg=channel.json_body)
  1867. self.assertEqual(
  1868. "This endpoint can only be used with local users",
  1869. channel.json_body["error"],
  1870. )
  1871. def test_room_does_not_exist(self) -> None:
  1872. """
  1873. Check that unknown rooms/server return error 404.
  1874. """
  1875. url = "/_synapse/admin/v1/join/!unknown:test"
  1876. channel = self.make_request(
  1877. "POST",
  1878. url,
  1879. content={"user_id": self.second_user_id},
  1880. access_token=self.admin_user_tok,
  1881. )
  1882. self.assertEqual(404, channel.code, msg=channel.json_body)
  1883. self.assertEqual(
  1884. "Can't join remote room because no servers that are in the room have been provided.",
  1885. channel.json_body["error"],
  1886. )
  1887. def test_room_is_not_valid(self) -> None:
  1888. """
  1889. Check that invalid room names, return an error 400.
  1890. """
  1891. url = "/_synapse/admin/v1/join/invalidroom"
  1892. channel = self.make_request(
  1893. "POST",
  1894. url,
  1895. content={"user_id": self.second_user_id},
  1896. access_token=self.admin_user_tok,
  1897. )
  1898. self.assertEqual(400, channel.code, msg=channel.json_body)
  1899. self.assertEqual(
  1900. "invalidroom was not legal room ID or room alias",
  1901. channel.json_body["error"],
  1902. )
  1903. def test_join_public_room(self) -> None:
  1904. """
  1905. Test joining a local user to a public room with "JoinRules.PUBLIC"
  1906. """
  1907. channel = self.make_request(
  1908. "POST",
  1909. self.url,
  1910. content={"user_id": self.second_user_id},
  1911. access_token=self.admin_user_tok,
  1912. )
  1913. self.assertEqual(200, channel.code, msg=channel.json_body)
  1914. self.assertEqual(self.public_room_id, channel.json_body["room_id"])
  1915. # Validate if user is a member of the room
  1916. channel = self.make_request(
  1917. "GET",
  1918. "/_matrix/client/r0/joined_rooms",
  1919. access_token=self.second_tok,
  1920. )
  1921. self.assertEqual(200, channel.code, msg=channel.json_body)
  1922. self.assertEqual(self.public_room_id, channel.json_body["joined_rooms"][0])
  1923. def test_join_private_room_if_not_member(self) -> None:
  1924. """
  1925. Test joining a local user to a private room with "JoinRules.INVITE"
  1926. when server admin is not member of this room.
  1927. """
  1928. private_room_id = self.helper.create_room_as(
  1929. self.creator, tok=self.creator_tok, is_public=False
  1930. )
  1931. url = f"/_synapse/admin/v1/join/{private_room_id}"
  1932. channel = self.make_request(
  1933. "POST",
  1934. url,
  1935. content={"user_id": self.second_user_id},
  1936. access_token=self.admin_user_tok,
  1937. )
  1938. self.assertEqual(403, channel.code, msg=channel.json_body)
  1939. self.assertEqual(Codes.FORBIDDEN, channel.json_body["errcode"])
  1940. def test_join_private_room_if_member(self) -> None:
  1941. """
  1942. Test joining a local user to a private room with "JoinRules.INVITE",
  1943. when server admin is member of this room.
  1944. """
  1945. private_room_id = self.helper.create_room_as(
  1946. self.creator, tok=self.creator_tok, is_public=False
  1947. )
  1948. self.helper.invite(
  1949. room=private_room_id,
  1950. src=self.creator,
  1951. targ=self.admin_user,
  1952. tok=self.creator_tok,
  1953. )
  1954. self.helper.join(
  1955. room=private_room_id, user=self.admin_user, tok=self.admin_user_tok
  1956. )
  1957. # Validate if server admin is a member of the room
  1958. channel = self.make_request(
  1959. "GET",
  1960. "/_matrix/client/r0/joined_rooms",
  1961. access_token=self.admin_user_tok,
  1962. )
  1963. self.assertEqual(200, channel.code, msg=channel.json_body)
  1964. self.assertEqual(private_room_id, channel.json_body["joined_rooms"][0])
  1965. # Join user to room.
  1966. url = f"/_synapse/admin/v1/join/{private_room_id}"
  1967. channel = self.make_request(
  1968. "POST",
  1969. url,
  1970. content={"user_id": self.second_user_id},
  1971. access_token=self.admin_user_tok,
  1972. )
  1973. self.assertEqual(200, channel.code, msg=channel.json_body)
  1974. self.assertEqual(private_room_id, channel.json_body["room_id"])
  1975. # Validate if user is a member of the room
  1976. channel = self.make_request(
  1977. "GET",
  1978. "/_matrix/client/r0/joined_rooms",
  1979. access_token=self.second_tok,
  1980. )
  1981. self.assertEqual(200, channel.code, msg=channel.json_body)
  1982. self.assertEqual(private_room_id, channel.json_body["joined_rooms"][0])
  1983. def test_join_private_room_if_owner(self) -> None:
  1984. """
  1985. Test joining a local user to a private room with "JoinRules.INVITE",
  1986. when server admin is owner of this room.
  1987. """
  1988. private_room_id = self.helper.create_room_as(
  1989. self.admin_user, tok=self.admin_user_tok, is_public=False
  1990. )
  1991. url = f"/_synapse/admin/v1/join/{private_room_id}"
  1992. channel = self.make_request(
  1993. "POST",
  1994. url,
  1995. content={"user_id": self.second_user_id},
  1996. access_token=self.admin_user_tok,
  1997. )
  1998. self.assertEqual(200, channel.code, msg=channel.json_body)
  1999. self.assertEqual(private_room_id, channel.json_body["room_id"])
  2000. # Validate if user is a member of the room
  2001. channel = self.make_request(
  2002. "GET",
  2003. "/_matrix/client/r0/joined_rooms",
  2004. access_token=self.second_tok,
  2005. )
  2006. self.assertEqual(200, channel.code, msg=channel.json_body)
  2007. self.assertEqual(private_room_id, channel.json_body["joined_rooms"][0])
  2008. def test_context_as_non_admin(self) -> None:
  2009. """
  2010. Test that, without being admin, one cannot use the context admin API
  2011. """
  2012. # Create a room.
  2013. user_id = self.register_user("test", "test")
  2014. user_tok = self.login("test", "test")
  2015. self.register_user("test_2", "test")
  2016. user_tok_2 = self.login("test_2", "test")
  2017. room_id = self.helper.create_room_as(user_id, tok=user_tok)
  2018. # Populate the room with events.
  2019. events = []
  2020. for i in range(30):
  2021. events.append(
  2022. self.helper.send_event(
  2023. room_id, "com.example.test", content={"index": i}, tok=user_tok
  2024. )
  2025. )
  2026. # Now attempt to find the context using the admin API without being admin.
  2027. midway = (len(events) - 1) // 2
  2028. for tok in [user_tok, user_tok_2]:
  2029. channel = self.make_request(
  2030. "GET",
  2031. "/_synapse/admin/v1/rooms/%s/context/%s"
  2032. % (room_id, events[midway]["event_id"]),
  2033. access_token=tok,
  2034. )
  2035. self.assertEqual(403, channel.code, msg=channel.json_body)
  2036. self.assertEqual(Codes.FORBIDDEN, channel.json_body["errcode"])
  2037. def test_context_as_admin(self) -> None:
  2038. """
  2039. Test that, as admin, we can find the context of an event without having joined the room.
  2040. """
  2041. # Create a room. We're not part of it.
  2042. user_id = self.register_user("test", "test")
  2043. user_tok = self.login("test", "test")
  2044. room_id = self.helper.create_room_as(user_id, tok=user_tok)
  2045. # Populate the room with events.
  2046. events = []
  2047. for i in range(30):
  2048. events.append(
  2049. self.helper.send_event(
  2050. room_id, "com.example.test", content={"index": i}, tok=user_tok
  2051. )
  2052. )
  2053. # Now let's fetch the context for this room.
  2054. midway = (len(events) - 1) // 2
  2055. channel = self.make_request(
  2056. "GET",
  2057. "/_synapse/admin/v1/rooms/%s/context/%s"
  2058. % (room_id, events[midway]["event_id"]),
  2059. access_token=self.admin_user_tok,
  2060. )
  2061. self.assertEqual(200, channel.code, msg=channel.json_body)
  2062. self.assertEqual(
  2063. channel.json_body["event"]["event_id"], events[midway]["event_id"]
  2064. )
  2065. for found_event in channel.json_body["events_before"]:
  2066. for j, posted_event in enumerate(events):
  2067. if found_event["event_id"] == posted_event["event_id"]:
  2068. self.assertTrue(j < midway)
  2069. break
  2070. else:
  2071. self.fail("Event %s from events_before not found" % j)
  2072. for found_event in channel.json_body["events_after"]:
  2073. for j, posted_event in enumerate(events):
  2074. if found_event["event_id"] == posted_event["event_id"]:
  2075. self.assertTrue(j > midway)
  2076. break
  2077. else:
  2078. self.fail("Event %s from events_after not found" % j)
  2079. class MakeRoomAdminTestCase(unittest.HomeserverTestCase):
  2080. servlets = [
  2081. synapse.rest.admin.register_servlets,
  2082. room.register_servlets,
  2083. login.register_servlets,
  2084. ]
  2085. def prepare(self, reactor: MemoryReactor, clock: Clock, hs: HomeServer) -> None:
  2086. self.admin_user = self.register_user("admin", "pass", admin=True)
  2087. self.admin_user_tok = self.login("admin", "pass")
  2088. self.creator = self.register_user("creator", "test")
  2089. self.creator_tok = self.login("creator", "test")
  2090. self.second_user_id = self.register_user("second", "test")
  2091. self.second_tok = self.login("second", "test")
  2092. self.public_room_id = self.helper.create_room_as(
  2093. self.creator, tok=self.creator_tok, is_public=True
  2094. )
  2095. self.url = "/_synapse/admin/v1/rooms/{}/make_room_admin".format(
  2096. self.public_room_id
  2097. )
  2098. def test_public_room(self) -> None:
  2099. """Test that getting admin in a public room works."""
  2100. room_id = self.helper.create_room_as(
  2101. self.creator, tok=self.creator_tok, is_public=True
  2102. )
  2103. channel = self.make_request(
  2104. "POST",
  2105. f"/_synapse/admin/v1/rooms/{room_id}/make_room_admin",
  2106. content={},
  2107. access_token=self.admin_user_tok,
  2108. )
  2109. self.assertEqual(200, channel.code, msg=channel.json_body)
  2110. # Now we test that we can join the room and ban a user.
  2111. self.helper.join(room_id, self.admin_user, tok=self.admin_user_tok)
  2112. self.helper.change_membership(
  2113. room_id,
  2114. self.admin_user,
  2115. "@test:test",
  2116. Membership.BAN,
  2117. tok=self.admin_user_tok,
  2118. )
  2119. def test_private_room(self) -> None:
  2120. """Test that getting admin in a private room works and we get invited."""
  2121. room_id = self.helper.create_room_as(
  2122. self.creator,
  2123. tok=self.creator_tok,
  2124. is_public=False,
  2125. )
  2126. channel = self.make_request(
  2127. "POST",
  2128. f"/_synapse/admin/v1/rooms/{room_id}/make_room_admin",
  2129. content={},
  2130. access_token=self.admin_user_tok,
  2131. )
  2132. self.assertEqual(200, channel.code, msg=channel.json_body)
  2133. # Now we test that we can join the room (we should have received an
  2134. # invite) and can ban a user.
  2135. self.helper.join(room_id, self.admin_user, tok=self.admin_user_tok)
  2136. self.helper.change_membership(
  2137. room_id,
  2138. self.admin_user,
  2139. "@test:test",
  2140. Membership.BAN,
  2141. tok=self.admin_user_tok,
  2142. )
  2143. def test_other_user(self) -> None:
  2144. """Test that giving admin in a public room works to a non-admin user works."""
  2145. room_id = self.helper.create_room_as(
  2146. self.creator, tok=self.creator_tok, is_public=True
  2147. )
  2148. channel = self.make_request(
  2149. "POST",
  2150. f"/_synapse/admin/v1/rooms/{room_id}/make_room_admin",
  2151. content={"user_id": self.second_user_id},
  2152. access_token=self.admin_user_tok,
  2153. )
  2154. self.assertEqual(200, channel.code, msg=channel.json_body)
  2155. # Now we test that we can join the room and ban a user.
  2156. self.helper.join(room_id, self.second_user_id, tok=self.second_tok)
  2157. self.helper.change_membership(
  2158. room_id,
  2159. self.second_user_id,
  2160. "@test:test",
  2161. Membership.BAN,
  2162. tok=self.second_tok,
  2163. )
  2164. def test_not_enough_power(self) -> None:
  2165. """Test that we get a sensible error if there are no local room admins."""
  2166. room_id = self.helper.create_room_as(
  2167. self.creator, tok=self.creator_tok, is_public=True
  2168. )
  2169. # The creator drops admin rights in the room.
  2170. pl = self.helper.get_state(
  2171. room_id, EventTypes.PowerLevels, tok=self.creator_tok
  2172. )
  2173. pl["users"][self.creator] = 0
  2174. self.helper.send_state(
  2175. room_id, EventTypes.PowerLevels, body=pl, tok=self.creator_tok
  2176. )
  2177. channel = self.make_request(
  2178. "POST",
  2179. f"/_synapse/admin/v1/rooms/{room_id}/make_room_admin",
  2180. content={},
  2181. access_token=self.admin_user_tok,
  2182. )
  2183. # We expect this to fail with a 400 as there are no room admins.
  2184. #
  2185. # (Note we assert the error message to ensure that it's not denied for
  2186. # some other reason)
  2187. self.assertEqual(400, channel.code, msg=channel.json_body)
  2188. self.assertEqual(
  2189. channel.json_body["error"],
  2190. "No local admin user in room with power to update power levels.",
  2191. )
  2192. class BlockRoomTestCase(unittest.HomeserverTestCase):
  2193. servlets = [
  2194. synapse.rest.admin.register_servlets,
  2195. room.register_servlets,
  2196. login.register_servlets,
  2197. ]
  2198. def prepare(self, reactor: MemoryReactor, clock: Clock, hs: HomeServer) -> None:
  2199. self._store = hs.get_datastores().main
  2200. self.admin_user = self.register_user("admin", "pass", admin=True)
  2201. self.admin_user_tok = self.login("admin", "pass")
  2202. self.other_user = self.register_user("user", "pass")
  2203. self.other_user_tok = self.login("user", "pass")
  2204. self.room_id = self.helper.create_room_as(
  2205. self.other_user, tok=self.other_user_tok
  2206. )
  2207. self.url = "/_synapse/admin/v1/rooms/%s/block"
  2208. @parameterized.expand([("PUT",), ("GET",)])
  2209. def test_requester_is_no_admin(self, method: str) -> None:
  2210. """If the user is not a server admin, an error 403 is returned."""
  2211. channel = self.make_request(
  2212. method,
  2213. self.url % self.room_id,
  2214. content={},
  2215. access_token=self.other_user_tok,
  2216. )
  2217. self.assertEqual(403, channel.code, msg=channel.json_body)
  2218. self.assertEqual(Codes.FORBIDDEN, channel.json_body["errcode"])
  2219. @parameterized.expand([("PUT",), ("GET",)])
  2220. def test_room_is_not_valid(self, method: str) -> None:
  2221. """Check that invalid room names, return an error 400."""
  2222. channel = self.make_request(
  2223. method,
  2224. self.url % "invalidroom",
  2225. content={},
  2226. access_token=self.admin_user_tok,
  2227. )
  2228. self.assertEqual(400, channel.code, msg=channel.json_body)
  2229. self.assertEqual(
  2230. "invalidroom is not a legal room ID",
  2231. channel.json_body["error"],
  2232. )
  2233. def test_block_is_not_valid(self) -> None:
  2234. """If parameter `block` is not valid, return an error."""
  2235. # `block` is not valid
  2236. channel = self.make_request(
  2237. "PUT",
  2238. self.url % self.room_id,
  2239. content={"block": "NotBool"},
  2240. access_token=self.admin_user_tok,
  2241. )
  2242. self.assertEqual(400, channel.code, msg=channel.json_body)
  2243. self.assertEqual(Codes.BAD_JSON, channel.json_body["errcode"])
  2244. # `block` is not set
  2245. channel = self.make_request(
  2246. "PUT",
  2247. self.url % self.room_id,
  2248. content={},
  2249. access_token=self.admin_user_tok,
  2250. )
  2251. self.assertEqual(400, channel.code, msg=channel.json_body)
  2252. self.assertEqual(Codes.MISSING_PARAM, channel.json_body["errcode"])
  2253. # no content is send
  2254. channel = self.make_request(
  2255. "PUT",
  2256. self.url % self.room_id,
  2257. access_token=self.admin_user_tok,
  2258. )
  2259. self.assertEqual(400, channel.code, msg=channel.json_body)
  2260. self.assertEqual(Codes.NOT_JSON, channel.json_body["errcode"])
  2261. def test_block_room(self) -> None:
  2262. """Test that block a room is successful."""
  2263. def _request_and_test_block_room(room_id: str) -> None:
  2264. self._is_blocked(room_id, expect=False)
  2265. channel = self.make_request(
  2266. "PUT",
  2267. self.url % room_id,
  2268. content={"block": True},
  2269. access_token=self.admin_user_tok,
  2270. )
  2271. self.assertEqual(200, channel.code, msg=channel.json_body)
  2272. self.assertTrue(channel.json_body["block"])
  2273. self._is_blocked(room_id, expect=True)
  2274. # known internal room
  2275. _request_and_test_block_room(self.room_id)
  2276. # unknown internal room
  2277. _request_and_test_block_room("!unknown:test")
  2278. # unknown remote room
  2279. _request_and_test_block_room("!unknown:remote")
  2280. def test_block_room_twice(self) -> None:
  2281. """Test that block a room that is already blocked is successful."""
  2282. self._is_blocked(self.room_id, expect=False)
  2283. for _ in range(2):
  2284. channel = self.make_request(
  2285. "PUT",
  2286. self.url % self.room_id,
  2287. content={"block": True},
  2288. access_token=self.admin_user_tok,
  2289. )
  2290. self.assertEqual(200, channel.code, msg=channel.json_body)
  2291. self.assertTrue(channel.json_body["block"])
  2292. self._is_blocked(self.room_id, expect=True)
  2293. def test_unblock_room(self) -> None:
  2294. """Test that unblock a room is successful."""
  2295. def _request_and_test_unblock_room(room_id: str) -> None:
  2296. self._block_room(room_id)
  2297. channel = self.make_request(
  2298. "PUT",
  2299. self.url % room_id,
  2300. content={"block": False},
  2301. access_token=self.admin_user_tok,
  2302. )
  2303. self.assertEqual(200, channel.code, msg=channel.json_body)
  2304. self.assertFalse(channel.json_body["block"])
  2305. self._is_blocked(room_id, expect=False)
  2306. # known internal room
  2307. _request_and_test_unblock_room(self.room_id)
  2308. # unknown internal room
  2309. _request_and_test_unblock_room("!unknown:test")
  2310. # unknown remote room
  2311. _request_and_test_unblock_room("!unknown:remote")
  2312. def test_unblock_room_twice(self) -> None:
  2313. """Test that unblock a room that is not blocked is successful."""
  2314. self._block_room(self.room_id)
  2315. for _ in range(2):
  2316. channel = self.make_request(
  2317. "PUT",
  2318. self.url % self.room_id,
  2319. content={"block": False},
  2320. access_token=self.admin_user_tok,
  2321. )
  2322. self.assertEqual(200, channel.code, msg=channel.json_body)
  2323. self.assertFalse(channel.json_body["block"])
  2324. self._is_blocked(self.room_id, expect=False)
  2325. def test_get_blocked_room(self) -> None:
  2326. """Test get status of a blocked room"""
  2327. def _request_blocked_room(room_id: str) -> None:
  2328. self._block_room(room_id)
  2329. channel = self.make_request(
  2330. "GET",
  2331. self.url % room_id,
  2332. access_token=self.admin_user_tok,
  2333. )
  2334. self.assertEqual(200, channel.code, msg=channel.json_body)
  2335. self.assertTrue(channel.json_body["block"])
  2336. self.assertEqual(self.other_user, channel.json_body["user_id"])
  2337. # known internal room
  2338. _request_blocked_room(self.room_id)
  2339. # unknown internal room
  2340. _request_blocked_room("!unknown:test")
  2341. # unknown remote room
  2342. _request_blocked_room("!unknown:remote")
  2343. def test_get_unblocked_room(self) -> None:
  2344. """Test get status of a unblocked room"""
  2345. def _request_unblocked_room(room_id: str) -> None:
  2346. self._is_blocked(room_id, expect=False)
  2347. channel = self.make_request(
  2348. "GET",
  2349. self.url % room_id,
  2350. access_token=self.admin_user_tok,
  2351. )
  2352. self.assertEqual(200, channel.code, msg=channel.json_body)
  2353. self.assertFalse(channel.json_body["block"])
  2354. self.assertNotIn("user_id", channel.json_body)
  2355. # known internal room
  2356. _request_unblocked_room(self.room_id)
  2357. # unknown internal room
  2358. _request_unblocked_room("!unknown:test")
  2359. # unknown remote room
  2360. _request_unblocked_room("!unknown:remote")
  2361. def _is_blocked(self, room_id: str, expect: bool = True) -> None:
  2362. """Assert that the room is blocked or not"""
  2363. d = self._store.is_room_blocked(room_id)
  2364. if expect:
  2365. self.assertTrue(self.get_success(d))
  2366. else:
  2367. self.assertIsNone(self.get_success(d))
  2368. def _block_room(self, room_id: str) -> None:
  2369. """Block a room in database"""
  2370. self.get_success(self._store.block_room(room_id, self.other_user))
  2371. self._is_blocked(room_id, expect=True)
  2372. PURGE_TABLES = [
  2373. "current_state_events",
  2374. "event_backward_extremities",
  2375. "event_forward_extremities",
  2376. "event_json",
  2377. "event_push_actions",
  2378. "event_search",
  2379. "events",
  2380. "receipts_graph",
  2381. "receipts_linearized",
  2382. "room_aliases",
  2383. "room_depth",
  2384. "room_memberships",
  2385. "room_stats_state",
  2386. "room_stats_current",
  2387. "room_stats_earliest_token",
  2388. "rooms",
  2389. "stream_ordering_to_exterm",
  2390. "users_in_public_rooms",
  2391. "users_who_share_private_rooms",
  2392. "appservice_room_list",
  2393. "e2e_room_keys",
  2394. "event_push_summary",
  2395. "pusher_throttle",
  2396. "room_account_data",
  2397. "room_tags",
  2398. # "state_groups", # Current impl leaves orphaned state groups around.
  2399. "state_groups_state",
  2400. "federation_inbound_events_staging",
  2401. ]