test_room.py 63 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764
  1. # Copyright 2020 Dirk Klimpel
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. import json
  15. import urllib.parse
  16. from typing import List, Optional
  17. from unittest.mock import Mock
  18. import synapse.rest.admin
  19. from synapse.api.constants import EventTypes, Membership
  20. from synapse.api.errors import Codes
  21. from synapse.rest.client.v1 import directory, events, login, room
  22. from tests import unittest
  23. """Tests admin REST events for /rooms paths."""
  24. class ShutdownRoomTestCase(unittest.HomeserverTestCase):
  25. servlets = [
  26. synapse.rest.admin.register_servlets_for_client_rest_resource,
  27. login.register_servlets,
  28. events.register_servlets,
  29. room.register_servlets,
  30. room.register_deprecated_servlets,
  31. ]
  32. def prepare(self, reactor, clock, hs):
  33. self.event_creation_handler = hs.get_event_creation_handler()
  34. hs.config.user_consent_version = "1"
  35. consent_uri_builder = Mock()
  36. consent_uri_builder.build_user_consent_uri.return_value = "http://example.com"
  37. self.event_creation_handler._consent_uri_builder = consent_uri_builder
  38. self.store = hs.get_datastore()
  39. self.admin_user = self.register_user("admin", "pass", admin=True)
  40. self.admin_user_tok = self.login("admin", "pass")
  41. self.other_user = self.register_user("user", "pass")
  42. self.other_user_token = self.login("user", "pass")
  43. # Mark the admin user as having consented
  44. self.get_success(self.store.user_set_consent_version(self.admin_user, "1"))
  45. def test_shutdown_room_consent(self):
  46. """Test that we can shutdown rooms with local users who have not
  47. yet accepted the privacy policy. This used to fail when we tried to
  48. force part the user from the old room.
  49. """
  50. self.event_creation_handler._block_events_without_consent_error = None
  51. room_id = self.helper.create_room_as(self.other_user, tok=self.other_user_token)
  52. # Assert one user in room
  53. users_in_room = self.get_success(self.store.get_users_in_room(room_id))
  54. self.assertEqual([self.other_user], users_in_room)
  55. # Enable require consent to send events
  56. self.event_creation_handler._block_events_without_consent_error = "Error"
  57. # Assert that the user is getting consent error
  58. self.helper.send(
  59. room_id, body="foo", tok=self.other_user_token, expect_code=403
  60. )
  61. # Test that the admin can still send shutdown
  62. url = "/_synapse/admin/v1/shutdown_room/" + room_id
  63. channel = self.make_request(
  64. "POST",
  65. url.encode("ascii"),
  66. json.dumps({"new_room_user_id": self.admin_user}),
  67. access_token=self.admin_user_tok,
  68. )
  69. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  70. # Assert there is now no longer anyone in the room
  71. users_in_room = self.get_success(self.store.get_users_in_room(room_id))
  72. self.assertEqual([], users_in_room)
  73. def test_shutdown_room_block_peek(self):
  74. """Test that a world_readable room can no longer be peeked into after
  75. it has been shut down.
  76. """
  77. self.event_creation_handler._block_events_without_consent_error = None
  78. room_id = self.helper.create_room_as(self.other_user, tok=self.other_user_token)
  79. # Enable world readable
  80. url = "rooms/%s/state/m.room.history_visibility" % (room_id,)
  81. channel = self.make_request(
  82. "PUT",
  83. url.encode("ascii"),
  84. json.dumps({"history_visibility": "world_readable"}),
  85. access_token=self.other_user_token,
  86. )
  87. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  88. # Test that the admin can still send shutdown
  89. url = "/_synapse/admin/v1/shutdown_room/" + room_id
  90. channel = self.make_request(
  91. "POST",
  92. url.encode("ascii"),
  93. json.dumps({"new_room_user_id": self.admin_user}),
  94. access_token=self.admin_user_tok,
  95. )
  96. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  97. # Assert we can no longer peek into the room
  98. self._assert_peek(room_id, expect_code=403)
  99. def _assert_peek(self, room_id, expect_code):
  100. """Assert that the admin user can (or cannot) peek into the room."""
  101. url = "rooms/%s/initialSync" % (room_id,)
  102. channel = self.make_request(
  103. "GET", url.encode("ascii"), access_token=self.admin_user_tok
  104. )
  105. self.assertEqual(
  106. expect_code, int(channel.result["code"]), msg=channel.result["body"]
  107. )
  108. url = "events?timeout=0&room_id=" + room_id
  109. channel = self.make_request(
  110. "GET", url.encode("ascii"), access_token=self.admin_user_tok
  111. )
  112. self.assertEqual(
  113. expect_code, int(channel.result["code"]), msg=channel.result["body"]
  114. )
  115. class DeleteRoomTestCase(unittest.HomeserverTestCase):
  116. servlets = [
  117. synapse.rest.admin.register_servlets,
  118. login.register_servlets,
  119. events.register_servlets,
  120. room.register_servlets,
  121. room.register_deprecated_servlets,
  122. ]
  123. def prepare(self, reactor, clock, hs):
  124. self.event_creation_handler = hs.get_event_creation_handler()
  125. hs.config.user_consent_version = "1"
  126. consent_uri_builder = Mock()
  127. consent_uri_builder.build_user_consent_uri.return_value = "http://example.com"
  128. self.event_creation_handler._consent_uri_builder = consent_uri_builder
  129. self.store = hs.get_datastore()
  130. self.admin_user = self.register_user("admin", "pass", admin=True)
  131. self.admin_user_tok = self.login("admin", "pass")
  132. self.other_user = self.register_user("user", "pass")
  133. self.other_user_tok = self.login("user", "pass")
  134. # Mark the admin user as having consented
  135. self.get_success(self.store.user_set_consent_version(self.admin_user, "1"))
  136. self.room_id = self.helper.create_room_as(
  137. self.other_user, tok=self.other_user_tok
  138. )
  139. self.url = "/_synapse/admin/v1/rooms/%s/delete" % self.room_id
  140. def test_requester_is_no_admin(self):
  141. """
  142. If the user is not a server admin, an error 403 is returned.
  143. """
  144. channel = self.make_request(
  145. "POST",
  146. self.url,
  147. json.dumps({}),
  148. access_token=self.other_user_tok,
  149. )
  150. self.assertEqual(403, int(channel.result["code"]), msg=channel.result["body"])
  151. self.assertEqual(Codes.FORBIDDEN, channel.json_body["errcode"])
  152. def test_room_does_not_exist(self):
  153. """
  154. Check that unknown rooms/server return error 404.
  155. """
  156. url = "/_synapse/admin/v1/rooms/!unknown:test/delete"
  157. channel = self.make_request(
  158. "POST",
  159. url,
  160. json.dumps({}),
  161. access_token=self.admin_user_tok,
  162. )
  163. self.assertEqual(404, int(channel.result["code"]), msg=channel.result["body"])
  164. self.assertEqual(Codes.NOT_FOUND, channel.json_body["errcode"])
  165. def test_room_is_not_valid(self):
  166. """
  167. Check that invalid room names, return an error 400.
  168. """
  169. url = "/_synapse/admin/v1/rooms/invalidroom/delete"
  170. channel = self.make_request(
  171. "POST",
  172. url,
  173. json.dumps({}),
  174. access_token=self.admin_user_tok,
  175. )
  176. self.assertEqual(400, int(channel.result["code"]), msg=channel.result["body"])
  177. self.assertEqual(
  178. "invalidroom is not a legal room ID",
  179. channel.json_body["error"],
  180. )
  181. def test_new_room_user_does_not_exist(self):
  182. """
  183. Tests that the user ID must be from local server but it does not have to exist.
  184. """
  185. body = json.dumps({"new_room_user_id": "@unknown:test"})
  186. channel = self.make_request(
  187. "POST",
  188. self.url,
  189. content=body.encode(encoding="utf_8"),
  190. access_token=self.admin_user_tok,
  191. )
  192. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  193. self.assertIn("new_room_id", channel.json_body)
  194. self.assertIn("kicked_users", channel.json_body)
  195. self.assertIn("failed_to_kick_users", channel.json_body)
  196. self.assertIn("local_aliases", channel.json_body)
  197. def test_new_room_user_is_not_local(self):
  198. """
  199. Check that only local users can create new room to move members.
  200. """
  201. body = json.dumps({"new_room_user_id": "@not:exist.bla"})
  202. channel = self.make_request(
  203. "POST",
  204. self.url,
  205. content=body.encode(encoding="utf_8"),
  206. access_token=self.admin_user_tok,
  207. )
  208. self.assertEqual(400, int(channel.result["code"]), msg=channel.result["body"])
  209. self.assertEqual(
  210. "User must be our own: @not:exist.bla",
  211. channel.json_body["error"],
  212. )
  213. def test_block_is_not_bool(self):
  214. """
  215. If parameter `block` is not boolean, return an error
  216. """
  217. body = json.dumps({"block": "NotBool"})
  218. channel = self.make_request(
  219. "POST",
  220. self.url,
  221. content=body.encode(encoding="utf_8"),
  222. access_token=self.admin_user_tok,
  223. )
  224. self.assertEqual(400, int(channel.result["code"]), msg=channel.result["body"])
  225. self.assertEqual(Codes.BAD_JSON, channel.json_body["errcode"])
  226. def test_purge_is_not_bool(self):
  227. """
  228. If parameter `purge` is not boolean, return an error
  229. """
  230. body = json.dumps({"purge": "NotBool"})
  231. channel = self.make_request(
  232. "POST",
  233. self.url,
  234. content=body.encode(encoding="utf_8"),
  235. access_token=self.admin_user_tok,
  236. )
  237. self.assertEqual(400, int(channel.result["code"]), msg=channel.result["body"])
  238. self.assertEqual(Codes.BAD_JSON, channel.json_body["errcode"])
  239. def test_purge_room_and_block(self):
  240. """Test to purge a room and block it.
  241. Members will not be moved to a new room and will not receive a message.
  242. """
  243. # Test that room is not purged
  244. with self.assertRaises(AssertionError):
  245. self._is_purged(self.room_id)
  246. # Test that room is not blocked
  247. self._is_blocked(self.room_id, expect=False)
  248. # Assert one user in room
  249. self._is_member(room_id=self.room_id, user_id=self.other_user)
  250. body = json.dumps({"block": True, "purge": True})
  251. channel = self.make_request(
  252. "POST",
  253. self.url.encode("ascii"),
  254. content=body.encode(encoding="utf_8"),
  255. access_token=self.admin_user_tok,
  256. )
  257. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  258. self.assertEqual(None, channel.json_body["new_room_id"])
  259. self.assertEqual(self.other_user, channel.json_body["kicked_users"][0])
  260. self.assertIn("failed_to_kick_users", channel.json_body)
  261. self.assertIn("local_aliases", channel.json_body)
  262. self._is_purged(self.room_id)
  263. self._is_blocked(self.room_id, expect=True)
  264. self._has_no_members(self.room_id)
  265. def test_purge_room_and_not_block(self):
  266. """Test to purge a room and do not block it.
  267. Members will not be moved to a new room and will not receive a message.
  268. """
  269. # Test that room is not purged
  270. with self.assertRaises(AssertionError):
  271. self._is_purged(self.room_id)
  272. # Test that room is not blocked
  273. self._is_blocked(self.room_id, expect=False)
  274. # Assert one user in room
  275. self._is_member(room_id=self.room_id, user_id=self.other_user)
  276. body = json.dumps({"block": False, "purge": True})
  277. channel = self.make_request(
  278. "POST",
  279. self.url.encode("ascii"),
  280. content=body.encode(encoding="utf_8"),
  281. access_token=self.admin_user_tok,
  282. )
  283. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  284. self.assertEqual(None, channel.json_body["new_room_id"])
  285. self.assertEqual(self.other_user, channel.json_body["kicked_users"][0])
  286. self.assertIn("failed_to_kick_users", channel.json_body)
  287. self.assertIn("local_aliases", channel.json_body)
  288. self._is_purged(self.room_id)
  289. self._is_blocked(self.room_id, expect=False)
  290. self._has_no_members(self.room_id)
  291. def test_block_room_and_not_purge(self):
  292. """Test to block a room without purging it.
  293. Members will not be moved to a new room and will not receive a message.
  294. The room will not be purged.
  295. """
  296. # Test that room is not purged
  297. with self.assertRaises(AssertionError):
  298. self._is_purged(self.room_id)
  299. # Test that room is not blocked
  300. self._is_blocked(self.room_id, expect=False)
  301. # Assert one user in room
  302. self._is_member(room_id=self.room_id, user_id=self.other_user)
  303. body = json.dumps({"block": False, "purge": False})
  304. channel = self.make_request(
  305. "POST",
  306. self.url.encode("ascii"),
  307. content=body.encode(encoding="utf_8"),
  308. access_token=self.admin_user_tok,
  309. )
  310. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  311. self.assertEqual(None, channel.json_body["new_room_id"])
  312. self.assertEqual(self.other_user, channel.json_body["kicked_users"][0])
  313. self.assertIn("failed_to_kick_users", channel.json_body)
  314. self.assertIn("local_aliases", channel.json_body)
  315. with self.assertRaises(AssertionError):
  316. self._is_purged(self.room_id)
  317. self._is_blocked(self.room_id, expect=False)
  318. self._has_no_members(self.room_id)
  319. def test_shutdown_room_consent(self):
  320. """Test that we can shutdown rooms with local users who have not
  321. yet accepted the privacy policy. This used to fail when we tried to
  322. force part the user from the old room.
  323. Members will be moved to a new room and will receive a message.
  324. """
  325. self.event_creation_handler._block_events_without_consent_error = None
  326. # Assert one user in room
  327. users_in_room = self.get_success(self.store.get_users_in_room(self.room_id))
  328. self.assertEqual([self.other_user], users_in_room)
  329. # Enable require consent to send events
  330. self.event_creation_handler._block_events_without_consent_error = "Error"
  331. # Assert that the user is getting consent error
  332. self.helper.send(
  333. self.room_id, body="foo", tok=self.other_user_tok, expect_code=403
  334. )
  335. # Test that room is not purged
  336. with self.assertRaises(AssertionError):
  337. self._is_purged(self.room_id)
  338. # Assert one user in room
  339. self._is_member(room_id=self.room_id, user_id=self.other_user)
  340. # Test that the admin can still send shutdown
  341. url = "/_synapse/admin/v1/rooms/%s/delete" % self.room_id
  342. channel = self.make_request(
  343. "POST",
  344. url.encode("ascii"),
  345. json.dumps({"new_room_user_id": self.admin_user}),
  346. access_token=self.admin_user_tok,
  347. )
  348. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  349. self.assertEqual(self.other_user, channel.json_body["kicked_users"][0])
  350. self.assertIn("new_room_id", channel.json_body)
  351. self.assertIn("failed_to_kick_users", channel.json_body)
  352. self.assertIn("local_aliases", channel.json_body)
  353. # Test that member has moved to new room
  354. self._is_member(
  355. room_id=channel.json_body["new_room_id"], user_id=self.other_user
  356. )
  357. self._is_purged(self.room_id)
  358. self._has_no_members(self.room_id)
  359. def test_shutdown_room_block_peek(self):
  360. """Test that a world_readable room can no longer be peeked into after
  361. it has been shut down.
  362. Members will be moved to a new room and will receive a message.
  363. """
  364. self.event_creation_handler._block_events_without_consent_error = None
  365. # Enable world readable
  366. url = "rooms/%s/state/m.room.history_visibility" % (self.room_id,)
  367. channel = self.make_request(
  368. "PUT",
  369. url.encode("ascii"),
  370. json.dumps({"history_visibility": "world_readable"}),
  371. access_token=self.other_user_tok,
  372. )
  373. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  374. # Test that room is not purged
  375. with self.assertRaises(AssertionError):
  376. self._is_purged(self.room_id)
  377. # Assert one user in room
  378. self._is_member(room_id=self.room_id, user_id=self.other_user)
  379. # Test that the admin can still send shutdown
  380. url = "/_synapse/admin/v1/rooms/%s/delete" % self.room_id
  381. channel = self.make_request(
  382. "POST",
  383. url.encode("ascii"),
  384. json.dumps({"new_room_user_id": self.admin_user}),
  385. access_token=self.admin_user_tok,
  386. )
  387. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  388. self.assertEqual(self.other_user, channel.json_body["kicked_users"][0])
  389. self.assertIn("new_room_id", channel.json_body)
  390. self.assertIn("failed_to_kick_users", channel.json_body)
  391. self.assertIn("local_aliases", channel.json_body)
  392. # Test that member has moved to new room
  393. self._is_member(
  394. room_id=channel.json_body["new_room_id"], user_id=self.other_user
  395. )
  396. self._is_purged(self.room_id)
  397. self._has_no_members(self.room_id)
  398. # Assert we can no longer peek into the room
  399. self._assert_peek(self.room_id, expect_code=403)
  400. def _is_blocked(self, room_id, expect=True):
  401. """Assert that the room is blocked or not"""
  402. d = self.store.is_room_blocked(room_id)
  403. if expect:
  404. self.assertTrue(self.get_success(d))
  405. else:
  406. self.assertIsNone(self.get_success(d))
  407. def _has_no_members(self, room_id):
  408. """Assert there is now no longer anyone in the room"""
  409. users_in_room = self.get_success(self.store.get_users_in_room(room_id))
  410. self.assertEqual([], users_in_room)
  411. def _is_member(self, room_id, user_id):
  412. """Test that user is member of the room"""
  413. users_in_room = self.get_success(self.store.get_users_in_room(room_id))
  414. self.assertIn(user_id, users_in_room)
  415. def _is_purged(self, room_id):
  416. """Test that the following tables have been purged of all rows related to the room."""
  417. for table in PURGE_TABLES:
  418. count = self.get_success(
  419. self.store.db_pool.simple_select_one_onecol(
  420. table=table,
  421. keyvalues={"room_id": room_id},
  422. retcol="COUNT(*)",
  423. desc="test_purge_room",
  424. )
  425. )
  426. self.assertEqual(count, 0, msg="Rows not purged in {}".format(table))
  427. def _assert_peek(self, room_id, expect_code):
  428. """Assert that the admin user can (or cannot) peek into the room."""
  429. url = "rooms/%s/initialSync" % (room_id,)
  430. channel = self.make_request(
  431. "GET", url.encode("ascii"), access_token=self.admin_user_tok
  432. )
  433. self.assertEqual(
  434. expect_code, int(channel.result["code"]), msg=channel.result["body"]
  435. )
  436. url = "events?timeout=0&room_id=" + room_id
  437. channel = self.make_request(
  438. "GET", url.encode("ascii"), access_token=self.admin_user_tok
  439. )
  440. self.assertEqual(
  441. expect_code, int(channel.result["code"]), msg=channel.result["body"]
  442. )
  443. class PurgeRoomTestCase(unittest.HomeserverTestCase):
  444. """Test /purge_room admin API."""
  445. servlets = [
  446. synapse.rest.admin.register_servlets,
  447. login.register_servlets,
  448. room.register_servlets,
  449. ]
  450. def prepare(self, reactor, clock, hs):
  451. self.store = hs.get_datastore()
  452. self.admin_user = self.register_user("admin", "pass", admin=True)
  453. self.admin_user_tok = self.login("admin", "pass")
  454. def test_purge_room(self):
  455. room_id = self.helper.create_room_as(self.admin_user, tok=self.admin_user_tok)
  456. # All users have to have left the room.
  457. self.helper.leave(room_id, user=self.admin_user, tok=self.admin_user_tok)
  458. url = "/_synapse/admin/v1/purge_room"
  459. channel = self.make_request(
  460. "POST",
  461. url.encode("ascii"),
  462. {"room_id": room_id},
  463. access_token=self.admin_user_tok,
  464. )
  465. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  466. # Test that the following tables have been purged of all rows related to the room.
  467. for table in PURGE_TABLES:
  468. count = self.get_success(
  469. self.store.db_pool.simple_select_one_onecol(
  470. table=table,
  471. keyvalues={"room_id": room_id},
  472. retcol="COUNT(*)",
  473. desc="test_purge_room",
  474. )
  475. )
  476. self.assertEqual(count, 0, msg="Rows not purged in {}".format(table))
  477. class RoomTestCase(unittest.HomeserverTestCase):
  478. """Test /room admin API."""
  479. servlets = [
  480. synapse.rest.admin.register_servlets,
  481. login.register_servlets,
  482. room.register_servlets,
  483. directory.register_servlets,
  484. ]
  485. def prepare(self, reactor, clock, hs):
  486. # Create user
  487. self.admin_user = self.register_user("admin", "pass", admin=True)
  488. self.admin_user_tok = self.login("admin", "pass")
  489. def test_list_rooms(self):
  490. """Test that we can list rooms"""
  491. # Create 3 test rooms
  492. total_rooms = 3
  493. room_ids = []
  494. for _ in range(total_rooms):
  495. room_id = self.helper.create_room_as(
  496. self.admin_user, tok=self.admin_user_tok
  497. )
  498. room_ids.append(room_id)
  499. # Request the list of rooms
  500. url = "/_synapse/admin/v1/rooms"
  501. channel = self.make_request(
  502. "GET",
  503. url.encode("ascii"),
  504. access_token=self.admin_user_tok,
  505. )
  506. # Check request completed successfully
  507. self.assertEqual(200, int(channel.code), msg=channel.json_body)
  508. # Check that response json body contains a "rooms" key
  509. self.assertTrue(
  510. "rooms" in channel.json_body,
  511. msg="Response body does not " "contain a 'rooms' key",
  512. )
  513. # Check that 3 rooms were returned
  514. self.assertEqual(3, len(channel.json_body["rooms"]), msg=channel.json_body)
  515. # Check their room_ids match
  516. returned_room_ids = [room["room_id"] for room in channel.json_body["rooms"]]
  517. self.assertEqual(room_ids, returned_room_ids)
  518. # Check that all fields are available
  519. for r in channel.json_body["rooms"]:
  520. self.assertIn("name", r)
  521. self.assertIn("canonical_alias", r)
  522. self.assertIn("joined_members", r)
  523. self.assertIn("joined_local_members", r)
  524. self.assertIn("version", r)
  525. self.assertIn("creator", r)
  526. self.assertIn("encryption", r)
  527. self.assertIn("federatable", r)
  528. self.assertIn("public", r)
  529. self.assertIn("join_rules", r)
  530. self.assertIn("guest_access", r)
  531. self.assertIn("history_visibility", r)
  532. self.assertIn("state_events", r)
  533. # Check that the correct number of total rooms was returned
  534. self.assertEqual(channel.json_body["total_rooms"], total_rooms)
  535. # Check that the offset is correct
  536. # Should be 0 as we aren't paginating
  537. self.assertEqual(channel.json_body["offset"], 0)
  538. # Check that the prev_batch parameter is not present
  539. self.assertNotIn("prev_batch", channel.json_body)
  540. # We shouldn't receive a next token here as there's no further rooms to show
  541. self.assertNotIn("next_batch", channel.json_body)
  542. def test_list_rooms_pagination(self):
  543. """Test that we can get a full list of rooms through pagination"""
  544. # Create 5 test rooms
  545. total_rooms = 5
  546. room_ids = []
  547. for _ in range(total_rooms):
  548. room_id = self.helper.create_room_as(
  549. self.admin_user, tok=self.admin_user_tok
  550. )
  551. room_ids.append(room_id)
  552. # Set the name of the rooms so we get a consistent returned ordering
  553. for idx, room_id in enumerate(room_ids):
  554. self.helper.send_state(
  555. room_id,
  556. "m.room.name",
  557. {"name": str(idx)},
  558. tok=self.admin_user_tok,
  559. )
  560. # Request the list of rooms
  561. returned_room_ids = []
  562. start = 0
  563. limit = 2
  564. run_count = 0
  565. should_repeat = True
  566. while should_repeat:
  567. run_count += 1
  568. url = "/_synapse/admin/v1/rooms?from=%d&limit=%d&order_by=%s" % (
  569. start,
  570. limit,
  571. "name",
  572. )
  573. channel = self.make_request(
  574. "GET",
  575. url.encode("ascii"),
  576. access_token=self.admin_user_tok,
  577. )
  578. self.assertEqual(
  579. 200, int(channel.result["code"]), msg=channel.result["body"]
  580. )
  581. self.assertTrue("rooms" in channel.json_body)
  582. for r in channel.json_body["rooms"]:
  583. returned_room_ids.append(r["room_id"])
  584. # Check that the correct number of total rooms was returned
  585. self.assertEqual(channel.json_body["total_rooms"], total_rooms)
  586. # Check that the offset is correct
  587. # We're only getting 2 rooms each page, so should be 2 * last run_count
  588. self.assertEqual(channel.json_body["offset"], 2 * (run_count - 1))
  589. if run_count > 1:
  590. # Check the value of prev_batch is correct
  591. self.assertEqual(channel.json_body["prev_batch"], 2 * (run_count - 2))
  592. if "next_batch" not in channel.json_body:
  593. # We have reached the end of the list
  594. should_repeat = False
  595. else:
  596. # Make another query with an updated start value
  597. start = channel.json_body["next_batch"]
  598. # We should've queried the endpoint 3 times
  599. self.assertEqual(
  600. run_count,
  601. 3,
  602. msg="Should've queried 3 times for 5 rooms with limit 2 per query",
  603. )
  604. # Check that we received all of the room ids
  605. self.assertEqual(room_ids, returned_room_ids)
  606. url = "/_synapse/admin/v1/rooms?from=%d&limit=%d" % (start, limit)
  607. channel = self.make_request(
  608. "GET",
  609. url.encode("ascii"),
  610. access_token=self.admin_user_tok,
  611. )
  612. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  613. def test_correct_room_attributes(self):
  614. """Test the correct attributes for a room are returned"""
  615. # Create a test room
  616. room_id = self.helper.create_room_as(self.admin_user, tok=self.admin_user_tok)
  617. test_alias = "#test:test"
  618. test_room_name = "something"
  619. # Have another user join the room
  620. user_2 = self.register_user("user4", "pass")
  621. user_tok_2 = self.login("user4", "pass")
  622. self.helper.join(room_id, user_2, tok=user_tok_2)
  623. # Create a new alias to this room
  624. url = "/_matrix/client/r0/directory/room/%s" % (urllib.parse.quote(test_alias),)
  625. channel = self.make_request(
  626. "PUT",
  627. url.encode("ascii"),
  628. {"room_id": room_id},
  629. access_token=self.admin_user_tok,
  630. )
  631. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  632. # Set this new alias as the canonical alias for this room
  633. self.helper.send_state(
  634. room_id,
  635. "m.room.aliases",
  636. {"aliases": [test_alias]},
  637. tok=self.admin_user_tok,
  638. state_key="test",
  639. )
  640. self.helper.send_state(
  641. room_id,
  642. "m.room.canonical_alias",
  643. {"alias": test_alias},
  644. tok=self.admin_user_tok,
  645. )
  646. # Set a name for the room
  647. self.helper.send_state(
  648. room_id,
  649. "m.room.name",
  650. {"name": test_room_name},
  651. tok=self.admin_user_tok,
  652. )
  653. # Request the list of rooms
  654. url = "/_synapse/admin/v1/rooms"
  655. channel = self.make_request(
  656. "GET",
  657. url.encode("ascii"),
  658. access_token=self.admin_user_tok,
  659. )
  660. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  661. # Check that rooms were returned
  662. self.assertTrue("rooms" in channel.json_body)
  663. rooms = channel.json_body["rooms"]
  664. # Check that only one room was returned
  665. self.assertEqual(len(rooms), 1)
  666. # And that the value of the total_rooms key was correct
  667. self.assertEqual(channel.json_body["total_rooms"], 1)
  668. # Check that the offset is correct
  669. # We're not paginating, so should be 0
  670. self.assertEqual(channel.json_body["offset"], 0)
  671. # Check that there is no `prev_batch`
  672. self.assertNotIn("prev_batch", channel.json_body)
  673. # Check that there is no `next_batch`
  674. self.assertNotIn("next_batch", channel.json_body)
  675. # Check that all provided attributes are set
  676. r = rooms[0]
  677. self.assertEqual(room_id, r["room_id"])
  678. self.assertEqual(test_room_name, r["name"])
  679. self.assertEqual(test_alias, r["canonical_alias"])
  680. def test_room_list_sort_order(self):
  681. """Test room list sort ordering. alphabetical name versus number of members,
  682. reversing the order, etc.
  683. """
  684. def _set_canonical_alias(room_id: str, test_alias: str, admin_user_tok: str):
  685. # Create a new alias to this room
  686. url = "/_matrix/client/r0/directory/room/%s" % (
  687. urllib.parse.quote(test_alias),
  688. )
  689. channel = self.make_request(
  690. "PUT",
  691. url.encode("ascii"),
  692. {"room_id": room_id},
  693. access_token=admin_user_tok,
  694. )
  695. self.assertEqual(
  696. 200, int(channel.result["code"]), msg=channel.result["body"]
  697. )
  698. # Set this new alias as the canonical alias for this room
  699. self.helper.send_state(
  700. room_id,
  701. "m.room.aliases",
  702. {"aliases": [test_alias]},
  703. tok=admin_user_tok,
  704. state_key="test",
  705. )
  706. self.helper.send_state(
  707. room_id,
  708. "m.room.canonical_alias",
  709. {"alias": test_alias},
  710. tok=admin_user_tok,
  711. )
  712. def _order_test(
  713. order_type: str,
  714. expected_room_list: List[str],
  715. reverse: bool = False,
  716. ):
  717. """Request the list of rooms in a certain order. Assert that order is what
  718. we expect
  719. Args:
  720. order_type: The type of ordering to give the server
  721. expected_room_list: The list of room_ids in the order we expect to get
  722. back from the server
  723. """
  724. # Request the list of rooms in the given order
  725. url = "/_synapse/admin/v1/rooms?order_by=%s" % (order_type,)
  726. if reverse:
  727. url += "&dir=b"
  728. channel = self.make_request(
  729. "GET",
  730. url.encode("ascii"),
  731. access_token=self.admin_user_tok,
  732. )
  733. self.assertEqual(200, channel.code, msg=channel.json_body)
  734. # Check that rooms were returned
  735. self.assertTrue("rooms" in channel.json_body)
  736. rooms = channel.json_body["rooms"]
  737. # Check for the correct total_rooms value
  738. self.assertEqual(channel.json_body["total_rooms"], 3)
  739. # Check that the offset is correct
  740. # We're not paginating, so should be 0
  741. self.assertEqual(channel.json_body["offset"], 0)
  742. # Check that there is no `prev_batch`
  743. self.assertNotIn("prev_batch", channel.json_body)
  744. # Check that there is no `next_batch`
  745. self.assertNotIn("next_batch", channel.json_body)
  746. # Check that rooms were returned in alphabetical order
  747. returned_order = [r["room_id"] for r in rooms]
  748. self.assertListEqual(expected_room_list, returned_order) # order is checked
  749. # Create 3 test rooms
  750. room_id_1 = self.helper.create_room_as(self.admin_user, tok=self.admin_user_tok)
  751. room_id_2 = self.helper.create_room_as(self.admin_user, tok=self.admin_user_tok)
  752. room_id_3 = self.helper.create_room_as(self.admin_user, tok=self.admin_user_tok)
  753. # Set room names in alphabetical order. room 1 -> A, 2 -> B, 3 -> C
  754. self.helper.send_state(
  755. room_id_1,
  756. "m.room.name",
  757. {"name": "A"},
  758. tok=self.admin_user_tok,
  759. )
  760. self.helper.send_state(
  761. room_id_2,
  762. "m.room.name",
  763. {"name": "B"},
  764. tok=self.admin_user_tok,
  765. )
  766. self.helper.send_state(
  767. room_id_3,
  768. "m.room.name",
  769. {"name": "C"},
  770. tok=self.admin_user_tok,
  771. )
  772. # Set room canonical room aliases
  773. _set_canonical_alias(room_id_1, "#A_alias:test", self.admin_user_tok)
  774. _set_canonical_alias(room_id_2, "#B_alias:test", self.admin_user_tok)
  775. _set_canonical_alias(room_id_3, "#C_alias:test", self.admin_user_tok)
  776. # Set room member size in the reverse order. room 1 -> 1 member, 2 -> 2, 3 -> 3
  777. user_1 = self.register_user("bob1", "pass")
  778. user_1_tok = self.login("bob1", "pass")
  779. self.helper.join(room_id_2, user_1, tok=user_1_tok)
  780. user_2 = self.register_user("bob2", "pass")
  781. user_2_tok = self.login("bob2", "pass")
  782. self.helper.join(room_id_3, user_2, tok=user_2_tok)
  783. user_3 = self.register_user("bob3", "pass")
  784. user_3_tok = self.login("bob3", "pass")
  785. self.helper.join(room_id_3, user_3, tok=user_3_tok)
  786. # Test different sort orders, with forward and reverse directions
  787. _order_test("name", [room_id_1, room_id_2, room_id_3])
  788. _order_test("name", [room_id_3, room_id_2, room_id_1], reverse=True)
  789. _order_test("canonical_alias", [room_id_1, room_id_2, room_id_3])
  790. _order_test("canonical_alias", [room_id_3, room_id_2, room_id_1], reverse=True)
  791. _order_test("joined_members", [room_id_3, room_id_2, room_id_1])
  792. _order_test("joined_members", [room_id_1, room_id_2, room_id_3], reverse=True)
  793. _order_test("joined_local_members", [room_id_3, room_id_2, room_id_1])
  794. _order_test(
  795. "joined_local_members", [room_id_1, room_id_2, room_id_3], reverse=True
  796. )
  797. _order_test("version", [room_id_1, room_id_2, room_id_3])
  798. _order_test("version", [room_id_1, room_id_2, room_id_3], reverse=True)
  799. _order_test("creator", [room_id_1, room_id_2, room_id_3])
  800. _order_test("creator", [room_id_1, room_id_2, room_id_3], reverse=True)
  801. _order_test("encryption", [room_id_1, room_id_2, room_id_3])
  802. _order_test("encryption", [room_id_1, room_id_2, room_id_3], reverse=True)
  803. _order_test("federatable", [room_id_1, room_id_2, room_id_3])
  804. _order_test("federatable", [room_id_1, room_id_2, room_id_3], reverse=True)
  805. _order_test("public", [room_id_1, room_id_2, room_id_3])
  806. # Different sort order of SQlite and PostreSQL
  807. # _order_test("public", [room_id_3, room_id_2, room_id_1], reverse=True)
  808. _order_test("join_rules", [room_id_1, room_id_2, room_id_3])
  809. _order_test("join_rules", [room_id_1, room_id_2, room_id_3], reverse=True)
  810. _order_test("guest_access", [room_id_1, room_id_2, room_id_3])
  811. _order_test("guest_access", [room_id_1, room_id_2, room_id_3], reverse=True)
  812. _order_test("history_visibility", [room_id_1, room_id_2, room_id_3])
  813. _order_test(
  814. "history_visibility", [room_id_1, room_id_2, room_id_3], reverse=True
  815. )
  816. _order_test("state_events", [room_id_3, room_id_2, room_id_1])
  817. _order_test("state_events", [room_id_1, room_id_2, room_id_3], reverse=True)
  818. def test_search_term(self):
  819. """Test that searching for a room works correctly"""
  820. # Create two test rooms
  821. room_id_1 = self.helper.create_room_as(self.admin_user, tok=self.admin_user_tok)
  822. room_id_2 = self.helper.create_room_as(self.admin_user, tok=self.admin_user_tok)
  823. room_name_1 = "something"
  824. room_name_2 = "else"
  825. # Set the name for each room
  826. self.helper.send_state(
  827. room_id_1,
  828. "m.room.name",
  829. {"name": room_name_1},
  830. tok=self.admin_user_tok,
  831. )
  832. self.helper.send_state(
  833. room_id_2,
  834. "m.room.name",
  835. {"name": room_name_2},
  836. tok=self.admin_user_tok,
  837. )
  838. def _search_test(
  839. expected_room_id: Optional[str],
  840. search_term: str,
  841. expected_http_code: int = 200,
  842. ):
  843. """Search for a room and check that the returned room's id is a match
  844. Args:
  845. expected_room_id: The room_id expected to be returned by the API. Set
  846. to None to expect zero results for the search
  847. search_term: The term to search for room names with
  848. expected_http_code: The expected http code for the request
  849. """
  850. url = "/_synapse/admin/v1/rooms?search_term=%s" % (search_term,)
  851. channel = self.make_request(
  852. "GET",
  853. url.encode("ascii"),
  854. access_token=self.admin_user_tok,
  855. )
  856. self.assertEqual(expected_http_code, channel.code, msg=channel.json_body)
  857. if expected_http_code != 200:
  858. return
  859. # Check that rooms were returned
  860. self.assertTrue("rooms" in channel.json_body)
  861. rooms = channel.json_body["rooms"]
  862. # Check that the expected number of rooms were returned
  863. expected_room_count = 1 if expected_room_id else 0
  864. self.assertEqual(len(rooms), expected_room_count)
  865. self.assertEqual(channel.json_body["total_rooms"], expected_room_count)
  866. # Check that the offset is correct
  867. # We're not paginating, so should be 0
  868. self.assertEqual(channel.json_body["offset"], 0)
  869. # Check that there is no `prev_batch`
  870. self.assertNotIn("prev_batch", channel.json_body)
  871. # Check that there is no `next_batch`
  872. self.assertNotIn("next_batch", channel.json_body)
  873. if expected_room_id:
  874. # Check that the first returned room id is correct
  875. r = rooms[0]
  876. self.assertEqual(expected_room_id, r["room_id"])
  877. # Perform search tests
  878. _search_test(room_id_1, "something")
  879. _search_test(room_id_1, "thing")
  880. _search_test(room_id_2, "else")
  881. _search_test(room_id_2, "se")
  882. # Test case insensitive
  883. _search_test(room_id_1, "SOMETHING")
  884. _search_test(room_id_1, "THING")
  885. _search_test(room_id_2, "ELSE")
  886. _search_test(room_id_2, "SE")
  887. _search_test(None, "foo")
  888. _search_test(None, "bar")
  889. _search_test(None, "", expected_http_code=400)
  890. def test_single_room(self):
  891. """Test that a single room can be requested correctly"""
  892. # Create two test rooms
  893. room_id_1 = self.helper.create_room_as(self.admin_user, tok=self.admin_user_tok)
  894. room_id_2 = self.helper.create_room_as(self.admin_user, tok=self.admin_user_tok)
  895. room_name_1 = "something"
  896. room_name_2 = "else"
  897. # Set the name for each room
  898. self.helper.send_state(
  899. room_id_1,
  900. "m.room.name",
  901. {"name": room_name_1},
  902. tok=self.admin_user_tok,
  903. )
  904. self.helper.send_state(
  905. room_id_2,
  906. "m.room.name",
  907. {"name": room_name_2},
  908. tok=self.admin_user_tok,
  909. )
  910. url = "/_synapse/admin/v1/rooms/%s" % (room_id_1,)
  911. channel = self.make_request(
  912. "GET",
  913. url.encode("ascii"),
  914. access_token=self.admin_user_tok,
  915. )
  916. self.assertEqual(200, channel.code, msg=channel.json_body)
  917. self.assertIn("room_id", channel.json_body)
  918. self.assertIn("name", channel.json_body)
  919. self.assertIn("topic", channel.json_body)
  920. self.assertIn("avatar", channel.json_body)
  921. self.assertIn("canonical_alias", channel.json_body)
  922. self.assertIn("joined_members", channel.json_body)
  923. self.assertIn("joined_local_members", channel.json_body)
  924. self.assertIn("joined_local_devices", channel.json_body)
  925. self.assertIn("version", channel.json_body)
  926. self.assertIn("creator", channel.json_body)
  927. self.assertIn("encryption", channel.json_body)
  928. self.assertIn("federatable", channel.json_body)
  929. self.assertIn("public", channel.json_body)
  930. self.assertIn("join_rules", channel.json_body)
  931. self.assertIn("guest_access", channel.json_body)
  932. self.assertIn("history_visibility", channel.json_body)
  933. self.assertIn("state_events", channel.json_body)
  934. self.assertEqual(room_id_1, channel.json_body["room_id"])
  935. def test_single_room_devices(self):
  936. """Test that `joined_local_devices` can be requested correctly"""
  937. room_id_1 = self.helper.create_room_as(self.admin_user, tok=self.admin_user_tok)
  938. url = "/_synapse/admin/v1/rooms/%s" % (room_id_1,)
  939. channel = self.make_request(
  940. "GET",
  941. url.encode("ascii"),
  942. access_token=self.admin_user_tok,
  943. )
  944. self.assertEqual(200, channel.code, msg=channel.json_body)
  945. self.assertEqual(1, channel.json_body["joined_local_devices"])
  946. # Have another user join the room
  947. user_1 = self.register_user("foo", "pass")
  948. user_tok_1 = self.login("foo", "pass")
  949. self.helper.join(room_id_1, user_1, tok=user_tok_1)
  950. url = "/_synapse/admin/v1/rooms/%s" % (room_id_1,)
  951. channel = self.make_request(
  952. "GET",
  953. url.encode("ascii"),
  954. access_token=self.admin_user_tok,
  955. )
  956. self.assertEqual(200, channel.code, msg=channel.json_body)
  957. self.assertEqual(2, channel.json_body["joined_local_devices"])
  958. # leave room
  959. self.helper.leave(room_id_1, self.admin_user, tok=self.admin_user_tok)
  960. self.helper.leave(room_id_1, user_1, tok=user_tok_1)
  961. url = "/_synapse/admin/v1/rooms/%s" % (room_id_1,)
  962. channel = self.make_request(
  963. "GET",
  964. url.encode("ascii"),
  965. access_token=self.admin_user_tok,
  966. )
  967. self.assertEqual(200, channel.code, msg=channel.json_body)
  968. self.assertEqual(0, channel.json_body["joined_local_devices"])
  969. def test_room_members(self):
  970. """Test that room members can be requested correctly"""
  971. # Create two test rooms
  972. room_id_1 = self.helper.create_room_as(self.admin_user, tok=self.admin_user_tok)
  973. room_id_2 = self.helper.create_room_as(self.admin_user, tok=self.admin_user_tok)
  974. # Have another user join the room
  975. user_1 = self.register_user("foo", "pass")
  976. user_tok_1 = self.login("foo", "pass")
  977. self.helper.join(room_id_1, user_1, tok=user_tok_1)
  978. # Have another user join the room
  979. user_2 = self.register_user("bar", "pass")
  980. user_tok_2 = self.login("bar", "pass")
  981. self.helper.join(room_id_1, user_2, tok=user_tok_2)
  982. self.helper.join(room_id_2, user_2, tok=user_tok_2)
  983. # Have another user join the room
  984. user_3 = self.register_user("foobar", "pass")
  985. user_tok_3 = self.login("foobar", "pass")
  986. self.helper.join(room_id_2, user_3, tok=user_tok_3)
  987. url = "/_synapse/admin/v1/rooms/%s/members" % (room_id_1,)
  988. channel = self.make_request(
  989. "GET",
  990. url.encode("ascii"),
  991. access_token=self.admin_user_tok,
  992. )
  993. self.assertEqual(200, channel.code, msg=channel.json_body)
  994. self.assertCountEqual(
  995. ["@admin:test", "@foo:test", "@bar:test"], channel.json_body["members"]
  996. )
  997. self.assertEqual(channel.json_body["total"], 3)
  998. url = "/_synapse/admin/v1/rooms/%s/members" % (room_id_2,)
  999. channel = self.make_request(
  1000. "GET",
  1001. url.encode("ascii"),
  1002. access_token=self.admin_user_tok,
  1003. )
  1004. self.assertEqual(200, channel.code, msg=channel.json_body)
  1005. self.assertCountEqual(
  1006. ["@admin:test", "@bar:test", "@foobar:test"], channel.json_body["members"]
  1007. )
  1008. self.assertEqual(channel.json_body["total"], 3)
  1009. def test_room_state(self):
  1010. """Test that room state can be requested correctly"""
  1011. # Create two test rooms
  1012. room_id = self.helper.create_room_as(self.admin_user, tok=self.admin_user_tok)
  1013. url = "/_synapse/admin/v1/rooms/%s/state" % (room_id,)
  1014. channel = self.make_request(
  1015. "GET",
  1016. url.encode("ascii"),
  1017. access_token=self.admin_user_tok,
  1018. )
  1019. self.assertEqual(200, channel.code, msg=channel.json_body)
  1020. self.assertIn("state", channel.json_body)
  1021. # testing that the state events match is painful and not done here. We assume that
  1022. # the create_room already does the right thing, so no need to verify that we got
  1023. # the state events it created.
  1024. class JoinAliasRoomTestCase(unittest.HomeserverTestCase):
  1025. servlets = [
  1026. synapse.rest.admin.register_servlets,
  1027. room.register_servlets,
  1028. login.register_servlets,
  1029. ]
  1030. def prepare(self, reactor, clock, homeserver):
  1031. self.admin_user = self.register_user("admin", "pass", admin=True)
  1032. self.admin_user_tok = self.login("admin", "pass")
  1033. self.creator = self.register_user("creator", "test")
  1034. self.creator_tok = self.login("creator", "test")
  1035. self.second_user_id = self.register_user("second", "test")
  1036. self.second_tok = self.login("second", "test")
  1037. self.public_room_id = self.helper.create_room_as(
  1038. self.creator, tok=self.creator_tok, is_public=True
  1039. )
  1040. self.url = "/_synapse/admin/v1/join/{}".format(self.public_room_id)
  1041. def test_requester_is_no_admin(self):
  1042. """
  1043. If the user is not a server admin, an error 403 is returned.
  1044. """
  1045. body = json.dumps({"user_id": self.second_user_id})
  1046. channel = self.make_request(
  1047. "POST",
  1048. self.url,
  1049. content=body.encode(encoding="utf_8"),
  1050. access_token=self.second_tok,
  1051. )
  1052. self.assertEqual(403, int(channel.result["code"]), msg=channel.result["body"])
  1053. self.assertEqual(Codes.FORBIDDEN, channel.json_body["errcode"])
  1054. def test_invalid_parameter(self):
  1055. """
  1056. If a parameter is missing, return an error
  1057. """
  1058. body = json.dumps({"unknown_parameter": "@unknown:test"})
  1059. channel = self.make_request(
  1060. "POST",
  1061. self.url,
  1062. content=body.encode(encoding="utf_8"),
  1063. access_token=self.admin_user_tok,
  1064. )
  1065. self.assertEqual(400, int(channel.result["code"]), msg=channel.result["body"])
  1066. self.assertEqual(Codes.MISSING_PARAM, channel.json_body["errcode"])
  1067. def test_local_user_does_not_exist(self):
  1068. """
  1069. Tests that a lookup for a user that does not exist returns a 404
  1070. """
  1071. body = json.dumps({"user_id": "@unknown:test"})
  1072. channel = self.make_request(
  1073. "POST",
  1074. self.url,
  1075. content=body.encode(encoding="utf_8"),
  1076. access_token=self.admin_user_tok,
  1077. )
  1078. self.assertEqual(404, int(channel.result["code"]), msg=channel.result["body"])
  1079. self.assertEqual(Codes.NOT_FOUND, channel.json_body["errcode"])
  1080. def test_remote_user(self):
  1081. """
  1082. Check that only local user can join rooms.
  1083. """
  1084. body = json.dumps({"user_id": "@not:exist.bla"})
  1085. channel = self.make_request(
  1086. "POST",
  1087. self.url,
  1088. content=body.encode(encoding="utf_8"),
  1089. access_token=self.admin_user_tok,
  1090. )
  1091. self.assertEqual(400, int(channel.result["code"]), msg=channel.result["body"])
  1092. self.assertEqual(
  1093. "This endpoint can only be used with local users",
  1094. channel.json_body["error"],
  1095. )
  1096. def test_room_does_not_exist(self):
  1097. """
  1098. Check that unknown rooms/server return error 404.
  1099. """
  1100. body = json.dumps({"user_id": self.second_user_id})
  1101. url = "/_synapse/admin/v1/join/!unknown:test"
  1102. channel = self.make_request(
  1103. "POST",
  1104. url,
  1105. content=body.encode(encoding="utf_8"),
  1106. access_token=self.admin_user_tok,
  1107. )
  1108. self.assertEqual(404, int(channel.result["code"]), msg=channel.result["body"])
  1109. self.assertEqual("No known servers", channel.json_body["error"])
  1110. def test_room_is_not_valid(self):
  1111. """
  1112. Check that invalid room names, return an error 400.
  1113. """
  1114. body = json.dumps({"user_id": self.second_user_id})
  1115. url = "/_synapse/admin/v1/join/invalidroom"
  1116. channel = self.make_request(
  1117. "POST",
  1118. url,
  1119. content=body.encode(encoding="utf_8"),
  1120. access_token=self.admin_user_tok,
  1121. )
  1122. self.assertEqual(400, int(channel.result["code"]), msg=channel.result["body"])
  1123. self.assertEqual(
  1124. "invalidroom was not legal room ID or room alias",
  1125. channel.json_body["error"],
  1126. )
  1127. def test_join_public_room(self):
  1128. """
  1129. Test joining a local user to a public room with "JoinRules.PUBLIC"
  1130. """
  1131. body = json.dumps({"user_id": self.second_user_id})
  1132. channel = self.make_request(
  1133. "POST",
  1134. self.url,
  1135. content=body.encode(encoding="utf_8"),
  1136. access_token=self.admin_user_tok,
  1137. )
  1138. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  1139. self.assertEqual(self.public_room_id, channel.json_body["room_id"])
  1140. # Validate if user is a member of the room
  1141. channel = self.make_request(
  1142. "GET",
  1143. "/_matrix/client/r0/joined_rooms",
  1144. access_token=self.second_tok,
  1145. )
  1146. self.assertEquals(200, int(channel.result["code"]), msg=channel.result["body"])
  1147. self.assertEqual(self.public_room_id, channel.json_body["joined_rooms"][0])
  1148. def test_join_private_room_if_not_member(self):
  1149. """
  1150. Test joining a local user to a private room with "JoinRules.INVITE"
  1151. when server admin is not member of this room.
  1152. """
  1153. private_room_id = self.helper.create_room_as(
  1154. self.creator, tok=self.creator_tok, is_public=False
  1155. )
  1156. url = "/_synapse/admin/v1/join/{}".format(private_room_id)
  1157. body = json.dumps({"user_id": self.second_user_id})
  1158. channel = self.make_request(
  1159. "POST",
  1160. url,
  1161. content=body.encode(encoding="utf_8"),
  1162. access_token=self.admin_user_tok,
  1163. )
  1164. self.assertEqual(403, int(channel.result["code"]), msg=channel.result["body"])
  1165. self.assertEqual(Codes.FORBIDDEN, channel.json_body["errcode"])
  1166. def test_join_private_room_if_member(self):
  1167. """
  1168. Test joining a local user to a private room with "JoinRules.INVITE",
  1169. when server admin is member of this room.
  1170. """
  1171. private_room_id = self.helper.create_room_as(
  1172. self.creator, tok=self.creator_tok, is_public=False
  1173. )
  1174. self.helper.invite(
  1175. room=private_room_id,
  1176. src=self.creator,
  1177. targ=self.admin_user,
  1178. tok=self.creator_tok,
  1179. )
  1180. self.helper.join(
  1181. room=private_room_id, user=self.admin_user, tok=self.admin_user_tok
  1182. )
  1183. # Validate if server admin is a member of the room
  1184. channel = self.make_request(
  1185. "GET",
  1186. "/_matrix/client/r0/joined_rooms",
  1187. access_token=self.admin_user_tok,
  1188. )
  1189. self.assertEquals(200, int(channel.result["code"]), msg=channel.result["body"])
  1190. self.assertEqual(private_room_id, channel.json_body["joined_rooms"][0])
  1191. # Join user to room.
  1192. url = "/_synapse/admin/v1/join/{}".format(private_room_id)
  1193. body = json.dumps({"user_id": self.second_user_id})
  1194. channel = self.make_request(
  1195. "POST",
  1196. url,
  1197. content=body.encode(encoding="utf_8"),
  1198. access_token=self.admin_user_tok,
  1199. )
  1200. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  1201. self.assertEqual(private_room_id, channel.json_body["room_id"])
  1202. # Validate if user is a member of the room
  1203. channel = self.make_request(
  1204. "GET",
  1205. "/_matrix/client/r0/joined_rooms",
  1206. access_token=self.second_tok,
  1207. )
  1208. self.assertEquals(200, int(channel.result["code"]), msg=channel.result["body"])
  1209. self.assertEqual(private_room_id, channel.json_body["joined_rooms"][0])
  1210. def test_join_private_room_if_owner(self):
  1211. """
  1212. Test joining a local user to a private room with "JoinRules.INVITE",
  1213. when server admin is owner of this room.
  1214. """
  1215. private_room_id = self.helper.create_room_as(
  1216. self.admin_user, tok=self.admin_user_tok, is_public=False
  1217. )
  1218. url = "/_synapse/admin/v1/join/{}".format(private_room_id)
  1219. body = json.dumps({"user_id": self.second_user_id})
  1220. channel = self.make_request(
  1221. "POST",
  1222. url,
  1223. content=body.encode(encoding="utf_8"),
  1224. access_token=self.admin_user_tok,
  1225. )
  1226. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  1227. self.assertEqual(private_room_id, channel.json_body["room_id"])
  1228. # Validate if user is a member of the room
  1229. channel = self.make_request(
  1230. "GET",
  1231. "/_matrix/client/r0/joined_rooms",
  1232. access_token=self.second_tok,
  1233. )
  1234. self.assertEquals(200, int(channel.result["code"]), msg=channel.result["body"])
  1235. self.assertEqual(private_room_id, channel.json_body["joined_rooms"][0])
  1236. def test_context_as_non_admin(self):
  1237. """
  1238. Test that, without being admin, one cannot use the context admin API
  1239. """
  1240. # Create a room.
  1241. user_id = self.register_user("test", "test")
  1242. user_tok = self.login("test", "test")
  1243. self.register_user("test_2", "test")
  1244. user_tok_2 = self.login("test_2", "test")
  1245. room_id = self.helper.create_room_as(user_id, tok=user_tok)
  1246. # Populate the room with events.
  1247. events = []
  1248. for i in range(30):
  1249. events.append(
  1250. self.helper.send_event(
  1251. room_id, "com.example.test", content={"index": i}, tok=user_tok
  1252. )
  1253. )
  1254. # Now attempt to find the context using the admin API without being admin.
  1255. midway = (len(events) - 1) // 2
  1256. for tok in [user_tok, user_tok_2]:
  1257. channel = self.make_request(
  1258. "GET",
  1259. "/_synapse/admin/v1/rooms/%s/context/%s"
  1260. % (room_id, events[midway]["event_id"]),
  1261. access_token=tok,
  1262. )
  1263. self.assertEquals(
  1264. 403, int(channel.result["code"]), msg=channel.result["body"]
  1265. )
  1266. self.assertEqual(Codes.FORBIDDEN, channel.json_body["errcode"])
  1267. def test_context_as_admin(self):
  1268. """
  1269. Test that, as admin, we can find the context of an event without having joined the room.
  1270. """
  1271. # Create a room. We're not part of it.
  1272. user_id = self.register_user("test", "test")
  1273. user_tok = self.login("test", "test")
  1274. room_id = self.helper.create_room_as(user_id, tok=user_tok)
  1275. # Populate the room with events.
  1276. events = []
  1277. for i in range(30):
  1278. events.append(
  1279. self.helper.send_event(
  1280. room_id, "com.example.test", content={"index": i}, tok=user_tok
  1281. )
  1282. )
  1283. # Now let's fetch the context for this room.
  1284. midway = (len(events) - 1) // 2
  1285. channel = self.make_request(
  1286. "GET",
  1287. "/_synapse/admin/v1/rooms/%s/context/%s"
  1288. % (room_id, events[midway]["event_id"]),
  1289. access_token=self.admin_user_tok,
  1290. )
  1291. self.assertEquals(200, int(channel.result["code"]), msg=channel.result["body"])
  1292. self.assertEquals(
  1293. channel.json_body["event"]["event_id"], events[midway]["event_id"]
  1294. )
  1295. for found_event in channel.json_body["events_before"]:
  1296. for j, posted_event in enumerate(events):
  1297. if found_event["event_id"] == posted_event["event_id"]:
  1298. self.assertTrue(j < midway)
  1299. break
  1300. else:
  1301. self.fail("Event %s from events_before not found" % j)
  1302. for found_event in channel.json_body["events_after"]:
  1303. for j, posted_event in enumerate(events):
  1304. if found_event["event_id"] == posted_event["event_id"]:
  1305. self.assertTrue(j > midway)
  1306. break
  1307. else:
  1308. self.fail("Event %s from events_after not found" % j)
  1309. class MakeRoomAdminTestCase(unittest.HomeserverTestCase):
  1310. servlets = [
  1311. synapse.rest.admin.register_servlets,
  1312. room.register_servlets,
  1313. login.register_servlets,
  1314. ]
  1315. def prepare(self, reactor, clock, homeserver):
  1316. self.admin_user = self.register_user("admin", "pass", admin=True)
  1317. self.admin_user_tok = self.login("admin", "pass")
  1318. self.creator = self.register_user("creator", "test")
  1319. self.creator_tok = self.login("creator", "test")
  1320. self.second_user_id = self.register_user("second", "test")
  1321. self.second_tok = self.login("second", "test")
  1322. self.public_room_id = self.helper.create_room_as(
  1323. self.creator, tok=self.creator_tok, is_public=True
  1324. )
  1325. self.url = "/_synapse/admin/v1/rooms/{}/make_room_admin".format(
  1326. self.public_room_id
  1327. )
  1328. def test_public_room(self):
  1329. """Test that getting admin in a public room works."""
  1330. room_id = self.helper.create_room_as(
  1331. self.creator, tok=self.creator_tok, is_public=True
  1332. )
  1333. channel = self.make_request(
  1334. "POST",
  1335. "/_synapse/admin/v1/rooms/{}/make_room_admin".format(room_id),
  1336. content={},
  1337. access_token=self.admin_user_tok,
  1338. )
  1339. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  1340. # Now we test that we can join the room and ban a user.
  1341. self.helper.join(room_id, self.admin_user, tok=self.admin_user_tok)
  1342. self.helper.change_membership(
  1343. room_id,
  1344. self.admin_user,
  1345. "@test:test",
  1346. Membership.BAN,
  1347. tok=self.admin_user_tok,
  1348. )
  1349. def test_private_room(self):
  1350. """Test that getting admin in a private room works and we get invited."""
  1351. room_id = self.helper.create_room_as(
  1352. self.creator,
  1353. tok=self.creator_tok,
  1354. is_public=False,
  1355. )
  1356. channel = self.make_request(
  1357. "POST",
  1358. "/_synapse/admin/v1/rooms/{}/make_room_admin".format(room_id),
  1359. content={},
  1360. access_token=self.admin_user_tok,
  1361. )
  1362. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  1363. # Now we test that we can join the room (we should have received an
  1364. # invite) and can ban a user.
  1365. self.helper.join(room_id, self.admin_user, tok=self.admin_user_tok)
  1366. self.helper.change_membership(
  1367. room_id,
  1368. self.admin_user,
  1369. "@test:test",
  1370. Membership.BAN,
  1371. tok=self.admin_user_tok,
  1372. )
  1373. def test_other_user(self):
  1374. """Test that giving admin in a public room works to a non-admin user works."""
  1375. room_id = self.helper.create_room_as(
  1376. self.creator, tok=self.creator_tok, is_public=True
  1377. )
  1378. channel = self.make_request(
  1379. "POST",
  1380. "/_synapse/admin/v1/rooms/{}/make_room_admin".format(room_id),
  1381. content={"user_id": self.second_user_id},
  1382. access_token=self.admin_user_tok,
  1383. )
  1384. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  1385. # Now we test that we can join the room and ban a user.
  1386. self.helper.join(room_id, self.second_user_id, tok=self.second_tok)
  1387. self.helper.change_membership(
  1388. room_id,
  1389. self.second_user_id,
  1390. "@test:test",
  1391. Membership.BAN,
  1392. tok=self.second_tok,
  1393. )
  1394. def test_not_enough_power(self):
  1395. """Test that we get a sensible error if there are no local room admins."""
  1396. room_id = self.helper.create_room_as(
  1397. self.creator, tok=self.creator_tok, is_public=True
  1398. )
  1399. # The creator drops admin rights in the room.
  1400. pl = self.helper.get_state(
  1401. room_id, EventTypes.PowerLevels, tok=self.creator_tok
  1402. )
  1403. pl["users"][self.creator] = 0
  1404. self.helper.send_state(
  1405. room_id, EventTypes.PowerLevels, body=pl, tok=self.creator_tok
  1406. )
  1407. channel = self.make_request(
  1408. "POST",
  1409. "/_synapse/admin/v1/rooms/{}/make_room_admin".format(room_id),
  1410. content={},
  1411. access_token=self.admin_user_tok,
  1412. )
  1413. # We expect this to fail with a 400 as there are no room admins.
  1414. #
  1415. # (Note we assert the error message to ensure that it's not denied for
  1416. # some other reason)
  1417. self.assertEqual(400, int(channel.result["code"]), msg=channel.result["body"])
  1418. self.assertEqual(
  1419. channel.json_body["error"],
  1420. "No local admin user in room with power to update power levels.",
  1421. )
  1422. PURGE_TABLES = [
  1423. "current_state_events",
  1424. "event_backward_extremities",
  1425. "event_forward_extremities",
  1426. "event_json",
  1427. "event_push_actions",
  1428. "event_search",
  1429. "events",
  1430. "group_rooms",
  1431. "public_room_list_stream",
  1432. "receipts_graph",
  1433. "receipts_linearized",
  1434. "room_aliases",
  1435. "room_depth",
  1436. "room_memberships",
  1437. "room_stats_state",
  1438. "room_stats_current",
  1439. "room_stats_historical",
  1440. "room_stats_earliest_token",
  1441. "rooms",
  1442. "stream_ordering_to_exterm",
  1443. "users_in_public_rooms",
  1444. "users_who_share_private_rooms",
  1445. "appservice_room_list",
  1446. "e2e_room_keys",
  1447. "event_push_summary",
  1448. "pusher_throttle",
  1449. "group_summary_rooms",
  1450. "room_account_data",
  1451. "room_tags",
  1452. # "state_groups", # Current impl leaves orphaned state groups around.
  1453. "state_groups_state",
  1454. ]