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.
 
 
 
 
 
 

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