test_room.py 89 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492
  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. ]