test_admin.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563
  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 hashlib
  16. import hmac
  17. import json
  18. from mock import Mock
  19. import synapse.rest.admin
  20. from synapse.api.constants import UserTypes
  21. from synapse.http.server import JsonResource
  22. from synapse.rest.admin import VersionServlet
  23. from synapse.rest.client.v1 import events, login, room
  24. from synapse.rest.client.v2_alpha import groups
  25. from tests import unittest
  26. class VersionTestCase(unittest.HomeserverTestCase):
  27. url = "/_synapse/admin/v1/server_version"
  28. def create_test_json_resource(self):
  29. resource = JsonResource(self.hs)
  30. VersionServlet(self.hs).register(resource)
  31. return resource
  32. def test_version_string(self):
  33. request, channel = self.make_request("GET", self.url, shorthand=False)
  34. self.render(request)
  35. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  36. self.assertEqual(
  37. {"server_version", "python_version"}, set(channel.json_body.keys())
  38. )
  39. class UserRegisterTestCase(unittest.HomeserverTestCase):
  40. servlets = [synapse.rest.admin.register_servlets_for_client_rest_resource]
  41. def make_homeserver(self, reactor, clock):
  42. self.url = "/_matrix/client/r0/admin/register"
  43. self.registration_handler = Mock()
  44. self.identity_handler = Mock()
  45. self.login_handler = Mock()
  46. self.device_handler = Mock()
  47. self.device_handler.check_device_registered = Mock(return_value="FAKE")
  48. self.datastore = Mock(return_value=Mock())
  49. self.datastore.get_current_state_deltas = Mock(return_value=[])
  50. self.secrets = Mock()
  51. self.hs = self.setup_test_homeserver()
  52. self.hs.config.registration_shared_secret = "shared"
  53. self.hs.get_media_repository = Mock()
  54. self.hs.get_deactivate_account_handler = Mock()
  55. return self.hs
  56. def test_disabled(self):
  57. """
  58. If there is no shared secret, registration through this method will be
  59. prevented.
  60. """
  61. self.hs.config.registration_shared_secret = None
  62. request, channel = self.make_request("POST", self.url, b"{}")
  63. self.render(request)
  64. self.assertEqual(400, int(channel.result["code"]), msg=channel.result["body"])
  65. self.assertEqual(
  66. "Shared secret registration is not enabled", channel.json_body["error"]
  67. )
  68. def test_get_nonce(self):
  69. """
  70. Calling GET on the endpoint will return a randomised nonce, using the
  71. homeserver's secrets provider.
  72. """
  73. secrets = Mock()
  74. secrets.token_hex = Mock(return_value="abcd")
  75. self.hs.get_secrets = Mock(return_value=secrets)
  76. request, channel = self.make_request("GET", self.url)
  77. self.render(request)
  78. self.assertEqual(channel.json_body, {"nonce": "abcd"})
  79. def test_expired_nonce(self):
  80. """
  81. Calling GET on the endpoint will return a randomised nonce, which will
  82. only last for SALT_TIMEOUT (60s).
  83. """
  84. request, channel = self.make_request("GET", self.url)
  85. self.render(request)
  86. nonce = channel.json_body["nonce"]
  87. # 59 seconds
  88. self.reactor.advance(59)
  89. body = json.dumps({"nonce": nonce})
  90. request, channel = self.make_request("POST", self.url, body.encode("utf8"))
  91. self.render(request)
  92. self.assertEqual(400, int(channel.result["code"]), msg=channel.result["body"])
  93. self.assertEqual("username must be specified", channel.json_body["error"])
  94. # 61 seconds
  95. self.reactor.advance(2)
  96. request, channel = self.make_request("POST", self.url, body.encode("utf8"))
  97. self.render(request)
  98. self.assertEqual(400, int(channel.result["code"]), msg=channel.result["body"])
  99. self.assertEqual("unrecognised nonce", channel.json_body["error"])
  100. def test_register_incorrect_nonce(self):
  101. """
  102. Only the provided nonce can be used, as it's checked in the MAC.
  103. """
  104. request, channel = self.make_request("GET", self.url)
  105. self.render(request)
  106. nonce = channel.json_body["nonce"]
  107. want_mac = hmac.new(key=b"shared", digestmod=hashlib.sha1)
  108. want_mac.update(b"notthenonce\x00bob\x00abc123\x00admin")
  109. want_mac = want_mac.hexdigest()
  110. body = json.dumps(
  111. {
  112. "nonce": nonce,
  113. "username": "bob",
  114. "password": "abc123",
  115. "admin": True,
  116. "mac": want_mac,
  117. }
  118. )
  119. request, channel = self.make_request("POST", self.url, body.encode("utf8"))
  120. self.render(request)
  121. self.assertEqual(403, int(channel.result["code"]), msg=channel.result["body"])
  122. self.assertEqual("HMAC incorrect", channel.json_body["error"])
  123. def test_register_correct_nonce(self):
  124. """
  125. When the correct nonce is provided, and the right key is provided, the
  126. user is registered.
  127. """
  128. request, channel = self.make_request("GET", self.url)
  129. self.render(request)
  130. nonce = channel.json_body["nonce"]
  131. want_mac = hmac.new(key=b"shared", digestmod=hashlib.sha1)
  132. want_mac.update(
  133. nonce.encode("ascii") + b"\x00bob\x00abc123\x00admin\x00support"
  134. )
  135. want_mac = want_mac.hexdigest()
  136. body = json.dumps(
  137. {
  138. "nonce": nonce,
  139. "username": "bob",
  140. "password": "abc123",
  141. "admin": True,
  142. "user_type": UserTypes.SUPPORT,
  143. "mac": want_mac,
  144. }
  145. )
  146. request, channel = self.make_request("POST", self.url, body.encode("utf8"))
  147. self.render(request)
  148. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  149. self.assertEqual("@bob:test", channel.json_body["user_id"])
  150. def test_nonce_reuse(self):
  151. """
  152. A valid unrecognised nonce.
  153. """
  154. request, channel = self.make_request("GET", self.url)
  155. self.render(request)
  156. nonce = channel.json_body["nonce"]
  157. want_mac = hmac.new(key=b"shared", digestmod=hashlib.sha1)
  158. want_mac.update(nonce.encode("ascii") + b"\x00bob\x00abc123\x00admin")
  159. want_mac = want_mac.hexdigest()
  160. body = json.dumps(
  161. {
  162. "nonce": nonce,
  163. "username": "bob",
  164. "password": "abc123",
  165. "admin": True,
  166. "mac": want_mac,
  167. }
  168. )
  169. request, channel = self.make_request("POST", self.url, body.encode("utf8"))
  170. self.render(request)
  171. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  172. self.assertEqual("@bob:test", channel.json_body["user_id"])
  173. # Now, try and reuse it
  174. request, channel = self.make_request("POST", self.url, body.encode("utf8"))
  175. self.render(request)
  176. self.assertEqual(400, int(channel.result["code"]), msg=channel.result["body"])
  177. self.assertEqual("unrecognised nonce", channel.json_body["error"])
  178. def test_missing_parts(self):
  179. """
  180. Synapse will complain if you don't give nonce, username, password, and
  181. mac. Admin and user_types are optional. Additional checks are done for length
  182. and type.
  183. """
  184. def nonce():
  185. request, channel = self.make_request("GET", self.url)
  186. self.render(request)
  187. return channel.json_body["nonce"]
  188. #
  189. # Nonce check
  190. #
  191. # Must be present
  192. body = json.dumps({})
  193. request, channel = self.make_request("POST", self.url, body.encode("utf8"))
  194. self.render(request)
  195. self.assertEqual(400, int(channel.result["code"]), msg=channel.result["body"])
  196. self.assertEqual("nonce must be specified", channel.json_body["error"])
  197. #
  198. # Username checks
  199. #
  200. # Must be present
  201. body = json.dumps({"nonce": nonce()})
  202. request, channel = self.make_request("POST", self.url, body.encode("utf8"))
  203. self.render(request)
  204. self.assertEqual(400, int(channel.result["code"]), msg=channel.result["body"])
  205. self.assertEqual("username must be specified", channel.json_body["error"])
  206. # Must be a string
  207. body = json.dumps({"nonce": nonce(), "username": 1234})
  208. request, channel = self.make_request("POST", self.url, body.encode("utf8"))
  209. self.render(request)
  210. self.assertEqual(400, int(channel.result["code"]), msg=channel.result["body"])
  211. self.assertEqual("Invalid username", channel.json_body["error"])
  212. # Must not have null bytes
  213. body = json.dumps({"nonce": nonce(), "username": "abcd\u0000"})
  214. request, channel = self.make_request("POST", self.url, body.encode("utf8"))
  215. self.render(request)
  216. self.assertEqual(400, int(channel.result["code"]), msg=channel.result["body"])
  217. self.assertEqual("Invalid username", channel.json_body["error"])
  218. # Must not have null bytes
  219. body = json.dumps({"nonce": nonce(), "username": "a" * 1000})
  220. request, channel = self.make_request("POST", self.url, body.encode("utf8"))
  221. self.render(request)
  222. self.assertEqual(400, int(channel.result["code"]), msg=channel.result["body"])
  223. self.assertEqual("Invalid username", channel.json_body["error"])
  224. #
  225. # Password checks
  226. #
  227. # Must be present
  228. body = json.dumps({"nonce": nonce(), "username": "a"})
  229. request, channel = self.make_request("POST", self.url, body.encode("utf8"))
  230. self.render(request)
  231. self.assertEqual(400, int(channel.result["code"]), msg=channel.result["body"])
  232. self.assertEqual("password must be specified", channel.json_body["error"])
  233. # Must be a string
  234. body = json.dumps({"nonce": nonce(), "username": "a", "password": 1234})
  235. request, channel = self.make_request("POST", self.url, body.encode("utf8"))
  236. self.render(request)
  237. self.assertEqual(400, int(channel.result["code"]), msg=channel.result["body"])
  238. self.assertEqual("Invalid password", channel.json_body["error"])
  239. # Must not have null bytes
  240. body = json.dumps({"nonce": nonce(), "username": "a", "password": "abcd\u0000"})
  241. request, channel = self.make_request("POST", self.url, body.encode("utf8"))
  242. self.render(request)
  243. self.assertEqual(400, int(channel.result["code"]), msg=channel.result["body"])
  244. self.assertEqual("Invalid password", channel.json_body["error"])
  245. # Super long
  246. body = json.dumps({"nonce": nonce(), "username": "a", "password": "A" * 1000})
  247. request, channel = self.make_request("POST", self.url, body.encode("utf8"))
  248. self.render(request)
  249. self.assertEqual(400, int(channel.result["code"]), msg=channel.result["body"])
  250. self.assertEqual("Invalid password", channel.json_body["error"])
  251. #
  252. # user_type check
  253. #
  254. # Invalid user_type
  255. body = json.dumps(
  256. {
  257. "nonce": nonce(),
  258. "username": "a",
  259. "password": "1234",
  260. "user_type": "invalid",
  261. }
  262. )
  263. request, channel = self.make_request("POST", self.url, body.encode("utf8"))
  264. self.render(request)
  265. self.assertEqual(400, int(channel.result["code"]), msg=channel.result["body"])
  266. self.assertEqual("Invalid user type", channel.json_body["error"])
  267. class ShutdownRoomTestCase(unittest.HomeserverTestCase):
  268. servlets = [
  269. synapse.rest.admin.register_servlets_for_client_rest_resource,
  270. login.register_servlets,
  271. events.register_servlets,
  272. room.register_servlets,
  273. room.register_deprecated_servlets,
  274. ]
  275. def prepare(self, reactor, clock, hs):
  276. self.event_creation_handler = hs.get_event_creation_handler()
  277. hs.config.user_consent_version = "1"
  278. consent_uri_builder = Mock()
  279. consent_uri_builder.build_user_consent_uri.return_value = "http://example.com"
  280. self.event_creation_handler._consent_uri_builder = consent_uri_builder
  281. self.store = hs.get_datastore()
  282. self.admin_user = self.register_user("admin", "pass", admin=True)
  283. self.admin_user_tok = self.login("admin", "pass")
  284. self.other_user = self.register_user("user", "pass")
  285. self.other_user_token = self.login("user", "pass")
  286. # Mark the admin user as having consented
  287. self.get_success(self.store.user_set_consent_version(self.admin_user, "1"))
  288. def test_shutdown_room_consent(self):
  289. """Test that we can shutdown rooms with local users who have not
  290. yet accepted the privacy policy. This used to fail when we tried to
  291. force part the user from the old room.
  292. """
  293. self.event_creation_handler._block_events_without_consent_error = None
  294. room_id = self.helper.create_room_as(self.other_user, tok=self.other_user_token)
  295. # Assert one user in room
  296. users_in_room = self.get_success(self.store.get_users_in_room(room_id))
  297. self.assertEqual([self.other_user], users_in_room)
  298. # Enable require consent to send events
  299. self.event_creation_handler._block_events_without_consent_error = "Error"
  300. # Assert that the user is getting consent error
  301. self.helper.send(
  302. room_id, body="foo", tok=self.other_user_token, expect_code=403
  303. )
  304. # Test that the admin can still send shutdown
  305. url = "admin/shutdown_room/" + room_id
  306. request, channel = self.make_request(
  307. "POST",
  308. url.encode("ascii"),
  309. json.dumps({"new_room_user_id": self.admin_user}),
  310. access_token=self.admin_user_tok,
  311. )
  312. self.render(request)
  313. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  314. # Assert there is now no longer anyone in the room
  315. users_in_room = self.get_success(self.store.get_users_in_room(room_id))
  316. self.assertEqual([], users_in_room)
  317. def test_shutdown_room_block_peek(self):
  318. """Test that a world_readable room can no longer be peeked into after
  319. it has been shut down.
  320. """
  321. self.event_creation_handler._block_events_without_consent_error = None
  322. room_id = self.helper.create_room_as(self.other_user, tok=self.other_user_token)
  323. # Enable world readable
  324. url = "rooms/%s/state/m.room.history_visibility" % (room_id,)
  325. request, channel = self.make_request(
  326. "PUT",
  327. url.encode("ascii"),
  328. json.dumps({"history_visibility": "world_readable"}),
  329. access_token=self.other_user_token,
  330. )
  331. self.render(request)
  332. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  333. # Test that the admin can still send shutdown
  334. url = "admin/shutdown_room/" + room_id
  335. request, channel = self.make_request(
  336. "POST",
  337. url.encode("ascii"),
  338. json.dumps({"new_room_user_id": self.admin_user}),
  339. access_token=self.admin_user_tok,
  340. )
  341. self.render(request)
  342. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  343. # Assert we can no longer peek into the room
  344. self._assert_peek(room_id, expect_code=403)
  345. def _assert_peek(self, room_id, expect_code):
  346. """Assert that the admin user can (or cannot) peek into the room.
  347. """
  348. url = "rooms/%s/initialSync" % (room_id,)
  349. request, channel = self.make_request(
  350. "GET", url.encode("ascii"), access_token=self.admin_user_tok
  351. )
  352. self.render(request)
  353. self.assertEqual(
  354. expect_code, int(channel.result["code"]), msg=channel.result["body"]
  355. )
  356. url = "events?timeout=0&room_id=" + room_id
  357. request, channel = self.make_request(
  358. "GET", url.encode("ascii"), access_token=self.admin_user_tok
  359. )
  360. self.render(request)
  361. self.assertEqual(
  362. expect_code, int(channel.result["code"]), msg=channel.result["body"]
  363. )
  364. class DeleteGroupTestCase(unittest.HomeserverTestCase):
  365. servlets = [
  366. synapse.rest.admin.register_servlets_for_client_rest_resource,
  367. login.register_servlets,
  368. groups.register_servlets,
  369. ]
  370. def prepare(self, reactor, clock, hs):
  371. self.store = hs.get_datastore()
  372. self.admin_user = self.register_user("admin", "pass", admin=True)
  373. self.admin_user_tok = self.login("admin", "pass")
  374. self.other_user = self.register_user("user", "pass")
  375. self.other_user_token = self.login("user", "pass")
  376. def test_delete_group(self):
  377. # Create a new group
  378. request, channel = self.make_request(
  379. "POST",
  380. "/create_group".encode("ascii"),
  381. access_token=self.admin_user_tok,
  382. content={"localpart": "test"},
  383. )
  384. self.render(request)
  385. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  386. group_id = channel.json_body["group_id"]
  387. self._check_group(group_id, expect_code=200)
  388. # Invite/join another user
  389. url = "/groups/%s/admin/users/invite/%s" % (group_id, self.other_user)
  390. request, channel = self.make_request(
  391. "PUT", url.encode("ascii"), access_token=self.admin_user_tok, content={}
  392. )
  393. self.render(request)
  394. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  395. url = "/groups/%s/self/accept_invite" % (group_id,)
  396. request, channel = self.make_request(
  397. "PUT", url.encode("ascii"), access_token=self.other_user_token, content={}
  398. )
  399. self.render(request)
  400. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  401. # Check other user knows they're in the group
  402. self.assertIn(group_id, self._get_groups_user_is_in(self.admin_user_tok))
  403. self.assertIn(group_id, self._get_groups_user_is_in(self.other_user_token))
  404. # Now delete the group
  405. url = "/admin/delete_group/" + group_id
  406. request, channel = self.make_request(
  407. "POST",
  408. url.encode("ascii"),
  409. access_token=self.admin_user_tok,
  410. content={"localpart": "test"},
  411. )
  412. self.render(request)
  413. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  414. # Check group returns 404
  415. self._check_group(group_id, expect_code=404)
  416. # Check users don't think they're in the group
  417. self.assertNotIn(group_id, self._get_groups_user_is_in(self.admin_user_tok))
  418. self.assertNotIn(group_id, self._get_groups_user_is_in(self.other_user_token))
  419. def _check_group(self, group_id, expect_code):
  420. """Assert that trying to fetch the given group results in the given
  421. HTTP status code
  422. """
  423. url = "/groups/%s/profile" % (group_id,)
  424. request, channel = self.make_request(
  425. "GET", url.encode("ascii"), access_token=self.admin_user_tok
  426. )
  427. self.render(request)
  428. self.assertEqual(
  429. expect_code, int(channel.result["code"]), msg=channel.result["body"]
  430. )
  431. def _get_groups_user_is_in(self, access_token):
  432. """Returns the list of groups the user is in (given their access token)
  433. """
  434. request, channel = self.make_request(
  435. "GET", "/joined_groups".encode("ascii"), access_token=access_token
  436. )
  437. self.render(request)
  438. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  439. return channel.json_body["groups"]