registration_tokens.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335
  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 not isinstance(length, int):
  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 (isinstance(uses_allowed, int) and uses_allowed >= 0)
  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 not isinstance(expiry_time, (int, type(None))):
  147. raise SynapseError(
  148. HTTPStatus.BAD_REQUEST,
  149. "expiry_time must be an integer or null",
  150. Codes.INVALID_PARAM,
  151. )
  152. if isinstance(expiry_time, int) and expiry_time < self.clock.time_msec():
  153. raise SynapseError(
  154. HTTPStatus.BAD_REQUEST,
  155. "expiry_time must not be in the past",
  156. Codes.INVALID_PARAM,
  157. )
  158. created = await self.store.create_registration_token(
  159. token, uses_allowed, expiry_time
  160. )
  161. if not created:
  162. raise SynapseError(
  163. HTTPStatus.BAD_REQUEST,
  164. f"Token already exists: {token}",
  165. Codes.INVALID_PARAM,
  166. )
  167. resp = {
  168. "token": token,
  169. "uses_allowed": uses_allowed,
  170. "pending": 0,
  171. "completed": 0,
  172. "expiry_time": expiry_time,
  173. }
  174. return HTTPStatus.OK, resp
  175. class RegistrationTokenRestServlet(RestServlet):
  176. """Retrieve, update, or delete the given token.
  177. For example,
  178. to retrieve a token:
  179. GET /_synapse/admin/v1/registration_tokens/abcd
  180. 200 OK
  181. {
  182. "token": "abcd",
  183. "uses_allowed": 3,
  184. "pending": 0,
  185. "completed": 1,
  186. "expiry_time": null
  187. }
  188. to update a token:
  189. PUT /_synapse/admin/v1/registration_tokens/defg
  190. {
  191. "uses_allowed": 5,
  192. "expiry_time": 4781243146000
  193. }
  194. 200 OK
  195. {
  196. "token": "defg",
  197. "uses_allowed": 5,
  198. "pending": 0,
  199. "completed": 0,
  200. "expiry_time": 4781243146000
  201. }
  202. to delete a token:
  203. DELETE /_synapse/admin/v1/registration_tokens/wxyz
  204. 200 OK
  205. {}
  206. """
  207. PATTERNS = admin_patterns("/registration_tokens/(?P<token>[^/]*)$")
  208. def __init__(self, hs: "HomeServer"):
  209. self.clock = hs.get_clock()
  210. self.auth = hs.get_auth()
  211. self.store = hs.get_datastores().main
  212. async def on_GET(self, request: SynapseRequest, token: str) -> Tuple[int, JsonDict]:
  213. """Retrieve a registration token."""
  214. await assert_requester_is_admin(self.auth, request)
  215. token_info = await self.store.get_one_registration_token(token)
  216. # If no result return a 404
  217. if token_info is None:
  218. raise NotFoundError(f"No such registration token: {token}")
  219. return HTTPStatus.OK, token_info
  220. async def on_PUT(self, request: SynapseRequest, token: str) -> Tuple[int, JsonDict]:
  221. """Update a registration token."""
  222. await assert_requester_is_admin(self.auth, request)
  223. body = parse_json_object_from_request(request)
  224. new_attributes = {}
  225. # Only add uses_allowed to new_attributes if it is present and valid
  226. if "uses_allowed" in body:
  227. uses_allowed = body["uses_allowed"]
  228. if not (
  229. uses_allowed is None
  230. or (isinstance(uses_allowed, int) and uses_allowed >= 0)
  231. ):
  232. raise SynapseError(
  233. HTTPStatus.BAD_REQUEST,
  234. "uses_allowed must be a non-negative integer or null",
  235. Codes.INVALID_PARAM,
  236. )
  237. new_attributes["uses_allowed"] = uses_allowed
  238. if "expiry_time" in body:
  239. expiry_time = body["expiry_time"]
  240. if not isinstance(expiry_time, (int, type(None))):
  241. raise SynapseError(
  242. HTTPStatus.BAD_REQUEST,
  243. "expiry_time must be an integer or null",
  244. Codes.INVALID_PARAM,
  245. )
  246. if isinstance(expiry_time, int) and expiry_time < self.clock.time_msec():
  247. raise SynapseError(
  248. HTTPStatus.BAD_REQUEST,
  249. "expiry_time must not be in the past",
  250. Codes.INVALID_PARAM,
  251. )
  252. new_attributes["expiry_time"] = expiry_time
  253. if len(new_attributes) == 0:
  254. # Nothing to update, get token info to return
  255. token_info = await self.store.get_one_registration_token(token)
  256. else:
  257. token_info = await self.store.update_registration_token(
  258. token, new_attributes
  259. )
  260. # If no result return a 404
  261. if token_info is None:
  262. raise NotFoundError(f"No such registration token: {token}")
  263. return HTTPStatus.OK, token_info
  264. async def on_DELETE(
  265. self, request: SynapseRequest, token: str
  266. ) -> Tuple[int, JsonDict]:
  267. """Delete a registration token."""
  268. await assert_requester_is_admin(self.auth, request)
  269. if await self.store.delete_registration_token(token):
  270. return HTTPStatus.OK, {}
  271. raise NotFoundError(f"No such registration token: {token}")