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.
 
 
 
 
 
 

921 lines
26 KiB

  1. # Copyright 2014-2016 OpenMarket Ltd
  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. """ This module contains base REST classes for constructing REST servlets. """
  15. import enum
  16. import logging
  17. from http import HTTPStatus
  18. from typing import (
  19. TYPE_CHECKING,
  20. List,
  21. Mapping,
  22. Optional,
  23. Sequence,
  24. Tuple,
  25. Type,
  26. TypeVar,
  27. overload,
  28. )
  29. from synapse._pydantic_compat import HAS_PYDANTIC_V2
  30. if TYPE_CHECKING or HAS_PYDANTIC_V2:
  31. from pydantic.v1 import BaseModel, MissingError, PydanticValueError, ValidationError
  32. from pydantic.v1.error_wrappers import ErrorWrapper
  33. else:
  34. from pydantic import BaseModel, MissingError, PydanticValueError, ValidationError
  35. from pydantic.error_wrappers import ErrorWrapper
  36. from typing_extensions import Literal
  37. from twisted.web.server import Request
  38. from synapse.api.errors import Codes, SynapseError
  39. from synapse.http import redact_uri
  40. from synapse.http.server import HttpServer
  41. from synapse.types import JsonDict, RoomAlias, RoomID, StrCollection
  42. from synapse.util import json_decoder
  43. if TYPE_CHECKING:
  44. from synapse.server import HomeServer
  45. logger = logging.getLogger(__name__)
  46. @overload
  47. def parse_integer(request: Request, name: str, default: int) -> int:
  48. ...
  49. @overload
  50. def parse_integer(request: Request, name: str, *, required: Literal[True]) -> int:
  51. ...
  52. @overload
  53. def parse_integer(
  54. request: Request, name: str, default: Optional[int] = None, required: bool = False
  55. ) -> Optional[int]:
  56. ...
  57. def parse_integer(
  58. request: Request, name: str, default: Optional[int] = None, required: bool = False
  59. ) -> Optional[int]:
  60. """Parse an integer parameter from the request string
  61. Args:
  62. request: the twisted HTTP request.
  63. name: the name of the query parameter.
  64. default: value to use if the parameter is absent, defaults to None.
  65. required: whether to raise a 400 SynapseError if the parameter is absent,
  66. defaults to False.
  67. Returns:
  68. An int value or the default.
  69. Raises:
  70. SynapseError: if the parameter is absent and required, or if the
  71. parameter is present and not an integer.
  72. """
  73. args: Mapping[bytes, Sequence[bytes]] = request.args # type: ignore
  74. return parse_integer_from_args(args, name, default, required)
  75. @overload
  76. def parse_integer_from_args(
  77. args: Mapping[bytes, Sequence[bytes]],
  78. name: str,
  79. default: Optional[int] = None,
  80. ) -> Optional[int]:
  81. ...
  82. @overload
  83. def parse_integer_from_args(
  84. args: Mapping[bytes, Sequence[bytes]],
  85. name: str,
  86. *,
  87. required: Literal[True],
  88. ) -> int:
  89. ...
  90. @overload
  91. def parse_integer_from_args(
  92. args: Mapping[bytes, Sequence[bytes]],
  93. name: str,
  94. default: Optional[int] = None,
  95. required: bool = False,
  96. ) -> Optional[int]:
  97. ...
  98. def parse_integer_from_args(
  99. args: Mapping[bytes, Sequence[bytes]],
  100. name: str,
  101. default: Optional[int] = None,
  102. required: bool = False,
  103. ) -> Optional[int]:
  104. """Parse an integer parameter from the request string
  105. Args:
  106. args: A mapping of request args as bytes to a list of bytes (e.g. request.args).
  107. name: the name of the query parameter.
  108. default: value to use if the parameter is absent, defaults to None.
  109. required: whether to raise a 400 SynapseError if the parameter is absent,
  110. defaults to False.
  111. Returns:
  112. An int value or the default.
  113. Raises:
  114. SynapseError: if the parameter is absent and required, or if the
  115. parameter is present and not an integer.
  116. """
  117. name_bytes = name.encode("ascii")
  118. if name_bytes in args:
  119. try:
  120. return int(args[name_bytes][0])
  121. except Exception:
  122. message = "Query parameter %r must be an integer" % (name,)
  123. raise SynapseError(
  124. HTTPStatus.BAD_REQUEST, message, errcode=Codes.INVALID_PARAM
  125. )
  126. else:
  127. if required:
  128. message = "Missing integer query parameter %r" % (name,)
  129. raise SynapseError(
  130. HTTPStatus.BAD_REQUEST, message, errcode=Codes.MISSING_PARAM
  131. )
  132. else:
  133. return default
  134. @overload
  135. def parse_boolean(request: Request, name: str, default: bool) -> bool:
  136. ...
  137. @overload
  138. def parse_boolean(request: Request, name: str, *, required: Literal[True]) -> bool:
  139. ...
  140. @overload
  141. def parse_boolean(
  142. request: Request, name: str, default: Optional[bool] = None, required: bool = False
  143. ) -> Optional[bool]:
  144. ...
  145. def parse_boolean(
  146. request: Request, name: str, default: Optional[bool] = None, required: bool = False
  147. ) -> Optional[bool]:
  148. """Parse a boolean parameter from the request query string
  149. Args:
  150. request: the twisted HTTP request.
  151. name: the name of the query parameter.
  152. default: value to use if the parameter is absent, defaults to None.
  153. required: whether to raise a 400 SynapseError if the parameter is absent,
  154. defaults to False.
  155. Returns:
  156. A bool value or the default.
  157. Raises:
  158. SynapseError: if the parameter is absent and required, or if the
  159. parameter is present and not one of "true" or "false".
  160. """
  161. args: Mapping[bytes, Sequence[bytes]] = request.args # type: ignore
  162. return parse_boolean_from_args(args, name, default, required)
  163. @overload
  164. def parse_boolean_from_args(
  165. args: Mapping[bytes, Sequence[bytes]],
  166. name: str,
  167. default: bool,
  168. ) -> bool:
  169. ...
  170. @overload
  171. def parse_boolean_from_args(
  172. args: Mapping[bytes, Sequence[bytes]],
  173. name: str,
  174. *,
  175. required: Literal[True],
  176. ) -> bool:
  177. ...
  178. @overload
  179. def parse_boolean_from_args(
  180. args: Mapping[bytes, Sequence[bytes]],
  181. name: str,
  182. default: Optional[bool] = None,
  183. required: bool = False,
  184. ) -> Optional[bool]:
  185. ...
  186. def parse_boolean_from_args(
  187. args: Mapping[bytes, Sequence[bytes]],
  188. name: str,
  189. default: Optional[bool] = None,
  190. required: bool = False,
  191. ) -> Optional[bool]:
  192. """Parse a boolean parameter from the request query string
  193. Args:
  194. args: A mapping of request args as bytes to a list of bytes (e.g. request.args).
  195. name: the name of the query parameter.
  196. default: value to use if the parameter is absent, defaults to None.
  197. required: whether to raise a 400 SynapseError if the parameter is absent,
  198. defaults to False.
  199. Returns:
  200. A bool value or the default.
  201. Raises:
  202. SynapseError: if the parameter is absent and required, or if the
  203. parameter is present and not one of "true" or "false".
  204. """
  205. name_bytes = name.encode("ascii")
  206. if name_bytes in args:
  207. try:
  208. return {b"true": True, b"false": False}[args[name_bytes][0]]
  209. except Exception:
  210. message = (
  211. "Boolean query parameter %r must be one of ['true', 'false']"
  212. ) % (name,)
  213. raise SynapseError(
  214. HTTPStatus.BAD_REQUEST, message, errcode=Codes.INVALID_PARAM
  215. )
  216. else:
  217. if required:
  218. message = "Missing boolean query parameter %r" % (name,)
  219. raise SynapseError(
  220. HTTPStatus.BAD_REQUEST, message, errcode=Codes.MISSING_PARAM
  221. )
  222. else:
  223. return default
  224. @overload
  225. def parse_bytes_from_args(
  226. args: Mapping[bytes, Sequence[bytes]],
  227. name: str,
  228. default: Optional[bytes] = None,
  229. ) -> Optional[bytes]:
  230. ...
  231. @overload
  232. def parse_bytes_from_args(
  233. args: Mapping[bytes, Sequence[bytes]],
  234. name: str,
  235. default: Literal[None] = None,
  236. *,
  237. required: Literal[True],
  238. ) -> bytes:
  239. ...
  240. @overload
  241. def parse_bytes_from_args(
  242. args: Mapping[bytes, Sequence[bytes]],
  243. name: str,
  244. default: Optional[bytes] = None,
  245. required: bool = False,
  246. ) -> Optional[bytes]:
  247. ...
  248. def parse_bytes_from_args(
  249. args: Mapping[bytes, Sequence[bytes]],
  250. name: str,
  251. default: Optional[bytes] = None,
  252. required: bool = False,
  253. ) -> Optional[bytes]:
  254. """
  255. Parse a string parameter as bytes from the request query string.
  256. Args:
  257. args: A mapping of request args as bytes to a list of bytes (e.g. request.args).
  258. name: the name of the query parameter.
  259. default: value to use if the parameter is absent,
  260. defaults to None. Must be bytes if encoding is None.
  261. required: whether to raise a 400 SynapseError if the
  262. parameter is absent, defaults to False.
  263. Returns:
  264. Bytes or the default value.
  265. Raises:
  266. SynapseError if the parameter is absent and required.
  267. """
  268. name_bytes = name.encode("ascii")
  269. if name_bytes in args:
  270. return args[name_bytes][0]
  271. elif required:
  272. message = "Missing string query parameter %s" % (name,)
  273. raise SynapseError(HTTPStatus.BAD_REQUEST, message, errcode=Codes.MISSING_PARAM)
  274. return default
  275. @overload
  276. def parse_string(
  277. request: Request,
  278. name: str,
  279. default: str,
  280. *,
  281. allowed_values: Optional[StrCollection] = None,
  282. encoding: str = "ascii",
  283. ) -> str:
  284. ...
  285. @overload
  286. def parse_string(
  287. request: Request,
  288. name: str,
  289. *,
  290. required: Literal[True],
  291. allowed_values: Optional[StrCollection] = None,
  292. encoding: str = "ascii",
  293. ) -> str:
  294. ...
  295. @overload
  296. def parse_string(
  297. request: Request,
  298. name: str,
  299. *,
  300. default: Optional[str] = None,
  301. required: bool = False,
  302. allowed_values: Optional[StrCollection] = None,
  303. encoding: str = "ascii",
  304. ) -> Optional[str]:
  305. ...
  306. def parse_string(
  307. request: Request,
  308. name: str,
  309. default: Optional[str] = None,
  310. required: bool = False,
  311. allowed_values: Optional[StrCollection] = None,
  312. encoding: str = "ascii",
  313. ) -> Optional[str]:
  314. """
  315. Parse a string parameter from the request query string.
  316. If encoding is not None, the content of the query param will be
  317. decoded to Unicode using the encoding, otherwise it will be encoded
  318. Args:
  319. request: the twisted HTTP request.
  320. name: the name of the query parameter.
  321. default: value to use if the parameter is absent, defaults to None.
  322. required: whether to raise a 400 SynapseError if the
  323. parameter is absent, defaults to False.
  324. allowed_values: List of allowed values for the
  325. string, or None if any value is allowed, defaults to None. Must be
  326. the same type as name, if given.
  327. encoding: The encoding to decode the string content with.
  328. Returns:
  329. A string value or the default.
  330. Raises:
  331. SynapseError if the parameter is absent and required, or if the
  332. parameter is present, must be one of a list of allowed values and
  333. is not one of those allowed values.
  334. """
  335. args: Mapping[bytes, Sequence[bytes]] = request.args # type: ignore
  336. return parse_string_from_args(
  337. args,
  338. name,
  339. default,
  340. required=required,
  341. allowed_values=allowed_values,
  342. encoding=encoding,
  343. )
  344. EnumT = TypeVar("EnumT", bound=enum.Enum)
  345. @overload
  346. def parse_enum(
  347. request: Request,
  348. name: str,
  349. E: Type[EnumT],
  350. default: EnumT,
  351. ) -> EnumT:
  352. ...
  353. @overload
  354. def parse_enum(
  355. request: Request,
  356. name: str,
  357. E: Type[EnumT],
  358. *,
  359. required: Literal[True],
  360. ) -> EnumT:
  361. ...
  362. def parse_enum(
  363. request: Request,
  364. name: str,
  365. E: Type[EnumT],
  366. default: Optional[EnumT] = None,
  367. required: bool = False,
  368. ) -> Optional[EnumT]:
  369. """
  370. Parse an enum parameter from the request query string.
  371. Note that the enum *must only have string values*.
  372. Args:
  373. request: the twisted HTTP request.
  374. name: the name of the query parameter.
  375. E: the enum which represents valid values
  376. default: enum value to use if the parameter is absent, defaults to None.
  377. required: whether to raise a 400 SynapseError if the
  378. parameter is absent, defaults to False.
  379. Returns:
  380. An enum value.
  381. Raises:
  382. SynapseError if the parameter is absent and required, or if the
  383. parameter is present, must be one of a list of allowed values and
  384. is not one of those allowed values.
  385. """
  386. # Assert the enum values are strings.
  387. assert all(
  388. isinstance(e.value, str) for e in E
  389. ), "parse_enum only works with string values"
  390. str_value = parse_string(
  391. request,
  392. name,
  393. default=default.value if default is not None else None,
  394. required=required,
  395. allowed_values=[e.value for e in E],
  396. )
  397. if str_value is None:
  398. return None
  399. return E(str_value)
  400. def _parse_string_value(
  401. value: bytes,
  402. allowed_values: Optional[StrCollection],
  403. name: str,
  404. encoding: str,
  405. ) -> str:
  406. try:
  407. value_str = value.decode(encoding)
  408. except ValueError:
  409. raise SynapseError(
  410. HTTPStatus.BAD_REQUEST, "Query parameter %r must be %s" % (name, encoding)
  411. )
  412. if allowed_values is not None and value_str not in allowed_values:
  413. message = "Query parameter %r must be one of [%s]" % (
  414. name,
  415. ", ".join(repr(v) for v in allowed_values),
  416. )
  417. raise SynapseError(HTTPStatus.BAD_REQUEST, message, errcode=Codes.INVALID_PARAM)
  418. else:
  419. return value_str
  420. @overload
  421. def parse_strings_from_args(
  422. args: Mapping[bytes, Sequence[bytes]],
  423. name: str,
  424. *,
  425. allowed_values: Optional[StrCollection] = None,
  426. encoding: str = "ascii",
  427. ) -> Optional[List[str]]:
  428. ...
  429. @overload
  430. def parse_strings_from_args(
  431. args: Mapping[bytes, Sequence[bytes]],
  432. name: str,
  433. default: List[str],
  434. *,
  435. allowed_values: Optional[StrCollection] = None,
  436. encoding: str = "ascii",
  437. ) -> List[str]:
  438. ...
  439. @overload
  440. def parse_strings_from_args(
  441. args: Mapping[bytes, Sequence[bytes]],
  442. name: str,
  443. *,
  444. required: Literal[True],
  445. allowed_values: Optional[StrCollection] = None,
  446. encoding: str = "ascii",
  447. ) -> List[str]:
  448. ...
  449. @overload
  450. def parse_strings_from_args(
  451. args: Mapping[bytes, Sequence[bytes]],
  452. name: str,
  453. default: Optional[List[str]] = None,
  454. *,
  455. required: bool = False,
  456. allowed_values: Optional[StrCollection] = None,
  457. encoding: str = "ascii",
  458. ) -> Optional[List[str]]:
  459. ...
  460. def parse_strings_from_args(
  461. args: Mapping[bytes, Sequence[bytes]],
  462. name: str,
  463. default: Optional[List[str]] = None,
  464. required: bool = False,
  465. allowed_values: Optional[StrCollection] = None,
  466. encoding: str = "ascii",
  467. ) -> Optional[List[str]]:
  468. """
  469. Parse a string parameter from the request query string list.
  470. The content of the query param will be decoded to Unicode using the encoding.
  471. Args:
  472. args: A mapping of request args as bytes to a list of bytes (e.g. request.args).
  473. name: the name of the query parameter.
  474. default: value to use if the parameter is absent, defaults to None.
  475. required: whether to raise a 400 SynapseError if the
  476. parameter is absent, defaults to False.
  477. allowed_values: List of allowed values for the
  478. string, or None if any value is allowed, defaults to None.
  479. encoding: The encoding to decode the string content with.
  480. Returns:
  481. A string value or the default.
  482. Raises:
  483. SynapseError if the parameter is absent and required, or if the
  484. parameter is present, must be one of a list of allowed values and
  485. is not one of those allowed values.
  486. """
  487. name_bytes = name.encode("ascii")
  488. if name_bytes in args:
  489. values = args[name_bytes]
  490. return [
  491. _parse_string_value(value, allowed_values, name=name, encoding=encoding)
  492. for value in values
  493. ]
  494. else:
  495. if required:
  496. message = "Missing string query parameter %r" % (name,)
  497. raise SynapseError(
  498. HTTPStatus.BAD_REQUEST, message, errcode=Codes.MISSING_PARAM
  499. )
  500. return default
  501. @overload
  502. def parse_string_from_args(
  503. args: Mapping[bytes, Sequence[bytes]],
  504. name: str,
  505. default: Optional[str] = None,
  506. *,
  507. allowed_values: Optional[StrCollection] = None,
  508. encoding: str = "ascii",
  509. ) -> Optional[str]:
  510. ...
  511. @overload
  512. def parse_string_from_args(
  513. args: Mapping[bytes, Sequence[bytes]],
  514. name: str,
  515. default: Optional[str] = None,
  516. *,
  517. required: Literal[True],
  518. allowed_values: Optional[StrCollection] = None,
  519. encoding: str = "ascii",
  520. ) -> str:
  521. ...
  522. @overload
  523. def parse_string_from_args(
  524. args: Mapping[bytes, Sequence[bytes]],
  525. name: str,
  526. default: Optional[str] = None,
  527. required: bool = False,
  528. allowed_values: Optional[StrCollection] = None,
  529. encoding: str = "ascii",
  530. ) -> Optional[str]:
  531. ...
  532. def parse_string_from_args(
  533. args: Mapping[bytes, Sequence[bytes]],
  534. name: str,
  535. default: Optional[str] = None,
  536. required: bool = False,
  537. allowed_values: Optional[StrCollection] = None,
  538. encoding: str = "ascii",
  539. ) -> Optional[str]:
  540. """
  541. Parse the string parameter from the request query string list
  542. and return the first result.
  543. The content of the query param will be decoded to Unicode using the encoding.
  544. Args:
  545. args: A mapping of request args as bytes to a list of bytes (e.g. request.args).
  546. name: the name of the query parameter.
  547. default: value to use if the parameter is absent, defaults to None.
  548. required: whether to raise a 400 SynapseError if the
  549. parameter is absent, defaults to False.
  550. allowed_values: List of allowed values for the
  551. string, or None if any value is allowed, defaults to None. Must be
  552. the same type as name, if given.
  553. encoding: The encoding to decode the string content with.
  554. Returns:
  555. A string value or the default.
  556. Raises:
  557. SynapseError if the parameter is absent and required, or if the
  558. parameter is present, must be one of a list of allowed values and
  559. is not one of those allowed values.
  560. """
  561. strings = parse_strings_from_args(
  562. args,
  563. name,
  564. default=[default] if default is not None else None,
  565. required=required,
  566. allowed_values=allowed_values,
  567. encoding=encoding,
  568. )
  569. if strings is None:
  570. return None
  571. return strings[0]
  572. @overload
  573. def parse_json_value_from_request(request: Request) -> JsonDict:
  574. ...
  575. @overload
  576. def parse_json_value_from_request(
  577. request: Request, allow_empty_body: Literal[False]
  578. ) -> JsonDict:
  579. ...
  580. @overload
  581. def parse_json_value_from_request(
  582. request: Request, allow_empty_body: bool = False
  583. ) -> Optional[JsonDict]:
  584. ...
  585. def parse_json_value_from_request(
  586. request: Request, allow_empty_body: bool = False
  587. ) -> Optional[JsonDict]:
  588. """Parse a JSON value from the body of a twisted HTTP request.
  589. Args:
  590. request: the twisted HTTP request.
  591. allow_empty_body: if True, an empty body will be accepted and turned into None
  592. Returns:
  593. The JSON value.
  594. Raises:
  595. SynapseError if the request body couldn't be decoded as JSON.
  596. """
  597. try:
  598. content_bytes = request.content.read() # type: ignore
  599. except Exception:
  600. raise SynapseError(HTTPStatus.BAD_REQUEST, "Error reading JSON content.")
  601. if not content_bytes and allow_empty_body:
  602. return None
  603. try:
  604. content = json_decoder.decode(content_bytes.decode("utf-8"))
  605. except Exception as e:
  606. logger.warning(
  607. "Unable to parse JSON from %s %s response: %s (%s)",
  608. request.method.decode("ascii", errors="replace"),
  609. redact_uri(request.uri.decode("ascii", errors="replace")),
  610. e,
  611. content_bytes,
  612. )
  613. raise SynapseError(
  614. HTTPStatus.BAD_REQUEST, "Content not JSON.", errcode=Codes.NOT_JSON
  615. )
  616. return content
  617. def parse_json_object_from_request(
  618. request: Request, allow_empty_body: bool = False
  619. ) -> JsonDict:
  620. """Parse a JSON object from the body of a twisted HTTP request.
  621. Args:
  622. request: the twisted HTTP request.
  623. allow_empty_body: if True, an empty body will be accepted and turned into
  624. an empty dict.
  625. Raises:
  626. SynapseError if the request body couldn't be decoded as JSON or
  627. if it wasn't a JSON object.
  628. """
  629. content = parse_json_value_from_request(request, allow_empty_body=allow_empty_body)
  630. if allow_empty_body and content is None:
  631. return {}
  632. if not isinstance(content, dict):
  633. message = "Content must be a JSON object."
  634. raise SynapseError(HTTPStatus.BAD_REQUEST, message, errcode=Codes.BAD_JSON)
  635. return content
  636. Model = TypeVar("Model", bound=BaseModel)
  637. def validate_json_object(content: JsonDict, model_type: Type[Model]) -> Model:
  638. """Validate a deserialized JSON object using the given pydantic model.
  639. Raises:
  640. SynapseError if the request body couldn't be decoded as JSON or
  641. if it wasn't a JSON object.
  642. """
  643. try:
  644. instance = model_type.parse_obj(content)
  645. except ValidationError as e:
  646. # Choose a matrix error code. The catch-all is BAD_JSON, but we try to find a
  647. # more specific error if possible (which occasionally helps us to be spec-
  648. # compliant) This is a bit awkward because the spec's error codes aren't very
  649. # clear-cut: BAD_JSON arguably overlaps with MISSING_PARAM and INVALID_PARAM.
  650. errcode = Codes.BAD_JSON
  651. raw_errors = e.raw_errors
  652. if len(raw_errors) == 1 and isinstance(raw_errors[0], ErrorWrapper):
  653. raw_error = raw_errors[0].exc
  654. if isinstance(raw_error, MissingError):
  655. errcode = Codes.MISSING_PARAM
  656. elif isinstance(raw_error, PydanticValueError):
  657. errcode = Codes.INVALID_PARAM
  658. raise SynapseError(HTTPStatus.BAD_REQUEST, str(e), errcode=errcode)
  659. return instance
  660. def parse_and_validate_json_object_from_request(
  661. request: Request, model_type: Type[Model]
  662. ) -> Model:
  663. """Parse a JSON object from the body of a twisted HTTP request, then deserialise and
  664. validate using the given pydantic model.
  665. Raises:
  666. SynapseError if the request body couldn't be decoded as JSON or
  667. if it wasn't a JSON object.
  668. """
  669. content = parse_json_object_from_request(request, allow_empty_body=False)
  670. return validate_json_object(content, model_type)
  671. def assert_params_in_dict(body: JsonDict, required: StrCollection) -> None:
  672. absent = []
  673. for k in required:
  674. if k not in body:
  675. absent.append(k)
  676. if len(absent) > 0:
  677. raise SynapseError(
  678. HTTPStatus.BAD_REQUEST, "Missing params: %r" % absent, Codes.MISSING_PARAM
  679. )
  680. class RestServlet:
  681. """A Synapse REST Servlet.
  682. An implementing class can either provide its own custom 'register' method,
  683. or use the automatic pattern handling provided by the base class.
  684. To use this latter, the implementing class instead provides a `PATTERN`
  685. class attribute containing a pre-compiled regular expression. The automatic
  686. register method will then use this method to register any of the following
  687. instance methods associated with the corresponding HTTP method:
  688. on_GET
  689. on_PUT
  690. on_POST
  691. on_DELETE
  692. Automatically handles turning CodeMessageExceptions thrown by these methods
  693. into the appropriate HTTP response.
  694. """
  695. def register(self, http_server: HttpServer) -> None:
  696. """Register this servlet with the given HTTP server."""
  697. patterns = getattr(self, "PATTERNS", None)
  698. if patterns:
  699. for method in ("GET", "PUT", "POST", "DELETE"):
  700. if hasattr(self, "on_%s" % (method,)):
  701. servlet_classname = self.__class__.__name__
  702. method_handler = getattr(self, "on_%s" % (method,))
  703. http_server.register_paths(
  704. method, patterns, method_handler, servlet_classname
  705. )
  706. else:
  707. raise NotImplementedError("RestServlet must register something.")
  708. class ResolveRoomIdMixin:
  709. def __init__(self, hs: "HomeServer"):
  710. self.room_member_handler = hs.get_room_member_handler()
  711. async def resolve_room_id(
  712. self, room_identifier: str, remote_room_hosts: Optional[List[str]] = None
  713. ) -> Tuple[str, Optional[List[str]]]:
  714. """
  715. Resolve a room identifier to a room ID, if necessary.
  716. This also performanes checks to ensure the room ID is of the proper form.
  717. Args:
  718. room_identifier: The room ID or alias.
  719. remote_room_hosts: The potential remote room hosts to use.
  720. Returns:
  721. The resolved room ID.
  722. Raises:
  723. SynapseError if the room ID is of the wrong form.
  724. """
  725. if RoomID.is_valid(room_identifier):
  726. resolved_room_id = room_identifier
  727. elif RoomAlias.is_valid(room_identifier):
  728. room_alias = RoomAlias.from_string(room_identifier)
  729. (
  730. room_id,
  731. remote_room_hosts,
  732. ) = await self.room_member_handler.lookup_room_alias(room_alias)
  733. resolved_room_id = room_id.to_string()
  734. else:
  735. raise SynapseError(
  736. HTTPStatus.BAD_REQUEST,
  737. "%s was not legal room ID or room alias" % (room_identifier,),
  738. )
  739. if not resolved_room_id:
  740. raise SynapseError(
  741. HTTPStatus.BAD_REQUEST,
  742. "Unknown room ID or room alias %s" % room_identifier,
  743. )
  744. return resolved_room_id, remote_room_hosts