test_room.py 102 KB

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