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.
 
 
 
 
 
 

1031 line
35 KiB

  1. # Copyright 2014-2016 OpenMarket Ltd
  2. # Copyright 2018 New Vector Ltd
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. import abc
  16. import html
  17. import logging
  18. import types
  19. import urllib
  20. import urllib.parse
  21. from http import HTTPStatus
  22. from http.client import FOUND
  23. from inspect import isawaitable
  24. from typing import (
  25. TYPE_CHECKING,
  26. Any,
  27. Awaitable,
  28. Callable,
  29. Dict,
  30. Iterable,
  31. Iterator,
  32. List,
  33. Optional,
  34. Pattern,
  35. Tuple,
  36. Union,
  37. )
  38. import attr
  39. import jinja2
  40. from canonicaljson import encode_canonical_json
  41. from typing_extensions import Protocol
  42. from zope.interface import implementer
  43. from twisted.internet import defer, interfaces
  44. from twisted.internet.defer import CancelledError
  45. from twisted.python import failure
  46. from twisted.web import resource
  47. try:
  48. from twisted.web.pages import notFound
  49. except ImportError:
  50. from twisted.web.resource import NoResource as notFound # type: ignore[assignment]
  51. from twisted.web.resource import IResource
  52. from twisted.web.server import NOT_DONE_YET, Request
  53. from twisted.web.static import File
  54. from twisted.web.util import redirectTo
  55. from synapse.api.errors import (
  56. CodeMessageException,
  57. Codes,
  58. RedirectException,
  59. SynapseError,
  60. UnrecognizedRequestError,
  61. )
  62. from synapse.config.homeserver import HomeServerConfig
  63. from synapse.logging.context import defer_to_thread, preserve_fn, run_in_background
  64. from synapse.logging.opentracing import active_span, start_active_span, trace_servlet
  65. from synapse.util import json_encoder
  66. from synapse.util.caches import intern_dict
  67. from synapse.util.cancellation import is_function_cancellable
  68. from synapse.util.iterutils import chunk_seq
  69. if TYPE_CHECKING:
  70. import opentracing
  71. from synapse.http.site import SynapseRequest
  72. from synapse.server import HomeServer
  73. logger = logging.getLogger(__name__)
  74. HTML_ERROR_TEMPLATE = """<!DOCTYPE html>
  75. <html lang=en>
  76. <head>
  77. <meta charset="utf-8">
  78. <title>Error {code}</title>
  79. </head>
  80. <body>
  81. <p>{msg}</p>
  82. </body>
  83. </html>
  84. """
  85. # A fictional HTTP status code for requests where the client has disconnected and we
  86. # successfully cancelled the request. Used only for logging purposes. Clients will never
  87. # observe this code unless cancellations leak across requests or we raise a
  88. # `CancelledError` ourselves.
  89. # Analogous to nginx's 499 status code:
  90. # https://github.com/nginx/nginx/blob/release-1.21.6/src/http/ngx_http_request.h#L128-L134
  91. HTTP_STATUS_REQUEST_CANCELLED = 499
  92. def return_json_error(
  93. f: failure.Failure, request: "SynapseRequest", config: Optional[HomeServerConfig]
  94. ) -> None:
  95. """Sends a JSON error response to clients."""
  96. if f.check(SynapseError):
  97. # mypy doesn't understand that f.check asserts the type.
  98. exc: SynapseError = f.value
  99. error_code = exc.code
  100. error_dict = exc.error_dict(config)
  101. if exc.headers is not None:
  102. for header, value in exc.headers.items():
  103. request.setHeader(header, value)
  104. error_ctx = exc.debug_context
  105. if error_ctx:
  106. logger.info(
  107. "%s SynapseError: %s - %s (%s)", request, error_code, exc.msg, error_ctx
  108. )
  109. else:
  110. logger.info("%s SynapseError: %s - %s", request, error_code, exc.msg)
  111. elif f.check(CancelledError):
  112. error_code = HTTP_STATUS_REQUEST_CANCELLED
  113. error_dict = {"error": "Request cancelled", "errcode": Codes.UNKNOWN}
  114. if not request._disconnected:
  115. logger.error(
  116. "Got cancellation before client disconnection from %r: %r",
  117. request.request_metrics.name,
  118. request,
  119. exc_info=(f.type, f.value, f.getTracebackObject()),
  120. )
  121. else:
  122. error_code = 500
  123. error_dict = {"error": "Internal server error", "errcode": Codes.UNKNOWN}
  124. logger.error(
  125. "Failed handle request via %r: %r",
  126. request.request_metrics.name,
  127. request,
  128. exc_info=(f.type, f.value, f.getTracebackObject()),
  129. )
  130. # Only respond with an error response if we haven't already started writing,
  131. # otherwise lets just kill the connection
  132. if request.startedWriting:
  133. if request.transport:
  134. try:
  135. request.transport.abortConnection()
  136. except Exception:
  137. # abortConnection throws if the connection is already closed
  138. pass
  139. else:
  140. respond_with_json(
  141. request,
  142. error_code,
  143. error_dict,
  144. send_cors=True,
  145. )
  146. def return_html_error(
  147. f: failure.Failure,
  148. request: Request,
  149. error_template: Union[str, jinja2.Template],
  150. ) -> None:
  151. """Sends an HTML error page corresponding to the given failure.
  152. Handles RedirectException and other CodeMessageExceptions (such as SynapseError)
  153. Args:
  154. f: the error to report
  155. request: the failing request
  156. error_template: the HTML template. Can be either a string (with `{code}`,
  157. `{msg}` placeholders), or a jinja2 template
  158. """
  159. if f.check(CodeMessageException):
  160. # mypy doesn't understand that f.check asserts the type.
  161. cme: CodeMessageException = f.value
  162. code = cme.code
  163. msg = cme.msg
  164. if cme.headers is not None:
  165. for header, value in cme.headers.items():
  166. request.setHeader(header, value)
  167. if isinstance(cme, RedirectException):
  168. logger.info("%s redirect to %s", request, cme.location)
  169. request.setHeader(b"location", cme.location)
  170. request.cookies.extend(cme.cookies)
  171. elif isinstance(cme, SynapseError):
  172. logger.info("%s SynapseError: %s - %s", request, code, msg)
  173. else:
  174. logger.error(
  175. "Failed handle request %r",
  176. request,
  177. exc_info=(f.type, f.value, f.getTracebackObject()),
  178. )
  179. elif f.check(CancelledError):
  180. code = HTTP_STATUS_REQUEST_CANCELLED
  181. msg = "Request cancelled"
  182. if not request._disconnected:
  183. logger.error(
  184. "Got cancellation before client disconnection when handling request %r",
  185. request,
  186. exc_info=(f.type, f.value, f.getTracebackObject()),
  187. )
  188. else:
  189. code = HTTPStatus.INTERNAL_SERVER_ERROR
  190. msg = "Internal server error"
  191. logger.error(
  192. "Failed handle request %r",
  193. request,
  194. exc_info=(f.type, f.value, f.getTracebackObject()),
  195. )
  196. if isinstance(error_template, str):
  197. body = error_template.format(code=code, msg=html.escape(msg))
  198. else:
  199. body = error_template.render(code=code, msg=msg)
  200. respond_with_html(request, code, body)
  201. def wrap_async_request_handler(
  202. h: Callable[["_AsyncResource", "SynapseRequest"], Awaitable[None]]
  203. ) -> Callable[["_AsyncResource", "SynapseRequest"], "defer.Deferred[None]"]:
  204. """Wraps an async request handler so that it calls request.processing.
  205. This helps ensure that work done by the request handler after the request is completed
  206. is correctly recorded against the request metrics/logs.
  207. The handler method must have a signature of "handle_foo(self, request)",
  208. where "request" must be a SynapseRequest.
  209. The handler may return a deferred, in which case the completion of the request isn't
  210. logged until the deferred completes.
  211. """
  212. async def wrapped_async_request_handler(
  213. self: "_AsyncResource", request: "SynapseRequest"
  214. ) -> None:
  215. with request.processing():
  216. await h(self, request)
  217. # we need to preserve_fn here, because the synchronous render method won't yield for
  218. # us (obviously)
  219. return preserve_fn(wrapped_async_request_handler)
  220. # Type of a callback method for processing requests
  221. # it is actually called with a SynapseRequest and a kwargs dict for the params,
  222. # but I can't figure out how to represent that.
  223. ServletCallback = Callable[
  224. ..., Union[None, Awaitable[None], Tuple[int, Any], Awaitable[Tuple[int, Any]]]
  225. ]
  226. class HttpServer(Protocol):
  227. """Interface for registering callbacks on a HTTP server"""
  228. def register_paths(
  229. self,
  230. method: str,
  231. path_patterns: Iterable[Pattern[str]],
  232. callback: ServletCallback,
  233. servlet_classname: str,
  234. ) -> None:
  235. """Register a callback that gets fired if we receive a http request
  236. with the given method for a path that matches the given regex.
  237. If the regex contains groups these gets passed to the callback via
  238. an unpacked tuple.
  239. The callback may be marked with the `@cancellable` decorator, which will
  240. cause request processing to be cancelled when clients disconnect early.
  241. Args:
  242. method: The HTTP method to listen to.
  243. path_patterns: The regex used to match requests.
  244. callback: The function to fire if we receive a matched
  245. request. The first argument will be the request object and
  246. subsequent arguments will be any matched groups from the regex.
  247. This should return either tuple of (code, response), or None.
  248. servlet_classname: The name of the handler to be used in prometheus
  249. and opentracing logs.
  250. """
  251. class _AsyncResource(resource.Resource, metaclass=abc.ABCMeta):
  252. """Base class for resources that have async handlers.
  253. Sub classes can either implement `_async_render_<METHOD>` to handle
  254. requests by method, or override `_async_render` to handle all requests.
  255. Args:
  256. extract_context: Whether to attempt to extract the opentracing
  257. context from the request the servlet is handling.
  258. """
  259. def __init__(self, extract_context: bool = False):
  260. super().__init__()
  261. self._extract_context = extract_context
  262. def render(self, request: "SynapseRequest") -> int:
  263. """This gets called by twisted every time someone sends us a request."""
  264. request.render_deferred = defer.ensureDeferred(
  265. self._async_render_wrapper(request)
  266. )
  267. return NOT_DONE_YET
  268. @wrap_async_request_handler
  269. async def _async_render_wrapper(self, request: "SynapseRequest") -> None:
  270. """This is a wrapper that delegates to `_async_render` and handles
  271. exceptions, return values, metrics, etc.
  272. """
  273. try:
  274. request.request_metrics.name = self.__class__.__name__
  275. with trace_servlet(request, self._extract_context):
  276. callback_return = await self._async_render(request)
  277. if callback_return is not None:
  278. code, response = callback_return
  279. self._send_response(request, code, response)
  280. except Exception:
  281. # failure.Failure() fishes the original Failure out
  282. # of our stack, and thus gives us a sensible stack
  283. # trace.
  284. f = failure.Failure()
  285. self._send_error_response(f, request)
  286. async def _async_render(
  287. self, request: "SynapseRequest"
  288. ) -> Optional[Tuple[int, Any]]:
  289. """Delegates to `_async_render_<METHOD>` methods, or returns a 400 if
  290. no appropriate method exists. Can be overridden in sub classes for
  291. different routing.
  292. """
  293. # Treat HEAD requests as GET requests.
  294. request_method = request.method.decode("ascii")
  295. if request_method == "HEAD":
  296. request_method = "GET"
  297. method_handler = getattr(self, "_async_render_%s" % (request_method,), None)
  298. if method_handler:
  299. request.is_render_cancellable = is_function_cancellable(method_handler)
  300. raw_callback_return = method_handler(request)
  301. # Is it synchronous? We'll allow this for now.
  302. if isawaitable(raw_callback_return):
  303. callback_return = await raw_callback_return
  304. else:
  305. callback_return = raw_callback_return
  306. return callback_return
  307. # A request with an unknown method (for a known endpoint) was received.
  308. raise UnrecognizedRequestError(code=405)
  309. @abc.abstractmethod
  310. def _send_response(
  311. self,
  312. request: "SynapseRequest",
  313. code: int,
  314. response_object: Any,
  315. ) -> None:
  316. raise NotImplementedError()
  317. @abc.abstractmethod
  318. def _send_error_response(
  319. self,
  320. f: failure.Failure,
  321. request: "SynapseRequest",
  322. ) -> None:
  323. raise NotImplementedError()
  324. class DirectServeJsonResource(_AsyncResource):
  325. """A resource that will call `self._async_on_<METHOD>` on new requests,
  326. formatting responses and errors as JSON.
  327. """
  328. def __init__(self, canonical_json: bool = False, extract_context: bool = False):
  329. super().__init__(extract_context)
  330. self.canonical_json = canonical_json
  331. def _send_response(
  332. self,
  333. request: "SynapseRequest",
  334. code: int,
  335. response_object: Any,
  336. ) -> None:
  337. """Implements _AsyncResource._send_response"""
  338. # TODO: Only enable CORS for the requests that need it.
  339. respond_with_json(
  340. request,
  341. code,
  342. response_object,
  343. send_cors=True,
  344. canonical_json=self.canonical_json,
  345. )
  346. def _send_error_response(
  347. self,
  348. f: failure.Failure,
  349. request: "SynapseRequest",
  350. ) -> None:
  351. """Implements _AsyncResource._send_error_response"""
  352. return_json_error(f, request, None)
  353. @attr.s(slots=True, frozen=True, auto_attribs=True)
  354. class _PathEntry:
  355. callback: ServletCallback
  356. servlet_classname: str
  357. class JsonResource(DirectServeJsonResource):
  358. """This implements the HttpServer interface and provides JSON support for
  359. Resources.
  360. Register callbacks via register_paths()
  361. Callbacks can return a tuple of status code and a dict in which case the
  362. the dict will automatically be sent to the client as a JSON object.
  363. The JsonResource is primarily intended for returning JSON, but callbacks
  364. may send something other than JSON, they may do so by using the methods
  365. on the request object and instead returning None.
  366. """
  367. isLeaf = True
  368. def __init__(
  369. self,
  370. hs: "HomeServer",
  371. canonical_json: bool = True,
  372. extract_context: bool = False,
  373. ):
  374. super().__init__(canonical_json, extract_context)
  375. self.clock = hs.get_clock()
  376. # Map of path regex -> method -> callback.
  377. self._routes: Dict[Pattern[str], Dict[bytes, _PathEntry]] = {}
  378. self.hs = hs
  379. def register_paths(
  380. self,
  381. method: str,
  382. path_patterns: Iterable[Pattern[str]],
  383. callback: ServletCallback,
  384. servlet_classname: str,
  385. ) -> None:
  386. """
  387. Registers a request handler against a regular expression. Later request URLs are
  388. checked against these regular expressions in order to identify an appropriate
  389. handler for that request.
  390. Args:
  391. method: GET, POST etc
  392. path_patterns: A list of regular expressions to which the request
  393. URLs are compared.
  394. callback: The handler for the request. Usually a Servlet
  395. servlet_classname: The name of the handler to be used in prometheus
  396. and opentracing logs.
  397. """
  398. method_bytes = method.encode("utf-8")
  399. for path_pattern in path_patterns:
  400. logger.debug("Registering for %s %s", method, path_pattern.pattern)
  401. self._routes.setdefault(path_pattern, {})[method_bytes] = _PathEntry(
  402. callback, servlet_classname
  403. )
  404. def _get_handler_for_request(
  405. self, request: "SynapseRequest"
  406. ) -> Tuple[ServletCallback, str, Dict[str, str]]:
  407. """Finds a callback method to handle the given request.
  408. Returns:
  409. A tuple of the callback to use, the name of the servlet, and the
  410. key word arguments to pass to the callback
  411. """
  412. # At this point the path must be bytes.
  413. request_path_bytes: bytes = request.path # type: ignore
  414. request_path = request_path_bytes.decode("ascii")
  415. # Treat HEAD requests as GET requests.
  416. request_method = request.method
  417. if request_method == b"HEAD":
  418. request_method = b"GET"
  419. # Loop through all the registered callbacks to check if the method
  420. # and path regex match
  421. for path_pattern, methods in self._routes.items():
  422. m = path_pattern.match(request_path)
  423. if m:
  424. # We found a matching path!
  425. path_entry = methods.get(request_method)
  426. if not path_entry:
  427. raise UnrecognizedRequestError(code=405)
  428. return path_entry.callback, path_entry.servlet_classname, m.groupdict()
  429. # Huh. No one wanted to handle that? Fiiiiiine.
  430. raise UnrecognizedRequestError(code=404)
  431. async def _async_render(self, request: "SynapseRequest") -> Tuple[int, Any]:
  432. callback, servlet_classname, group_dict = self._get_handler_for_request(request)
  433. request.is_render_cancellable = is_function_cancellable(callback)
  434. # Make sure we have an appropriate name for this handler in prometheus
  435. # (rather than the default of JsonResource).
  436. request.request_metrics.name = servlet_classname
  437. # Now trigger the callback. If it returns a response, we send it
  438. # here. If it throws an exception, that is handled by the wrapper
  439. # installed by @request_handler.
  440. kwargs = intern_dict(
  441. {
  442. name: urllib.parse.unquote(value) if value else value
  443. for name, value in group_dict.items()
  444. }
  445. )
  446. raw_callback_return = callback(request, **kwargs)
  447. # Is it synchronous? We'll allow this for now.
  448. if isinstance(raw_callback_return, (defer.Deferred, types.CoroutineType)):
  449. callback_return = await raw_callback_return
  450. else:
  451. callback_return = raw_callback_return
  452. return callback_return
  453. def _send_error_response(
  454. self,
  455. f: failure.Failure,
  456. request: "SynapseRequest",
  457. ) -> None:
  458. """Implements _AsyncResource._send_error_response"""
  459. return_json_error(f, request, self.hs.config)
  460. class DirectServeHtmlResource(_AsyncResource):
  461. """A resource that will call `self._async_on_<METHOD>` on new requests,
  462. formatting responses and errors as HTML.
  463. """
  464. # The error template to use for this resource
  465. ERROR_TEMPLATE = HTML_ERROR_TEMPLATE
  466. def _send_response(
  467. self,
  468. request: "SynapseRequest",
  469. code: int,
  470. response_object: Any,
  471. ) -> None:
  472. """Implements _AsyncResource._send_response"""
  473. # We expect to get bytes for us to write
  474. assert isinstance(response_object, bytes)
  475. html_bytes = response_object
  476. respond_with_html_bytes(request, 200, html_bytes)
  477. def _send_error_response(
  478. self,
  479. f: failure.Failure,
  480. request: "SynapseRequest",
  481. ) -> None:
  482. """Implements _AsyncResource._send_error_response"""
  483. return_html_error(f, request, self.ERROR_TEMPLATE)
  484. class StaticResource(File):
  485. """
  486. A resource that represents a plain non-interpreted file or directory.
  487. Differs from the File resource by adding clickjacking protection.
  488. """
  489. def render_GET(self, request: Request) -> bytes:
  490. set_clickjacking_protection_headers(request)
  491. return super().render_GET(request)
  492. def directoryListing(self) -> IResource:
  493. return notFound()
  494. class UnrecognizedRequestResource(resource.Resource):
  495. """
  496. Similar to twisted.web.resource.NoResource, but returns a JSON 404 with an
  497. errcode of M_UNRECOGNIZED.
  498. """
  499. def render(self, request: "SynapseRequest") -> int:
  500. f = failure.Failure(UnrecognizedRequestError(code=404))
  501. return_json_error(f, request, None)
  502. # A response has already been sent but Twisted requires either NOT_DONE_YET
  503. # or the response bytes as a return value.
  504. return NOT_DONE_YET
  505. def getChild(self, name: str, request: Request) -> resource.Resource:
  506. return self
  507. class RootRedirect(resource.Resource):
  508. """Redirects the root '/' path to another path."""
  509. def __init__(self, path: str):
  510. super().__init__()
  511. self.url = path
  512. def render_GET(self, request: Request) -> bytes:
  513. return redirectTo(self.url.encode("ascii"), request)
  514. def getChild(self, name: str, request: Request) -> resource.Resource:
  515. if len(name) == 0:
  516. return self # select ourselves as the child to render
  517. return super().getChild(name, request)
  518. class OptionsResource(resource.Resource):
  519. """Responds to OPTION requests for itself and all children."""
  520. def render_OPTIONS(self, request: "SynapseRequest") -> bytes:
  521. request.setResponseCode(204)
  522. request.setHeader(b"Content-Length", b"0")
  523. set_cors_headers(request)
  524. return b""
  525. def getChildWithDefault(self, path: str, request: Request) -> resource.Resource:
  526. if request.method == b"OPTIONS":
  527. return self # select ourselves as the child to render
  528. return super().getChildWithDefault(path, request)
  529. class RootOptionsRedirectResource(OptionsResource, RootRedirect):
  530. pass
  531. @implementer(interfaces.IPushProducer)
  532. class _ByteProducer:
  533. """
  534. Iteratively write bytes to the request.
  535. """
  536. # The minimum number of bytes for each chunk. Note that the last chunk will
  537. # usually be smaller than this.
  538. min_chunk_size = 1024
  539. def __init__(
  540. self,
  541. request: Request,
  542. iterator: Iterator[bytes],
  543. ):
  544. self._request: Optional[Request] = request
  545. self._iterator = iterator
  546. self._paused = False
  547. try:
  548. self._request.registerProducer(self, True)
  549. except AttributeError as e:
  550. # Calling self._request.registerProducer might raise an AttributeError since
  551. # the underlying Twisted code calls self._request.channel.registerProducer,
  552. # however self._request.channel will be None if the connection was lost.
  553. logger.info("Connection disconnected before response was written: %r", e)
  554. # We drop our references to data we'll not use.
  555. self._request = None
  556. self._iterator = iter(())
  557. else:
  558. # Start producing if `registerProducer` was successful
  559. self.resumeProducing()
  560. def _send_data(self, data: List[bytes]) -> None:
  561. """
  562. Send a list of bytes as a chunk of a response.
  563. """
  564. if not data or not self._request:
  565. return
  566. self._request.write(b"".join(data))
  567. def pauseProducing(self) -> None:
  568. self._paused = True
  569. def resumeProducing(self) -> None:
  570. # We've stopped producing in the meantime (note that this might be
  571. # re-entrant after calling write).
  572. if not self._request:
  573. return
  574. self._paused = False
  575. # Write until there's backpressure telling us to stop.
  576. while not self._paused:
  577. # Get the next chunk and write it to the request.
  578. #
  579. # The output of the JSON encoder is buffered and coalesced until
  580. # min_chunk_size is reached. This is because JSON encoders produce
  581. # very small output per iteration and the Request object converts
  582. # each call to write() to a separate chunk. Without this there would
  583. # be an explosion in bytes written (e.g. b"{" becoming "1\r\n{\r\n").
  584. #
  585. # Note that buffer stores a list of bytes (instead of appending to
  586. # bytes) to hopefully avoid many allocations.
  587. buffer = []
  588. buffered_bytes = 0
  589. while buffered_bytes < self.min_chunk_size:
  590. try:
  591. data = next(self._iterator)
  592. buffer.append(data)
  593. buffered_bytes += len(data)
  594. except StopIteration:
  595. # The entire JSON object has been serialized, write any
  596. # remaining data, finalize the producer and the request, and
  597. # clean-up any references.
  598. self._send_data(buffer)
  599. self._request.unregisterProducer()
  600. self._request.finish()
  601. self.stopProducing()
  602. return
  603. self._send_data(buffer)
  604. def stopProducing(self) -> None:
  605. # Clear a circular reference.
  606. self._request = None
  607. def _encode_json_bytes(json_object: object) -> bytes:
  608. """
  609. Encode an object into JSON. Returns an iterator of bytes.
  610. """
  611. return json_encoder.encode(json_object).encode("utf-8")
  612. def respond_with_json(
  613. request: "SynapseRequest",
  614. code: int,
  615. json_object: Any,
  616. send_cors: bool = False,
  617. canonical_json: bool = True,
  618. ) -> Optional[int]:
  619. """Sends encoded JSON in response to the given request.
  620. Args:
  621. request: The http request to respond to.
  622. code: The HTTP response code.
  623. json_object: The object to serialize to JSON.
  624. send_cors: Whether to send Cross-Origin Resource Sharing headers
  625. https://fetch.spec.whatwg.org/#http-cors-protocol
  626. canonical_json: Whether to use the canonicaljson algorithm when encoding
  627. the JSON bytes.
  628. Returns:
  629. twisted.web.server.NOT_DONE_YET if the request is still active.
  630. """
  631. # The response code must always be set, for logging purposes.
  632. request.setResponseCode(code)
  633. # could alternatively use request.notifyFinish() and flip a flag when
  634. # the Deferred fires, but since the flag is RIGHT THERE it seems like
  635. # a waste.
  636. if request._disconnected:
  637. logger.warning(
  638. "Not sending response to request %s, already disconnected.", request
  639. )
  640. return None
  641. if canonical_json:
  642. encoder: Callable[[object], bytes] = encode_canonical_json
  643. else:
  644. encoder = _encode_json_bytes
  645. request.setHeader(b"Content-Type", b"application/json")
  646. request.setHeader(b"Cache-Control", b"no-cache, no-store, must-revalidate")
  647. if send_cors:
  648. set_cors_headers(request)
  649. run_in_background(
  650. _async_write_json_to_request_in_thread, request, encoder, json_object
  651. )
  652. return NOT_DONE_YET
  653. def respond_with_json_bytes(
  654. request: "SynapseRequest",
  655. code: int,
  656. json_bytes: bytes,
  657. send_cors: bool = False,
  658. ) -> Optional[int]:
  659. """Sends encoded JSON in response to the given request.
  660. Args:
  661. request: The http request to respond to.
  662. code: The HTTP response code.
  663. json_bytes: The json bytes to use as the response body.
  664. send_cors: Whether to send Cross-Origin Resource Sharing headers
  665. https://fetch.spec.whatwg.org/#http-cors-protocol
  666. Returns:
  667. twisted.web.server.NOT_DONE_YET if the request is still active.
  668. """
  669. # The response code must always be set, for logging purposes.
  670. request.setResponseCode(code)
  671. if request._disconnected:
  672. logger.warning(
  673. "Not sending response to request %s, already disconnected.", request
  674. )
  675. return None
  676. request.setHeader(b"Content-Type", b"application/json")
  677. request.setHeader(b"Content-Length", b"%d" % (len(json_bytes),))
  678. request.setHeader(b"Cache-Control", b"no-cache, no-store, must-revalidate")
  679. if send_cors:
  680. set_cors_headers(request)
  681. _write_bytes_to_request(request, json_bytes)
  682. return NOT_DONE_YET
  683. async def _async_write_json_to_request_in_thread(
  684. request: "SynapseRequest",
  685. json_encoder: Callable[[Any], bytes],
  686. json_object: Any,
  687. ) -> None:
  688. """Encodes the given JSON object on a thread and then writes it to the
  689. request.
  690. This is done so that encoding large JSON objects doesn't block the reactor
  691. thread.
  692. Note: We don't use JsonEncoder.iterencode here as that falls back to the
  693. Python implementation (rather than the C backend), which is *much* more
  694. expensive.
  695. """
  696. def encode(opentracing_span: "Optional[opentracing.Span]") -> bytes:
  697. # it might take a while for the threadpool to schedule us, so we write
  698. # opentracing logs once we actually get scheduled, so that we can see how
  699. # much that contributed.
  700. if opentracing_span:
  701. opentracing_span.log_kv({"event": "scheduled"})
  702. res = json_encoder(json_object)
  703. if opentracing_span:
  704. opentracing_span.log_kv({"event": "encoded"})
  705. return res
  706. with start_active_span("encode_json_response"):
  707. span = active_span()
  708. json_str = await defer_to_thread(request.reactor, encode, span)
  709. _write_bytes_to_request(request, json_str)
  710. def _write_bytes_to_request(request: Request, bytes_to_write: bytes) -> None:
  711. """Writes the bytes to the request using an appropriate producer.
  712. Note: This should be used instead of `Request.write` to correctly handle
  713. large response bodies.
  714. """
  715. # The problem with dumping all of the response into the `Request` object at
  716. # once (via `Request.write`) is that doing so starts the timeout for the
  717. # next request to be received: so if it takes longer than 60s to stream back
  718. # the response to the client, the client never gets it.
  719. #
  720. # The correct solution is to use a Producer; then the timeout is only
  721. # started once all of the content is sent over the TCP connection.
  722. # To make sure we don't write all of the bytes at once we split it up into
  723. # chunks.
  724. chunk_size = 4096
  725. bytes_generator = chunk_seq(bytes_to_write, chunk_size)
  726. # We use a `_ByteProducer` here rather than `NoRangeStaticProducer` as the
  727. # unit tests can't cope with being given a pull producer.
  728. _ByteProducer(request, bytes_generator)
  729. def set_cors_headers(request: "SynapseRequest") -> None:
  730. """Set the CORS headers so that javascript running in a web browsers can
  731. use this API
  732. Args:
  733. request: The http request to add CORS to.
  734. """
  735. request.setHeader(b"Access-Control-Allow-Origin", b"*")
  736. request.setHeader(
  737. b"Access-Control-Allow-Methods", b"GET, HEAD, POST, PUT, DELETE, OPTIONS"
  738. )
  739. if request.experimental_cors_msc3886:
  740. request.setHeader(
  741. b"Access-Control-Allow-Headers",
  742. b"X-Requested-With, Content-Type, Authorization, Date, If-Match, If-None-Match",
  743. )
  744. request.setHeader(
  745. b"Access-Control-Expose-Headers",
  746. b"ETag, Location, X-Max-Bytes",
  747. )
  748. else:
  749. request.setHeader(
  750. b"Access-Control-Allow-Headers",
  751. b"X-Requested-With, Content-Type, Authorization, Date",
  752. )
  753. request.setHeader(
  754. b"Access-Control-Expose-Headers",
  755. b"Synapse-Trace-Id, Server",
  756. )
  757. def set_corp_headers(request: Request) -> None:
  758. """Set the CORP headers so that javascript running in a web browsers can
  759. embed the resource returned from this request when their client requires
  760. the `Cross-Origin-Embedder-Policy: require-corp` header.
  761. Args:
  762. request: The http request to add the CORP header to.
  763. """
  764. request.setHeader(b"Cross-Origin-Resource-Policy", b"cross-origin")
  765. def respond_with_html(request: Request, code: int, html: str) -> None:
  766. """
  767. Wraps `respond_with_html_bytes` by first encoding HTML from a str to UTF-8 bytes.
  768. """
  769. respond_with_html_bytes(request, code, html.encode("utf-8"))
  770. def respond_with_html_bytes(request: Request, code: int, html_bytes: bytes) -> None:
  771. """
  772. Sends HTML (encoded as UTF-8 bytes) as the response to the given request.
  773. Note that this adds clickjacking protection headers and finishes the request.
  774. Args:
  775. request: The http request to respond to.
  776. code: The HTTP response code.
  777. html_bytes: The HTML bytes to use as the response body.
  778. """
  779. # The response code must always be set, for logging purposes.
  780. request.setResponseCode(code)
  781. # could alternatively use request.notifyFinish() and flip a flag when
  782. # the Deferred fires, but since the flag is RIGHT THERE it seems like
  783. # a waste.
  784. if request._disconnected:
  785. logger.warning(
  786. "Not sending response to request %s, already disconnected.", request
  787. )
  788. return None
  789. request.setHeader(b"Content-Type", b"text/html; charset=utf-8")
  790. request.setHeader(b"Content-Length", b"%d" % (len(html_bytes),))
  791. # Ensure this content cannot be embedded.
  792. set_clickjacking_protection_headers(request)
  793. request.write(html_bytes)
  794. finish_request(request)
  795. def set_clickjacking_protection_headers(request: Request) -> None:
  796. """
  797. Set headers to guard against clickjacking of embedded content.
  798. This sets the X-Frame-Options and Content-Security-Policy headers which instructs
  799. browsers to not allow the HTML of the response to be embedded onto another
  800. page.
  801. Args:
  802. request: The http request to add the headers to.
  803. """
  804. request.setHeader(b"X-Frame-Options", b"DENY")
  805. request.setHeader(b"Content-Security-Policy", b"frame-ancestors 'none';")
  806. def respond_with_redirect(
  807. request: "SynapseRequest", url: bytes, statusCode: int = FOUND, cors: bool = False
  808. ) -> None:
  809. """
  810. Write a 302 (or other specified status code) response to the request, if it is still alive.
  811. Args:
  812. request: The http request to respond to.
  813. url: The URL to redirect to.
  814. statusCode: The HTTP status code to use for the redirect (defaults to 302).
  815. cors: Whether to set CORS headers on the response.
  816. """
  817. logger.debug("Redirect to %s", url.decode("utf-8"))
  818. if cors:
  819. set_cors_headers(request)
  820. request.setResponseCode(statusCode)
  821. request.setHeader(b"location", url)
  822. finish_request(request)
  823. def finish_request(request: Request) -> None:
  824. """Finish writing the response to the request.
  825. Twisted throws a RuntimeException if the connection closed before the
  826. response was written but doesn't provide a convenient or reliable way to
  827. determine if the connection was closed. So we catch and log the RuntimeException
  828. You might think that ``request.notifyFinish`` could be used to tell if the
  829. request was finished. However the deferred it returns won't fire if the
  830. connection was already closed, meaning we'd have to have called the method
  831. right at the start of the request. By the time we want to write the response
  832. it will already be too late.
  833. """
  834. try:
  835. request.finish()
  836. except RuntimeError as e:
  837. logger.info("Connection disconnected before response was written: %r", e)