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.
 
 
 
 
 
 

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