test_room.py 89 KB

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