1
0

test_user.py 39 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117
  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. import synapse.rest.admin
  21. from synapse.api.constants import UserTypes
  22. from synapse.api.errors import Codes, HttpResponseException, ResourceLimitError
  23. from synapse.rest.client.v1 import login, room
  24. from synapse.rest.client.v2_alpha import sync
  25. from tests import unittest
  26. from tests.test_utils import make_awaitable
  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=make_awaitable(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=make_awaitable(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=make_awaitable(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. self._is_erased("@user:test", False)
  717. d = self.store.mark_user_erased("@user:test")
  718. self.assertIsNone(self.get_success(d))
  719. self._is_erased("@user:test", True)
  720. # Attempt to reactivate the user (without a password).
  721. request, channel = self.make_request(
  722. "PUT",
  723. self.url_other_user,
  724. access_token=self.admin_user_tok,
  725. content=json.dumps({"deactivated": False}).encode(encoding="utf_8"),
  726. )
  727. self.render(request)
  728. self.assertEqual(400, int(channel.result["code"]), msg=channel.result["body"])
  729. # Reactivate the user.
  730. request, channel = self.make_request(
  731. "PUT",
  732. self.url_other_user,
  733. access_token=self.admin_user_tok,
  734. content=json.dumps({"deactivated": False, "password": "foo"}).encode(
  735. encoding="utf_8"
  736. ),
  737. )
  738. self.render(request)
  739. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  740. # Get user
  741. request, channel = self.make_request(
  742. "GET", self.url_other_user, access_token=self.admin_user_tok,
  743. )
  744. self.render(request)
  745. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  746. self.assertEqual("@user:test", channel.json_body["name"])
  747. self.assertEqual(False, channel.json_body["deactivated"])
  748. self._is_erased("@user:test", False)
  749. def test_set_user_as_admin(self):
  750. """
  751. Test setting the admin flag on a user.
  752. """
  753. # Set a user as an admin
  754. body = json.dumps({"admin": True})
  755. request, channel = self.make_request(
  756. "PUT",
  757. self.url_other_user,
  758. access_token=self.admin_user_tok,
  759. content=body.encode(encoding="utf_8"),
  760. )
  761. self.render(request)
  762. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  763. self.assertEqual("@user:test", channel.json_body["name"])
  764. self.assertEqual(True, channel.json_body["admin"])
  765. # Get user
  766. request, channel = self.make_request(
  767. "GET", self.url_other_user, access_token=self.admin_user_tok,
  768. )
  769. self.render(request)
  770. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  771. self.assertEqual("@user:test", channel.json_body["name"])
  772. self.assertEqual(True, channel.json_body["admin"])
  773. def test_accidental_deactivation_prevention(self):
  774. """
  775. Ensure an account can't accidentally be deactivated by using a str value
  776. for the deactivated body parameter
  777. """
  778. url = "/_synapse/admin/v2/users/@bob:test"
  779. # Create user
  780. body = json.dumps({"password": "abc123"})
  781. request, channel = self.make_request(
  782. "PUT",
  783. url,
  784. access_token=self.admin_user_tok,
  785. content=body.encode(encoding="utf_8"),
  786. )
  787. self.render(request)
  788. self.assertEqual(201, int(channel.result["code"]), msg=channel.result["body"])
  789. self.assertEqual("@bob:test", channel.json_body["name"])
  790. self.assertEqual("bob", channel.json_body["displayname"])
  791. # Get user
  792. request, channel = self.make_request(
  793. "GET", url, access_token=self.admin_user_tok,
  794. )
  795. self.render(request)
  796. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  797. self.assertEqual("@bob:test", channel.json_body["name"])
  798. self.assertEqual("bob", channel.json_body["displayname"])
  799. self.assertEqual(0, channel.json_body["deactivated"])
  800. # Change password (and use a str for deactivate instead of a bool)
  801. body = json.dumps({"password": "abc123", "deactivated": "false"}) # oops!
  802. request, channel = self.make_request(
  803. "PUT",
  804. url,
  805. access_token=self.admin_user_tok,
  806. content=body.encode(encoding="utf_8"),
  807. )
  808. self.render(request)
  809. self.assertEqual(400, int(channel.result["code"]), msg=channel.result["body"])
  810. # Check user is not deactivated
  811. request, channel = self.make_request(
  812. "GET", url, access_token=self.admin_user_tok,
  813. )
  814. self.render(request)
  815. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  816. self.assertEqual("@bob:test", channel.json_body["name"])
  817. self.assertEqual("bob", channel.json_body["displayname"])
  818. # Ensure they're still alive
  819. self.assertEqual(0, channel.json_body["deactivated"])
  820. def _is_erased(self, user_id, expect):
  821. """Assert that the user is erased or not
  822. """
  823. d = self.store.is_user_erased(user_id)
  824. if expect:
  825. self.assertTrue(self.get_success(d))
  826. else:
  827. self.assertFalse(self.get_success(d))
  828. class UserMembershipRestTestCase(unittest.HomeserverTestCase):
  829. servlets = [
  830. synapse.rest.admin.register_servlets,
  831. login.register_servlets,
  832. room.register_servlets,
  833. ]
  834. def prepare(self, reactor, clock, hs):
  835. self.store = hs.get_datastore()
  836. self.admin_user = self.register_user("admin", "pass", admin=True)
  837. self.admin_user_tok = self.login("admin", "pass")
  838. self.other_user = self.register_user("user", "pass")
  839. self.url = "/_synapse/admin/v1/users/%s/joined_rooms" % urllib.parse.quote(
  840. self.other_user
  841. )
  842. def test_no_auth(self):
  843. """
  844. Try to list rooms of an user without authentication.
  845. """
  846. request, channel = self.make_request("GET", self.url, b"{}")
  847. self.render(request)
  848. self.assertEqual(401, int(channel.result["code"]), msg=channel.result["body"])
  849. self.assertEqual(Codes.MISSING_TOKEN, channel.json_body["errcode"])
  850. def test_requester_is_no_admin(self):
  851. """
  852. If the user is not a server admin, an error is returned.
  853. """
  854. other_user_token = self.login("user", "pass")
  855. request, channel = self.make_request(
  856. "GET", self.url, access_token=other_user_token,
  857. )
  858. self.render(request)
  859. self.assertEqual(403, int(channel.result["code"]), msg=channel.result["body"])
  860. self.assertEqual(Codes.FORBIDDEN, channel.json_body["errcode"])
  861. def test_user_does_not_exist(self):
  862. """
  863. Tests that a lookup for a user that does not exist returns a 404
  864. """
  865. url = "/_synapse/admin/v1/users/@unknown_person:test/joined_rooms"
  866. request, channel = self.make_request(
  867. "GET", url, access_token=self.admin_user_tok,
  868. )
  869. self.render(request)
  870. self.assertEqual(404, channel.code, msg=channel.json_body)
  871. self.assertEqual(Codes.NOT_FOUND, channel.json_body["errcode"])
  872. def test_user_is_not_local(self):
  873. """
  874. Tests that a lookup for a user that is not a local returns a 400
  875. """
  876. url = "/_synapse/admin/v1/users/@unknown_person:unknown_domain/joined_rooms"
  877. request, channel = self.make_request(
  878. "GET", url, access_token=self.admin_user_tok,
  879. )
  880. self.render(request)
  881. self.assertEqual(400, channel.code, msg=channel.json_body)
  882. self.assertEqual("Can only lookup local users", channel.json_body["error"])
  883. def test_no_memberships(self):
  884. """
  885. Tests that a normal lookup for rooms is successfully
  886. if user has no memberships
  887. """
  888. # Get rooms
  889. request, channel = self.make_request(
  890. "GET", self.url, access_token=self.admin_user_tok,
  891. )
  892. self.render(request)
  893. self.assertEqual(200, channel.code, msg=channel.json_body)
  894. self.assertEqual(0, channel.json_body["total"])
  895. self.assertEqual(0, len(channel.json_body["joined_rooms"]))
  896. def test_get_rooms(self):
  897. """
  898. Tests that a normal lookup for rooms is successfully
  899. """
  900. # Create rooms and join
  901. other_user_tok = self.login("user", "pass")
  902. number_rooms = 5
  903. for n in range(number_rooms):
  904. self.helper.create_room_as(self.other_user, tok=other_user_tok)
  905. # Get rooms
  906. request, channel = self.make_request(
  907. "GET", self.url, access_token=self.admin_user_tok,
  908. )
  909. self.render(request)
  910. self.assertEqual(200, channel.code, msg=channel.json_body)
  911. self.assertEqual(number_rooms, channel.json_body["total"])
  912. self.assertEqual(number_rooms, len(channel.json_body["joined_rooms"]))