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.
 
 
 
 
 
 

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