users.py 43 KB

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