test_room.py 55 KB

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