test_room.py 63 KB

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