users.py 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675
  1. # -*- coding: utf-8 -*-
  2. # Copyright 2019 The Matrix.org Foundation C.I.C.
  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 logging
  18. import re
  19. from http import HTTPStatus
  20. from synapse.api.constants import UserTypes
  21. from synapse.api.errors import Codes, NotFoundError, SynapseError
  22. from synapse.http.servlet import (
  23. RestServlet,
  24. assert_params_in_dict,
  25. parse_boolean,
  26. parse_integer,
  27. parse_json_object_from_request,
  28. parse_string,
  29. )
  30. from synapse.rest.admin._base import (
  31. assert_requester_is_admin,
  32. assert_user_is_admin,
  33. historical_admin_path_patterns,
  34. )
  35. from synapse.types import UserID
  36. logger = logging.getLogger(__name__)
  37. class UsersRestServlet(RestServlet):
  38. PATTERNS = historical_admin_path_patterns("/users/(?P<user_id>[^/]*)$")
  39. def __init__(self, hs):
  40. self.hs = hs
  41. self.store = hs.get_datastore()
  42. self.auth = hs.get_auth()
  43. self.admin_handler = hs.get_handlers().admin_handler
  44. async def on_GET(self, request, user_id):
  45. target_user = UserID.from_string(user_id)
  46. await assert_requester_is_admin(self.auth, request)
  47. if not self.hs.is_mine(target_user):
  48. raise SynapseError(400, "Can only users a local user")
  49. ret = await self.store.get_users()
  50. return 200, ret
  51. class UsersRestServletV2(RestServlet):
  52. PATTERNS = (re.compile("^/_synapse/admin/v2/users$"),)
  53. """Get request to list all local users.
  54. This needs user to have administrator access in Synapse.
  55. GET /_synapse/admin/v2/users?from=0&limit=10&guests=false
  56. returns:
  57. 200 OK with list of users if success otherwise an error.
  58. The parameters `from` and `limit` are required only for pagination.
  59. By default, a `limit` of 100 is used.
  60. The parameter `user_id` can be used to filter by user id.
  61. The parameter `guests` can be used to exclude guest users.
  62. The parameter `deactivated` can be used to include deactivated users.
  63. """
  64. def __init__(self, hs):
  65. self.hs = hs
  66. self.store = hs.get_datastore()
  67. self.auth = hs.get_auth()
  68. self.admin_handler = hs.get_handlers().admin_handler
  69. async def on_GET(self, request):
  70. await assert_requester_is_admin(self.auth, request)
  71. start = parse_integer(request, "from", default=0)
  72. limit = parse_integer(request, "limit", default=100)
  73. user_id = parse_string(request, "user_id", default=None)
  74. guests = parse_boolean(request, "guests", default=True)
  75. deactivated = parse_boolean(request, "deactivated", default=False)
  76. users, total = await self.store.get_users_paginate(
  77. start, limit, user_id, guests, deactivated
  78. )
  79. ret = {"users": users, "total": total}
  80. if len(users) >= limit:
  81. ret["next_token"] = str(start + len(users))
  82. return 200, ret
  83. class UserRestServletV2(RestServlet):
  84. PATTERNS = (re.compile("^/_synapse/admin/v2/users/(?P<user_id>[^/]+)$"),)
  85. """Get request to list user details.
  86. This needs user to have administrator access in Synapse.
  87. GET /_synapse/admin/v2/users/<user_id>
  88. returns:
  89. 200 OK with user details if success otherwise an error.
  90. Put request to allow an administrator to add or modify a user.
  91. This needs user to have administrator access in Synapse.
  92. We use PUT instead of POST since we already know the id of the user
  93. object to create. POST could be used to create guests.
  94. PUT /_synapse/admin/v2/users/<user_id>
  95. {
  96. "password": "secret",
  97. "displayname": "User"
  98. }
  99. returns:
  100. 201 OK with new user object if user was created or
  101. 200 OK with modified user object if user was modified
  102. otherwise an error.
  103. """
  104. def __init__(self, hs):
  105. self.hs = hs
  106. self.auth = hs.get_auth()
  107. self.admin_handler = hs.get_handlers().admin_handler
  108. self.store = hs.get_datastore()
  109. self.auth_handler = hs.get_auth_handler()
  110. self.profile_handler = hs.get_profile_handler()
  111. self.set_password_handler = hs.get_set_password_handler()
  112. self.deactivate_account_handler = hs.get_deactivate_account_handler()
  113. self.registration_handler = hs.get_registration_handler()
  114. self.pusher_pool = hs.get_pusherpool()
  115. async def on_GET(self, request, user_id):
  116. await assert_requester_is_admin(self.auth, request)
  117. target_user = UserID.from_string(user_id)
  118. if not self.hs.is_mine(target_user):
  119. raise SynapseError(400, "Can only lookup local users")
  120. ret = await self.admin_handler.get_user(target_user)
  121. if not ret:
  122. raise NotFoundError("User not found")
  123. return 200, ret
  124. async def on_PUT(self, request, user_id):
  125. requester = await self.auth.get_user_by_req(request)
  126. await assert_user_is_admin(self.auth, requester.user)
  127. target_user = UserID.from_string(user_id)
  128. body = parse_json_object_from_request(request)
  129. if not self.hs.is_mine(target_user):
  130. raise SynapseError(400, "This endpoint can only be used with local users")
  131. user = await self.admin_handler.get_user(target_user)
  132. user_id = target_user.to_string()
  133. if user: # modify user
  134. if "displayname" in body:
  135. await self.profile_handler.set_displayname(
  136. target_user, requester, body["displayname"], True
  137. )
  138. if "threepids" in body:
  139. # check for required parameters for each threepid
  140. for threepid in body["threepids"]:
  141. assert_params_in_dict(threepid, ["medium", "address"])
  142. # remove old threepids from user
  143. threepids = await self.store.user_get_threepids(user_id)
  144. for threepid in threepids:
  145. try:
  146. await self.auth_handler.delete_threepid(
  147. user_id, threepid["medium"], threepid["address"], None
  148. )
  149. except Exception:
  150. logger.exception("Failed to remove threepids")
  151. raise SynapseError(500, "Failed to remove threepids")
  152. # add new threepids to user
  153. current_time = self.hs.get_clock().time_msec()
  154. for threepid in body["threepids"]:
  155. await self.auth_handler.add_threepid(
  156. user_id, threepid["medium"], threepid["address"], current_time
  157. )
  158. if "avatar_url" in body and type(body["avatar_url"]) == str:
  159. await self.profile_handler.set_avatar_url(
  160. target_user, requester, body["avatar_url"], True
  161. )
  162. if "admin" in body:
  163. set_admin_to = bool(body["admin"])
  164. if set_admin_to != user["admin"]:
  165. auth_user = requester.user
  166. if target_user == auth_user and not set_admin_to:
  167. raise SynapseError(400, "You may not demote yourself.")
  168. await self.store.set_server_admin(target_user, set_admin_to)
  169. if "password" in body:
  170. if not isinstance(body["password"], str) or len(body["password"]) > 512:
  171. raise SynapseError(400, "Invalid password")
  172. else:
  173. new_password = body["password"]
  174. logout_devices = True
  175. new_password_hash = await self.auth_handler.hash(new_password)
  176. await self.set_password_handler.set_password(
  177. target_user.to_string(),
  178. new_password_hash,
  179. logout_devices,
  180. requester,
  181. )
  182. if "deactivated" in body:
  183. deactivate = body["deactivated"]
  184. if not isinstance(deactivate, bool):
  185. raise SynapseError(
  186. 400, "'deactivated' parameter is not of type boolean"
  187. )
  188. if deactivate and not user["deactivated"]:
  189. await self.deactivate_account_handler.deactivate_account(
  190. target_user.to_string(), False
  191. )
  192. user = await self.admin_handler.get_user(target_user)
  193. return 200, user
  194. else: # create user
  195. password = body.get("password")
  196. password_hash = None
  197. if password is not None:
  198. if not isinstance(password, str) or len(password) > 512:
  199. raise SynapseError(400, "Invalid password")
  200. password_hash = await self.auth_handler.hash(password)
  201. admin = body.get("admin", None)
  202. user_type = body.get("user_type", None)
  203. displayname = body.get("displayname", None)
  204. threepids = body.get("threepids", None)
  205. if user_type is not None and user_type not in UserTypes.ALL_USER_TYPES:
  206. raise SynapseError(400, "Invalid user type")
  207. user_id = await self.registration_handler.register_user(
  208. localpart=target_user.localpart,
  209. password_hash=password_hash,
  210. admin=bool(admin),
  211. default_display_name=displayname,
  212. user_type=user_type,
  213. by_admin=True,
  214. )
  215. if "threepids" in body:
  216. # check for required parameters for each threepid
  217. for threepid in body["threepids"]:
  218. assert_params_in_dict(threepid, ["medium", "address"])
  219. current_time = self.hs.get_clock().time_msec()
  220. for threepid in body["threepids"]:
  221. await self.auth_handler.add_threepid(
  222. user_id, threepid["medium"], threepid["address"], current_time
  223. )
  224. if (
  225. self.hs.config.email_enable_notifs
  226. and self.hs.config.email_notif_for_new_users
  227. ):
  228. await self.pusher_pool.add_pusher(
  229. user_id=user_id,
  230. access_token=None,
  231. kind="email",
  232. app_id="m.email",
  233. app_display_name="Email Notifications",
  234. device_display_name=threepid["address"],
  235. pushkey=threepid["address"],
  236. lang=None, # We don't know a user's language here
  237. data={},
  238. )
  239. if "avatar_url" in body and type(body["avatar_url"]) == str:
  240. await self.profile_handler.set_avatar_url(
  241. user_id, requester, body["avatar_url"], True
  242. )
  243. ret = await self.admin_handler.get_user(target_user)
  244. return 201, ret
  245. class UserRegisterServlet(RestServlet):
  246. """
  247. Attributes:
  248. NONCE_TIMEOUT (int): Seconds until a generated nonce won't be accepted
  249. nonces (dict[str, int]): The nonces that we will accept. A dict of
  250. nonce to the time it was generated, in int seconds.
  251. """
  252. PATTERNS = historical_admin_path_patterns("/register")
  253. NONCE_TIMEOUT = 60
  254. def __init__(self, hs):
  255. self.auth_handler = hs.get_auth_handler()
  256. self.reactor = hs.get_reactor()
  257. self.nonces = {}
  258. self.hs = hs
  259. def _clear_old_nonces(self):
  260. """
  261. Clear out old nonces that are older than NONCE_TIMEOUT.
  262. """
  263. now = int(self.reactor.seconds())
  264. for k, v in list(self.nonces.items()):
  265. if now - v > self.NONCE_TIMEOUT:
  266. del self.nonces[k]
  267. def on_GET(self, request):
  268. """
  269. Generate a new nonce.
  270. """
  271. self._clear_old_nonces()
  272. nonce = self.hs.get_secrets().token_hex(64)
  273. self.nonces[nonce] = int(self.reactor.seconds())
  274. return 200, {"nonce": nonce}
  275. async def on_POST(self, request):
  276. self._clear_old_nonces()
  277. if not self.hs.config.registration_shared_secret:
  278. raise SynapseError(400, "Shared secret registration is not enabled")
  279. body = parse_json_object_from_request(request)
  280. if "nonce" not in body:
  281. raise SynapseError(400, "nonce must be specified", errcode=Codes.BAD_JSON)
  282. nonce = body["nonce"]
  283. if nonce not in self.nonces:
  284. raise SynapseError(400, "unrecognised nonce")
  285. # Delete the nonce, so it can't be reused, even if it's invalid
  286. del self.nonces[nonce]
  287. if "username" not in body:
  288. raise SynapseError(
  289. 400, "username must be specified", errcode=Codes.BAD_JSON
  290. )
  291. else:
  292. if not isinstance(body["username"], str) or len(body["username"]) > 512:
  293. raise SynapseError(400, "Invalid username")
  294. username = body["username"].encode("utf-8")
  295. if b"\x00" in username:
  296. raise SynapseError(400, "Invalid username")
  297. if "password" not in body:
  298. raise SynapseError(
  299. 400, "password must be specified", errcode=Codes.BAD_JSON
  300. )
  301. else:
  302. password = body["password"]
  303. if not isinstance(password, str) or len(password) > 512:
  304. raise SynapseError(400, "Invalid password")
  305. password_bytes = password.encode("utf-8")
  306. if b"\x00" in password_bytes:
  307. raise SynapseError(400, "Invalid password")
  308. password_hash = await self.auth_handler.hash(password)
  309. admin = body.get("admin", None)
  310. user_type = body.get("user_type", None)
  311. if user_type is not None and user_type not in UserTypes.ALL_USER_TYPES:
  312. raise SynapseError(400, "Invalid user type")
  313. got_mac = body["mac"]
  314. want_mac_builder = hmac.new(
  315. key=self.hs.config.registration_shared_secret.encode(),
  316. digestmod=hashlib.sha1,
  317. )
  318. want_mac_builder.update(nonce.encode("utf8"))
  319. want_mac_builder.update(b"\x00")
  320. want_mac_builder.update(username)
  321. want_mac_builder.update(b"\x00")
  322. want_mac_builder.update(password_bytes)
  323. want_mac_builder.update(b"\x00")
  324. want_mac_builder.update(b"admin" if admin else b"notadmin")
  325. if user_type:
  326. want_mac_builder.update(b"\x00")
  327. want_mac_builder.update(user_type.encode("utf8"))
  328. want_mac = want_mac_builder.hexdigest()
  329. if not hmac.compare_digest(want_mac.encode("ascii"), got_mac.encode("ascii")):
  330. raise SynapseError(403, "HMAC incorrect")
  331. # Reuse the parts of RegisterRestServlet to reduce code duplication
  332. from synapse.rest.client.v2_alpha.register import RegisterRestServlet
  333. register = RegisterRestServlet(self.hs)
  334. user_id = await register.registration_handler.register_user(
  335. localpart=body["username"].lower(),
  336. password_hash=password_hash,
  337. admin=bool(admin),
  338. user_type=user_type,
  339. by_admin=True,
  340. )
  341. result = await register._create_registration_details(user_id, body)
  342. return 200, result
  343. class WhoisRestServlet(RestServlet):
  344. PATTERNS = historical_admin_path_patterns("/whois/(?P<user_id>[^/]*)")
  345. def __init__(self, hs):
  346. self.hs = hs
  347. self.auth = hs.get_auth()
  348. self.handlers = hs.get_handlers()
  349. async def on_GET(self, request, user_id):
  350. target_user = UserID.from_string(user_id)
  351. requester = await self.auth.get_user_by_req(request)
  352. auth_user = requester.user
  353. if target_user != auth_user:
  354. await assert_user_is_admin(self.auth, auth_user)
  355. if not self.hs.is_mine(target_user):
  356. raise SynapseError(400, "Can only whois a local user")
  357. ret = await self.handlers.admin_handler.get_whois(target_user)
  358. return 200, ret
  359. class DeactivateAccountRestServlet(RestServlet):
  360. PATTERNS = historical_admin_path_patterns("/deactivate/(?P<target_user_id>[^/]*)")
  361. def __init__(self, hs):
  362. self._deactivate_account_handler = hs.get_deactivate_account_handler()
  363. self.auth = hs.get_auth()
  364. async def on_POST(self, request, target_user_id):
  365. await assert_requester_is_admin(self.auth, request)
  366. body = parse_json_object_from_request(request, allow_empty_body=True)
  367. erase = body.get("erase", False)
  368. if not isinstance(erase, bool):
  369. raise SynapseError(
  370. HTTPStatus.BAD_REQUEST,
  371. "Param 'erase' must be a boolean, if given",
  372. Codes.BAD_JSON,
  373. )
  374. UserID.from_string(target_user_id)
  375. result = await self._deactivate_account_handler.deactivate_account(
  376. target_user_id, erase
  377. )
  378. if result:
  379. id_server_unbind_result = "success"
  380. else:
  381. id_server_unbind_result = "no-support"
  382. return 200, {"id_server_unbind_result": id_server_unbind_result}
  383. class AccountValidityRenewServlet(RestServlet):
  384. PATTERNS = historical_admin_path_patterns("/account_validity/validity$")
  385. def __init__(self, hs):
  386. """
  387. Args:
  388. hs (synapse.server.HomeServer): server
  389. """
  390. self.hs = hs
  391. self.account_activity_handler = hs.get_account_validity_handler()
  392. self.auth = hs.get_auth()
  393. async def on_POST(self, request):
  394. await assert_requester_is_admin(self.auth, request)
  395. body = parse_json_object_from_request(request)
  396. if "user_id" not in body:
  397. raise SynapseError(400, "Missing property 'user_id' in the request body")
  398. expiration_ts = await self.account_activity_handler.renew_account_for_user(
  399. body["user_id"],
  400. body.get("expiration_ts"),
  401. not body.get("enable_renewal_emails", True),
  402. )
  403. res = {"expiration_ts": expiration_ts}
  404. return 200, res
  405. class ResetPasswordRestServlet(RestServlet):
  406. """Post request to allow an administrator reset password for a user.
  407. This needs user to have administrator access in Synapse.
  408. Example:
  409. http://localhost:8008/_synapse/admin/v1/reset_password/
  410. @user:to_reset_password?access_token=admin_access_token
  411. JsonBodyToSend:
  412. {
  413. "new_password": "secret"
  414. }
  415. Returns:
  416. 200 OK with empty object if success otherwise an error.
  417. """
  418. PATTERNS = historical_admin_path_patterns(
  419. "/reset_password/(?P<target_user_id>[^/]*)"
  420. )
  421. def __init__(self, hs):
  422. self.store = hs.get_datastore()
  423. self.hs = hs
  424. self.auth = hs.get_auth()
  425. self.auth_handler = hs.get_auth_handler()
  426. self._set_password_handler = hs.get_set_password_handler()
  427. async def on_POST(self, request, target_user_id):
  428. """Post request to allow an administrator reset password for a user.
  429. This needs user to have administrator access in Synapse.
  430. """
  431. requester = await self.auth.get_user_by_req(request)
  432. await assert_user_is_admin(self.auth, requester.user)
  433. UserID.from_string(target_user_id)
  434. params = parse_json_object_from_request(request)
  435. assert_params_in_dict(params, ["new_password"])
  436. new_password = params["new_password"]
  437. logout_devices = params.get("logout_devices", True)
  438. new_password_hash = await self.auth_handler.hash(new_password)
  439. await self._set_password_handler.set_password(
  440. target_user_id, new_password_hash, logout_devices, requester
  441. )
  442. return 200, {}
  443. class SearchUsersRestServlet(RestServlet):
  444. """Get request to search user table for specific users according to
  445. search term.
  446. This needs user to have administrator access in Synapse.
  447. Example:
  448. http://localhost:8008/_synapse/admin/v1/search_users/
  449. @admin:user?access_token=admin_access_token&term=alice
  450. Returns:
  451. 200 OK with json object {list[dict[str, Any]], count} or empty object.
  452. """
  453. PATTERNS = historical_admin_path_patterns("/search_users/(?P<target_user_id>[^/]*)")
  454. def __init__(self, hs):
  455. self.hs = hs
  456. self.store = hs.get_datastore()
  457. self.auth = hs.get_auth()
  458. self.handlers = hs.get_handlers()
  459. async def on_GET(self, request, target_user_id):
  460. """Get request to search user table for specific users according to
  461. search term.
  462. This needs user to have a administrator access in Synapse.
  463. """
  464. await assert_requester_is_admin(self.auth, request)
  465. target_user = UserID.from_string(target_user_id)
  466. # To allow all users to get the users list
  467. # if not is_admin and target_user != auth_user:
  468. # raise AuthError(403, "You are not a server admin")
  469. if not self.hs.is_mine(target_user):
  470. raise SynapseError(400, "Can only users a local user")
  471. term = parse_string(request, "term", required=True)
  472. logger.info("term: %s ", term)
  473. ret = await self.handlers.store.search_users(term)
  474. return 200, ret
  475. class UserAdminServlet(RestServlet):
  476. """
  477. Get or set whether or not a user is a server administrator.
  478. Note that only local users can be server administrators, and that an
  479. administrator may not demote themselves.
  480. Only server administrators can use this API.
  481. Examples:
  482. * Get
  483. GET /_synapse/admin/v1/users/@nonadmin:example.com/admin
  484. response on success:
  485. {
  486. "admin": false
  487. }
  488. * Set
  489. PUT /_synapse/admin/v1/users/@reivilibre:librepush.net/admin
  490. request body:
  491. {
  492. "admin": true
  493. }
  494. response on success:
  495. {}
  496. """
  497. PATTERNS = (re.compile("^/_synapse/admin/v1/users/(?P<user_id>[^/]*)/admin$"),)
  498. def __init__(self, hs):
  499. self.hs = hs
  500. self.store = hs.get_datastore()
  501. self.auth = hs.get_auth()
  502. async def on_GET(self, request, user_id):
  503. await assert_requester_is_admin(self.auth, request)
  504. target_user = UserID.from_string(user_id)
  505. if not self.hs.is_mine(target_user):
  506. raise SynapseError(400, "Only local users can be admins of this homeserver")
  507. is_admin = await self.store.is_server_admin(target_user)
  508. return 200, {"admin": is_admin}
  509. async def on_PUT(self, request, user_id):
  510. requester = await self.auth.get_user_by_req(request)
  511. await assert_user_is_admin(self.auth, requester.user)
  512. auth_user = requester.user
  513. target_user = UserID.from_string(user_id)
  514. body = parse_json_object_from_request(request)
  515. assert_params_in_dict(body, ["admin"])
  516. if not self.hs.is_mine(target_user):
  517. raise SynapseError(400, "Only local users can be admins of this homeserver")
  518. set_admin_to = bool(body["admin"])
  519. if target_user == auth_user and not set_admin_to:
  520. raise SynapseError(400, "You may not demote yourself.")
  521. await self.store.set_server_admin(target_user, set_admin_to)
  522. return 200, {}