servlet.py 25 KB

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