1
0

test_room.py 98 KB

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