Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.
 
 
 
 
 
 

342 строки
11 KiB

  1. # Copyright 2021 Callum Brown
  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 logging
  15. import string
  16. from http import HTTPStatus
  17. from typing import TYPE_CHECKING, Tuple
  18. from synapse.api.errors import Codes, NotFoundError, SynapseError
  19. from synapse.http.servlet import (
  20. RestServlet,
  21. parse_boolean,
  22. parse_json_object_from_request,
  23. )
  24. from synapse.http.site import SynapseRequest
  25. from synapse.rest.admin._base import admin_patterns, assert_requester_is_admin
  26. from synapse.types import JsonDict
  27. if TYPE_CHECKING:
  28. from synapse.server import HomeServer
  29. logger = logging.getLogger(__name__)
  30. class ListRegistrationTokensRestServlet(RestServlet):
  31. """List registration tokens.
  32. To list all tokens:
  33. GET /_synapse/admin/v1/registration_tokens
  34. 200 OK
  35. {
  36. "registration_tokens": [
  37. {
  38. "token": "abcd",
  39. "uses_allowed": 3,
  40. "pending": 0,
  41. "completed": 1,
  42. "expiry_time": null
  43. },
  44. {
  45. "token": "wxyz",
  46. "uses_allowed": null,
  47. "pending": 0,
  48. "completed": 9,
  49. "expiry_time": 1625394937000
  50. }
  51. ]
  52. }
  53. The optional query parameter `valid` can be used to filter the response.
  54. If it is `true`, only valid tokens are returned. If it is `false`, only
  55. tokens that have expired or have had all uses exhausted are returned.
  56. If it is omitted, all tokens are returned regardless of validity.
  57. """
  58. PATTERNS = admin_patterns("/registration_tokens$")
  59. def __init__(self, hs: "HomeServer"):
  60. self.auth = hs.get_auth()
  61. self.store = hs.get_datastores().main
  62. async def on_GET(self, request: SynapseRequest) -> Tuple[int, JsonDict]:
  63. await assert_requester_is_admin(self.auth, request)
  64. valid = parse_boolean(request, "valid")
  65. token_list = await self.store.get_registration_tokens(valid)
  66. return HTTPStatus.OK, {"registration_tokens": token_list}
  67. class NewRegistrationTokenRestServlet(RestServlet):
  68. """Create a new registration token.
  69. For example, to create a token specifying some fields:
  70. POST /_synapse/admin/v1/registration_tokens/new
  71. {
  72. "token": "defg",
  73. "uses_allowed": 1
  74. }
  75. 200 OK
  76. {
  77. "token": "defg",
  78. "uses_allowed": 1,
  79. "pending": 0,
  80. "completed": 0,
  81. "expiry_time": null
  82. }
  83. Defaults are used for any fields not specified.
  84. """
  85. PATTERNS = admin_patterns("/registration_tokens/new$")
  86. def __init__(self, hs: "HomeServer"):
  87. self.auth = hs.get_auth()
  88. self.store = hs.get_datastores().main
  89. self.clock = hs.get_clock()
  90. # A string of all the characters allowed to be in a registration_token
  91. self.allowed_chars = string.ascii_letters + string.digits + "._~-"
  92. self.allowed_chars_set = set(self.allowed_chars)
  93. async def on_POST(self, request: SynapseRequest) -> Tuple[int, JsonDict]:
  94. await assert_requester_is_admin(self.auth, request)
  95. body = parse_json_object_from_request(request)
  96. if "token" in body:
  97. token = body["token"]
  98. if not isinstance(token, str):
  99. raise SynapseError(
  100. HTTPStatus.BAD_REQUEST,
  101. "token must be a string",
  102. Codes.INVALID_PARAM,
  103. )
  104. if not (0 < len(token) <= 64):
  105. raise SynapseError(
  106. HTTPStatus.BAD_REQUEST,
  107. "token must not be empty and must not be longer than 64 characters",
  108. Codes.INVALID_PARAM,
  109. )
  110. if not set(token).issubset(self.allowed_chars_set):
  111. raise SynapseError(
  112. HTTPStatus.BAD_REQUEST,
  113. "token must consist only of characters matched by the regex [A-Za-z0-9-_]",
  114. Codes.INVALID_PARAM,
  115. )
  116. else:
  117. # Get length of token to generate (default is 16)
  118. length = body.get("length", 16)
  119. if type(length) is not int: # noqa: E721
  120. raise SynapseError(
  121. HTTPStatus.BAD_REQUEST,
  122. "length must be an integer",
  123. Codes.INVALID_PARAM,
  124. )
  125. if not (0 < length <= 64):
  126. raise SynapseError(
  127. HTTPStatus.BAD_REQUEST,
  128. "length must be greater than zero and not greater than 64",
  129. Codes.INVALID_PARAM,
  130. )
  131. # Generate token
  132. token = await self.store.generate_registration_token(
  133. length, self.allowed_chars
  134. )
  135. uses_allowed = body.get("uses_allowed", None)
  136. if not (
  137. uses_allowed is None
  138. or (type(uses_allowed) is int and uses_allowed >= 0) # noqa: E721
  139. ):
  140. raise SynapseError(
  141. HTTPStatus.BAD_REQUEST,
  142. "uses_allowed must be a non-negative integer or null",
  143. Codes.INVALID_PARAM,
  144. )
  145. expiry_time = body.get("expiry_time", None)
  146. if expiry_time is not None and type(expiry_time) is not int: # noqa: E721
  147. raise SynapseError(
  148. HTTPStatus.BAD_REQUEST,
  149. "expiry_time must be an integer or null",
  150. Codes.INVALID_PARAM,
  151. )
  152. if (
  153. type(expiry_time) is int # noqa: E721
  154. and expiry_time < self.clock.time_msec()
  155. ):
  156. raise SynapseError(
  157. HTTPStatus.BAD_REQUEST,
  158. "expiry_time must not be in the past",
  159. Codes.INVALID_PARAM,
  160. )
  161. created = await self.store.create_registration_token(
  162. token, uses_allowed, expiry_time
  163. )
  164. if not created:
  165. raise SynapseError(
  166. HTTPStatus.BAD_REQUEST,
  167. f"Token already exists: {token}",
  168. Codes.INVALID_PARAM,
  169. )
  170. resp = {
  171. "token": token,
  172. "uses_allowed": uses_allowed,
  173. "pending": 0,
  174. "completed": 0,
  175. "expiry_time": expiry_time,
  176. }
  177. return HTTPStatus.OK, resp
  178. class RegistrationTokenRestServlet(RestServlet):
  179. """Retrieve, update, or delete the given token.
  180. For example,
  181. to retrieve a token:
  182. GET /_synapse/admin/v1/registration_tokens/abcd
  183. 200 OK
  184. {
  185. "token": "abcd",
  186. "uses_allowed": 3,
  187. "pending": 0,
  188. "completed": 1,
  189. "expiry_time": null
  190. }
  191. to update a token:
  192. PUT /_synapse/admin/v1/registration_tokens/defg
  193. {
  194. "uses_allowed": 5,
  195. "expiry_time": 4781243146000
  196. }
  197. 200 OK
  198. {
  199. "token": "defg",
  200. "uses_allowed": 5,
  201. "pending": 0,
  202. "completed": 0,
  203. "expiry_time": 4781243146000
  204. }
  205. to delete a token:
  206. DELETE /_synapse/admin/v1/registration_tokens/wxyz
  207. 200 OK
  208. {}
  209. """
  210. PATTERNS = admin_patterns("/registration_tokens/(?P<token>[^/]*)$")
  211. def __init__(self, hs: "HomeServer"):
  212. self.clock = hs.get_clock()
  213. self.auth = hs.get_auth()
  214. self.store = hs.get_datastores().main
  215. async def on_GET(self, request: SynapseRequest, token: str) -> Tuple[int, JsonDict]:
  216. """Retrieve a registration token."""
  217. await assert_requester_is_admin(self.auth, request)
  218. token_info = await self.store.get_one_registration_token(token)
  219. # If no result return a 404
  220. if token_info is None:
  221. raise NotFoundError(f"No such registration token: {token}")
  222. return HTTPStatus.OK, token_info
  223. async def on_PUT(self, request: SynapseRequest, token: str) -> Tuple[int, JsonDict]:
  224. """Update a registration token."""
  225. await assert_requester_is_admin(self.auth, request)
  226. body = parse_json_object_from_request(request)
  227. new_attributes = {}
  228. # Only add uses_allowed to new_attributes if it is present and valid
  229. if "uses_allowed" in body:
  230. uses_allowed = body["uses_allowed"]
  231. if not (
  232. uses_allowed is None
  233. or (type(uses_allowed) is int and uses_allowed >= 0) # noqa: E721
  234. ):
  235. raise SynapseError(
  236. HTTPStatus.BAD_REQUEST,
  237. "uses_allowed must be a non-negative integer or null",
  238. Codes.INVALID_PARAM,
  239. )
  240. new_attributes["uses_allowed"] = uses_allowed
  241. if "expiry_time" in body:
  242. expiry_time = body["expiry_time"]
  243. if expiry_time is not None and type(expiry_time) is not int: # noqa: E721
  244. raise SynapseError(
  245. HTTPStatus.BAD_REQUEST,
  246. "expiry_time must be an integer or null",
  247. Codes.INVALID_PARAM,
  248. )
  249. if (
  250. type(expiry_time) is int # noqa: E721
  251. and expiry_time < self.clock.time_msec()
  252. ):
  253. raise SynapseError(
  254. HTTPStatus.BAD_REQUEST,
  255. "expiry_time must not be in the past",
  256. Codes.INVALID_PARAM,
  257. )
  258. new_attributes["expiry_time"] = expiry_time
  259. if len(new_attributes) == 0:
  260. # Nothing to update, get token info to return
  261. token_info = await self.store.get_one_registration_token(token)
  262. else:
  263. token_info = await self.store.update_registration_token(
  264. token, new_attributes
  265. )
  266. # If no result return a 404
  267. if token_info is None:
  268. raise NotFoundError(f"No such registration token: {token}")
  269. return HTTPStatus.OK, token_info
  270. async def on_DELETE(
  271. self, request: SynapseRequest, token: str
  272. ) -> Tuple[int, JsonDict]:
  273. """Delete a registration token."""
  274. await assert_requester_is_admin(self.auth, request)
  275. if await self.store.delete_registration_token(token):
  276. return HTTPStatus.OK, {}
  277. raise NotFoundError(f"No such registration token: {token}")