test_server.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479
  1. # Copyright 2018 New Vector 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. import re
  15. from http import HTTPStatus
  16. from typing import Awaitable, Callable, Dict, NoReturn, Optional, Tuple
  17. from twisted.internet.defer import Deferred
  18. from twisted.web.resource import Resource
  19. from synapse.api.errors import Codes, RedirectException, SynapseError
  20. from synapse.config.server import parse_listener_def
  21. from synapse.http.server import (
  22. DirectServeHtmlResource,
  23. DirectServeJsonResource,
  24. JsonResource,
  25. OptionsResource,
  26. )
  27. from synapse.http.site import SynapseRequest, SynapseSite
  28. from synapse.logging.context import make_deferred_yieldable
  29. from synapse.types import JsonDict
  30. from synapse.util import Clock
  31. from synapse.util.cancellation import cancellable
  32. from tests import unittest
  33. from tests.http.server._base import test_disconnect
  34. from tests.server import (
  35. FakeChannel,
  36. FakeSite,
  37. ThreadedMemoryReactorClock,
  38. make_request,
  39. setup_test_homeserver,
  40. )
  41. class JsonResourceTests(unittest.TestCase):
  42. def setUp(self) -> None:
  43. self.reactor = ThreadedMemoryReactorClock()
  44. self.hs_clock = Clock(self.reactor)
  45. self.homeserver = setup_test_homeserver(
  46. self.addCleanup,
  47. federation_http_client=None,
  48. clock=self.hs_clock,
  49. reactor=self.reactor,
  50. )
  51. def test_handler_for_request(self) -> None:
  52. """
  53. JsonResource.handler_for_request gives correctly decoded URL args to
  54. the callback, while Twisted will give the raw bytes of URL query
  55. arguments.
  56. """
  57. got_kwargs = {}
  58. def _callback(
  59. request: SynapseRequest, **kwargs: object
  60. ) -> Tuple[int, Dict[str, object]]:
  61. got_kwargs.update(kwargs)
  62. return 200, kwargs
  63. res = JsonResource(self.homeserver)
  64. res.register_paths(
  65. "GET",
  66. [re.compile("^/_matrix/foo/(?P<room_id>[^/]*)$")],
  67. _callback,
  68. "test_servlet",
  69. )
  70. make_request(
  71. self.reactor,
  72. FakeSite(res, self.reactor),
  73. b"GET",
  74. b"/_matrix/foo/%E2%98%83?a=%E2%98%83",
  75. )
  76. self.assertEqual(got_kwargs, {"room_id": "\N{SNOWMAN}"})
  77. def test_callback_direct_exception(self) -> None:
  78. """
  79. If the web callback raises an uncaught exception, it will be translated
  80. into a 500.
  81. """
  82. def _callback(request: SynapseRequest, **kwargs: object) -> NoReturn:
  83. raise Exception("boo")
  84. res = JsonResource(self.homeserver)
  85. res.register_paths(
  86. "GET", [re.compile("^/_matrix/foo$")], _callback, "test_servlet"
  87. )
  88. channel = make_request(
  89. self.reactor, FakeSite(res, self.reactor), b"GET", b"/_matrix/foo"
  90. )
  91. self.assertEqual(channel.code, 500)
  92. def test_callback_indirect_exception(self) -> None:
  93. """
  94. If the web callback raises an uncaught exception in a Deferred, it will
  95. be translated into a 500.
  96. """
  97. def _throw(*args: object) -> NoReturn:
  98. raise Exception("boo")
  99. def _callback(request: SynapseRequest, **kwargs: object) -> "Deferred[None]":
  100. d: "Deferred[None]" = Deferred()
  101. d.addCallback(_throw)
  102. self.reactor.callLater(0.5, d.callback, True)
  103. return make_deferred_yieldable(d)
  104. res = JsonResource(self.homeserver)
  105. res.register_paths(
  106. "GET", [re.compile("^/_matrix/foo$")], _callback, "test_servlet"
  107. )
  108. channel = make_request(
  109. self.reactor, FakeSite(res, self.reactor), b"GET", b"/_matrix/foo"
  110. )
  111. self.assertEqual(channel.code, 500)
  112. def test_callback_synapseerror(self) -> None:
  113. """
  114. If the web callback raises a SynapseError, it returns the appropriate
  115. status code and message set in it.
  116. """
  117. def _callback(request: SynapseRequest, **kwargs: object) -> NoReturn:
  118. raise SynapseError(403, "Forbidden!!one!", Codes.FORBIDDEN)
  119. res = JsonResource(self.homeserver)
  120. res.register_paths(
  121. "GET", [re.compile("^/_matrix/foo$")], _callback, "test_servlet"
  122. )
  123. channel = make_request(
  124. self.reactor, FakeSite(res, self.reactor), b"GET", b"/_matrix/foo"
  125. )
  126. self.assertEqual(channel.code, 403)
  127. self.assertEqual(channel.json_body["error"], "Forbidden!!one!")
  128. self.assertEqual(channel.json_body["errcode"], "M_FORBIDDEN")
  129. def test_no_handler(self) -> None:
  130. """
  131. If there is no handler to process the request, Synapse will return 400.
  132. """
  133. def _callback(request: SynapseRequest, **kwargs: object) -> None:
  134. """
  135. Not ever actually called!
  136. """
  137. self.fail("shouldn't ever get here")
  138. res = JsonResource(self.homeserver)
  139. res.register_paths(
  140. "GET", [re.compile("^/_matrix/foo$")], _callback, "test_servlet"
  141. )
  142. channel = make_request(
  143. self.reactor, FakeSite(res, self.reactor), b"GET", b"/_matrix/foobar"
  144. )
  145. self.assertEqual(channel.code, 400)
  146. self.assertEqual(channel.json_body["error"], "Unrecognized request")
  147. self.assertEqual(channel.json_body["errcode"], "M_UNRECOGNIZED")
  148. def test_head_request(self) -> None:
  149. """
  150. JsonResource.handler_for_request gives correctly decoded URL args to
  151. the callback, while Twisted will give the raw bytes of URL query
  152. arguments.
  153. """
  154. def _callback(
  155. request: SynapseRequest, **kwargs: object
  156. ) -> Tuple[int, Dict[str, object]]:
  157. return 200, {"result": True}
  158. res = JsonResource(self.homeserver)
  159. res.register_paths(
  160. "GET",
  161. [re.compile("^/_matrix/foo$")],
  162. _callback,
  163. "test_servlet",
  164. )
  165. # The path was registered as GET, but this is a HEAD request.
  166. channel = make_request(
  167. self.reactor, FakeSite(res, self.reactor), b"HEAD", b"/_matrix/foo"
  168. )
  169. self.assertEqual(channel.code, 200)
  170. self.assertNotIn("body", channel.result)
  171. class OptionsResourceTests(unittest.TestCase):
  172. def setUp(self) -> None:
  173. self.reactor = ThreadedMemoryReactorClock()
  174. class DummyResource(Resource):
  175. isLeaf = True
  176. def render(self, request: SynapseRequest) -> bytes:
  177. # Type-ignore: mypy thinks request.path is Optional[Any], not bytes.
  178. return request.path # type: ignore[return-value]
  179. # Setup a resource with some children.
  180. self.resource = OptionsResource()
  181. self.resource.putChild(b"res", DummyResource())
  182. def _make_request(self, method: bytes, path: bytes) -> FakeChannel:
  183. """Create a request from the method/path and return a channel with the response."""
  184. # Create a site and query for the resource.
  185. site = SynapseSite(
  186. "test",
  187. "site_tag",
  188. parse_listener_def(0, {"type": "http", "port": 0}),
  189. self.resource,
  190. "1.0",
  191. max_request_body_size=4096,
  192. reactor=self.reactor,
  193. )
  194. # render the request and return the channel
  195. channel = make_request(self.reactor, site, method, path, shorthand=False)
  196. return channel
  197. def test_unknown_options_request(self) -> None:
  198. """An OPTIONS requests to an unknown URL still returns 204 No Content."""
  199. channel = self._make_request(b"OPTIONS", b"/foo/")
  200. self.assertEqual(channel.code, 204)
  201. self.assertNotIn("body", channel.result)
  202. # Ensure the correct CORS headers have been added
  203. self.assertTrue(
  204. channel.headers.hasHeader(b"Access-Control-Allow-Origin"),
  205. "has CORS Origin header",
  206. )
  207. self.assertTrue(
  208. channel.headers.hasHeader(b"Access-Control-Allow-Methods"),
  209. "has CORS Methods header",
  210. )
  211. self.assertTrue(
  212. channel.headers.hasHeader(b"Access-Control-Allow-Headers"),
  213. "has CORS Headers header",
  214. )
  215. def test_known_options_request(self) -> None:
  216. """An OPTIONS requests to an known URL still returns 204 No Content."""
  217. channel = self._make_request(b"OPTIONS", b"/res/")
  218. self.assertEqual(channel.code, 204)
  219. self.assertNotIn("body", channel.result)
  220. # Ensure the correct CORS headers have been added
  221. self.assertTrue(
  222. channel.headers.hasHeader(b"Access-Control-Allow-Origin"),
  223. "has CORS Origin header",
  224. )
  225. self.assertTrue(
  226. channel.headers.hasHeader(b"Access-Control-Allow-Methods"),
  227. "has CORS Methods header",
  228. )
  229. self.assertTrue(
  230. channel.headers.hasHeader(b"Access-Control-Allow-Headers"),
  231. "has CORS Headers header",
  232. )
  233. def test_unknown_request(self) -> None:
  234. """A non-OPTIONS request to an unknown URL should 404."""
  235. channel = self._make_request(b"GET", b"/foo/")
  236. self.assertEqual(channel.code, 404)
  237. def test_known_request(self) -> None:
  238. """A non-OPTIONS request to an known URL should query the proper resource."""
  239. channel = self._make_request(b"GET", b"/res/")
  240. self.assertEqual(channel.code, 200)
  241. self.assertEqual(channel.result["body"], b"/res/")
  242. class WrapHtmlRequestHandlerTests(unittest.TestCase):
  243. class TestResource(DirectServeHtmlResource):
  244. callback: Optional[Callable[..., Awaitable[None]]]
  245. async def _async_render_GET(self, request: SynapseRequest) -> None:
  246. assert self.callback is not None
  247. await self.callback(request)
  248. def setUp(self) -> None:
  249. self.reactor = ThreadedMemoryReactorClock()
  250. def test_good_response(self) -> None:
  251. async def callback(request: SynapseRequest) -> None:
  252. request.write(b"response")
  253. request.finish()
  254. res = WrapHtmlRequestHandlerTests.TestResource()
  255. res.callback = callback
  256. channel = make_request(
  257. self.reactor, FakeSite(res, self.reactor), b"GET", b"/path"
  258. )
  259. self.assertEqual(channel.code, 200)
  260. body = channel.result["body"]
  261. self.assertEqual(body, b"response")
  262. def test_redirect_exception(self) -> None:
  263. """
  264. If the callback raises a RedirectException, it is turned into a 30x
  265. with the right location.
  266. """
  267. async def callback(request: SynapseRequest, **kwargs: object) -> None:
  268. raise RedirectException(b"/look/an/eagle", 301)
  269. res = WrapHtmlRequestHandlerTests.TestResource()
  270. res.callback = callback
  271. channel = make_request(
  272. self.reactor, FakeSite(res, self.reactor), b"GET", b"/path"
  273. )
  274. self.assertEqual(channel.code, 301)
  275. headers = channel.result["headers"]
  276. location_headers = [v for k, v in headers if k == b"Location"]
  277. self.assertEqual(location_headers, [b"/look/an/eagle"])
  278. def test_redirect_exception_with_cookie(self) -> None:
  279. """
  280. If the callback raises a RedirectException which sets a cookie, that is
  281. returned too
  282. """
  283. async def callback(request: SynapseRequest, **kwargs: object) -> NoReturn:
  284. e = RedirectException(b"/no/over/there", 304)
  285. e.cookies.append(b"session=yespls")
  286. raise e
  287. res = WrapHtmlRequestHandlerTests.TestResource()
  288. res.callback = callback
  289. channel = make_request(
  290. self.reactor, FakeSite(res, self.reactor), b"GET", b"/path"
  291. )
  292. self.assertEqual(channel.code, 304)
  293. headers = channel.result["headers"]
  294. location_headers = [v for k, v in headers if k == b"Location"]
  295. self.assertEqual(location_headers, [b"/no/over/there"])
  296. cookies_headers = [v for k, v in headers if k == b"Set-Cookie"]
  297. self.assertEqual(cookies_headers, [b"session=yespls"])
  298. def test_head_request(self) -> None:
  299. """A head request should work by being turned into a GET request."""
  300. async def callback(request: SynapseRequest) -> None:
  301. request.write(b"response")
  302. request.finish()
  303. res = WrapHtmlRequestHandlerTests.TestResource()
  304. res.callback = callback
  305. channel = make_request(
  306. self.reactor, FakeSite(res, self.reactor), b"HEAD", b"/path"
  307. )
  308. self.assertEqual(channel.code, 200)
  309. self.assertNotIn("body", channel.result)
  310. class CancellableDirectServeJsonResource(DirectServeJsonResource):
  311. def __init__(self, clock: Clock):
  312. super().__init__()
  313. self.clock = clock
  314. @cancellable
  315. async def _async_render_GET(self, request: SynapseRequest) -> Tuple[int, JsonDict]:
  316. await self.clock.sleep(1.0)
  317. return HTTPStatus.OK, {"result": True}
  318. async def _async_render_POST(self, request: SynapseRequest) -> Tuple[int, JsonDict]:
  319. await self.clock.sleep(1.0)
  320. return HTTPStatus.OK, {"result": True}
  321. class CancellableDirectServeHtmlResource(DirectServeHtmlResource):
  322. ERROR_TEMPLATE = "{code} {msg}"
  323. def __init__(self, clock: Clock):
  324. super().__init__()
  325. self.clock = clock
  326. @cancellable
  327. async def _async_render_GET(self, request: SynapseRequest) -> Tuple[int, bytes]:
  328. await self.clock.sleep(1.0)
  329. return HTTPStatus.OK, b"ok"
  330. async def _async_render_POST(self, request: SynapseRequest) -> Tuple[int, bytes]:
  331. await self.clock.sleep(1.0)
  332. return HTTPStatus.OK, b"ok"
  333. class DirectServeJsonResourceCancellationTests(unittest.TestCase):
  334. """Tests for `DirectServeJsonResource` cancellation."""
  335. def setUp(self) -> None:
  336. self.reactor = ThreadedMemoryReactorClock()
  337. self.clock = Clock(self.reactor)
  338. self.resource = CancellableDirectServeJsonResource(self.clock)
  339. self.site = FakeSite(self.resource, self.reactor)
  340. def test_cancellable_disconnect(self) -> None:
  341. """Test that handlers with the `@cancellable` flag can be cancelled."""
  342. channel = make_request(
  343. self.reactor, self.site, "GET", "/sleep", await_result=False
  344. )
  345. test_disconnect(
  346. self.reactor,
  347. channel,
  348. expect_cancellation=True,
  349. expected_body={"error": "Request cancelled", "errcode": Codes.UNKNOWN},
  350. )
  351. def test_uncancellable_disconnect(self) -> None:
  352. """Test that handlers without the `@cancellable` flag cannot be cancelled."""
  353. channel = make_request(
  354. self.reactor, self.site, "POST", "/sleep", await_result=False
  355. )
  356. test_disconnect(
  357. self.reactor,
  358. channel,
  359. expect_cancellation=False,
  360. expected_body={"result": True},
  361. )
  362. class DirectServeHtmlResourceCancellationTests(unittest.TestCase):
  363. """Tests for `DirectServeHtmlResource` cancellation."""
  364. def setUp(self) -> None:
  365. self.reactor = ThreadedMemoryReactorClock()
  366. self.clock = Clock(self.reactor)
  367. self.resource = CancellableDirectServeHtmlResource(self.clock)
  368. self.site = FakeSite(self.resource, self.reactor)
  369. def test_cancellable_disconnect(self) -> None:
  370. """Test that handlers with the `@cancellable` flag can be cancelled."""
  371. channel = make_request(
  372. self.reactor, self.site, "GET", "/sleep", await_result=False
  373. )
  374. test_disconnect(
  375. self.reactor,
  376. channel,
  377. expect_cancellation=True,
  378. expected_body=b"499 Request cancelled",
  379. )
  380. def test_uncancellable_disconnect(self) -> None:
  381. """Test that handlers without the `@cancellable` flag cannot be cancelled."""
  382. channel = make_request(
  383. self.reactor, self.site, "POST", "/sleep", await_result=False
  384. )
  385. test_disconnect(
  386. self.reactor, channel, expect_cancellation=False, expected_body=b"ok"
  387. )