You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

1259 lines
43 KiB

  1. # Copyright 2019 The Matrix.org Foundation C.I.C.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. import hashlib
  15. import hmac
  16. import logging
  17. import secrets
  18. from http import HTTPStatus
  19. from typing import TYPE_CHECKING, Dict, List, Optional, Tuple
  20. from synapse.api.constants import Direction, 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_enum,
  27. parse_integer,
  28. parse_json_object_from_request,
  29. parse_string,
  30. )
  31. from synapse.http.site import SynapseRequest
  32. from synapse.rest.admin._base import (
  33. admin_patterns,
  34. assert_requester_is_admin,
  35. assert_user_is_admin,
  36. )
  37. from synapse.rest.client._base import client_patterns
  38. from synapse.storage.databases.main.registration import ExternalIDReuseException
  39. from synapse.storage.databases.main.stats import UserSortOrder
  40. from synapse.types import JsonDict, UserID
  41. if TYPE_CHECKING:
  42. from synapse.server import HomeServer
  43. logger = logging.getLogger(__name__)
  44. class UsersRestServletV2(RestServlet):
  45. PATTERNS = admin_patterns("/users$", "v2")
  46. """Get request to list all local users.
  47. This needs user to have administrator access in Synapse.
  48. GET /_synapse/admin/v2/users?from=0&limit=10&guests=false
  49. returns:
  50. 200 OK with list of users if success otherwise an error.
  51. The parameters `from` and `limit` are required only for pagination.
  52. By default, a `limit` of 100 is used.
  53. The parameter `user_id` can be used to filter by user id.
  54. The parameter `name` can be used to filter by user id or display name.
  55. The parameter `guests` can be used to exclude guest users.
  56. The parameter `deactivated` can be used to include deactivated users.
  57. The parameter `order_by` can be used to order the result.
  58. """
  59. def __init__(self, hs: "HomeServer"):
  60. self.store = hs.get_datastores().main
  61. self.auth = hs.get_auth()
  62. self.admin_handler = hs.get_admin_handler()
  63. self._msc3866_enabled = hs.config.experimental.msc3866.enabled
  64. async def on_GET(self, request: SynapseRequest) -> Tuple[int, JsonDict]:
  65. await assert_requester_is_admin(self.auth, request)
  66. start = parse_integer(request, "from", default=0)
  67. limit = parse_integer(request, "limit", default=100)
  68. if start < 0:
  69. raise SynapseError(
  70. HTTPStatus.BAD_REQUEST,
  71. "Query parameter from must be a string representing a positive integer.",
  72. errcode=Codes.INVALID_PARAM,
  73. )
  74. if limit < 0:
  75. raise SynapseError(
  76. HTTPStatus.BAD_REQUEST,
  77. "Query parameter limit must be a string representing a positive integer.",
  78. errcode=Codes.INVALID_PARAM,
  79. )
  80. user_id = parse_string(request, "user_id")
  81. name = parse_string(request, "name")
  82. guests = parse_boolean(request, "guests", default=True)
  83. deactivated = parse_boolean(request, "deactivated", default=False)
  84. # If support for MSC3866 is not enabled, apply no filtering based on the
  85. # `approved` column.
  86. if self._msc3866_enabled:
  87. approved = parse_boolean(request, "approved", default=True)
  88. else:
  89. approved = True
  90. order_by = parse_string(
  91. request,
  92. "order_by",
  93. default=UserSortOrder.NAME.value,
  94. allowed_values=(
  95. UserSortOrder.NAME.value,
  96. UserSortOrder.DISPLAYNAME.value,
  97. UserSortOrder.GUEST.value,
  98. UserSortOrder.ADMIN.value,
  99. UserSortOrder.DEACTIVATED.value,
  100. UserSortOrder.USER_TYPE.value,
  101. UserSortOrder.AVATAR_URL.value,
  102. UserSortOrder.SHADOW_BANNED.value,
  103. UserSortOrder.CREATION_TS.value,
  104. ),
  105. )
  106. direction = parse_enum(request, "dir", Direction, default=Direction.FORWARDS)
  107. users, total = await self.store.get_users_paginate(
  108. start,
  109. limit,
  110. user_id,
  111. name,
  112. guests,
  113. deactivated,
  114. order_by,
  115. direction,
  116. approved,
  117. )
  118. # If support for MSC3866 is not enabled, don't show the approval flag.
  119. if not self._msc3866_enabled:
  120. for user in users:
  121. del user["approved"]
  122. ret = {"users": users, "total": total}
  123. if (start + limit) < total:
  124. ret["next_token"] = str(start + len(users))
  125. return HTTPStatus.OK, ret
  126. class UserRestServletV2(RestServlet):
  127. PATTERNS = admin_patterns("/users/(?P<user_id>[^/]*)$", "v2")
  128. """Get request to list user details.
  129. This needs user to have administrator access in Synapse.
  130. GET /_synapse/admin/v2/users/<user_id>
  131. returns:
  132. 200 OK with user details if success otherwise an error.
  133. Put request to allow an administrator to add or modify a user.
  134. This needs user to have administrator access in Synapse.
  135. We use PUT instead of POST since we already know the id of the user
  136. object to create. POST could be used to create guests.
  137. PUT /_synapse/admin/v2/users/<user_id>
  138. {
  139. "password": "secret",
  140. "displayname": "User"
  141. }
  142. returns:
  143. 201 OK with new user object if user was created or
  144. 200 OK with modified user object if user was modified
  145. otherwise an error.
  146. """
  147. def __init__(self, hs: "HomeServer"):
  148. self.hs = hs
  149. self.auth = hs.get_auth()
  150. self.admin_handler = hs.get_admin_handler()
  151. self.store = hs.get_datastores().main
  152. self.auth_handler = hs.get_auth_handler()
  153. self.profile_handler = hs.get_profile_handler()
  154. self.set_password_handler = hs.get_set_password_handler()
  155. self.deactivate_account_handler = hs.get_deactivate_account_handler()
  156. self.registration_handler = hs.get_registration_handler()
  157. self.pusher_pool = hs.get_pusherpool()
  158. self._msc3866_enabled = hs.config.experimental.msc3866.enabled
  159. async def on_GET(
  160. self, request: SynapseRequest, user_id: str
  161. ) -> Tuple[int, JsonDict]:
  162. await assert_requester_is_admin(self.auth, request)
  163. target_user = UserID.from_string(user_id)
  164. if not self.hs.is_mine(target_user):
  165. raise SynapseError(HTTPStatus.BAD_REQUEST, "Can only look up local users")
  166. user_info_dict = await self.admin_handler.get_user(target_user)
  167. if not user_info_dict:
  168. raise NotFoundError("User not found")
  169. return HTTPStatus.OK, user_info_dict
  170. async def on_PUT(
  171. self, request: SynapseRequest, user_id: str
  172. ) -> Tuple[int, JsonDict]:
  173. requester = await self.auth.get_user_by_req(request)
  174. await assert_user_is_admin(self.auth, requester)
  175. target_user = UserID.from_string(user_id)
  176. body = parse_json_object_from_request(request)
  177. if not self.hs.is_mine(target_user):
  178. raise SynapseError(
  179. HTTPStatus.BAD_REQUEST,
  180. "This endpoint can only be used with local users",
  181. )
  182. user = await self.admin_handler.get_user(target_user)
  183. user_id = target_user.to_string()
  184. # check for required parameters for each threepid
  185. threepids = body.get("threepids")
  186. if threepids is not None:
  187. for threepid in threepids:
  188. assert_params_in_dict(threepid, ["medium", "address"])
  189. # check for required parameters for each external_id
  190. external_ids = body.get("external_ids")
  191. if external_ids is not None:
  192. for external_id in external_ids:
  193. assert_params_in_dict(external_id, ["auth_provider", "external_id"])
  194. user_type = body.get("user_type", None)
  195. if user_type is not None and user_type not in UserTypes.ALL_USER_TYPES:
  196. raise SynapseError(HTTPStatus.BAD_REQUEST, "Invalid user type")
  197. set_admin_to = body.get("admin", False)
  198. if not isinstance(set_admin_to, bool):
  199. raise SynapseError(
  200. HTTPStatus.BAD_REQUEST,
  201. "Param 'admin' must be a boolean, if given",
  202. Codes.BAD_JSON,
  203. )
  204. password = body.get("password", None)
  205. if password is not None:
  206. if not isinstance(password, str) or len(password) > 512:
  207. raise SynapseError(HTTPStatus.BAD_REQUEST, "Invalid password")
  208. logout_devices = body.get("logout_devices", True)
  209. if not isinstance(logout_devices, bool):
  210. raise SynapseError(
  211. HTTPStatus.BAD_REQUEST,
  212. "'logout_devices' parameter is not of type boolean",
  213. )
  214. deactivate = body.get("deactivated", False)
  215. if not isinstance(deactivate, bool):
  216. raise SynapseError(
  217. HTTPStatus.BAD_REQUEST, "'deactivated' parameter is not of type boolean"
  218. )
  219. approved: Optional[bool] = None
  220. if "approved" in body and self._msc3866_enabled:
  221. approved = body["approved"]
  222. if not isinstance(approved, bool):
  223. raise SynapseError(
  224. HTTPStatus.BAD_REQUEST,
  225. "'approved' parameter is not of type boolean",
  226. )
  227. # convert List[Dict[str, str]] into List[Tuple[str, str]]
  228. if external_ids is not None:
  229. new_external_ids = [
  230. (external_id["auth_provider"], external_id["external_id"])
  231. for external_id in external_ids
  232. ]
  233. # convert List[Dict[str, str]] into Set[Tuple[str, str]]
  234. if threepids is not None:
  235. new_threepids = {
  236. (threepid["medium"], threepid["address"]) for threepid in threepids
  237. }
  238. if user: # modify user
  239. if "displayname" in body:
  240. await self.profile_handler.set_displayname(
  241. target_user, requester, body["displayname"], True
  242. )
  243. if threepids is not None:
  244. # get changed threepids (added and removed)
  245. # convert List[Dict[str, Any]] into Set[Tuple[str, str]]
  246. cur_threepids = {
  247. (threepid["medium"], threepid["address"])
  248. for threepid in await self.store.user_get_threepids(user_id)
  249. }
  250. add_threepids = new_threepids - cur_threepids
  251. del_threepids = cur_threepids - new_threepids
  252. # remove old threepids
  253. for medium, address in del_threepids:
  254. try:
  255. await self.auth_handler.delete_threepid(
  256. user_id, medium, address, None
  257. )
  258. except Exception:
  259. logger.exception("Failed to remove threepids")
  260. raise SynapseError(500, "Failed to remove threepids")
  261. # add new threepids
  262. current_time = self.hs.get_clock().time_msec()
  263. for medium, address in add_threepids:
  264. await self.auth_handler.add_threepid(
  265. user_id, medium, address, current_time
  266. )
  267. if external_ids is not None:
  268. try:
  269. await self.store.replace_user_external_id(
  270. new_external_ids,
  271. user_id,
  272. )
  273. except ExternalIDReuseException:
  274. raise SynapseError(
  275. HTTPStatus.CONFLICT, "External id is already in use."
  276. )
  277. if "avatar_url" in body and isinstance(body["avatar_url"], str):
  278. await self.profile_handler.set_avatar_url(
  279. target_user, requester, body["avatar_url"], True
  280. )
  281. if "admin" in body:
  282. if set_admin_to != user["admin"]:
  283. auth_user = requester.user
  284. if target_user == auth_user and not set_admin_to:
  285. raise SynapseError(
  286. HTTPStatus.BAD_REQUEST, "You may not demote yourself."
  287. )
  288. await self.store.set_server_admin(target_user, set_admin_to)
  289. if password is not None:
  290. new_password_hash = await self.auth_handler.hash(password)
  291. await self.set_password_handler.set_password(
  292. target_user.to_string(),
  293. new_password_hash,
  294. logout_devices,
  295. requester,
  296. )
  297. if "deactivated" in body:
  298. if deactivate and not user["deactivated"]:
  299. await self.deactivate_account_handler.deactivate_account(
  300. target_user.to_string(), False, requester, by_admin=True
  301. )
  302. elif not deactivate and user["deactivated"]:
  303. if (
  304. "password" not in body
  305. and self.auth_handler.can_change_password()
  306. ):
  307. raise SynapseError(
  308. HTTPStatus.BAD_REQUEST,
  309. "Must provide a password to re-activate an account.",
  310. )
  311. await self.deactivate_account_handler.activate_account(
  312. target_user.to_string()
  313. )
  314. if "user_type" in body:
  315. await self.store.set_user_type(target_user, user_type)
  316. if approved is not None:
  317. await self.store.update_user_approval_status(target_user, approved)
  318. user = await self.admin_handler.get_user(target_user)
  319. assert user is not None
  320. return HTTPStatus.OK, user
  321. else: # create user
  322. displayname = body.get("displayname", None)
  323. password_hash = None
  324. if password is not None:
  325. password_hash = await self.auth_handler.hash(password)
  326. new_user_approved = True
  327. if self._msc3866_enabled and approved is not None:
  328. new_user_approved = approved
  329. user_id = await self.registration_handler.register_user(
  330. localpart=target_user.localpart,
  331. password_hash=password_hash,
  332. admin=set_admin_to,
  333. default_display_name=displayname,
  334. user_type=user_type,
  335. by_admin=True,
  336. approved=new_user_approved,
  337. )
  338. if threepids is not None:
  339. current_time = self.hs.get_clock().time_msec()
  340. for medium, address in new_threepids:
  341. await self.auth_handler.add_threepid(
  342. user_id, medium, address, current_time
  343. )
  344. if (
  345. self.hs.config.email.email_enable_notifs
  346. and self.hs.config.email.email_notif_for_new_users
  347. and medium == "email"
  348. ):
  349. await self.pusher_pool.add_or_update_pusher(
  350. user_id=user_id,
  351. access_token=None,
  352. kind="email",
  353. app_id="m.email",
  354. app_display_name="Email Notifications",
  355. device_display_name=address,
  356. pushkey=address,
  357. lang=None,
  358. data={},
  359. )
  360. if external_ids is not None:
  361. try:
  362. for auth_provider, external_id in new_external_ids:
  363. await self.store.record_user_external_id(
  364. auth_provider,
  365. external_id,
  366. user_id,
  367. )
  368. except ExternalIDReuseException:
  369. raise SynapseError(
  370. HTTPStatus.CONFLICT, "External id is already in use."
  371. )
  372. if "avatar_url" in body and isinstance(body["avatar_url"], str):
  373. await self.profile_handler.set_avatar_url(
  374. target_user, requester, body["avatar_url"], True
  375. )
  376. user_info_dict = await self.admin_handler.get_user(target_user)
  377. assert user_info_dict is not None
  378. return HTTPStatus.CREATED, user_info_dict
  379. class UserRegisterServlet(RestServlet):
  380. """
  381. Attributes:
  382. NONCE_TIMEOUT (int): Seconds until a generated nonce won't be accepted
  383. nonces (dict[str, int]): The nonces that we will accept. A dict of
  384. nonce to the time it was generated, in int seconds.
  385. """
  386. PATTERNS = admin_patterns("/register$")
  387. NONCE_TIMEOUT = 60
  388. def __init__(self, hs: "HomeServer"):
  389. self.auth_handler = hs.get_auth_handler()
  390. self.reactor = hs.get_reactor()
  391. self.nonces: Dict[str, int] = {}
  392. self.hs = hs
  393. def _clear_old_nonces(self) -> None:
  394. """
  395. Clear out old nonces that are older than NONCE_TIMEOUT.
  396. """
  397. now = int(self.reactor.seconds())
  398. for k, v in list(self.nonces.items()):
  399. if now - v > self.NONCE_TIMEOUT:
  400. del self.nonces[k]
  401. def on_GET(self, request: SynapseRequest) -> Tuple[int, JsonDict]:
  402. """
  403. Generate a new nonce.
  404. """
  405. self._clear_old_nonces()
  406. nonce = secrets.token_hex(64)
  407. self.nonces[nonce] = int(self.reactor.seconds())
  408. return HTTPStatus.OK, {"nonce": nonce}
  409. async def on_POST(self, request: SynapseRequest) -> Tuple[int, JsonDict]:
  410. self._clear_old_nonces()
  411. if not self.hs.config.registration.registration_shared_secret:
  412. raise SynapseError(
  413. HTTPStatus.BAD_REQUEST, "Shared secret registration is not enabled"
  414. )
  415. body = parse_json_object_from_request(request)
  416. if "nonce" not in body:
  417. raise SynapseError(
  418. HTTPStatus.BAD_REQUEST,
  419. "nonce must be specified",
  420. errcode=Codes.BAD_JSON,
  421. )
  422. nonce = body["nonce"]
  423. if nonce not in self.nonces:
  424. raise SynapseError(HTTPStatus.BAD_REQUEST, "unrecognised nonce")
  425. # Delete the nonce, so it can't be reused, even if it's invalid
  426. del self.nonces[nonce]
  427. if "username" not in body:
  428. raise SynapseError(
  429. HTTPStatus.BAD_REQUEST,
  430. "username must be specified",
  431. errcode=Codes.BAD_JSON,
  432. )
  433. else:
  434. if not isinstance(body["username"], str) or len(body["username"]) > 512:
  435. raise SynapseError(HTTPStatus.BAD_REQUEST, "Invalid username")
  436. username = body["username"].encode("utf-8")
  437. if b"\x00" in username:
  438. raise SynapseError(HTTPStatus.BAD_REQUEST, "Invalid username")
  439. if "password" not in body:
  440. raise SynapseError(
  441. HTTPStatus.BAD_REQUEST,
  442. "password must be specified",
  443. errcode=Codes.BAD_JSON,
  444. )
  445. else:
  446. password = body["password"]
  447. if not isinstance(password, str) or len(password) > 512:
  448. raise SynapseError(HTTPStatus.BAD_REQUEST, "Invalid password")
  449. password_bytes = password.encode("utf-8")
  450. if b"\x00" in password_bytes:
  451. raise SynapseError(HTTPStatus.BAD_REQUEST, "Invalid password")
  452. password_hash = await self.auth_handler.hash(password)
  453. admin = body.get("admin", None)
  454. user_type = body.get("user_type", None)
  455. displayname = body.get("displayname", None)
  456. if user_type is not None and user_type not in UserTypes.ALL_USER_TYPES:
  457. raise SynapseError(HTTPStatus.BAD_REQUEST, "Invalid user type")
  458. if "mac" not in body:
  459. raise SynapseError(
  460. HTTPStatus.BAD_REQUEST, "mac must be specified", errcode=Codes.BAD_JSON
  461. )
  462. got_mac = body["mac"]
  463. want_mac_builder = hmac.new(
  464. key=self.hs.config.registration.registration_shared_secret.encode(),
  465. digestmod=hashlib.sha1,
  466. )
  467. want_mac_builder.update(nonce.encode("utf8"))
  468. want_mac_builder.update(b"\x00")
  469. want_mac_builder.update(username)
  470. want_mac_builder.update(b"\x00")
  471. want_mac_builder.update(password_bytes)
  472. want_mac_builder.update(b"\x00")
  473. want_mac_builder.update(b"admin" if admin else b"notadmin")
  474. if user_type:
  475. want_mac_builder.update(b"\x00")
  476. want_mac_builder.update(user_type.encode("utf8"))
  477. want_mac = want_mac_builder.hexdigest()
  478. if not hmac.compare_digest(want_mac.encode("ascii"), got_mac.encode("ascii")):
  479. raise SynapseError(HTTPStatus.FORBIDDEN, "HMAC incorrect")
  480. # Reuse the parts of RegisterRestServlet to reduce code duplication
  481. from synapse.rest.client.register import RegisterRestServlet
  482. register = RegisterRestServlet(self.hs)
  483. user_id = await register.registration_handler.register_user(
  484. localpart=body["username"].lower(),
  485. password_hash=password_hash,
  486. admin=bool(admin),
  487. user_type=user_type,
  488. default_display_name=displayname,
  489. by_admin=True,
  490. approved=True,
  491. )
  492. result = await register._create_registration_details(user_id, body)
  493. return HTTPStatus.OK, result
  494. class WhoisRestServlet(RestServlet):
  495. path_regex = "/whois/(?P<user_id>[^/]*)$"
  496. PATTERNS = [
  497. *admin_patterns(path_regex),
  498. # URL for spec reason
  499. # https://matrix.org/docs/spec/client_server/r0.6.1#get-matrix-client-r0-admin-whois-userid
  500. *client_patterns("/admin" + path_regex, v1=True),
  501. ]
  502. def __init__(self, hs: "HomeServer"):
  503. self.auth = hs.get_auth()
  504. self.admin_handler = hs.get_admin_handler()
  505. self.is_mine = hs.is_mine
  506. async def on_GET(
  507. self, request: SynapseRequest, user_id: str
  508. ) -> Tuple[int, JsonDict]:
  509. target_user = UserID.from_string(user_id)
  510. requester = await self.auth.get_user_by_req(request)
  511. if target_user != requester.user:
  512. await assert_user_is_admin(self.auth, requester)
  513. if not self.is_mine(target_user):
  514. raise SynapseError(HTTPStatus.BAD_REQUEST, "Can only whois a local user")
  515. ret = await self.admin_handler.get_whois(target_user)
  516. return HTTPStatus.OK, ret
  517. class DeactivateAccountRestServlet(RestServlet):
  518. PATTERNS = admin_patterns("/deactivate/(?P<target_user_id>[^/]*)$")
  519. def __init__(self, hs: "HomeServer"):
  520. self._deactivate_account_handler = hs.get_deactivate_account_handler()
  521. self.auth = hs.get_auth()
  522. self.is_mine = hs.is_mine
  523. self.store = hs.get_datastores().main
  524. async def on_POST(
  525. self, request: SynapseRequest, target_user_id: str
  526. ) -> Tuple[int, JsonDict]:
  527. requester = await self.auth.get_user_by_req(request)
  528. await assert_user_is_admin(self.auth, requester)
  529. if not self.is_mine(UserID.from_string(target_user_id)):
  530. raise SynapseError(
  531. HTTPStatus.BAD_REQUEST, "Can only deactivate local users"
  532. )
  533. if not await self.store.get_user_by_id(target_user_id):
  534. raise NotFoundError("User not found")
  535. body = parse_json_object_from_request(request, allow_empty_body=True)
  536. erase = body.get("erase", False)
  537. if not isinstance(erase, bool):
  538. raise SynapseError(
  539. HTTPStatus.BAD_REQUEST,
  540. "Param 'erase' must be a boolean, if given",
  541. Codes.BAD_JSON,
  542. )
  543. result = await self._deactivate_account_handler.deactivate_account(
  544. target_user_id, erase, requester, by_admin=True
  545. )
  546. if result:
  547. id_server_unbind_result = "success"
  548. else:
  549. id_server_unbind_result = "no-support"
  550. return HTTPStatus.OK, {"id_server_unbind_result": id_server_unbind_result}
  551. class AccountValidityRenewServlet(RestServlet):
  552. PATTERNS = admin_patterns("/account_validity/validity$")
  553. def __init__(self, hs: "HomeServer"):
  554. self.account_activity_handler = hs.get_account_validity_handler()
  555. self.auth = hs.get_auth()
  556. async def on_POST(self, request: SynapseRequest) -> Tuple[int, JsonDict]:
  557. await assert_requester_is_admin(self.auth, request)
  558. if self.account_activity_handler.on_legacy_admin_request_callback:
  559. expiration_ts = (
  560. await (
  561. self.account_activity_handler.on_legacy_admin_request_callback(
  562. request
  563. )
  564. )
  565. )
  566. else:
  567. body = parse_json_object_from_request(request)
  568. if "user_id" not in body:
  569. raise SynapseError(
  570. HTTPStatus.BAD_REQUEST,
  571. "Missing property 'user_id' in the request body",
  572. )
  573. expiration_ts = await self.account_activity_handler.renew_account_for_user(
  574. body["user_id"],
  575. body.get("expiration_ts"),
  576. not body.get("enable_renewal_emails", True),
  577. )
  578. res = {"expiration_ts": expiration_ts}
  579. return HTTPStatus.OK, res
  580. class ResetPasswordRestServlet(RestServlet):
  581. """Post request to allow an administrator reset password for a user.
  582. This needs user to have administrator access in Synapse.
  583. Example:
  584. http://localhost:8008/_synapse/admin/v1/reset_password/
  585. @user:to_reset_password?access_token=admin_access_token
  586. JsonBodyToSend:
  587. {
  588. "new_password": "secret"
  589. }
  590. Returns:
  591. 200 OK with empty object if success otherwise an error.
  592. """
  593. PATTERNS = admin_patterns("/reset_password/(?P<target_user_id>[^/]*)$")
  594. def __init__(self, hs: "HomeServer"):
  595. self.store = hs.get_datastores().main
  596. self.auth = hs.get_auth()
  597. self.auth_handler = hs.get_auth_handler()
  598. self._set_password_handler = hs.get_set_password_handler()
  599. async def on_POST(
  600. self, request: SynapseRequest, target_user_id: str
  601. ) -> Tuple[int, JsonDict]:
  602. """Post request to allow an administrator reset password for a user.
  603. This needs user to have administrator access in Synapse.
  604. """
  605. requester = await self.auth.get_user_by_req(request)
  606. await assert_user_is_admin(self.auth, requester)
  607. UserID.from_string(target_user_id)
  608. params = parse_json_object_from_request(request)
  609. assert_params_in_dict(params, ["new_password"])
  610. new_password = params["new_password"]
  611. logout_devices = params.get("logout_devices", True)
  612. new_password_hash = await self.auth_handler.hash(new_password)
  613. await self._set_password_handler.set_password(
  614. target_user_id, new_password_hash, logout_devices, requester
  615. )
  616. return HTTPStatus.OK, {}
  617. class SearchUsersRestServlet(RestServlet):
  618. """Get request to search user table for specific users according to
  619. search term.
  620. This needs user to have administrator access in Synapse.
  621. Example:
  622. http://localhost:8008/_synapse/admin/v1/search_users/
  623. @admin:user?access_token=admin_access_token&term=alice
  624. Returns:
  625. 200 OK with json object {list[dict[str, Any]], count} or empty object.
  626. """
  627. PATTERNS = admin_patterns("/search_users/(?P<target_user_id>[^/]*)$")
  628. def __init__(self, hs: "HomeServer"):
  629. self.store = hs.get_datastores().main
  630. self.auth = hs.get_auth()
  631. self.is_mine = hs.is_mine
  632. async def on_GET(
  633. self, request: SynapseRequest, target_user_id: str
  634. ) -> Tuple[int, Optional[List[JsonDict]]]:
  635. """Get request to search user table for specific users according to
  636. search term.
  637. This needs user to have a administrator access in Synapse.
  638. """
  639. await assert_requester_is_admin(self.auth, request)
  640. target_user = UserID.from_string(target_user_id)
  641. # To allow all users to get the users list
  642. # if not is_admin and target_user != auth_user:
  643. # raise AuthError(HTTPStatus.FORBIDDEN, "You are not a server admin")
  644. if not self.is_mine(target_user):
  645. raise SynapseError(HTTPStatus.BAD_REQUEST, "Can only users a local user")
  646. term = parse_string(request, "term", required=True)
  647. logger.info("term: %s ", term)
  648. ret = await self.store.search_users(term)
  649. return HTTPStatus.OK, ret
  650. class UserAdminServlet(RestServlet):
  651. """
  652. Get or set whether or not a user is a server administrator.
  653. Note that only local users can be server administrators, and that an
  654. administrator may not demote themselves.
  655. Only server administrators can use this API.
  656. Examples:
  657. * Get
  658. GET /_synapse/admin/v1/users/@nonadmin:example.com/admin
  659. response on success:
  660. {
  661. "admin": false
  662. }
  663. * Set
  664. PUT /_synapse/admin/v1/users/@reivilibre:librepush.net/admin
  665. request body:
  666. {
  667. "admin": true
  668. }
  669. response on success:
  670. {}
  671. """
  672. PATTERNS = admin_patterns("/users/(?P<user_id>[^/]*)/admin$")
  673. def __init__(self, hs: "HomeServer"):
  674. self.store = hs.get_datastores().main
  675. self.auth = hs.get_auth()
  676. self.is_mine = hs.is_mine
  677. async def on_GET(
  678. self, request: SynapseRequest, user_id: str
  679. ) -> Tuple[int, JsonDict]:
  680. await assert_requester_is_admin(self.auth, request)
  681. target_user = UserID.from_string(user_id)
  682. if not self.is_mine(target_user):
  683. raise SynapseError(
  684. HTTPStatus.BAD_REQUEST,
  685. "Only local users can be admins of this homeserver",
  686. )
  687. is_admin = await self.store.is_server_admin(target_user)
  688. return HTTPStatus.OK, {"admin": is_admin}
  689. async def on_PUT(
  690. self, request: SynapseRequest, user_id: str
  691. ) -> Tuple[int, JsonDict]:
  692. requester = await self.auth.get_user_by_req(request)
  693. await assert_user_is_admin(self.auth, requester)
  694. auth_user = requester.user
  695. target_user = UserID.from_string(user_id)
  696. body = parse_json_object_from_request(request)
  697. assert_params_in_dict(body, ["admin"])
  698. if not self.is_mine(target_user):
  699. raise SynapseError(
  700. HTTPStatus.BAD_REQUEST,
  701. "Only local users can be admins of this homeserver",
  702. )
  703. set_admin_to = bool(body["admin"])
  704. if target_user == auth_user and not set_admin_to:
  705. raise SynapseError(HTTPStatus.BAD_REQUEST, "You may not demote yourself.")
  706. await self.store.set_server_admin(target_user, set_admin_to)
  707. return HTTPStatus.OK, {}
  708. class UserMembershipRestServlet(RestServlet):
  709. """
  710. Get room list of an user.
  711. """
  712. PATTERNS = admin_patterns("/users/(?P<user_id>[^/]*)/joined_rooms$")
  713. def __init__(self, hs: "HomeServer"):
  714. self.is_mine = hs.is_mine
  715. self.auth = hs.get_auth()
  716. self.store = hs.get_datastores().main
  717. async def on_GET(
  718. self, request: SynapseRequest, user_id: str
  719. ) -> Tuple[int, JsonDict]:
  720. await assert_requester_is_admin(self.auth, request)
  721. room_ids = await self.store.get_rooms_for_user(user_id)
  722. ret = {"joined_rooms": list(room_ids), "total": len(room_ids)}
  723. return HTTPStatus.OK, ret
  724. class PushersRestServlet(RestServlet):
  725. """
  726. Gets information about all pushers for a specific `user_id`.
  727. Example:
  728. http://localhost:8008/_synapse/admin/v1/users/
  729. @user:server/pushers
  730. Returns:
  731. A dictionary with keys:
  732. pushers: Dictionary containing pushers information.
  733. total: Number of pushers in dictionary `pushers`.
  734. """
  735. PATTERNS = admin_patterns("/users/(?P<user_id>[^/]*)/pushers$")
  736. def __init__(self, hs: "HomeServer"):
  737. self.is_mine = hs.is_mine
  738. self.store = hs.get_datastores().main
  739. self.auth = hs.get_auth()
  740. async def on_GET(
  741. self, request: SynapseRequest, user_id: str
  742. ) -> Tuple[int, JsonDict]:
  743. await assert_requester_is_admin(self.auth, request)
  744. if not self.is_mine(UserID.from_string(user_id)):
  745. raise SynapseError(HTTPStatus.BAD_REQUEST, "Can only look up local users")
  746. if not await self.store.get_user_by_id(user_id):
  747. raise NotFoundError("User not found")
  748. pushers = await self.store.get_pushers_by_user_id(user_id)
  749. filtered_pushers = [p.as_dict() for p in pushers]
  750. return HTTPStatus.OK, {
  751. "pushers": filtered_pushers,
  752. "total": len(filtered_pushers),
  753. }
  754. class UserTokenRestServlet(RestServlet):
  755. """An admin API for logging in as a user.
  756. Example:
  757. POST /_synapse/admin/v1/users/@test:example.com/login
  758. {}
  759. 200 OK
  760. {
  761. "access_token": "<some_token>"
  762. }
  763. """
  764. PATTERNS = admin_patterns("/users/(?P<user_id>[^/]*)/login$")
  765. def __init__(self, hs: "HomeServer"):
  766. self.store = hs.get_datastores().main
  767. self.auth = hs.get_auth()
  768. self.auth_handler = hs.get_auth_handler()
  769. self.is_mine_id = hs.is_mine_id
  770. async def on_POST(
  771. self, request: SynapseRequest, user_id: str
  772. ) -> Tuple[int, JsonDict]:
  773. requester = await self.auth.get_user_by_req(request)
  774. await assert_user_is_admin(self.auth, requester)
  775. auth_user = requester.user
  776. if not self.is_mine_id(user_id):
  777. raise SynapseError(
  778. HTTPStatus.BAD_REQUEST, "Only local users can be logged in as"
  779. )
  780. body = parse_json_object_from_request(request, allow_empty_body=True)
  781. valid_until_ms = body.get("valid_until_ms")
  782. if type(valid_until_ms) not in (int, type(None)):
  783. raise SynapseError(
  784. HTTPStatus.BAD_REQUEST, "'valid_until_ms' parameter must be an int"
  785. )
  786. if auth_user.to_string() == user_id:
  787. raise SynapseError(
  788. HTTPStatus.BAD_REQUEST, "Cannot use admin API to login as self"
  789. )
  790. token = await self.auth_handler.create_access_token_for_user_id(
  791. user_id=auth_user.to_string(),
  792. device_id=None,
  793. valid_until_ms=valid_until_ms,
  794. puppets_user_id=user_id,
  795. )
  796. return HTTPStatus.OK, {"access_token": token}
  797. class ShadowBanRestServlet(RestServlet):
  798. """An admin API for controlling whether a user is shadow-banned.
  799. A shadow-banned users receives successful responses to their client-server
  800. API requests, but the events are not propagated into rooms.
  801. Shadow-banning a user should be used as a tool of last resort and may lead
  802. to confusing or broken behaviour for the client.
  803. Example of shadow-banning a user:
  804. POST /_synapse/admin/v1/users/@test:example.com/shadow_ban
  805. {}
  806. 200 OK
  807. {}
  808. Example of removing a user from being shadow-banned:
  809. DELETE /_synapse/admin/v1/users/@test:example.com/shadow_ban
  810. {}
  811. 200 OK
  812. {}
  813. """
  814. PATTERNS = admin_patterns("/users/(?P<user_id>[^/]*)/shadow_ban$")
  815. def __init__(self, hs: "HomeServer"):
  816. self.store = hs.get_datastores().main
  817. self.auth = hs.get_auth()
  818. self.is_mine_id = hs.is_mine_id
  819. async def on_POST(
  820. self, request: SynapseRequest, user_id: str
  821. ) -> Tuple[int, JsonDict]:
  822. await assert_requester_is_admin(self.auth, request)
  823. if not self.is_mine_id(user_id):
  824. raise SynapseError(
  825. HTTPStatus.BAD_REQUEST, "Only local users can be shadow-banned"
  826. )
  827. await self.store.set_shadow_banned(UserID.from_string(user_id), True)
  828. return HTTPStatus.OK, {}
  829. async def on_DELETE(
  830. self, request: SynapseRequest, user_id: str
  831. ) -> Tuple[int, JsonDict]:
  832. await assert_requester_is_admin(self.auth, request)
  833. if not self.is_mine_id(user_id):
  834. raise SynapseError(
  835. HTTPStatus.BAD_REQUEST, "Only local users can be shadow-banned"
  836. )
  837. await self.store.set_shadow_banned(UserID.from_string(user_id), False)
  838. return HTTPStatus.OK, {}
  839. class RateLimitRestServlet(RestServlet):
  840. """An admin API to override ratelimiting for an user.
  841. Example:
  842. POST /_synapse/admin/v1/users/@test:example.com/override_ratelimit
  843. {
  844. "messages_per_second": 0,
  845. "burst_count": 0
  846. }
  847. 200 OK
  848. {
  849. "messages_per_second": 0,
  850. "burst_count": 0
  851. }
  852. """
  853. PATTERNS = admin_patterns("/users/(?P<user_id>[^/]*)/override_ratelimit$")
  854. def __init__(self, hs: "HomeServer"):
  855. self.store = hs.get_datastores().main
  856. self.auth = hs.get_auth()
  857. self.is_mine_id = hs.is_mine_id
  858. async def on_GET(
  859. self, request: SynapseRequest, user_id: str
  860. ) -> Tuple[int, JsonDict]:
  861. await assert_requester_is_admin(self.auth, request)
  862. if not self.is_mine_id(user_id):
  863. raise SynapseError(HTTPStatus.BAD_REQUEST, "Can only look up local users")
  864. if not await self.store.get_user_by_id(user_id):
  865. raise NotFoundError("User not found")
  866. ratelimit = await self.store.get_ratelimit_for_user(user_id)
  867. if ratelimit:
  868. # convert `null` to `0` for consistency
  869. # both values do the same in retelimit handler
  870. ret = {
  871. "messages_per_second": 0
  872. if ratelimit.messages_per_second is None
  873. else ratelimit.messages_per_second,
  874. "burst_count": 0
  875. if ratelimit.burst_count is None
  876. else ratelimit.burst_count,
  877. }
  878. else:
  879. ret = {}
  880. return HTTPStatus.OK, ret
  881. async def on_POST(
  882. self, request: SynapseRequest, user_id: str
  883. ) -> Tuple[int, JsonDict]:
  884. await assert_requester_is_admin(self.auth, request)
  885. if not self.is_mine_id(user_id):
  886. raise SynapseError(
  887. HTTPStatus.BAD_REQUEST, "Only local users can be ratelimited"
  888. )
  889. if not await self.store.get_user_by_id(user_id):
  890. raise NotFoundError("User not found")
  891. body = parse_json_object_from_request(request, allow_empty_body=True)
  892. messages_per_second = body.get("messages_per_second", 0)
  893. burst_count = body.get("burst_count", 0)
  894. if type(messages_per_second) is not int or messages_per_second < 0:
  895. raise SynapseError(
  896. HTTPStatus.BAD_REQUEST,
  897. "%r parameter must be a positive int" % (messages_per_second,),
  898. errcode=Codes.INVALID_PARAM,
  899. )
  900. if type(burst_count) is not int or burst_count < 0:
  901. raise SynapseError(
  902. HTTPStatus.BAD_REQUEST,
  903. "%r parameter must be a positive int" % (burst_count,),
  904. errcode=Codes.INVALID_PARAM,
  905. )
  906. await self.store.set_ratelimit_for_user(
  907. user_id, messages_per_second, burst_count
  908. )
  909. ratelimit = await self.store.get_ratelimit_for_user(user_id)
  910. assert ratelimit is not None
  911. ret = {
  912. "messages_per_second": ratelimit.messages_per_second,
  913. "burst_count": ratelimit.burst_count,
  914. }
  915. return HTTPStatus.OK, ret
  916. async def on_DELETE(
  917. self, request: SynapseRequest, user_id: str
  918. ) -> Tuple[int, JsonDict]:
  919. await assert_requester_is_admin(self.auth, request)
  920. if not self.is_mine_id(user_id):
  921. raise SynapseError(
  922. HTTPStatus.BAD_REQUEST, "Only local users can be ratelimited"
  923. )
  924. if not await self.store.get_user_by_id(user_id):
  925. raise NotFoundError("User not found")
  926. await self.store.delete_ratelimit_for_user(user_id)
  927. return HTTPStatus.OK, {}
  928. class AccountDataRestServlet(RestServlet):
  929. """Retrieve the given user's account data"""
  930. PATTERNS = admin_patterns("/users/(?P<user_id>[^/]*)/accountdata")
  931. def __init__(self, hs: "HomeServer"):
  932. self._auth = hs.get_auth()
  933. self._store = hs.get_datastores().main
  934. self._is_mine_id = hs.is_mine_id
  935. async def on_GET(
  936. self, request: SynapseRequest, user_id: str
  937. ) -> Tuple[int, JsonDict]:
  938. await assert_requester_is_admin(self._auth, request)
  939. if not self._is_mine_id(user_id):
  940. raise SynapseError(HTTPStatus.BAD_REQUEST, "Can only look up local users")
  941. if not await self._store.get_user_by_id(user_id):
  942. raise NotFoundError("User not found")
  943. global_data = await self._store.get_global_account_data_for_user(user_id)
  944. by_room_data = await self._store.get_room_account_data_for_user(user_id)
  945. return HTTPStatus.OK, {
  946. "account_data": {
  947. "global": global_data,
  948. "rooms": by_room_data,
  949. },
  950. }
  951. class UserByExternalId(RestServlet):
  952. """Find a user based on an external ID from an auth provider"""
  953. PATTERNS = admin_patterns(
  954. "/auth_providers/(?P<provider>[^/]*)/users/(?P<external_id>[^/]*)"
  955. )
  956. def __init__(self, hs: "HomeServer"):
  957. self._auth = hs.get_auth()
  958. self._store = hs.get_datastores().main
  959. async def on_GET(
  960. self,
  961. request: SynapseRequest,
  962. provider: str,
  963. external_id: str,
  964. ) -> Tuple[int, JsonDict]:
  965. await assert_requester_is_admin(self._auth, request)
  966. user_id = await self._store.get_user_by_external_id(provider, external_id)
  967. if user_id is None:
  968. raise NotFoundError("User not found")
  969. return HTTPStatus.OK, {"user_id": user_id}
  970. class UserByThreePid(RestServlet):
  971. """Find a user based on 3PID of a particular medium"""
  972. PATTERNS = admin_patterns("/threepid/(?P<medium>[^/]*)/users/(?P<address>[^/]*)")
  973. def __init__(self, hs: "HomeServer"):
  974. self._auth = hs.get_auth()
  975. self._store = hs.get_datastores().main
  976. async def on_GET(
  977. self,
  978. request: SynapseRequest,
  979. medium: str,
  980. address: str,
  981. ) -> Tuple[int, JsonDict]:
  982. await assert_requester_is_admin(self._auth, request)
  983. user_id = await self._store.get_user_id_by_threepid(medium, address)
  984. if user_id is None:
  985. raise NotFoundError("User not found")
  986. return HTTPStatus.OK, {"user_id": user_id}