test_user.py 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998
  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. import urllib.parse
  19. from mock import Mock
  20. from twisted.internet import defer
  21. import synapse.rest.admin
  22. from synapse.api.constants import UserTypes
  23. from synapse.api.errors import HttpResponseException, ResourceLimitError
  24. from synapse.rest.client.v1 import login
  25. from synapse.rest.client.v2_alpha import sync
  26. from tests import unittest
  27. from tests.unittest import override_config
  28. class UserRegisterTestCase(unittest.HomeserverTestCase):
  29. servlets = [synapse.rest.admin.register_servlets_for_client_rest_resource]
  30. def make_homeserver(self, reactor, clock):
  31. self.url = "/_matrix/client/r0/admin/register"
  32. self.registration_handler = Mock()
  33. self.identity_handler = Mock()
  34. self.login_handler = Mock()
  35. self.device_handler = Mock()
  36. self.device_handler.check_device_registered = Mock(return_value="FAKE")
  37. self.datastore = Mock(return_value=Mock())
  38. self.datastore.get_current_state_deltas = Mock(return_value=(0, []))
  39. self.secrets = Mock()
  40. self.hs = self.setup_test_homeserver()
  41. self.hs.config.registration_shared_secret = "shared"
  42. self.hs.get_media_repository = Mock()
  43. self.hs.get_deactivate_account_handler = Mock()
  44. return self.hs
  45. def test_disabled(self):
  46. """
  47. If there is no shared secret, registration through this method will be
  48. prevented.
  49. """
  50. self.hs.config.registration_shared_secret = None
  51. request, channel = self.make_request("POST", self.url, b"{}")
  52. self.render(request)
  53. self.assertEqual(400, int(channel.result["code"]), msg=channel.result["body"])
  54. self.assertEqual(
  55. "Shared secret registration is not enabled", channel.json_body["error"]
  56. )
  57. def test_get_nonce(self):
  58. """
  59. Calling GET on the endpoint will return a randomised nonce, using the
  60. homeserver's secrets provider.
  61. """
  62. secrets = Mock()
  63. secrets.token_hex = Mock(return_value="abcd")
  64. self.hs.get_secrets = Mock(return_value=secrets)
  65. request, channel = self.make_request("GET", self.url)
  66. self.render(request)
  67. self.assertEqual(channel.json_body, {"nonce": "abcd"})
  68. def test_expired_nonce(self):
  69. """
  70. Calling GET on the endpoint will return a randomised nonce, which will
  71. only last for SALT_TIMEOUT (60s).
  72. """
  73. request, channel = self.make_request("GET", self.url)
  74. self.render(request)
  75. nonce = channel.json_body["nonce"]
  76. # 59 seconds
  77. self.reactor.advance(59)
  78. body = json.dumps({"nonce": nonce})
  79. request, channel = self.make_request("POST", self.url, body.encode("utf8"))
  80. self.render(request)
  81. self.assertEqual(400, int(channel.result["code"]), msg=channel.result["body"])
  82. self.assertEqual("username must be specified", channel.json_body["error"])
  83. # 61 seconds
  84. self.reactor.advance(2)
  85. request, channel = self.make_request("POST", self.url, body.encode("utf8"))
  86. self.render(request)
  87. self.assertEqual(400, int(channel.result["code"]), msg=channel.result["body"])
  88. self.assertEqual("unrecognised nonce", channel.json_body["error"])
  89. def test_register_incorrect_nonce(self):
  90. """
  91. Only the provided nonce can be used, as it's checked in the MAC.
  92. """
  93. request, channel = self.make_request("GET", self.url)
  94. self.render(request)
  95. nonce = channel.json_body["nonce"]
  96. want_mac = hmac.new(key=b"shared", digestmod=hashlib.sha1)
  97. want_mac.update(b"notthenonce\x00bob\x00abc123\x00admin")
  98. want_mac = want_mac.hexdigest()
  99. body = json.dumps(
  100. {
  101. "nonce": nonce,
  102. "username": "bob",
  103. "password": "abc123",
  104. "admin": True,
  105. "mac": want_mac,
  106. }
  107. )
  108. request, channel = self.make_request("POST", self.url, body.encode("utf8"))
  109. self.render(request)
  110. self.assertEqual(403, int(channel.result["code"]), msg=channel.result["body"])
  111. self.assertEqual("HMAC incorrect", channel.json_body["error"])
  112. def test_register_correct_nonce(self):
  113. """
  114. When the correct nonce is provided, and the right key is provided, the
  115. user is registered.
  116. """
  117. request, channel = self.make_request("GET", self.url)
  118. self.render(request)
  119. nonce = channel.json_body["nonce"]
  120. want_mac = hmac.new(key=b"shared", digestmod=hashlib.sha1)
  121. want_mac.update(
  122. nonce.encode("ascii") + b"\x00bob\x00abc123\x00admin\x00support"
  123. )
  124. want_mac = want_mac.hexdigest()
  125. body = json.dumps(
  126. {
  127. "nonce": nonce,
  128. "username": "bob",
  129. "password": "abc123",
  130. "admin": True,
  131. "user_type": UserTypes.SUPPORT,
  132. "mac": want_mac,
  133. }
  134. )
  135. request, channel = self.make_request("POST", self.url, body.encode("utf8"))
  136. self.render(request)
  137. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  138. self.assertEqual("@bob:test", channel.json_body["user_id"])
  139. def test_nonce_reuse(self):
  140. """
  141. A valid unrecognised nonce.
  142. """
  143. request, channel = self.make_request("GET", self.url)
  144. self.render(request)
  145. nonce = channel.json_body["nonce"]
  146. want_mac = hmac.new(key=b"shared", digestmod=hashlib.sha1)
  147. want_mac.update(nonce.encode("ascii") + b"\x00bob\x00abc123\x00admin")
  148. want_mac = want_mac.hexdigest()
  149. body = json.dumps(
  150. {
  151. "nonce": nonce,
  152. "username": "bob",
  153. "password": "abc123",
  154. "admin": True,
  155. "mac": want_mac,
  156. }
  157. )
  158. request, channel = self.make_request("POST", self.url, body.encode("utf8"))
  159. self.render(request)
  160. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  161. self.assertEqual("@bob:test", channel.json_body["user_id"])
  162. # Now, try and reuse it
  163. request, channel = self.make_request("POST", self.url, body.encode("utf8"))
  164. self.render(request)
  165. self.assertEqual(400, int(channel.result["code"]), msg=channel.result["body"])
  166. self.assertEqual("unrecognised nonce", channel.json_body["error"])
  167. def test_missing_parts(self):
  168. """
  169. Synapse will complain if you don't give nonce, username, password, and
  170. mac. Admin and user_types are optional. Additional checks are done for length
  171. and type.
  172. """
  173. def nonce():
  174. request, channel = self.make_request("GET", self.url)
  175. self.render(request)
  176. return channel.json_body["nonce"]
  177. #
  178. # Nonce check
  179. #
  180. # Must be present
  181. body = json.dumps({})
  182. request, channel = self.make_request("POST", self.url, body.encode("utf8"))
  183. self.render(request)
  184. self.assertEqual(400, int(channel.result["code"]), msg=channel.result["body"])
  185. self.assertEqual("nonce must be specified", channel.json_body["error"])
  186. #
  187. # Username checks
  188. #
  189. # Must be present
  190. body = json.dumps({"nonce": nonce()})
  191. request, channel = self.make_request("POST", self.url, body.encode("utf8"))
  192. self.render(request)
  193. self.assertEqual(400, int(channel.result["code"]), msg=channel.result["body"])
  194. self.assertEqual("username must be specified", channel.json_body["error"])
  195. # Must be a string
  196. body = json.dumps({"nonce": nonce(), "username": 1234})
  197. request, channel = self.make_request("POST", self.url, body.encode("utf8"))
  198. self.render(request)
  199. self.assertEqual(400, int(channel.result["code"]), msg=channel.result["body"])
  200. self.assertEqual("Invalid username", channel.json_body["error"])
  201. # Must not have null bytes
  202. body = json.dumps({"nonce": nonce(), "username": "abcd\u0000"})
  203. request, channel = self.make_request("POST", self.url, body.encode("utf8"))
  204. self.render(request)
  205. self.assertEqual(400, int(channel.result["code"]), msg=channel.result["body"])
  206. self.assertEqual("Invalid username", channel.json_body["error"])
  207. # Must not have null bytes
  208. body = json.dumps({"nonce": nonce(), "username": "a" * 1000})
  209. request, channel = self.make_request("POST", self.url, body.encode("utf8"))
  210. self.render(request)
  211. self.assertEqual(400, int(channel.result["code"]), msg=channel.result["body"])
  212. self.assertEqual("Invalid username", channel.json_body["error"])
  213. #
  214. # Password checks
  215. #
  216. # Must be present
  217. body = json.dumps({"nonce": nonce(), "username": "a"})
  218. request, channel = self.make_request("POST", self.url, body.encode("utf8"))
  219. self.render(request)
  220. self.assertEqual(400, int(channel.result["code"]), msg=channel.result["body"])
  221. self.assertEqual("password must be specified", channel.json_body["error"])
  222. # Must be a string
  223. body = json.dumps({"nonce": nonce(), "username": "a", "password": 1234})
  224. request, channel = self.make_request("POST", self.url, body.encode("utf8"))
  225. self.render(request)
  226. self.assertEqual(400, int(channel.result["code"]), msg=channel.result["body"])
  227. self.assertEqual("Invalid password", channel.json_body["error"])
  228. # Must not have null bytes
  229. body = json.dumps({"nonce": nonce(), "username": "a", "password": "abcd\u0000"})
  230. request, channel = self.make_request("POST", self.url, body.encode("utf8"))
  231. self.render(request)
  232. self.assertEqual(400, int(channel.result["code"]), msg=channel.result["body"])
  233. self.assertEqual("Invalid password", channel.json_body["error"])
  234. # Super long
  235. body = json.dumps({"nonce": nonce(), "username": "a", "password": "A" * 1000})
  236. request, channel = self.make_request("POST", self.url, body.encode("utf8"))
  237. self.render(request)
  238. self.assertEqual(400, int(channel.result["code"]), msg=channel.result["body"])
  239. self.assertEqual("Invalid password", channel.json_body["error"])
  240. #
  241. # user_type check
  242. #
  243. # Invalid user_type
  244. body = json.dumps(
  245. {
  246. "nonce": nonce(),
  247. "username": "a",
  248. "password": "1234",
  249. "user_type": "invalid",
  250. }
  251. )
  252. request, channel = self.make_request("POST", self.url, body.encode("utf8"))
  253. self.render(request)
  254. self.assertEqual(400, int(channel.result["code"]), msg=channel.result["body"])
  255. self.assertEqual("Invalid user type", channel.json_body["error"])
  256. @override_config(
  257. {"limit_usage_by_mau": True, "max_mau_value": 2, "mau_trial_days": 0}
  258. )
  259. def test_register_mau_limit_reached(self):
  260. """
  261. Check we can register a user via the shared secret registration API
  262. even if the MAU limit is reached.
  263. """
  264. handler = self.hs.get_registration_handler()
  265. store = self.hs.get_datastore()
  266. # Set monthly active users to the limit
  267. store.get_monthly_active_count = Mock(
  268. return_value=defer.succeed(self.hs.config.max_mau_value)
  269. )
  270. # Check that the blocking of monthly active users is working as expected
  271. # The registration of a new user fails due to the limit
  272. self.get_failure(
  273. handler.register_user(localpart="local_part"), ResourceLimitError
  274. )
  275. # Register new user with admin API
  276. request, channel = self.make_request("GET", self.url)
  277. self.render(request)
  278. nonce = channel.json_body["nonce"]
  279. want_mac = hmac.new(key=b"shared", digestmod=hashlib.sha1)
  280. want_mac.update(
  281. nonce.encode("ascii") + b"\x00bob\x00abc123\x00admin\x00support"
  282. )
  283. want_mac = want_mac.hexdigest()
  284. body = json.dumps(
  285. {
  286. "nonce": nonce,
  287. "username": "bob",
  288. "password": "abc123",
  289. "admin": True,
  290. "user_type": UserTypes.SUPPORT,
  291. "mac": want_mac,
  292. }
  293. )
  294. request, channel = self.make_request("POST", self.url, body.encode("utf8"))
  295. self.render(request)
  296. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  297. self.assertEqual("@bob:test", channel.json_body["user_id"])
  298. class UsersListTestCase(unittest.HomeserverTestCase):
  299. servlets = [
  300. synapse.rest.admin.register_servlets,
  301. login.register_servlets,
  302. ]
  303. url = "/_synapse/admin/v2/users"
  304. def prepare(self, reactor, clock, hs):
  305. self.admin_user = self.register_user("admin", "pass", admin=True)
  306. self.admin_user_tok = self.login("admin", "pass")
  307. self.register_user("user1", "pass1", admin=False)
  308. self.register_user("user2", "pass2", admin=False)
  309. def test_no_auth(self):
  310. """
  311. Try to list users without authentication.
  312. """
  313. request, channel = self.make_request("GET", self.url, b"{}")
  314. self.render(request)
  315. self.assertEqual(401, int(channel.result["code"]), msg=channel.result["body"])
  316. self.assertEqual("M_MISSING_TOKEN", channel.json_body["errcode"])
  317. def test_all_users(self):
  318. """
  319. List all users, including deactivated users.
  320. """
  321. request, channel = self.make_request(
  322. "GET",
  323. self.url + "?deactivated=true",
  324. b"{}",
  325. access_token=self.admin_user_tok,
  326. )
  327. self.render(request)
  328. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  329. self.assertEqual(3, len(channel.json_body["users"]))
  330. self.assertEqual(3, channel.json_body["total"])
  331. class UserRestTestCase(unittest.HomeserverTestCase):
  332. servlets = [
  333. synapse.rest.admin.register_servlets,
  334. login.register_servlets,
  335. sync.register_servlets,
  336. ]
  337. def prepare(self, reactor, clock, hs):
  338. self.store = hs.get_datastore()
  339. self.admin_user = self.register_user("admin", "pass", admin=True)
  340. self.admin_user_tok = self.login("admin", "pass")
  341. self.other_user = self.register_user("user", "pass")
  342. self.other_user_token = self.login("user", "pass")
  343. self.url_other_user = "/_synapse/admin/v2/users/%s" % urllib.parse.quote(
  344. self.other_user
  345. )
  346. def test_requester_is_no_admin(self):
  347. """
  348. If the user is not a server admin, an error is returned.
  349. """
  350. url = "/_synapse/admin/v2/users/@bob:test"
  351. request, channel = self.make_request(
  352. "GET", url, access_token=self.other_user_token,
  353. )
  354. self.render(request)
  355. self.assertEqual(403, int(channel.result["code"]), msg=channel.result["body"])
  356. self.assertEqual("You are not a server admin", channel.json_body["error"])
  357. request, channel = self.make_request(
  358. "PUT", url, access_token=self.other_user_token, content=b"{}",
  359. )
  360. self.render(request)
  361. self.assertEqual(403, int(channel.result["code"]), msg=channel.result["body"])
  362. self.assertEqual("You are not a server admin", channel.json_body["error"])
  363. def test_user_does_not_exist(self):
  364. """
  365. Tests that a lookup for a user that does not exist returns a 404
  366. """
  367. request, channel = self.make_request(
  368. "GET",
  369. "/_synapse/admin/v2/users/@unknown_person:test",
  370. access_token=self.admin_user_tok,
  371. )
  372. self.render(request)
  373. self.assertEqual(404, channel.code, msg=channel.json_body)
  374. self.assertEqual("M_NOT_FOUND", channel.json_body["errcode"])
  375. def test_create_server_admin(self):
  376. """
  377. Check that a new admin user is created successfully.
  378. """
  379. url = "/_synapse/admin/v2/users/@bob:test"
  380. # Create user (server admin)
  381. body = json.dumps(
  382. {
  383. "password": "abc123",
  384. "admin": True,
  385. "displayname": "Bob's name",
  386. "threepids": [{"medium": "email", "address": "bob@bob.bob"}],
  387. "avatar_url": None,
  388. }
  389. )
  390. request, channel = self.make_request(
  391. "PUT",
  392. url,
  393. access_token=self.admin_user_tok,
  394. content=body.encode(encoding="utf_8"),
  395. )
  396. self.render(request)
  397. self.assertEqual(201, int(channel.result["code"]), msg=channel.result["body"])
  398. self.assertEqual("@bob:test", channel.json_body["name"])
  399. self.assertEqual("Bob's name", channel.json_body["displayname"])
  400. self.assertEqual("email", channel.json_body["threepids"][0]["medium"])
  401. self.assertEqual("bob@bob.bob", channel.json_body["threepids"][0]["address"])
  402. self.assertEqual(True, channel.json_body["admin"])
  403. # Get user
  404. request, channel = self.make_request(
  405. "GET", url, access_token=self.admin_user_tok,
  406. )
  407. self.render(request)
  408. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  409. self.assertEqual("@bob:test", channel.json_body["name"])
  410. self.assertEqual("Bob's name", channel.json_body["displayname"])
  411. self.assertEqual("email", channel.json_body["threepids"][0]["medium"])
  412. self.assertEqual("bob@bob.bob", channel.json_body["threepids"][0]["address"])
  413. self.assertEqual(True, channel.json_body["admin"])
  414. self.assertEqual(False, channel.json_body["is_guest"])
  415. self.assertEqual(False, channel.json_body["deactivated"])
  416. def test_create_user(self):
  417. """
  418. Check that a new regular user is created successfully.
  419. """
  420. url = "/_synapse/admin/v2/users/@bob:test"
  421. # Create user
  422. body = json.dumps(
  423. {
  424. "password": "abc123",
  425. "admin": False,
  426. "displayname": "Bob's name",
  427. "threepids": [{"medium": "email", "address": "bob@bob.bob"}],
  428. }
  429. )
  430. request, channel = self.make_request(
  431. "PUT",
  432. url,
  433. access_token=self.admin_user_tok,
  434. content=body.encode(encoding="utf_8"),
  435. )
  436. self.render(request)
  437. self.assertEqual(201, int(channel.result["code"]), msg=channel.result["body"])
  438. self.assertEqual("@bob:test", channel.json_body["name"])
  439. self.assertEqual("Bob's name", channel.json_body["displayname"])
  440. self.assertEqual("email", channel.json_body["threepids"][0]["medium"])
  441. self.assertEqual("bob@bob.bob", channel.json_body["threepids"][0]["address"])
  442. self.assertEqual(False, channel.json_body["admin"])
  443. # Get user
  444. request, channel = self.make_request(
  445. "GET", url, access_token=self.admin_user_tok,
  446. )
  447. self.render(request)
  448. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  449. self.assertEqual("@bob:test", channel.json_body["name"])
  450. self.assertEqual("Bob's name", channel.json_body["displayname"])
  451. self.assertEqual("email", channel.json_body["threepids"][0]["medium"])
  452. self.assertEqual("bob@bob.bob", channel.json_body["threepids"][0]["address"])
  453. self.assertEqual(False, channel.json_body["admin"])
  454. self.assertEqual(False, channel.json_body["is_guest"])
  455. self.assertEqual(False, channel.json_body["deactivated"])
  456. @override_config(
  457. {"limit_usage_by_mau": True, "max_mau_value": 2, "mau_trial_days": 0}
  458. )
  459. def test_create_user_mau_limit_reached_active_admin(self):
  460. """
  461. Check that an admin can register a new user via the admin API
  462. even if the MAU limit is reached.
  463. Admin user was active before creating user.
  464. """
  465. handler = self.hs.get_registration_handler()
  466. # Sync to set admin user to active
  467. # before limit of monthly active users is reached
  468. request, channel = self.make_request(
  469. "GET", "/sync", access_token=self.admin_user_tok
  470. )
  471. self.render(request)
  472. if channel.code != 200:
  473. raise HttpResponseException(
  474. channel.code, channel.result["reason"], channel.result["body"]
  475. )
  476. # Set monthly active users to the limit
  477. self.store.get_monthly_active_count = Mock(
  478. return_value=defer.succeed(self.hs.config.max_mau_value)
  479. )
  480. # Check that the blocking of monthly active users is working as expected
  481. # The registration of a new user fails due to the limit
  482. self.get_failure(
  483. handler.register_user(localpart="local_part"), ResourceLimitError
  484. )
  485. # Register new user with admin API
  486. url = "/_synapse/admin/v2/users/@bob:test"
  487. # Create user
  488. body = json.dumps({"password": "abc123", "admin": False})
  489. request, channel = self.make_request(
  490. "PUT",
  491. url,
  492. access_token=self.admin_user_tok,
  493. content=body.encode(encoding="utf_8"),
  494. )
  495. self.render(request)
  496. self.assertEqual(201, int(channel.result["code"]), msg=channel.result["body"])
  497. self.assertEqual("@bob:test", channel.json_body["name"])
  498. self.assertEqual(False, channel.json_body["admin"])
  499. @override_config(
  500. {"limit_usage_by_mau": True, "max_mau_value": 2, "mau_trial_days": 0}
  501. )
  502. def test_create_user_mau_limit_reached_passive_admin(self):
  503. """
  504. Check that an admin can register a new user via the admin API
  505. even if the MAU limit is reached.
  506. Admin user was not active before creating user.
  507. """
  508. handler = self.hs.get_registration_handler()
  509. # Set monthly active users to the limit
  510. self.store.get_monthly_active_count = Mock(
  511. return_value=defer.succeed(self.hs.config.max_mau_value)
  512. )
  513. # Check that the blocking of monthly active users is working as expected
  514. # The registration of a new user fails due to the limit
  515. self.get_failure(
  516. handler.register_user(localpart="local_part"), ResourceLimitError
  517. )
  518. # Register new user with admin API
  519. url = "/_synapse/admin/v2/users/@bob:test"
  520. # Create user
  521. body = json.dumps({"password": "abc123", "admin": False})
  522. request, channel = self.make_request(
  523. "PUT",
  524. url,
  525. access_token=self.admin_user_tok,
  526. content=body.encode(encoding="utf_8"),
  527. )
  528. self.render(request)
  529. # Admin user is not blocked by mau anymore
  530. self.assertEqual(201, int(channel.result["code"]), msg=channel.result["body"])
  531. self.assertEqual("@bob:test", channel.json_body["name"])
  532. self.assertEqual(False, channel.json_body["admin"])
  533. @override_config(
  534. {
  535. "email": {
  536. "enable_notifs": True,
  537. "notif_for_new_users": True,
  538. "notif_from": "test@example.com",
  539. },
  540. "public_baseurl": "https://example.com",
  541. }
  542. )
  543. def test_create_user_email_notif_for_new_users(self):
  544. """
  545. Check that a new regular user is created successfully and
  546. got an email pusher.
  547. """
  548. url = "/_synapse/admin/v2/users/@bob:test"
  549. # Create user
  550. body = json.dumps(
  551. {
  552. "password": "abc123",
  553. "threepids": [{"medium": "email", "address": "bob@bob.bob"}],
  554. }
  555. )
  556. request, channel = self.make_request(
  557. "PUT",
  558. url,
  559. access_token=self.admin_user_tok,
  560. content=body.encode(encoding="utf_8"),
  561. )
  562. self.render(request)
  563. self.assertEqual(201, int(channel.result["code"]), msg=channel.result["body"])
  564. self.assertEqual("@bob:test", channel.json_body["name"])
  565. self.assertEqual("email", channel.json_body["threepids"][0]["medium"])
  566. self.assertEqual("bob@bob.bob", channel.json_body["threepids"][0]["address"])
  567. pushers = self.get_success(
  568. self.store.get_pushers_by({"user_name": "@bob:test"})
  569. )
  570. pushers = list(pushers)
  571. self.assertEqual(len(pushers), 1)
  572. self.assertEqual("@bob:test", pushers[0]["user_name"])
  573. @override_config(
  574. {
  575. "email": {
  576. "enable_notifs": False,
  577. "notif_for_new_users": False,
  578. "notif_from": "test@example.com",
  579. },
  580. "public_baseurl": "https://example.com",
  581. }
  582. )
  583. def test_create_user_email_no_notif_for_new_users(self):
  584. """
  585. Check that a new regular user is created successfully and
  586. got not an email pusher.
  587. """
  588. url = "/_synapse/admin/v2/users/@bob:test"
  589. # Create user
  590. body = json.dumps(
  591. {
  592. "password": "abc123",
  593. "threepids": [{"medium": "email", "address": "bob@bob.bob"}],
  594. }
  595. )
  596. request, channel = self.make_request(
  597. "PUT",
  598. url,
  599. access_token=self.admin_user_tok,
  600. content=body.encode(encoding="utf_8"),
  601. )
  602. self.render(request)
  603. self.assertEqual(201, int(channel.result["code"]), msg=channel.result["body"])
  604. self.assertEqual("@bob:test", channel.json_body["name"])
  605. self.assertEqual("email", channel.json_body["threepids"][0]["medium"])
  606. self.assertEqual("bob@bob.bob", channel.json_body["threepids"][0]["address"])
  607. pushers = self.get_success(
  608. self.store.get_pushers_by({"user_name": "@bob:test"})
  609. )
  610. pushers = list(pushers)
  611. self.assertEqual(len(pushers), 0)
  612. def test_set_password(self):
  613. """
  614. Test setting a new password for another user.
  615. """
  616. # Change password
  617. body = json.dumps({"password": "hahaha"})
  618. request, channel = self.make_request(
  619. "PUT",
  620. self.url_other_user,
  621. access_token=self.admin_user_tok,
  622. content=body.encode(encoding="utf_8"),
  623. )
  624. self.render(request)
  625. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  626. def test_set_displayname(self):
  627. """
  628. Test setting the displayname of another user.
  629. """
  630. # Modify user
  631. body = json.dumps({"displayname": "foobar"})
  632. request, channel = self.make_request(
  633. "PUT",
  634. self.url_other_user,
  635. access_token=self.admin_user_tok,
  636. content=body.encode(encoding="utf_8"),
  637. )
  638. self.render(request)
  639. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  640. self.assertEqual("@user:test", channel.json_body["name"])
  641. self.assertEqual("foobar", channel.json_body["displayname"])
  642. # Get user
  643. request, channel = self.make_request(
  644. "GET", self.url_other_user, access_token=self.admin_user_tok,
  645. )
  646. self.render(request)
  647. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  648. self.assertEqual("@user:test", channel.json_body["name"])
  649. self.assertEqual("foobar", channel.json_body["displayname"])
  650. def test_set_threepid(self):
  651. """
  652. Test setting threepid for an other user.
  653. """
  654. # Delete old and add new threepid to user
  655. body = json.dumps(
  656. {"threepids": [{"medium": "email", "address": "bob3@bob.bob"}]}
  657. )
  658. request, channel = self.make_request(
  659. "PUT",
  660. self.url_other_user,
  661. access_token=self.admin_user_tok,
  662. content=body.encode(encoding="utf_8"),
  663. )
  664. self.render(request)
  665. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  666. self.assertEqual("@user:test", channel.json_body["name"])
  667. self.assertEqual("email", channel.json_body["threepids"][0]["medium"])
  668. self.assertEqual("bob3@bob.bob", channel.json_body["threepids"][0]["address"])
  669. # Get user
  670. request, channel = self.make_request(
  671. "GET", self.url_other_user, access_token=self.admin_user_tok,
  672. )
  673. self.render(request)
  674. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  675. self.assertEqual("@user:test", channel.json_body["name"])
  676. self.assertEqual("email", channel.json_body["threepids"][0]["medium"])
  677. self.assertEqual("bob3@bob.bob", channel.json_body["threepids"][0]["address"])
  678. def test_deactivate_user(self):
  679. """
  680. Test deactivating another user.
  681. """
  682. # Deactivate user
  683. body = json.dumps({"deactivated": True})
  684. request, channel = self.make_request(
  685. "PUT",
  686. self.url_other_user,
  687. access_token=self.admin_user_tok,
  688. content=body.encode(encoding="utf_8"),
  689. )
  690. self.render(request)
  691. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  692. self.assertEqual("@user:test", channel.json_body["name"])
  693. self.assertEqual(True, channel.json_body["deactivated"])
  694. # the user is deactivated, the threepid will be deleted
  695. # Get user
  696. request, channel = self.make_request(
  697. "GET", self.url_other_user, access_token=self.admin_user_tok,
  698. )
  699. self.render(request)
  700. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  701. self.assertEqual("@user:test", channel.json_body["name"])
  702. self.assertEqual(True, channel.json_body["deactivated"])
  703. def test_reactivate_user(self):
  704. """
  705. Test reactivating another user.
  706. """
  707. # Deactivate the user.
  708. request, channel = self.make_request(
  709. "PUT",
  710. self.url_other_user,
  711. access_token=self.admin_user_tok,
  712. content=json.dumps({"deactivated": True}).encode(encoding="utf_8"),
  713. )
  714. self.render(request)
  715. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  716. # Attempt to reactivate the user (without a password).
  717. request, channel = self.make_request(
  718. "PUT",
  719. self.url_other_user,
  720. access_token=self.admin_user_tok,
  721. content=json.dumps({"deactivated": False}).encode(encoding="utf_8"),
  722. )
  723. self.render(request)
  724. self.assertEqual(400, int(channel.result["code"]), msg=channel.result["body"])
  725. # Reactivate the user.
  726. request, channel = self.make_request(
  727. "PUT",
  728. self.url_other_user,
  729. access_token=self.admin_user_tok,
  730. content=json.dumps({"deactivated": False, "password": "foo"}).encode(
  731. encoding="utf_8"
  732. ),
  733. )
  734. self.render(request)
  735. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  736. # Get user
  737. request, channel = self.make_request(
  738. "GET", self.url_other_user, access_token=self.admin_user_tok,
  739. )
  740. self.render(request)
  741. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  742. self.assertEqual("@user:test", channel.json_body["name"])
  743. self.assertEqual(False, channel.json_body["deactivated"])
  744. def test_set_user_as_admin(self):
  745. """
  746. Test setting the admin flag on a user.
  747. """
  748. # Set a user as an admin
  749. body = json.dumps({"admin": True})
  750. request, channel = self.make_request(
  751. "PUT",
  752. self.url_other_user,
  753. access_token=self.admin_user_tok,
  754. content=body.encode(encoding="utf_8"),
  755. )
  756. self.render(request)
  757. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  758. self.assertEqual("@user:test", channel.json_body["name"])
  759. self.assertEqual(True, channel.json_body["admin"])
  760. # Get user
  761. request, channel = self.make_request(
  762. "GET", self.url_other_user, access_token=self.admin_user_tok,
  763. )
  764. self.render(request)
  765. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  766. self.assertEqual("@user:test", channel.json_body["name"])
  767. self.assertEqual(True, channel.json_body["admin"])
  768. def test_accidental_deactivation_prevention(self):
  769. """
  770. Ensure an account can't accidentally be deactivated by using a str value
  771. for the deactivated body parameter
  772. """
  773. url = "/_synapse/admin/v2/users/@bob:test"
  774. # Create user
  775. body = json.dumps({"password": "abc123"})
  776. request, channel = self.make_request(
  777. "PUT",
  778. url,
  779. access_token=self.admin_user_tok,
  780. content=body.encode(encoding="utf_8"),
  781. )
  782. self.render(request)
  783. self.assertEqual(201, int(channel.result["code"]), msg=channel.result["body"])
  784. self.assertEqual("@bob:test", channel.json_body["name"])
  785. self.assertEqual("bob", channel.json_body["displayname"])
  786. # Get user
  787. request, channel = self.make_request(
  788. "GET", url, access_token=self.admin_user_tok,
  789. )
  790. self.render(request)
  791. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  792. self.assertEqual("@bob:test", channel.json_body["name"])
  793. self.assertEqual("bob", channel.json_body["displayname"])
  794. self.assertEqual(0, channel.json_body["deactivated"])
  795. # Change password (and use a str for deactivate instead of a bool)
  796. body = json.dumps({"password": "abc123", "deactivated": "false"}) # oops!
  797. request, channel = self.make_request(
  798. "PUT",
  799. url,
  800. access_token=self.admin_user_tok,
  801. content=body.encode(encoding="utf_8"),
  802. )
  803. self.render(request)
  804. self.assertEqual(400, int(channel.result["code"]), msg=channel.result["body"])
  805. # Check user is not deactivated
  806. request, channel = self.make_request(
  807. "GET", url, access_token=self.admin_user_tok,
  808. )
  809. self.render(request)
  810. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  811. self.assertEqual("@bob:test", channel.json_body["name"])
  812. self.assertEqual("bob", channel.json_body["displayname"])
  813. # Ensure they're still alive
  814. self.assertEqual(0, channel.json_body["deactivated"])