test_room.py 90 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516
  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, RoomTypes
  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. self.assertIn("room_type", r)
  926. self.assertIsNone(r["room_type"])
  927. # Check that the correct number of total rooms was returned
  928. self.assertEqual(channel.json_body["total_rooms"], total_rooms)
  929. # Check that the offset is correct
  930. # Should be 0 as we aren't paginating
  931. self.assertEqual(channel.json_body["offset"], 0)
  932. # Check that the prev_batch parameter is not present
  933. self.assertNotIn("prev_batch", channel.json_body)
  934. # We shouldn't receive a next token here as there's no further rooms to show
  935. self.assertNotIn("next_batch", channel.json_body)
  936. def test_list_rooms_pagination(self) -> None:
  937. """Test that we can get a full list of rooms through pagination"""
  938. # Create 5 test rooms
  939. total_rooms = 5
  940. room_ids = []
  941. for _ in range(total_rooms):
  942. room_id = self.helper.create_room_as(
  943. self.admin_user, tok=self.admin_user_tok
  944. )
  945. room_ids.append(room_id)
  946. # Set the name of the rooms so we get a consistent returned ordering
  947. for idx, room_id in enumerate(room_ids):
  948. self.helper.send_state(
  949. room_id,
  950. "m.room.name",
  951. {"name": str(idx)},
  952. tok=self.admin_user_tok,
  953. )
  954. # Request the list of rooms
  955. returned_room_ids = []
  956. start = 0
  957. limit = 2
  958. run_count = 0
  959. should_repeat = True
  960. while should_repeat:
  961. run_count += 1
  962. url = "/_synapse/admin/v1/rooms?from=%d&limit=%d&order_by=%s" % (
  963. start,
  964. limit,
  965. "name",
  966. )
  967. channel = self.make_request(
  968. "GET",
  969. url.encode("ascii"),
  970. access_token=self.admin_user_tok,
  971. )
  972. self.assertEqual(HTTPStatus.OK, channel.code, msg=channel.json_body)
  973. self.assertTrue("rooms" in channel.json_body)
  974. for r in channel.json_body["rooms"]:
  975. returned_room_ids.append(r["room_id"])
  976. # Check that the correct number of total rooms was returned
  977. self.assertEqual(channel.json_body["total_rooms"], total_rooms)
  978. # Check that the offset is correct
  979. # We're only getting 2 rooms each page, so should be 2 * last run_count
  980. self.assertEqual(channel.json_body["offset"], 2 * (run_count - 1))
  981. if run_count > 1:
  982. # Check the value of prev_batch is correct
  983. self.assertEqual(channel.json_body["prev_batch"], 2 * (run_count - 2))
  984. if "next_batch" not in channel.json_body:
  985. # We have reached the end of the list
  986. should_repeat = False
  987. else:
  988. # Make another query with an updated start value
  989. start = channel.json_body["next_batch"]
  990. # We should've queried the endpoint 3 times
  991. self.assertEqual(
  992. run_count,
  993. 3,
  994. msg="Should've queried 3 times for 5 rooms with limit 2 per query",
  995. )
  996. # Check that we received all of the room ids
  997. self.assertEqual(room_ids, returned_room_ids)
  998. url = "/_synapse/admin/v1/rooms?from=%d&limit=%d" % (start, limit)
  999. channel = self.make_request(
  1000. "GET",
  1001. url.encode("ascii"),
  1002. access_token=self.admin_user_tok,
  1003. )
  1004. self.assertEqual(HTTPStatus.OK, channel.code, msg=channel.json_body)
  1005. def test_correct_room_attributes(self) -> None:
  1006. """Test the correct attributes for a room are returned"""
  1007. # Create a test room
  1008. room_id = self.helper.create_room_as(
  1009. self.admin_user,
  1010. tok=self.admin_user_tok,
  1011. extra_content={"creation_content": {"type": RoomTypes.SPACE}},
  1012. )
  1013. test_alias = "#test:test"
  1014. test_room_name = "something"
  1015. # Have another user join the room
  1016. user_2 = self.register_user("user4", "pass")
  1017. user_tok_2 = self.login("user4", "pass")
  1018. self.helper.join(room_id, user_2, tok=user_tok_2)
  1019. # Create a new alias to this room
  1020. url = "/_matrix/client/r0/directory/room/%s" % (urllib.parse.quote(test_alias),)
  1021. channel = self.make_request(
  1022. "PUT",
  1023. url.encode("ascii"),
  1024. {"room_id": room_id},
  1025. access_token=self.admin_user_tok,
  1026. )
  1027. self.assertEqual(HTTPStatus.OK, channel.code, msg=channel.json_body)
  1028. # Set this new alias as the canonical alias for this room
  1029. self.helper.send_state(
  1030. room_id,
  1031. "m.room.aliases",
  1032. {"aliases": [test_alias]},
  1033. tok=self.admin_user_tok,
  1034. state_key="test",
  1035. )
  1036. self.helper.send_state(
  1037. room_id,
  1038. "m.room.canonical_alias",
  1039. {"alias": test_alias},
  1040. tok=self.admin_user_tok,
  1041. )
  1042. # Set a name for the room
  1043. self.helper.send_state(
  1044. room_id,
  1045. "m.room.name",
  1046. {"name": test_room_name},
  1047. tok=self.admin_user_tok,
  1048. )
  1049. # Request the list of rooms
  1050. url = "/_synapse/admin/v1/rooms"
  1051. channel = self.make_request(
  1052. "GET",
  1053. url.encode("ascii"),
  1054. access_token=self.admin_user_tok,
  1055. )
  1056. self.assertEqual(HTTPStatus.OK, channel.code, msg=channel.json_body)
  1057. # Check that rooms were returned
  1058. self.assertTrue("rooms" in channel.json_body)
  1059. rooms = channel.json_body["rooms"]
  1060. # Check that only one room was returned
  1061. self.assertEqual(len(rooms), 1)
  1062. # And that the value of the total_rooms key was correct
  1063. self.assertEqual(channel.json_body["total_rooms"], 1)
  1064. # Check that the offset is correct
  1065. # We're not paginating, so should be 0
  1066. self.assertEqual(channel.json_body["offset"], 0)
  1067. # Check that there is no `prev_batch`
  1068. self.assertNotIn("prev_batch", channel.json_body)
  1069. # Check that there is no `next_batch`
  1070. self.assertNotIn("next_batch", channel.json_body)
  1071. # Check that all provided attributes are set
  1072. r = rooms[0]
  1073. self.assertEqual(room_id, r["room_id"])
  1074. self.assertEqual(test_room_name, r["name"])
  1075. self.assertEqual(test_alias, r["canonical_alias"])
  1076. self.assertEqual(RoomTypes.SPACE, r["room_type"])
  1077. def test_room_list_sort_order(self) -> None:
  1078. """Test room list sort ordering. alphabetical name versus number of members,
  1079. reversing the order, etc.
  1080. """
  1081. def _order_test(
  1082. order_type: str,
  1083. expected_room_list: List[str],
  1084. reverse: bool = False,
  1085. ) -> None:
  1086. """Request the list of rooms in a certain order. Assert that order is what
  1087. we expect
  1088. Args:
  1089. order_type: The type of ordering to give the server
  1090. expected_room_list: The list of room_ids in the order we expect to get
  1091. back from the server
  1092. """
  1093. # Request the list of rooms in the given order
  1094. url = "/_synapse/admin/v1/rooms?order_by=%s" % (order_type,)
  1095. if reverse:
  1096. url += "&dir=b"
  1097. channel = self.make_request(
  1098. "GET",
  1099. url.encode("ascii"),
  1100. access_token=self.admin_user_tok,
  1101. )
  1102. self.assertEqual(HTTPStatus.OK, channel.code, msg=channel.json_body)
  1103. # Check that rooms were returned
  1104. self.assertTrue("rooms" in channel.json_body)
  1105. rooms = channel.json_body["rooms"]
  1106. # Check for the correct total_rooms value
  1107. self.assertEqual(channel.json_body["total_rooms"], 3)
  1108. # Check that the offset is correct
  1109. # We're not paginating, so should be 0
  1110. self.assertEqual(channel.json_body["offset"], 0)
  1111. # Check that there is no `prev_batch`
  1112. self.assertNotIn("prev_batch", channel.json_body)
  1113. # Check that there is no `next_batch`
  1114. self.assertNotIn("next_batch", channel.json_body)
  1115. # Check that rooms were returned in alphabetical order
  1116. returned_order = [r["room_id"] for r in rooms]
  1117. self.assertListEqual(expected_room_list, returned_order) # order is checked
  1118. # Create 3 test rooms
  1119. room_id_1 = self.helper.create_room_as(self.admin_user, tok=self.admin_user_tok)
  1120. room_id_2 = self.helper.create_room_as(self.admin_user, tok=self.admin_user_tok)
  1121. room_id_3 = self.helper.create_room_as(self.admin_user, tok=self.admin_user_tok)
  1122. # Also create a list sorted by IDs for properties that are equal (and thus sorted by room_id)
  1123. sorted_by_room_id_asc = [room_id_1, room_id_2, room_id_3]
  1124. sorted_by_room_id_asc.sort()
  1125. sorted_by_room_id_desc = sorted_by_room_id_asc.copy()
  1126. sorted_by_room_id_desc.reverse()
  1127. # Set room names in alphabetical order. room 1 -> A, 2 -> B, 3 -> C
  1128. self.helper.send_state(
  1129. room_id_1,
  1130. "m.room.name",
  1131. {"name": "A"},
  1132. tok=self.admin_user_tok,
  1133. )
  1134. self.helper.send_state(
  1135. room_id_2,
  1136. "m.room.name",
  1137. {"name": "B"},
  1138. tok=self.admin_user_tok,
  1139. )
  1140. self.helper.send_state(
  1141. room_id_3,
  1142. "m.room.name",
  1143. {"name": "C"},
  1144. tok=self.admin_user_tok,
  1145. )
  1146. # Set room canonical room aliases
  1147. self._set_canonical_alias(room_id_1, "#A_alias:test", self.admin_user_tok)
  1148. self._set_canonical_alias(room_id_2, "#B_alias:test", self.admin_user_tok)
  1149. self._set_canonical_alias(room_id_3, "#C_alias:test", self.admin_user_tok)
  1150. # Set room member size in the reverse order. room 1 -> 1 member, 2 -> 2, 3 -> 3
  1151. user_1 = self.register_user("bob1", "pass")
  1152. user_1_tok = self.login("bob1", "pass")
  1153. self.helper.join(room_id_2, user_1, tok=user_1_tok)
  1154. user_2 = self.register_user("bob2", "pass")
  1155. user_2_tok = self.login("bob2", "pass")
  1156. self.helper.join(room_id_3, user_2, tok=user_2_tok)
  1157. user_3 = self.register_user("bob3", "pass")
  1158. user_3_tok = self.login("bob3", "pass")
  1159. self.helper.join(room_id_3, user_3, tok=user_3_tok)
  1160. # Test different sort orders, with forward and reverse directions
  1161. _order_test("name", [room_id_1, room_id_2, room_id_3])
  1162. _order_test("name", [room_id_3, room_id_2, room_id_1], reverse=True)
  1163. _order_test("canonical_alias", [room_id_1, room_id_2, room_id_3])
  1164. _order_test("canonical_alias", [room_id_3, room_id_2, room_id_1], reverse=True)
  1165. # Note: joined_member counts are sorted in descending order when dir=f
  1166. _order_test("joined_members", [room_id_3, room_id_2, room_id_1])
  1167. _order_test("joined_members", [room_id_1, room_id_2, room_id_3], reverse=True)
  1168. # Note: joined_local_member counts are sorted in descending order when dir=f
  1169. _order_test("joined_local_members", [room_id_3, room_id_2, room_id_1])
  1170. _order_test(
  1171. "joined_local_members", [room_id_1, room_id_2, room_id_3], reverse=True
  1172. )
  1173. # Note: versions are sorted in descending order when dir=f
  1174. _order_test("version", sorted_by_room_id_asc, reverse=True)
  1175. _order_test("version", sorted_by_room_id_desc)
  1176. _order_test("creator", sorted_by_room_id_asc)
  1177. _order_test("creator", sorted_by_room_id_desc, reverse=True)
  1178. _order_test("encryption", sorted_by_room_id_asc)
  1179. _order_test("encryption", sorted_by_room_id_desc, reverse=True)
  1180. _order_test("federatable", sorted_by_room_id_asc)
  1181. _order_test("federatable", sorted_by_room_id_desc, reverse=True)
  1182. _order_test("public", sorted_by_room_id_asc)
  1183. _order_test("public", sorted_by_room_id_desc, reverse=True)
  1184. _order_test("join_rules", sorted_by_room_id_asc)
  1185. _order_test("join_rules", sorted_by_room_id_desc, reverse=True)
  1186. _order_test("guest_access", sorted_by_room_id_asc)
  1187. _order_test("guest_access", sorted_by_room_id_desc, reverse=True)
  1188. _order_test("history_visibility", sorted_by_room_id_asc)
  1189. _order_test("history_visibility", sorted_by_room_id_desc, reverse=True)
  1190. # Note: state_event counts are sorted in descending order when dir=f
  1191. _order_test("state_events", [room_id_3, room_id_2, room_id_1])
  1192. _order_test("state_events", [room_id_1, room_id_2, room_id_3], reverse=True)
  1193. def test_search_term(self) -> None:
  1194. """Test that searching for a room works correctly"""
  1195. # Create two test rooms
  1196. room_id_1 = self.helper.create_room_as(self.admin_user, tok=self.admin_user_tok)
  1197. room_id_2 = self.helper.create_room_as(self.admin_user, tok=self.admin_user_tok)
  1198. room_name_1 = "something"
  1199. room_name_2 = "LoremIpsum"
  1200. # Set the name for each room
  1201. self.helper.send_state(
  1202. room_id_1,
  1203. "m.room.name",
  1204. {"name": room_name_1},
  1205. tok=self.admin_user_tok,
  1206. )
  1207. self.helper.send_state(
  1208. room_id_2,
  1209. "m.room.name",
  1210. {"name": room_name_2},
  1211. tok=self.admin_user_tok,
  1212. )
  1213. self._set_canonical_alias(room_id_1, "#Room_Alias1:test", self.admin_user_tok)
  1214. def _search_test(
  1215. expected_room_id: Optional[str],
  1216. search_term: str,
  1217. expected_http_code: int = HTTPStatus.OK,
  1218. ) -> None:
  1219. """Search for a room and check that the returned room's id is a match
  1220. Args:
  1221. expected_room_id: The room_id expected to be returned by the API. Set
  1222. to None to expect zero results for the search
  1223. search_term: The term to search for room names with
  1224. expected_http_code: The expected http code for the request
  1225. """
  1226. url = "/_synapse/admin/v1/rooms?search_term=%s" % (search_term,)
  1227. channel = self.make_request(
  1228. "GET",
  1229. url.encode("ascii"),
  1230. access_token=self.admin_user_tok,
  1231. )
  1232. self.assertEqual(expected_http_code, channel.code, msg=channel.json_body)
  1233. if expected_http_code != HTTPStatus.OK:
  1234. return
  1235. # Check that rooms were returned
  1236. self.assertTrue("rooms" in channel.json_body)
  1237. rooms = channel.json_body["rooms"]
  1238. # Check that the expected number of rooms were returned
  1239. expected_room_count = 1 if expected_room_id else 0
  1240. self.assertEqual(len(rooms), expected_room_count)
  1241. self.assertEqual(channel.json_body["total_rooms"], expected_room_count)
  1242. # Check that the offset is correct
  1243. # We're not paginating, so should be 0
  1244. self.assertEqual(channel.json_body["offset"], 0)
  1245. # Check that there is no `prev_batch`
  1246. self.assertNotIn("prev_batch", channel.json_body)
  1247. # Check that there is no `next_batch`
  1248. self.assertNotIn("next_batch", channel.json_body)
  1249. if expected_room_id:
  1250. # Check that the first returned room id is correct
  1251. r = rooms[0]
  1252. self.assertEqual(expected_room_id, r["room_id"])
  1253. # Test searching by room name
  1254. _search_test(room_id_1, "something")
  1255. _search_test(room_id_1, "thing")
  1256. _search_test(room_id_2, "LoremIpsum")
  1257. _search_test(room_id_2, "lorem")
  1258. # Test case insensitive
  1259. _search_test(room_id_1, "SOMETHING")
  1260. _search_test(room_id_1, "THING")
  1261. _search_test(room_id_2, "LOREMIPSUM")
  1262. _search_test(room_id_2, "LOREM")
  1263. _search_test(None, "foo")
  1264. _search_test(None, "bar")
  1265. _search_test(None, "", expected_http_code=HTTPStatus.BAD_REQUEST)
  1266. # Test that the whole room id returns the room
  1267. _search_test(room_id_1, room_id_1)
  1268. # Test that the search by room_id is case sensitive
  1269. _search_test(None, room_id_1.lower())
  1270. # Test search part of local part of room id do not match
  1271. _search_test(None, room_id_1[1:10])
  1272. # Test that whole room alias return no result, because of domain
  1273. _search_test(None, "#Room_Alias1:test")
  1274. # Test search local part of alias
  1275. _search_test(room_id_1, "alias1")
  1276. def test_search_term_non_ascii(self) -> None:
  1277. """Test that searching for a room with non-ASCII characters works correctly"""
  1278. # Create test room
  1279. room_id = self.helper.create_room_as(self.admin_user, tok=self.admin_user_tok)
  1280. room_name = "ж"
  1281. # Set the name for the room
  1282. self.helper.send_state(
  1283. room_id,
  1284. "m.room.name",
  1285. {"name": room_name},
  1286. tok=self.admin_user_tok,
  1287. )
  1288. # make the request and test that the response is what we wanted
  1289. search_term = urllib.parse.quote("ж", "utf-8")
  1290. url = "/_synapse/admin/v1/rooms?search_term=%s" % (search_term,)
  1291. channel = self.make_request(
  1292. "GET",
  1293. url.encode("ascii"),
  1294. access_token=self.admin_user_tok,
  1295. )
  1296. self.assertEqual(HTTPStatus.OK, channel.code, msg=channel.json_body)
  1297. self.assertEqual(room_id, channel.json_body["rooms"][0].get("room_id"))
  1298. self.assertEqual("ж", channel.json_body["rooms"][0].get("name"))
  1299. def test_single_room(self) -> None:
  1300. """Test that a single room can be requested correctly"""
  1301. # Create two test rooms
  1302. room_id_1 = self.helper.create_room_as(self.admin_user, tok=self.admin_user_tok)
  1303. room_id_2 = self.helper.create_room_as(self.admin_user, tok=self.admin_user_tok)
  1304. room_name_1 = "something"
  1305. room_name_2 = "else"
  1306. # Set the name for each room
  1307. self.helper.send_state(
  1308. room_id_1,
  1309. "m.room.name",
  1310. {"name": room_name_1},
  1311. tok=self.admin_user_tok,
  1312. )
  1313. self.helper.send_state(
  1314. room_id_2,
  1315. "m.room.name",
  1316. {"name": room_name_2},
  1317. tok=self.admin_user_tok,
  1318. )
  1319. url = "/_synapse/admin/v1/rooms/%s" % (room_id_1,)
  1320. channel = self.make_request(
  1321. "GET",
  1322. url.encode("ascii"),
  1323. access_token=self.admin_user_tok,
  1324. )
  1325. self.assertEqual(HTTPStatus.OK, channel.code, msg=channel.json_body)
  1326. self.assertIn("room_id", channel.json_body)
  1327. self.assertIn("name", channel.json_body)
  1328. self.assertIn("topic", channel.json_body)
  1329. self.assertIn("avatar", channel.json_body)
  1330. self.assertIn("canonical_alias", channel.json_body)
  1331. self.assertIn("joined_members", channel.json_body)
  1332. self.assertIn("joined_local_members", channel.json_body)
  1333. self.assertIn("joined_local_devices", channel.json_body)
  1334. self.assertIn("version", channel.json_body)
  1335. self.assertIn("creator", channel.json_body)
  1336. self.assertIn("encryption", channel.json_body)
  1337. self.assertIn("federatable", channel.json_body)
  1338. self.assertIn("public", channel.json_body)
  1339. self.assertIn("join_rules", channel.json_body)
  1340. self.assertIn("guest_access", channel.json_body)
  1341. self.assertIn("history_visibility", channel.json_body)
  1342. self.assertIn("state_events", channel.json_body)
  1343. self.assertIn("room_type", channel.json_body)
  1344. self.assertEqual(room_id_1, channel.json_body["room_id"])
  1345. def test_single_room_devices(self) -> None:
  1346. """Test that `joined_local_devices` can be requested correctly"""
  1347. room_id_1 = self.helper.create_room_as(self.admin_user, tok=self.admin_user_tok)
  1348. url = "/_synapse/admin/v1/rooms/%s" % (room_id_1,)
  1349. channel = self.make_request(
  1350. "GET",
  1351. url.encode("ascii"),
  1352. access_token=self.admin_user_tok,
  1353. )
  1354. self.assertEqual(HTTPStatus.OK, channel.code, msg=channel.json_body)
  1355. self.assertEqual(1, channel.json_body["joined_local_devices"])
  1356. # Have another user join the room
  1357. user_1 = self.register_user("foo", "pass")
  1358. user_tok_1 = self.login("foo", "pass")
  1359. self.helper.join(room_id_1, user_1, tok=user_tok_1)
  1360. url = "/_synapse/admin/v1/rooms/%s" % (room_id_1,)
  1361. channel = self.make_request(
  1362. "GET",
  1363. url.encode("ascii"),
  1364. access_token=self.admin_user_tok,
  1365. )
  1366. self.assertEqual(HTTPStatus.OK, channel.code, msg=channel.json_body)
  1367. self.assertEqual(2, channel.json_body["joined_local_devices"])
  1368. # leave room
  1369. self.helper.leave(room_id_1, self.admin_user, tok=self.admin_user_tok)
  1370. self.helper.leave(room_id_1, user_1, tok=user_tok_1)
  1371. url = "/_synapse/admin/v1/rooms/%s" % (room_id_1,)
  1372. channel = self.make_request(
  1373. "GET",
  1374. url.encode("ascii"),
  1375. access_token=self.admin_user_tok,
  1376. )
  1377. self.assertEqual(HTTPStatus.OK, channel.code, msg=channel.json_body)
  1378. self.assertEqual(0, channel.json_body["joined_local_devices"])
  1379. def test_room_members(self) -> None:
  1380. """Test that room members can be requested correctly"""
  1381. # Create two test rooms
  1382. room_id_1 = self.helper.create_room_as(self.admin_user, tok=self.admin_user_tok)
  1383. room_id_2 = self.helper.create_room_as(self.admin_user, tok=self.admin_user_tok)
  1384. # Have another user join the room
  1385. user_1 = self.register_user("foo", "pass")
  1386. user_tok_1 = self.login("foo", "pass")
  1387. self.helper.join(room_id_1, user_1, tok=user_tok_1)
  1388. # Have another user join the room
  1389. user_2 = self.register_user("bar", "pass")
  1390. user_tok_2 = self.login("bar", "pass")
  1391. self.helper.join(room_id_1, user_2, tok=user_tok_2)
  1392. self.helper.join(room_id_2, user_2, tok=user_tok_2)
  1393. # Have another user join the room
  1394. user_3 = self.register_user("foobar", "pass")
  1395. user_tok_3 = self.login("foobar", "pass")
  1396. self.helper.join(room_id_2, user_3, tok=user_tok_3)
  1397. url = "/_synapse/admin/v1/rooms/%s/members" % (room_id_1,)
  1398. channel = self.make_request(
  1399. "GET",
  1400. url.encode("ascii"),
  1401. access_token=self.admin_user_tok,
  1402. )
  1403. self.assertEqual(HTTPStatus.OK, channel.code, msg=channel.json_body)
  1404. self.assertCountEqual(
  1405. ["@admin:test", "@foo:test", "@bar:test"], channel.json_body["members"]
  1406. )
  1407. self.assertEqual(channel.json_body["total"], 3)
  1408. url = "/_synapse/admin/v1/rooms/%s/members" % (room_id_2,)
  1409. channel = self.make_request(
  1410. "GET",
  1411. url.encode("ascii"),
  1412. access_token=self.admin_user_tok,
  1413. )
  1414. self.assertEqual(HTTPStatus.OK, channel.code, msg=channel.json_body)
  1415. self.assertCountEqual(
  1416. ["@admin:test", "@bar:test", "@foobar:test"], channel.json_body["members"]
  1417. )
  1418. self.assertEqual(channel.json_body["total"], 3)
  1419. def test_room_state(self) -> None:
  1420. """Test that room state can be requested correctly"""
  1421. # Create two test rooms
  1422. room_id = self.helper.create_room_as(self.admin_user, tok=self.admin_user_tok)
  1423. url = "/_synapse/admin/v1/rooms/%s/state" % (room_id,)
  1424. channel = self.make_request(
  1425. "GET",
  1426. url.encode("ascii"),
  1427. access_token=self.admin_user_tok,
  1428. )
  1429. self.assertEqual(HTTPStatus.OK, channel.code, msg=channel.json_body)
  1430. self.assertIn("state", channel.json_body)
  1431. # testing that the state events match is painful and not done here. We assume that
  1432. # the create_room already does the right thing, so no need to verify that we got
  1433. # the state events it created.
  1434. def _set_canonical_alias(
  1435. self, room_id: str, test_alias: str, admin_user_tok: str
  1436. ) -> None:
  1437. # Create a new alias to this room
  1438. url = "/_matrix/client/r0/directory/room/%s" % (urllib.parse.quote(test_alias),)
  1439. channel = self.make_request(
  1440. "PUT",
  1441. url.encode("ascii"),
  1442. {"room_id": room_id},
  1443. access_token=admin_user_tok,
  1444. )
  1445. self.assertEqual(HTTPStatus.OK, channel.code, msg=channel.json_body)
  1446. # Set this new alias as the canonical alias for this room
  1447. self.helper.send_state(
  1448. room_id,
  1449. "m.room.aliases",
  1450. {"aliases": [test_alias]},
  1451. tok=admin_user_tok,
  1452. state_key="test",
  1453. )
  1454. self.helper.send_state(
  1455. room_id,
  1456. "m.room.canonical_alias",
  1457. {"alias": test_alias},
  1458. tok=admin_user_tok,
  1459. )
  1460. def test_get_joined_members_after_leave_room(self) -> None:
  1461. """Test that requesting room members after leaving the room raises a 403 error."""
  1462. # create the room
  1463. user = self.register_user("foo", "pass")
  1464. user_tok = self.login("foo", "pass")
  1465. room_id = self.helper.create_room_as(user, tok=user_tok)
  1466. self.helper.leave(room_id, user, tok=user_tok)
  1467. # delete the rooms and get joined roomed membership
  1468. url = f"/_matrix/client/r0/rooms/{room_id}/joined_members"
  1469. channel = self.make_request("GET", url.encode("ascii"), access_token=user_tok)
  1470. self.assertEqual(HTTPStatus.FORBIDDEN, channel.code, msg=channel.json_body)
  1471. self.assertEqual(Codes.FORBIDDEN, channel.json_body["errcode"])
  1472. class JoinAliasRoomTestCase(unittest.HomeserverTestCase):
  1473. servlets = [
  1474. synapse.rest.admin.register_servlets,
  1475. room.register_servlets,
  1476. login.register_servlets,
  1477. ]
  1478. def prepare(self, reactor: MemoryReactor, clock: Clock, hs: HomeServer) -> None:
  1479. self.admin_user = self.register_user("admin", "pass", admin=True)
  1480. self.admin_user_tok = self.login("admin", "pass")
  1481. self.creator = self.register_user("creator", "test")
  1482. self.creator_tok = self.login("creator", "test")
  1483. self.second_user_id = self.register_user("second", "test")
  1484. self.second_tok = self.login("second", "test")
  1485. self.public_room_id = self.helper.create_room_as(
  1486. self.creator, tok=self.creator_tok, is_public=True
  1487. )
  1488. self.url = f"/_synapse/admin/v1/join/{self.public_room_id}"
  1489. def test_requester_is_no_admin(self) -> None:
  1490. """
  1491. If the user is not a server admin, an error HTTPStatus.FORBIDDEN is returned.
  1492. """
  1493. channel = self.make_request(
  1494. "POST",
  1495. self.url,
  1496. content={"user_id": self.second_user_id},
  1497. access_token=self.second_tok,
  1498. )
  1499. self.assertEqual(HTTPStatus.FORBIDDEN, channel.code, msg=channel.json_body)
  1500. self.assertEqual(Codes.FORBIDDEN, channel.json_body["errcode"])
  1501. def test_invalid_parameter(self) -> None:
  1502. """
  1503. If a parameter is missing, return an error
  1504. """
  1505. channel = self.make_request(
  1506. "POST",
  1507. self.url,
  1508. content={"unknown_parameter": "@unknown:test"},
  1509. access_token=self.admin_user_tok,
  1510. )
  1511. self.assertEqual(HTTPStatus.BAD_REQUEST, channel.code, msg=channel.json_body)
  1512. self.assertEqual(Codes.MISSING_PARAM, channel.json_body["errcode"])
  1513. def test_local_user_does_not_exist(self) -> None:
  1514. """
  1515. Tests that a lookup for a user that does not exist returns a HTTPStatus.NOT_FOUND
  1516. """
  1517. channel = self.make_request(
  1518. "POST",
  1519. self.url,
  1520. content={"user_id": "@unknown:test"},
  1521. access_token=self.admin_user_tok,
  1522. )
  1523. self.assertEqual(HTTPStatus.NOT_FOUND, channel.code, msg=channel.json_body)
  1524. self.assertEqual(Codes.NOT_FOUND, channel.json_body["errcode"])
  1525. def test_remote_user(self) -> None:
  1526. """
  1527. Check that only local user can join rooms.
  1528. """
  1529. channel = self.make_request(
  1530. "POST",
  1531. self.url,
  1532. content={"user_id": "@not:exist.bla"},
  1533. access_token=self.admin_user_tok,
  1534. )
  1535. self.assertEqual(HTTPStatus.BAD_REQUEST, channel.code, msg=channel.json_body)
  1536. self.assertEqual(
  1537. "This endpoint can only be used with local users",
  1538. channel.json_body["error"],
  1539. )
  1540. def test_room_does_not_exist(self) -> None:
  1541. """
  1542. Check that unknown rooms/server return error HTTPStatus.NOT_FOUND.
  1543. """
  1544. url = "/_synapse/admin/v1/join/!unknown:test"
  1545. channel = self.make_request(
  1546. "POST",
  1547. url,
  1548. content={"user_id": self.second_user_id},
  1549. access_token=self.admin_user_tok,
  1550. )
  1551. self.assertEqual(HTTPStatus.NOT_FOUND, channel.code, msg=channel.json_body)
  1552. self.assertEqual(
  1553. "Can't join remote room because no servers that are in the room have been provided.",
  1554. channel.json_body["error"],
  1555. )
  1556. def test_room_is_not_valid(self) -> None:
  1557. """
  1558. Check that invalid room names, return an error HTTPStatus.BAD_REQUEST.
  1559. """
  1560. url = "/_synapse/admin/v1/join/invalidroom"
  1561. channel = self.make_request(
  1562. "POST",
  1563. url,
  1564. content={"user_id": self.second_user_id},
  1565. access_token=self.admin_user_tok,
  1566. )
  1567. self.assertEqual(HTTPStatus.BAD_REQUEST, channel.code, msg=channel.json_body)
  1568. self.assertEqual(
  1569. "invalidroom was not legal room ID or room alias",
  1570. channel.json_body["error"],
  1571. )
  1572. def test_join_public_room(self) -> None:
  1573. """
  1574. Test joining a local user to a public room with "JoinRules.PUBLIC"
  1575. """
  1576. channel = self.make_request(
  1577. "POST",
  1578. self.url,
  1579. content={"user_id": self.second_user_id},
  1580. access_token=self.admin_user_tok,
  1581. )
  1582. self.assertEqual(HTTPStatus.OK, channel.code, msg=channel.json_body)
  1583. self.assertEqual(self.public_room_id, channel.json_body["room_id"])
  1584. # Validate if user is a member of the room
  1585. channel = self.make_request(
  1586. "GET",
  1587. "/_matrix/client/r0/joined_rooms",
  1588. access_token=self.second_tok,
  1589. )
  1590. self.assertEqual(HTTPStatus.OK, channel.code, msg=channel.json_body)
  1591. self.assertEqual(self.public_room_id, channel.json_body["joined_rooms"][0])
  1592. def test_join_private_room_if_not_member(self) -> None:
  1593. """
  1594. Test joining a local user to a private room with "JoinRules.INVITE"
  1595. when server admin is not member of this room.
  1596. """
  1597. private_room_id = self.helper.create_room_as(
  1598. self.creator, tok=self.creator_tok, is_public=False
  1599. )
  1600. url = f"/_synapse/admin/v1/join/{private_room_id}"
  1601. channel = self.make_request(
  1602. "POST",
  1603. url,
  1604. content={"user_id": self.second_user_id},
  1605. access_token=self.admin_user_tok,
  1606. )
  1607. self.assertEqual(HTTPStatus.FORBIDDEN, channel.code, msg=channel.json_body)
  1608. self.assertEqual(Codes.FORBIDDEN, channel.json_body["errcode"])
  1609. def test_join_private_room_if_member(self) -> None:
  1610. """
  1611. Test joining a local user to a private room with "JoinRules.INVITE",
  1612. when server admin is member of this room.
  1613. """
  1614. private_room_id = self.helper.create_room_as(
  1615. self.creator, tok=self.creator_tok, is_public=False
  1616. )
  1617. self.helper.invite(
  1618. room=private_room_id,
  1619. src=self.creator,
  1620. targ=self.admin_user,
  1621. tok=self.creator_tok,
  1622. )
  1623. self.helper.join(
  1624. room=private_room_id, user=self.admin_user, tok=self.admin_user_tok
  1625. )
  1626. # Validate if server admin is a member of the room
  1627. channel = self.make_request(
  1628. "GET",
  1629. "/_matrix/client/r0/joined_rooms",
  1630. access_token=self.admin_user_tok,
  1631. )
  1632. self.assertEqual(HTTPStatus.OK, channel.code, msg=channel.json_body)
  1633. self.assertEqual(private_room_id, channel.json_body["joined_rooms"][0])
  1634. # Join user to room.
  1635. url = f"/_synapse/admin/v1/join/{private_room_id}"
  1636. channel = self.make_request(
  1637. "POST",
  1638. url,
  1639. content={"user_id": self.second_user_id},
  1640. access_token=self.admin_user_tok,
  1641. )
  1642. self.assertEqual(HTTPStatus.OK, channel.code, msg=channel.json_body)
  1643. self.assertEqual(private_room_id, channel.json_body["room_id"])
  1644. # Validate if user is a member of the room
  1645. channel = self.make_request(
  1646. "GET",
  1647. "/_matrix/client/r0/joined_rooms",
  1648. access_token=self.second_tok,
  1649. )
  1650. self.assertEqual(HTTPStatus.OK, channel.code, msg=channel.json_body)
  1651. self.assertEqual(private_room_id, channel.json_body["joined_rooms"][0])
  1652. def test_join_private_room_if_owner(self) -> None:
  1653. """
  1654. Test joining a local user to a private room with "JoinRules.INVITE",
  1655. when server admin is owner of this room.
  1656. """
  1657. private_room_id = self.helper.create_room_as(
  1658. self.admin_user, tok=self.admin_user_tok, is_public=False
  1659. )
  1660. url = f"/_synapse/admin/v1/join/{private_room_id}"
  1661. channel = self.make_request(
  1662. "POST",
  1663. url,
  1664. content={"user_id": self.second_user_id},
  1665. access_token=self.admin_user_tok,
  1666. )
  1667. self.assertEqual(HTTPStatus.OK, channel.code, msg=channel.json_body)
  1668. self.assertEqual(private_room_id, channel.json_body["room_id"])
  1669. # Validate if user is a member of the room
  1670. channel = self.make_request(
  1671. "GET",
  1672. "/_matrix/client/r0/joined_rooms",
  1673. access_token=self.second_tok,
  1674. )
  1675. self.assertEqual(HTTPStatus.OK, channel.code, msg=channel.json_body)
  1676. self.assertEqual(private_room_id, channel.json_body["joined_rooms"][0])
  1677. def test_context_as_non_admin(self) -> None:
  1678. """
  1679. Test that, without being admin, one cannot use the context admin API
  1680. """
  1681. # Create a room.
  1682. user_id = self.register_user("test", "test")
  1683. user_tok = self.login("test", "test")
  1684. self.register_user("test_2", "test")
  1685. user_tok_2 = self.login("test_2", "test")
  1686. room_id = self.helper.create_room_as(user_id, tok=user_tok)
  1687. # Populate the room with events.
  1688. events = []
  1689. for i in range(30):
  1690. events.append(
  1691. self.helper.send_event(
  1692. room_id, "com.example.test", content={"index": i}, tok=user_tok
  1693. )
  1694. )
  1695. # Now attempt to find the context using the admin API without being admin.
  1696. midway = (len(events) - 1) // 2
  1697. for tok in [user_tok, user_tok_2]:
  1698. channel = self.make_request(
  1699. "GET",
  1700. "/_synapse/admin/v1/rooms/%s/context/%s"
  1701. % (room_id, events[midway]["event_id"]),
  1702. access_token=tok,
  1703. )
  1704. self.assertEqual(HTTPStatus.FORBIDDEN, channel.code, msg=channel.json_body)
  1705. self.assertEqual(Codes.FORBIDDEN, channel.json_body["errcode"])
  1706. def test_context_as_admin(self) -> None:
  1707. """
  1708. Test that, as admin, we can find the context of an event without having joined the room.
  1709. """
  1710. # Create a room. We're not part of it.
  1711. user_id = self.register_user("test", "test")
  1712. user_tok = self.login("test", "test")
  1713. room_id = self.helper.create_room_as(user_id, tok=user_tok)
  1714. # Populate the room with events.
  1715. events = []
  1716. for i in range(30):
  1717. events.append(
  1718. self.helper.send_event(
  1719. room_id, "com.example.test", content={"index": i}, tok=user_tok
  1720. )
  1721. )
  1722. # Now let's fetch the context for this room.
  1723. midway = (len(events) - 1) // 2
  1724. channel = self.make_request(
  1725. "GET",
  1726. "/_synapse/admin/v1/rooms/%s/context/%s"
  1727. % (room_id, events[midway]["event_id"]),
  1728. access_token=self.admin_user_tok,
  1729. )
  1730. self.assertEqual(HTTPStatus.OK, channel.code, msg=channel.json_body)
  1731. self.assertEqual(
  1732. channel.json_body["event"]["event_id"], events[midway]["event_id"]
  1733. )
  1734. for found_event in channel.json_body["events_before"]:
  1735. for j, posted_event in enumerate(events):
  1736. if found_event["event_id"] == posted_event["event_id"]:
  1737. self.assertTrue(j < midway)
  1738. break
  1739. else:
  1740. self.fail("Event %s from events_before not found" % j)
  1741. for found_event in channel.json_body["events_after"]:
  1742. for j, posted_event in enumerate(events):
  1743. if found_event["event_id"] == posted_event["event_id"]:
  1744. self.assertTrue(j > midway)
  1745. break
  1746. else:
  1747. self.fail("Event %s from events_after not found" % j)
  1748. class MakeRoomAdminTestCase(unittest.HomeserverTestCase):
  1749. servlets = [
  1750. synapse.rest.admin.register_servlets,
  1751. room.register_servlets,
  1752. login.register_servlets,
  1753. ]
  1754. def prepare(self, reactor: MemoryReactor, clock: Clock, hs: HomeServer) -> None:
  1755. self.admin_user = self.register_user("admin", "pass", admin=True)
  1756. self.admin_user_tok = self.login("admin", "pass")
  1757. self.creator = self.register_user("creator", "test")
  1758. self.creator_tok = self.login("creator", "test")
  1759. self.second_user_id = self.register_user("second", "test")
  1760. self.second_tok = self.login("second", "test")
  1761. self.public_room_id = self.helper.create_room_as(
  1762. self.creator, tok=self.creator_tok, is_public=True
  1763. )
  1764. self.url = "/_synapse/admin/v1/rooms/{}/make_room_admin".format(
  1765. self.public_room_id
  1766. )
  1767. def test_public_room(self) -> None:
  1768. """Test that getting admin in a public room works."""
  1769. room_id = self.helper.create_room_as(
  1770. self.creator, tok=self.creator_tok, is_public=True
  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 and ban a user.
  1780. self.helper.join(room_id, self.admin_user, tok=self.admin_user_tok)
  1781. self.helper.change_membership(
  1782. room_id,
  1783. self.admin_user,
  1784. "@test:test",
  1785. Membership.BAN,
  1786. tok=self.admin_user_tok,
  1787. )
  1788. def test_private_room(self) -> None:
  1789. """Test that getting admin in a private room works and we get invited."""
  1790. room_id = self.helper.create_room_as(
  1791. self.creator,
  1792. tok=self.creator_tok,
  1793. is_public=False,
  1794. )
  1795. channel = self.make_request(
  1796. "POST",
  1797. f"/_synapse/admin/v1/rooms/{room_id}/make_room_admin",
  1798. content={},
  1799. access_token=self.admin_user_tok,
  1800. )
  1801. self.assertEqual(HTTPStatus.OK, channel.code, msg=channel.json_body)
  1802. # Now we test that we can join the room (we should have received an
  1803. # invite) and can ban a user.
  1804. self.helper.join(room_id, self.admin_user, tok=self.admin_user_tok)
  1805. self.helper.change_membership(
  1806. room_id,
  1807. self.admin_user,
  1808. "@test:test",
  1809. Membership.BAN,
  1810. tok=self.admin_user_tok,
  1811. )
  1812. def test_other_user(self) -> None:
  1813. """Test that giving admin in a public room works to a non-admin user works."""
  1814. room_id = self.helper.create_room_as(
  1815. self.creator, tok=self.creator_tok, is_public=True
  1816. )
  1817. channel = self.make_request(
  1818. "POST",
  1819. f"/_synapse/admin/v1/rooms/{room_id}/make_room_admin",
  1820. content={"user_id": self.second_user_id},
  1821. access_token=self.admin_user_tok,
  1822. )
  1823. self.assertEqual(HTTPStatus.OK, channel.code, msg=channel.json_body)
  1824. # Now we test that we can join the room and ban a user.
  1825. self.helper.join(room_id, self.second_user_id, tok=self.second_tok)
  1826. self.helper.change_membership(
  1827. room_id,
  1828. self.second_user_id,
  1829. "@test:test",
  1830. Membership.BAN,
  1831. tok=self.second_tok,
  1832. )
  1833. def test_not_enough_power(self) -> None:
  1834. """Test that we get a sensible error if there are no local room admins."""
  1835. room_id = self.helper.create_room_as(
  1836. self.creator, tok=self.creator_tok, is_public=True
  1837. )
  1838. # The creator drops admin rights in the room.
  1839. pl = self.helper.get_state(
  1840. room_id, EventTypes.PowerLevels, tok=self.creator_tok
  1841. )
  1842. pl["users"][self.creator] = 0
  1843. self.helper.send_state(
  1844. room_id, EventTypes.PowerLevels, body=pl, tok=self.creator_tok
  1845. )
  1846. channel = self.make_request(
  1847. "POST",
  1848. f"/_synapse/admin/v1/rooms/{room_id}/make_room_admin",
  1849. content={},
  1850. access_token=self.admin_user_tok,
  1851. )
  1852. # We expect this to fail with a HTTPStatus.BAD_REQUEST as there are no room admins.
  1853. #
  1854. # (Note we assert the error message to ensure that it's not denied for
  1855. # some other reason)
  1856. self.assertEqual(HTTPStatus.BAD_REQUEST, channel.code, msg=channel.json_body)
  1857. self.assertEqual(
  1858. channel.json_body["error"],
  1859. "No local admin user in room with power to update power levels.",
  1860. )
  1861. class BlockRoomTestCase(unittest.HomeserverTestCase):
  1862. servlets = [
  1863. synapse.rest.admin.register_servlets,
  1864. room.register_servlets,
  1865. login.register_servlets,
  1866. ]
  1867. def prepare(self, reactor: MemoryReactor, clock: Clock, hs: HomeServer) -> None:
  1868. self._store = hs.get_datastores().main
  1869. self.admin_user = self.register_user("admin", "pass", admin=True)
  1870. self.admin_user_tok = self.login("admin", "pass")
  1871. self.other_user = self.register_user("user", "pass")
  1872. self.other_user_tok = self.login("user", "pass")
  1873. self.room_id = self.helper.create_room_as(
  1874. self.other_user, tok=self.other_user_tok
  1875. )
  1876. self.url = "/_synapse/admin/v1/rooms/%s/block"
  1877. @parameterized.expand([("PUT",), ("GET",)])
  1878. def test_requester_is_no_admin(self, method: str) -> None:
  1879. """If the user is not a server admin, an error HTTPStatus.FORBIDDEN is returned."""
  1880. channel = self.make_request(
  1881. method,
  1882. self.url % self.room_id,
  1883. content={},
  1884. access_token=self.other_user_tok,
  1885. )
  1886. self.assertEqual(HTTPStatus.FORBIDDEN, channel.code, msg=channel.json_body)
  1887. self.assertEqual(Codes.FORBIDDEN, channel.json_body["errcode"])
  1888. @parameterized.expand([("PUT",), ("GET",)])
  1889. def test_room_is_not_valid(self, method: str) -> None:
  1890. """Check that invalid room names, return an error HTTPStatus.BAD_REQUEST."""
  1891. channel = self.make_request(
  1892. method,
  1893. self.url % "invalidroom",
  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(
  1899. "invalidroom is not a legal room ID",
  1900. channel.json_body["error"],
  1901. )
  1902. def test_block_is_not_valid(self) -> None:
  1903. """If parameter `block` is not valid, return an error."""
  1904. # `block` is not valid
  1905. channel = self.make_request(
  1906. "PUT",
  1907. self.url % self.room_id,
  1908. content={"block": "NotBool"},
  1909. access_token=self.admin_user_tok,
  1910. )
  1911. self.assertEqual(HTTPStatus.BAD_REQUEST, channel.code, msg=channel.json_body)
  1912. self.assertEqual(Codes.BAD_JSON, channel.json_body["errcode"])
  1913. # `block` is not set
  1914. channel = self.make_request(
  1915. "PUT",
  1916. self.url % self.room_id,
  1917. content={},
  1918. access_token=self.admin_user_tok,
  1919. )
  1920. self.assertEqual(HTTPStatus.BAD_REQUEST, channel.code, msg=channel.json_body)
  1921. self.assertEqual(Codes.MISSING_PARAM, channel.json_body["errcode"])
  1922. # no content is send
  1923. channel = self.make_request(
  1924. "PUT",
  1925. self.url % self.room_id,
  1926. access_token=self.admin_user_tok,
  1927. )
  1928. self.assertEqual(HTTPStatus.BAD_REQUEST, channel.code, msg=channel.json_body)
  1929. self.assertEqual(Codes.NOT_JSON, channel.json_body["errcode"])
  1930. def test_block_room(self) -> None:
  1931. """Test that block a room is successful."""
  1932. def _request_and_test_block_room(room_id: str) -> None:
  1933. self._is_blocked(room_id, expect=False)
  1934. channel = self.make_request(
  1935. "PUT",
  1936. self.url % room_id,
  1937. content={"block": True},
  1938. access_token=self.admin_user_tok,
  1939. )
  1940. self.assertEqual(HTTPStatus.OK, channel.code, msg=channel.json_body)
  1941. self.assertTrue(channel.json_body["block"])
  1942. self._is_blocked(room_id, expect=True)
  1943. # known internal room
  1944. _request_and_test_block_room(self.room_id)
  1945. # unknown internal room
  1946. _request_and_test_block_room("!unknown:test")
  1947. # unknown remote room
  1948. _request_and_test_block_room("!unknown:remote")
  1949. def test_block_room_twice(self) -> None:
  1950. """Test that block a room that is already blocked is successful."""
  1951. self._is_blocked(self.room_id, expect=False)
  1952. for _ in range(2):
  1953. channel = self.make_request(
  1954. "PUT",
  1955. self.url % self.room_id,
  1956. content={"block": True},
  1957. access_token=self.admin_user_tok,
  1958. )
  1959. self.assertEqual(HTTPStatus.OK, channel.code, msg=channel.json_body)
  1960. self.assertTrue(channel.json_body["block"])
  1961. self._is_blocked(self.room_id, expect=True)
  1962. def test_unblock_room(self) -> None:
  1963. """Test that unblock a room is successful."""
  1964. def _request_and_test_unblock_room(room_id: str) -> None:
  1965. self._block_room(room_id)
  1966. channel = self.make_request(
  1967. "PUT",
  1968. self.url % room_id,
  1969. content={"block": False},
  1970. access_token=self.admin_user_tok,
  1971. )
  1972. self.assertEqual(HTTPStatus.OK, channel.code, msg=channel.json_body)
  1973. self.assertFalse(channel.json_body["block"])
  1974. self._is_blocked(room_id, expect=False)
  1975. # known internal room
  1976. _request_and_test_unblock_room(self.room_id)
  1977. # unknown internal room
  1978. _request_and_test_unblock_room("!unknown:test")
  1979. # unknown remote room
  1980. _request_and_test_unblock_room("!unknown:remote")
  1981. def test_unblock_room_twice(self) -> None:
  1982. """Test that unblock a room that is not blocked is successful."""
  1983. self._block_room(self.room_id)
  1984. for _ in range(2):
  1985. channel = self.make_request(
  1986. "PUT",
  1987. self.url % self.room_id,
  1988. content={"block": False},
  1989. access_token=self.admin_user_tok,
  1990. )
  1991. self.assertEqual(HTTPStatus.OK, channel.code, msg=channel.json_body)
  1992. self.assertFalse(channel.json_body["block"])
  1993. self._is_blocked(self.room_id, expect=False)
  1994. def test_get_blocked_room(self) -> None:
  1995. """Test get status of a blocked room"""
  1996. def _request_blocked_room(room_id: str) -> None:
  1997. self._block_room(room_id)
  1998. channel = self.make_request(
  1999. "GET",
  2000. self.url % room_id,
  2001. access_token=self.admin_user_tok,
  2002. )
  2003. self.assertEqual(HTTPStatus.OK, channel.code, msg=channel.json_body)
  2004. self.assertTrue(channel.json_body["block"])
  2005. self.assertEqual(self.other_user, channel.json_body["user_id"])
  2006. # known internal room
  2007. _request_blocked_room(self.room_id)
  2008. # unknown internal room
  2009. _request_blocked_room("!unknown:test")
  2010. # unknown remote room
  2011. _request_blocked_room("!unknown:remote")
  2012. def test_get_unblocked_room(self) -> None:
  2013. """Test get status of a unblocked room"""
  2014. def _request_unblocked_room(room_id: str) -> None:
  2015. self._is_blocked(room_id, expect=False)
  2016. channel = self.make_request(
  2017. "GET",
  2018. self.url % room_id,
  2019. access_token=self.admin_user_tok,
  2020. )
  2021. self.assertEqual(HTTPStatus.OK, channel.code, msg=channel.json_body)
  2022. self.assertFalse(channel.json_body["block"])
  2023. self.assertNotIn("user_id", channel.json_body)
  2024. # known internal room
  2025. _request_unblocked_room(self.room_id)
  2026. # unknown internal room
  2027. _request_unblocked_room("!unknown:test")
  2028. # unknown remote room
  2029. _request_unblocked_room("!unknown:remote")
  2030. def _is_blocked(self, room_id: str, expect: bool = True) -> None:
  2031. """Assert that the room is blocked or not"""
  2032. d = self._store.is_room_blocked(room_id)
  2033. if expect:
  2034. self.assertTrue(self.get_success(d))
  2035. else:
  2036. self.assertIsNone(self.get_success(d))
  2037. def _block_room(self, room_id: str) -> None:
  2038. """Block a room in database"""
  2039. self.get_success(self._store.block_room(room_id, self.other_user))
  2040. self._is_blocked(room_id, expect=True)
  2041. PURGE_TABLES = [
  2042. "current_state_events",
  2043. "event_backward_extremities",
  2044. "event_forward_extremities",
  2045. "event_json",
  2046. "event_push_actions",
  2047. "event_search",
  2048. "events",
  2049. "receipts_graph",
  2050. "receipts_linearized",
  2051. "room_aliases",
  2052. "room_depth",
  2053. "room_memberships",
  2054. "room_stats_state",
  2055. "room_stats_current",
  2056. "room_stats_earliest_token",
  2057. "rooms",
  2058. "stream_ordering_to_exterm",
  2059. "users_in_public_rooms",
  2060. "users_who_share_private_rooms",
  2061. "appservice_room_list",
  2062. "e2e_room_keys",
  2063. "event_push_summary",
  2064. "pusher_throttle",
  2065. "room_account_data",
  2066. "room_tags",
  2067. # "state_groups", # Current impl leaves orphaned state groups around.
  2068. "state_groups_state",
  2069. "federation_inbound_events_staging",
  2070. ]