test_admin.py 38 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079
  1. # -*- coding: utf-8 -*-
  2. # Copyright 2018 New Vector Ltd
  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 os
  17. import urllib.parse
  18. from binascii import unhexlify
  19. from typing import List, Optional
  20. from mock import Mock
  21. from twisted.internet.defer import Deferred
  22. import synapse.rest.admin
  23. from synapse.http.server import JsonResource
  24. from synapse.logging.context import make_deferred_yieldable
  25. from synapse.rest.admin import VersionServlet
  26. from synapse.rest.client.v1 import directory, events, login, room
  27. from synapse.rest.client.v2_alpha import groups
  28. from tests import unittest
  29. class VersionTestCase(unittest.HomeserverTestCase):
  30. url = "/_synapse/admin/v1/server_version"
  31. def create_test_json_resource(self):
  32. resource = JsonResource(self.hs)
  33. VersionServlet(self.hs).register(resource)
  34. return resource
  35. def test_version_string(self):
  36. request, channel = self.make_request("GET", self.url, shorthand=False)
  37. self.render(request)
  38. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  39. self.assertEqual(
  40. {"server_version", "python_version"}, set(channel.json_body.keys())
  41. )
  42. class ShutdownRoomTestCase(unittest.HomeserverTestCase):
  43. servlets = [
  44. synapse.rest.admin.register_servlets_for_client_rest_resource,
  45. login.register_servlets,
  46. events.register_servlets,
  47. room.register_servlets,
  48. room.register_deprecated_servlets,
  49. ]
  50. def prepare(self, reactor, clock, hs):
  51. self.event_creation_handler = hs.get_event_creation_handler()
  52. hs.config.user_consent_version = "1"
  53. consent_uri_builder = Mock()
  54. consent_uri_builder.build_user_consent_uri.return_value = "http://example.com"
  55. self.event_creation_handler._consent_uri_builder = consent_uri_builder
  56. self.store = hs.get_datastore()
  57. self.admin_user = self.register_user("admin", "pass", admin=True)
  58. self.admin_user_tok = self.login("admin", "pass")
  59. self.other_user = self.register_user("user", "pass")
  60. self.other_user_token = self.login("user", "pass")
  61. # Mark the admin user as having consented
  62. self.get_success(self.store.user_set_consent_version(self.admin_user, "1"))
  63. def test_shutdown_room_consent(self):
  64. """Test that we can shutdown rooms with local users who have not
  65. yet accepted the privacy policy. This used to fail when we tried to
  66. force part the user from the old room.
  67. """
  68. self.event_creation_handler._block_events_without_consent_error = None
  69. room_id = self.helper.create_room_as(self.other_user, tok=self.other_user_token)
  70. # Assert one user in room
  71. users_in_room = self.get_success(self.store.get_users_in_room(room_id))
  72. self.assertEqual([self.other_user], users_in_room)
  73. # Enable require consent to send events
  74. self.event_creation_handler._block_events_without_consent_error = "Error"
  75. # Assert that the user is getting consent error
  76. self.helper.send(
  77. room_id, body="foo", tok=self.other_user_token, expect_code=403
  78. )
  79. # Test that the admin can still send shutdown
  80. url = "admin/shutdown_room/" + room_id
  81. request, channel = self.make_request(
  82. "POST",
  83. url.encode("ascii"),
  84. json.dumps({"new_room_user_id": self.admin_user}),
  85. access_token=self.admin_user_tok,
  86. )
  87. self.render(request)
  88. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  89. # Assert there is now no longer anyone in the room
  90. users_in_room = self.get_success(self.store.get_users_in_room(room_id))
  91. self.assertEqual([], users_in_room)
  92. def test_shutdown_room_block_peek(self):
  93. """Test that a world_readable room can no longer be peeked into after
  94. it has been shut down.
  95. """
  96. self.event_creation_handler._block_events_without_consent_error = None
  97. room_id = self.helper.create_room_as(self.other_user, tok=self.other_user_token)
  98. # Enable world readable
  99. url = "rooms/%s/state/m.room.history_visibility" % (room_id,)
  100. request, channel = self.make_request(
  101. "PUT",
  102. url.encode("ascii"),
  103. json.dumps({"history_visibility": "world_readable"}),
  104. access_token=self.other_user_token,
  105. )
  106. self.render(request)
  107. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  108. # Test that the admin can still send shutdown
  109. url = "admin/shutdown_room/" + room_id
  110. request, channel = self.make_request(
  111. "POST",
  112. url.encode("ascii"),
  113. json.dumps({"new_room_user_id": self.admin_user}),
  114. access_token=self.admin_user_tok,
  115. )
  116. self.render(request)
  117. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  118. # Assert we can no longer peek into the room
  119. self._assert_peek(room_id, expect_code=403)
  120. def _assert_peek(self, room_id, expect_code):
  121. """Assert that the admin user can (or cannot) peek into the room.
  122. """
  123. url = "rooms/%s/initialSync" % (room_id,)
  124. request, channel = self.make_request(
  125. "GET", url.encode("ascii"), access_token=self.admin_user_tok
  126. )
  127. self.render(request)
  128. self.assertEqual(
  129. expect_code, int(channel.result["code"]), msg=channel.result["body"]
  130. )
  131. url = "events?timeout=0&room_id=" + room_id
  132. request, channel = self.make_request(
  133. "GET", url.encode("ascii"), access_token=self.admin_user_tok
  134. )
  135. self.render(request)
  136. self.assertEqual(
  137. expect_code, int(channel.result["code"]), msg=channel.result["body"]
  138. )
  139. class DeleteGroupTestCase(unittest.HomeserverTestCase):
  140. servlets = [
  141. synapse.rest.admin.register_servlets_for_client_rest_resource,
  142. login.register_servlets,
  143. groups.register_servlets,
  144. ]
  145. def prepare(self, reactor, clock, hs):
  146. self.store = hs.get_datastore()
  147. self.admin_user = self.register_user("admin", "pass", admin=True)
  148. self.admin_user_tok = self.login("admin", "pass")
  149. self.other_user = self.register_user("user", "pass")
  150. self.other_user_token = self.login("user", "pass")
  151. def test_delete_group(self):
  152. # Create a new group
  153. request, channel = self.make_request(
  154. "POST",
  155. "/create_group".encode("ascii"),
  156. access_token=self.admin_user_tok,
  157. content={"localpart": "test"},
  158. )
  159. self.render(request)
  160. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  161. group_id = channel.json_body["group_id"]
  162. self._check_group(group_id, expect_code=200)
  163. # Invite/join another user
  164. url = "/groups/%s/admin/users/invite/%s" % (group_id, self.other_user)
  165. request, channel = self.make_request(
  166. "PUT", url.encode("ascii"), access_token=self.admin_user_tok, content={}
  167. )
  168. self.render(request)
  169. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  170. url = "/groups/%s/self/accept_invite" % (group_id,)
  171. request, channel = self.make_request(
  172. "PUT", url.encode("ascii"), access_token=self.other_user_token, content={}
  173. )
  174. self.render(request)
  175. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  176. # Check other user knows they're in the group
  177. self.assertIn(group_id, self._get_groups_user_is_in(self.admin_user_tok))
  178. self.assertIn(group_id, self._get_groups_user_is_in(self.other_user_token))
  179. # Now delete the group
  180. url = "/admin/delete_group/" + group_id
  181. request, channel = self.make_request(
  182. "POST",
  183. url.encode("ascii"),
  184. access_token=self.admin_user_tok,
  185. content={"localpart": "test"},
  186. )
  187. self.render(request)
  188. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  189. # Check group returns 404
  190. self._check_group(group_id, expect_code=404)
  191. # Check users don't think they're in the group
  192. self.assertNotIn(group_id, self._get_groups_user_is_in(self.admin_user_tok))
  193. self.assertNotIn(group_id, self._get_groups_user_is_in(self.other_user_token))
  194. def _check_group(self, group_id, expect_code):
  195. """Assert that trying to fetch the given group results in the given
  196. HTTP status code
  197. """
  198. url = "/groups/%s/profile" % (group_id,)
  199. request, channel = self.make_request(
  200. "GET", url.encode("ascii"), access_token=self.admin_user_tok
  201. )
  202. self.render(request)
  203. self.assertEqual(
  204. expect_code, int(channel.result["code"]), msg=channel.result["body"]
  205. )
  206. def _get_groups_user_is_in(self, access_token):
  207. """Returns the list of groups the user is in (given their access token)
  208. """
  209. request, channel = self.make_request(
  210. "GET", "/joined_groups".encode("ascii"), access_token=access_token
  211. )
  212. self.render(request)
  213. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  214. return channel.json_body["groups"]
  215. class PurgeRoomTestCase(unittest.HomeserverTestCase):
  216. """Test /purge_room admin API.
  217. """
  218. servlets = [
  219. synapse.rest.admin.register_servlets,
  220. login.register_servlets,
  221. room.register_servlets,
  222. ]
  223. def prepare(self, reactor, clock, hs):
  224. self.store = hs.get_datastore()
  225. self.admin_user = self.register_user("admin", "pass", admin=True)
  226. self.admin_user_tok = self.login("admin", "pass")
  227. def test_purge_room(self):
  228. room_id = self.helper.create_room_as(self.admin_user, tok=self.admin_user_tok)
  229. # All users have to have left the room.
  230. self.helper.leave(room_id, user=self.admin_user, tok=self.admin_user_tok)
  231. url = "/_synapse/admin/v1/purge_room"
  232. request, channel = self.make_request(
  233. "POST",
  234. url.encode("ascii"),
  235. {"room_id": room_id},
  236. access_token=self.admin_user_tok,
  237. )
  238. self.render(request)
  239. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  240. # Test that the following tables have been purged of all rows related to the room.
  241. for table in (
  242. "current_state_events",
  243. "event_backward_extremities",
  244. "event_forward_extremities",
  245. "event_json",
  246. "event_push_actions",
  247. "event_search",
  248. "events",
  249. "group_rooms",
  250. "public_room_list_stream",
  251. "receipts_graph",
  252. "receipts_linearized",
  253. "room_aliases",
  254. "room_depth",
  255. "room_memberships",
  256. "room_stats_state",
  257. "room_stats_current",
  258. "room_stats_historical",
  259. "room_stats_earliest_token",
  260. "rooms",
  261. "stream_ordering_to_exterm",
  262. "users_in_public_rooms",
  263. "users_who_share_private_rooms",
  264. "appservice_room_list",
  265. "e2e_room_keys",
  266. "event_push_summary",
  267. "pusher_throttle",
  268. "group_summary_rooms",
  269. "local_invites",
  270. "room_account_data",
  271. "room_tags",
  272. # "state_groups", # Current impl leaves orphaned state groups around.
  273. "state_groups_state",
  274. ):
  275. count = self.get_success(
  276. self.store.db.simple_select_one_onecol(
  277. table=table,
  278. keyvalues={"room_id": room_id},
  279. retcol="COUNT(*)",
  280. desc="test_purge_room",
  281. )
  282. )
  283. self.assertEqual(count, 0, msg="Rows not purged in {}".format(table))
  284. class QuarantineMediaTestCase(unittest.HomeserverTestCase):
  285. """Test /quarantine_media admin API.
  286. """
  287. servlets = [
  288. synapse.rest.admin.register_servlets,
  289. synapse.rest.admin.register_servlets_for_media_repo,
  290. login.register_servlets,
  291. room.register_servlets,
  292. ]
  293. def prepare(self, reactor, clock, hs):
  294. self.store = hs.get_datastore()
  295. self.hs = hs
  296. # Allow for uploading and downloading to/from the media repo
  297. self.media_repo = hs.get_media_repository_resource()
  298. self.download_resource = self.media_repo.children[b"download"]
  299. self.upload_resource = self.media_repo.children[b"upload"]
  300. self.image_data = unhexlify(
  301. b"89504e470d0a1a0a0000000d4948445200000001000000010806"
  302. b"0000001f15c4890000000a49444154789c63000100000500010d"
  303. b"0a2db40000000049454e44ae426082"
  304. )
  305. def make_homeserver(self, reactor, clock):
  306. self.fetches = []
  307. def get_file(destination, path, output_stream, args=None, max_size=None):
  308. """
  309. Returns tuple[int,dict,str,int] of file length, response headers,
  310. absolute URI, and response code.
  311. """
  312. def write_to(r):
  313. data, response = r
  314. output_stream.write(data)
  315. return response
  316. d = Deferred()
  317. d.addCallback(write_to)
  318. self.fetches.append((d, destination, path, args))
  319. return make_deferred_yieldable(d)
  320. client = Mock()
  321. client.get_file = get_file
  322. self.storage_path = self.mktemp()
  323. self.media_store_path = self.mktemp()
  324. os.mkdir(self.storage_path)
  325. os.mkdir(self.media_store_path)
  326. config = self.default_config()
  327. config["media_store_path"] = self.media_store_path
  328. config["thumbnail_requirements"] = {}
  329. config["max_image_pixels"] = 2000000
  330. provider_config = {
  331. "module": "synapse.rest.media.v1.storage_provider.FileStorageProviderBackend",
  332. "store_local": True,
  333. "store_synchronous": False,
  334. "store_remote": True,
  335. "config": {"directory": self.storage_path},
  336. }
  337. config["media_storage_providers"] = [provider_config]
  338. hs = self.setup_test_homeserver(config=config, http_client=client)
  339. return hs
  340. def test_quarantine_media_requires_admin(self):
  341. self.register_user("nonadmin", "pass", admin=False)
  342. non_admin_user_tok = self.login("nonadmin", "pass")
  343. # Attempt quarantine media APIs as non-admin
  344. url = "/_synapse/admin/v1/media/quarantine/example.org/abcde12345"
  345. request, channel = self.make_request(
  346. "POST", url.encode("ascii"), access_token=non_admin_user_tok,
  347. )
  348. self.render(request)
  349. # Expect a forbidden error
  350. self.assertEqual(
  351. 403,
  352. int(channel.result["code"]),
  353. msg="Expected forbidden on quarantining media as a non-admin",
  354. )
  355. # And the roomID/userID endpoint
  356. url = "/_synapse/admin/v1/room/!room%3Aexample.com/media/quarantine"
  357. request, channel = self.make_request(
  358. "POST", url.encode("ascii"), access_token=non_admin_user_tok,
  359. )
  360. self.render(request)
  361. # Expect a forbidden error
  362. self.assertEqual(
  363. 403,
  364. int(channel.result["code"]),
  365. msg="Expected forbidden on quarantining media as a non-admin",
  366. )
  367. def test_quarantine_media_by_id(self):
  368. self.register_user("id_admin", "pass", admin=True)
  369. admin_user_tok = self.login("id_admin", "pass")
  370. self.register_user("id_nonadmin", "pass", admin=False)
  371. non_admin_user_tok = self.login("id_nonadmin", "pass")
  372. # Upload some media into the room
  373. response = self.helper.upload_media(
  374. self.upload_resource, self.image_data, tok=admin_user_tok
  375. )
  376. # Extract media ID from the response
  377. server_name_and_media_id = response["content_uri"][6:] # Cut off 'mxc://'
  378. server_name, media_id = server_name_and_media_id.split("/")
  379. # Attempt to access the media
  380. request, channel = self.make_request(
  381. "GET",
  382. server_name_and_media_id,
  383. shorthand=False,
  384. access_token=non_admin_user_tok,
  385. )
  386. request.render(self.download_resource)
  387. self.pump(1.0)
  388. # Should be successful
  389. self.assertEqual(200, int(channel.code), msg=channel.result["body"])
  390. # Quarantine the media
  391. url = "/_synapse/admin/v1/media/quarantine/%s/%s" % (
  392. urllib.parse.quote(server_name),
  393. urllib.parse.quote(media_id),
  394. )
  395. request, channel = self.make_request("POST", url, access_token=admin_user_tok,)
  396. self.render(request)
  397. self.pump(1.0)
  398. self.assertEqual(200, int(channel.code), msg=channel.result["body"])
  399. # Attempt to access the media
  400. request, channel = self.make_request(
  401. "GET",
  402. server_name_and_media_id,
  403. shorthand=False,
  404. access_token=admin_user_tok,
  405. )
  406. request.render(self.download_resource)
  407. self.pump(1.0)
  408. # Should be quarantined
  409. self.assertEqual(
  410. 404,
  411. int(channel.code),
  412. msg=(
  413. "Expected to receive a 404 on accessing quarantined media: %s"
  414. % server_name_and_media_id
  415. ),
  416. )
  417. def test_quarantine_all_media_in_room(self, override_url_template=None):
  418. self.register_user("room_admin", "pass", admin=True)
  419. admin_user_tok = self.login("room_admin", "pass")
  420. non_admin_user = self.register_user("room_nonadmin", "pass", admin=False)
  421. non_admin_user_tok = self.login("room_nonadmin", "pass")
  422. room_id = self.helper.create_room_as(non_admin_user, tok=admin_user_tok)
  423. self.helper.join(room_id, non_admin_user, tok=non_admin_user_tok)
  424. # Upload some media
  425. response_1 = self.helper.upload_media(
  426. self.upload_resource, self.image_data, tok=non_admin_user_tok
  427. )
  428. response_2 = self.helper.upload_media(
  429. self.upload_resource, self.image_data, tok=non_admin_user_tok
  430. )
  431. # Extract mxcs
  432. mxc_1 = response_1["content_uri"]
  433. mxc_2 = response_2["content_uri"]
  434. # Send it into the room
  435. self.helper.send_event(
  436. room_id,
  437. "m.room.message",
  438. content={"body": "image-1", "msgtype": "m.image", "url": mxc_1},
  439. txn_id="111",
  440. tok=non_admin_user_tok,
  441. )
  442. self.helper.send_event(
  443. room_id,
  444. "m.room.message",
  445. content={"body": "image-2", "msgtype": "m.image", "url": mxc_2},
  446. txn_id="222",
  447. tok=non_admin_user_tok,
  448. )
  449. # Quarantine all media in the room
  450. if override_url_template:
  451. url = override_url_template % urllib.parse.quote(room_id)
  452. else:
  453. url = "/_synapse/admin/v1/room/%s/media/quarantine" % urllib.parse.quote(
  454. room_id
  455. )
  456. request, channel = self.make_request("POST", url, access_token=admin_user_tok,)
  457. self.render(request)
  458. self.pump(1.0)
  459. self.assertEqual(200, int(channel.code), msg=channel.result["body"])
  460. self.assertEqual(
  461. json.loads(channel.result["body"].decode("utf-8")),
  462. {"num_quarantined": 2},
  463. "Expected 2 quarantined items",
  464. )
  465. # Convert mxc URLs to server/media_id strings
  466. server_and_media_id_1 = mxc_1[6:]
  467. server_and_media_id_2 = mxc_2[6:]
  468. # Test that we cannot download any of the media anymore
  469. request, channel = self.make_request(
  470. "GET",
  471. server_and_media_id_1,
  472. shorthand=False,
  473. access_token=non_admin_user_tok,
  474. )
  475. request.render(self.download_resource)
  476. self.pump(1.0)
  477. # Should be quarantined
  478. self.assertEqual(
  479. 404,
  480. int(channel.code),
  481. msg=(
  482. "Expected to receive a 404 on accessing quarantined media: %s"
  483. % server_and_media_id_1
  484. ),
  485. )
  486. request, channel = self.make_request(
  487. "GET",
  488. server_and_media_id_2,
  489. shorthand=False,
  490. access_token=non_admin_user_tok,
  491. )
  492. request.render(self.download_resource)
  493. self.pump(1.0)
  494. # Should be quarantined
  495. self.assertEqual(
  496. 404,
  497. int(channel.code),
  498. msg=(
  499. "Expected to receive a 404 on accessing quarantined media: %s"
  500. % server_and_media_id_2
  501. ),
  502. )
  503. def test_quaraantine_all_media_in_room_deprecated_api_path(self):
  504. # Perform the above test with the deprecated API path
  505. self.test_quarantine_all_media_in_room("/_synapse/admin/v1/quarantine_media/%s")
  506. def test_quarantine_all_media_by_user(self):
  507. self.register_user("user_admin", "pass", admin=True)
  508. admin_user_tok = self.login("user_admin", "pass")
  509. non_admin_user = self.register_user("user_nonadmin", "pass", admin=False)
  510. non_admin_user_tok = self.login("user_nonadmin", "pass")
  511. # Upload some media
  512. response_1 = self.helper.upload_media(
  513. self.upload_resource, self.image_data, tok=non_admin_user_tok
  514. )
  515. response_2 = self.helper.upload_media(
  516. self.upload_resource, self.image_data, tok=non_admin_user_tok
  517. )
  518. # Extract media IDs
  519. server_and_media_id_1 = response_1["content_uri"][6:]
  520. server_and_media_id_2 = response_2["content_uri"][6:]
  521. # Quarantine all media by this user
  522. url = "/_synapse/admin/v1/user/%s/media/quarantine" % urllib.parse.quote(
  523. non_admin_user
  524. )
  525. request, channel = self.make_request(
  526. "POST", url.encode("ascii"), access_token=admin_user_tok,
  527. )
  528. self.render(request)
  529. self.pump(1.0)
  530. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  531. self.assertEqual(
  532. json.loads(channel.result["body"].decode("utf-8")),
  533. {"num_quarantined": 2},
  534. "Expected 2 quarantined items",
  535. )
  536. # Attempt to access each piece of media
  537. request, channel = self.make_request(
  538. "GET",
  539. server_and_media_id_1,
  540. shorthand=False,
  541. access_token=non_admin_user_tok,
  542. )
  543. request.render(self.download_resource)
  544. self.pump(1.0)
  545. # Should be quarantined
  546. self.assertEqual(
  547. 404,
  548. int(channel.code),
  549. msg=(
  550. "Expected to receive a 404 on accessing quarantined media: %s"
  551. % server_and_media_id_1,
  552. ),
  553. )
  554. # Attempt to access each piece of media
  555. request, channel = self.make_request(
  556. "GET",
  557. server_and_media_id_2,
  558. shorthand=False,
  559. access_token=non_admin_user_tok,
  560. )
  561. request.render(self.download_resource)
  562. self.pump(1.0)
  563. # Should be quarantined
  564. self.assertEqual(
  565. 404,
  566. int(channel.code),
  567. msg=(
  568. "Expected to receive a 404 on accessing quarantined media: %s"
  569. % server_and_media_id_2
  570. ),
  571. )
  572. class RoomTestCase(unittest.HomeserverTestCase):
  573. """Test /room admin API.
  574. """
  575. servlets = [
  576. synapse.rest.admin.register_servlets,
  577. login.register_servlets,
  578. room.register_servlets,
  579. directory.register_servlets,
  580. ]
  581. def prepare(self, reactor, clock, hs):
  582. self.store = hs.get_datastore()
  583. # Create user
  584. self.admin_user = self.register_user("admin", "pass", admin=True)
  585. self.admin_user_tok = self.login("admin", "pass")
  586. def test_list_rooms(self):
  587. """Test that we can list rooms"""
  588. # Create 3 test rooms
  589. total_rooms = 3
  590. room_ids = []
  591. for x in range(total_rooms):
  592. room_id = self.helper.create_room_as(
  593. self.admin_user, tok=self.admin_user_tok
  594. )
  595. room_ids.append(room_id)
  596. # Request the list of rooms
  597. url = "/_synapse/admin/v1/rooms"
  598. request, channel = self.make_request(
  599. "GET", url.encode("ascii"), access_token=self.admin_user_tok,
  600. )
  601. self.render(request)
  602. # Check request completed successfully
  603. self.assertEqual(200, int(channel.code), msg=channel.json_body)
  604. # Check that response json body contains a "rooms" key
  605. self.assertTrue(
  606. "rooms" in channel.json_body,
  607. msg="Response body does not " "contain a 'rooms' key",
  608. )
  609. # Check that 3 rooms were returned
  610. self.assertEqual(3, len(channel.json_body["rooms"]), msg=channel.json_body)
  611. # Check their room_ids match
  612. returned_room_ids = [room["room_id"] for room in channel.json_body["rooms"]]
  613. self.assertEqual(room_ids, returned_room_ids)
  614. # Check that all fields are available
  615. for r in channel.json_body["rooms"]:
  616. self.assertIn("name", r)
  617. self.assertIn("canonical_alias", r)
  618. self.assertIn("joined_members", r)
  619. # Check that the correct number of total rooms was returned
  620. self.assertEqual(channel.json_body["total_rooms"], total_rooms)
  621. # Check that the offset is correct
  622. # Should be 0 as we aren't paginating
  623. self.assertEqual(channel.json_body["offset"], 0)
  624. # Check that the prev_batch parameter is not present
  625. self.assertNotIn("prev_batch", channel.json_body)
  626. # We shouldn't receive a next token here as there's no further rooms to show
  627. self.assertNotIn("next_batch", channel.json_body)
  628. def test_list_rooms_pagination(self):
  629. """Test that we can get a full list of rooms through pagination"""
  630. # Create 5 test rooms
  631. total_rooms = 5
  632. room_ids = []
  633. for x in range(total_rooms):
  634. room_id = self.helper.create_room_as(
  635. self.admin_user, tok=self.admin_user_tok
  636. )
  637. room_ids.append(room_id)
  638. # Set the name of the rooms so we get a consistent returned ordering
  639. for idx, room_id in enumerate(room_ids):
  640. self.helper.send_state(
  641. room_id, "m.room.name", {"name": str(idx)}, tok=self.admin_user_tok,
  642. )
  643. # Request the list of rooms
  644. returned_room_ids = []
  645. start = 0
  646. limit = 2
  647. run_count = 0
  648. should_repeat = True
  649. while should_repeat:
  650. run_count += 1
  651. url = "/_synapse/admin/v1/rooms?from=%d&limit=%d&order_by=%s" % (
  652. start,
  653. limit,
  654. "alphabetical",
  655. )
  656. request, channel = self.make_request(
  657. "GET", url.encode("ascii"), access_token=self.admin_user_tok,
  658. )
  659. self.render(request)
  660. self.assertEqual(
  661. 200, int(channel.result["code"]), msg=channel.result["body"]
  662. )
  663. self.assertTrue("rooms" in channel.json_body)
  664. for r in channel.json_body["rooms"]:
  665. returned_room_ids.append(r["room_id"])
  666. # Check that the correct number of total rooms was returned
  667. self.assertEqual(channel.json_body["total_rooms"], total_rooms)
  668. # Check that the offset is correct
  669. # We're only getting 2 rooms each page, so should be 2 * last run_count
  670. self.assertEqual(channel.json_body["offset"], 2 * (run_count - 1))
  671. if run_count > 1:
  672. # Check the value of prev_batch is correct
  673. self.assertEqual(channel.json_body["prev_batch"], 2 * (run_count - 2))
  674. if "next_batch" not in channel.json_body:
  675. # We have reached the end of the list
  676. should_repeat = False
  677. else:
  678. # Make another query with an updated start value
  679. start = channel.json_body["next_batch"]
  680. # We should've queried the endpoint 3 times
  681. self.assertEqual(
  682. run_count,
  683. 3,
  684. msg="Should've queried 3 times for 5 rooms with limit 2 per query",
  685. )
  686. # Check that we received all of the room ids
  687. self.assertEqual(room_ids, returned_room_ids)
  688. url = "/_synapse/admin/v1/rooms?from=%d&limit=%d" % (start, limit)
  689. request, channel = self.make_request(
  690. "GET", url.encode("ascii"), access_token=self.admin_user_tok,
  691. )
  692. self.render(request)
  693. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  694. def test_correct_room_attributes(self):
  695. """Test the correct attributes for a room are returned"""
  696. # Create a test room
  697. room_id = self.helper.create_room_as(self.admin_user, tok=self.admin_user_tok)
  698. test_alias = "#test:test"
  699. test_room_name = "something"
  700. # Have another user join the room
  701. user_2 = self.register_user("user4", "pass")
  702. user_tok_2 = self.login("user4", "pass")
  703. self.helper.join(room_id, user_2, tok=user_tok_2)
  704. # Create a new alias to this room
  705. url = "/_matrix/client/r0/directory/room/%s" % (urllib.parse.quote(test_alias),)
  706. request, channel = self.make_request(
  707. "PUT",
  708. url.encode("ascii"),
  709. {"room_id": room_id},
  710. access_token=self.admin_user_tok,
  711. )
  712. self.render(request)
  713. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  714. # Set this new alias as the canonical alias for this room
  715. self.helper.send_state(
  716. room_id,
  717. "m.room.aliases",
  718. {"aliases": [test_alias]},
  719. tok=self.admin_user_tok,
  720. state_key="test",
  721. )
  722. self.helper.send_state(
  723. room_id,
  724. "m.room.canonical_alias",
  725. {"alias": test_alias},
  726. tok=self.admin_user_tok,
  727. )
  728. # Set a name for the room
  729. self.helper.send_state(
  730. room_id, "m.room.name", {"name": test_room_name}, tok=self.admin_user_tok,
  731. )
  732. # Request the list of rooms
  733. url = "/_synapse/admin/v1/rooms"
  734. request, channel = self.make_request(
  735. "GET", url.encode("ascii"), access_token=self.admin_user_tok,
  736. )
  737. self.render(request)
  738. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  739. # Check that rooms were returned
  740. self.assertTrue("rooms" in channel.json_body)
  741. rooms = channel.json_body["rooms"]
  742. # Check that only one room was returned
  743. self.assertEqual(len(rooms), 1)
  744. # And that the value of the total_rooms key was correct
  745. self.assertEqual(channel.json_body["total_rooms"], 1)
  746. # Check that the offset is correct
  747. # We're not paginating, so should be 0
  748. self.assertEqual(channel.json_body["offset"], 0)
  749. # Check that there is no `prev_batch`
  750. self.assertNotIn("prev_batch", channel.json_body)
  751. # Check that there is no `next_batch`
  752. self.assertNotIn("next_batch", channel.json_body)
  753. # Check that all provided attributes are set
  754. r = rooms[0]
  755. self.assertEqual(room_id, r["room_id"])
  756. self.assertEqual(test_room_name, r["name"])
  757. self.assertEqual(test_alias, r["canonical_alias"])
  758. def test_room_list_sort_order(self):
  759. """Test room list sort ordering. alphabetical versus number of members,
  760. reversing the order, etc.
  761. """
  762. # Create 3 test rooms
  763. room_id_1 = self.helper.create_room_as(self.admin_user, tok=self.admin_user_tok)
  764. room_id_2 = self.helper.create_room_as(self.admin_user, tok=self.admin_user_tok)
  765. room_id_3 = self.helper.create_room_as(self.admin_user, tok=self.admin_user_tok)
  766. # Set room names in alphabetical order. room 1 -> A, 2 -> B, 3 -> C
  767. self.helper.send_state(
  768. room_id_1, "m.room.name", {"name": "A"}, tok=self.admin_user_tok,
  769. )
  770. self.helper.send_state(
  771. room_id_2, "m.room.name", {"name": "B"}, tok=self.admin_user_tok,
  772. )
  773. self.helper.send_state(
  774. room_id_3, "m.room.name", {"name": "C"}, tok=self.admin_user_tok,
  775. )
  776. # Set room member size in the reverse order. room 1 -> 1 member, 2 -> 2, 3 -> 3
  777. user_1 = self.register_user("bob1", "pass")
  778. user_1_tok = self.login("bob1", "pass")
  779. self.helper.join(room_id_2, user_1, tok=user_1_tok)
  780. user_2 = self.register_user("bob2", "pass")
  781. user_2_tok = self.login("bob2", "pass")
  782. self.helper.join(room_id_3, user_2, tok=user_2_tok)
  783. user_3 = self.register_user("bob3", "pass")
  784. user_3_tok = self.login("bob3", "pass")
  785. self.helper.join(room_id_3, user_3, tok=user_3_tok)
  786. def _order_test(
  787. order_type: str, expected_room_list: List[str], reverse: bool = False,
  788. ):
  789. """Request the list of rooms in a certain order. Assert that order is what
  790. we expect
  791. Args:
  792. order_type: The type of ordering to give the server
  793. expected_room_list: The list of room_ids in the order we expect to get
  794. back from the server
  795. """
  796. # Request the list of rooms in the given order
  797. url = "/_synapse/admin/v1/rooms?order_by=%s" % (order_type,)
  798. if reverse:
  799. url += "&dir=b"
  800. request, channel = self.make_request(
  801. "GET", url.encode("ascii"), access_token=self.admin_user_tok,
  802. )
  803. self.render(request)
  804. self.assertEqual(200, channel.code, msg=channel.json_body)
  805. # Check that rooms were returned
  806. self.assertTrue("rooms" in channel.json_body)
  807. rooms = channel.json_body["rooms"]
  808. # Check for the correct total_rooms value
  809. self.assertEqual(channel.json_body["total_rooms"], 3)
  810. # Check that the offset is correct
  811. # We're not paginating, so should be 0
  812. self.assertEqual(channel.json_body["offset"], 0)
  813. # Check that there is no `prev_batch`
  814. self.assertNotIn("prev_batch", channel.json_body)
  815. # Check that there is no `next_batch`
  816. self.assertNotIn("next_batch", channel.json_body)
  817. # Check that rooms were returned in alphabetical order
  818. returned_order = [r["room_id"] for r in rooms]
  819. self.assertListEqual(expected_room_list, returned_order) # order is checked
  820. # Test different sort orders, with forward and reverse directions
  821. _order_test("alphabetical", [room_id_1, room_id_2, room_id_3])
  822. _order_test("alphabetical", [room_id_3, room_id_2, room_id_1], reverse=True)
  823. _order_test("size", [room_id_3, room_id_2, room_id_1])
  824. _order_test("size", [room_id_1, room_id_2, room_id_3], reverse=True)
  825. def test_search_term(self):
  826. """Test that searching for a room works correctly"""
  827. # Create two test rooms
  828. room_id_1 = self.helper.create_room_as(self.admin_user, tok=self.admin_user_tok)
  829. room_id_2 = self.helper.create_room_as(self.admin_user, tok=self.admin_user_tok)
  830. room_name_1 = "something"
  831. room_name_2 = "else"
  832. # Set the name for each room
  833. self.helper.send_state(
  834. room_id_1, "m.room.name", {"name": room_name_1}, tok=self.admin_user_tok,
  835. )
  836. self.helper.send_state(
  837. room_id_2, "m.room.name", {"name": room_name_2}, tok=self.admin_user_tok,
  838. )
  839. def _search_test(
  840. expected_room_id: Optional[str],
  841. search_term: str,
  842. expected_http_code: int = 200,
  843. ):
  844. """Search for a room and check that the returned room's id is a match
  845. Args:
  846. expected_room_id: The room_id expected to be returned by the API. Set
  847. to None to expect zero results for the search
  848. search_term: The term to search for room names with
  849. expected_http_code: The expected http code for the request
  850. """
  851. url = "/_synapse/admin/v1/rooms?search_term=%s" % (search_term,)
  852. request, channel = self.make_request(
  853. "GET", url.encode("ascii"), access_token=self.admin_user_tok,
  854. )
  855. self.render(request)
  856. self.assertEqual(expected_http_code, channel.code, msg=channel.json_body)
  857. if expected_http_code != 200:
  858. return
  859. # Check that rooms were returned
  860. self.assertTrue("rooms" in channel.json_body)
  861. rooms = channel.json_body["rooms"]
  862. # Check that the expected number of rooms were returned
  863. expected_room_count = 1 if expected_room_id else 0
  864. self.assertEqual(len(rooms), expected_room_count)
  865. self.assertEqual(channel.json_body["total_rooms"], expected_room_count)
  866. # Check that the offset is correct
  867. # We're not paginating, so should be 0
  868. self.assertEqual(channel.json_body["offset"], 0)
  869. # Check that there is no `prev_batch`
  870. self.assertNotIn("prev_batch", channel.json_body)
  871. # Check that there is no `next_batch`
  872. self.assertNotIn("next_batch", channel.json_body)
  873. if expected_room_id:
  874. # Check that the first returned room id is correct
  875. r = rooms[0]
  876. self.assertEqual(expected_room_id, r["room_id"])
  877. # Perform search tests
  878. _search_test(room_id_1, "something")
  879. _search_test(room_id_1, "thing")
  880. _search_test(room_id_2, "else")
  881. _search_test(room_id_2, "se")
  882. _search_test(None, "foo")
  883. _search_test(None, "bar")
  884. _search_test(None, "", expected_http_code=400)