test_server.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519
  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(
  183. self, method: bytes, path: bytes, experimental_cors_msc3886: bool = False
  184. ) -> FakeChannel:
  185. """Create a request from the method/path and return a channel with the response."""
  186. # Create a site and query for the resource.
  187. site = SynapseSite(
  188. "test",
  189. "site_tag",
  190. parse_listener_def(
  191. 0,
  192. {
  193. "type": "http",
  194. "port": 0,
  195. "experimental_cors_msc3886": experimental_cors_msc3886,
  196. },
  197. ),
  198. self.resource,
  199. "1.0",
  200. max_request_body_size=4096,
  201. reactor=self.reactor,
  202. )
  203. # render the request and return the channel
  204. channel = make_request(self.reactor, site, method, path, shorthand=False)
  205. return channel
  206. def _check_cors_standard_headers(self, channel: FakeChannel) -> None:
  207. # Ensure the correct CORS headers have been added
  208. # as per https://spec.matrix.org/v1.4/client-server-api/#web-browser-clients
  209. self.assertEqual(
  210. channel.headers.getRawHeaders(b"Access-Control-Allow-Origin"),
  211. [b"*"],
  212. "has correct CORS Origin header",
  213. )
  214. self.assertEqual(
  215. channel.headers.getRawHeaders(b"Access-Control-Allow-Methods"),
  216. [b"GET, HEAD, POST, PUT, DELETE, OPTIONS"], # HEAD isn't in the spec
  217. "has correct CORS Methods header",
  218. )
  219. self.assertEqual(
  220. channel.headers.getRawHeaders(b"Access-Control-Allow-Headers"),
  221. [b"X-Requested-With, Content-Type, Authorization, Date"],
  222. "has correct CORS Headers header",
  223. )
  224. def _check_cors_msc3886_headers(self, channel: FakeChannel) -> None:
  225. # Ensure the correct CORS headers have been added
  226. # as per https://github.com/matrix-org/matrix-spec-proposals/blob/hughns/simple-rendezvous-capability/proposals/3886-simple-rendezvous-capability.md#cors
  227. self.assertEqual(
  228. channel.headers.getRawHeaders(b"Access-Control-Allow-Origin"),
  229. [b"*"],
  230. "has correct CORS Origin header",
  231. )
  232. self.assertEqual(
  233. channel.headers.getRawHeaders(b"Access-Control-Allow-Methods"),
  234. [b"GET, HEAD, POST, PUT, DELETE, OPTIONS"], # HEAD isn't in the spec
  235. "has correct CORS Methods header",
  236. )
  237. self.assertEqual(
  238. channel.headers.getRawHeaders(b"Access-Control-Allow-Headers"),
  239. [
  240. b"X-Requested-With, Content-Type, Authorization, Date, If-Match, If-None-Match"
  241. ],
  242. "has correct CORS Headers header",
  243. )
  244. self.assertEqual(
  245. channel.headers.getRawHeaders(b"Access-Control-Expose-Headers"),
  246. [b"ETag, Location, X-Max-Bytes"],
  247. "has correct CORS Expose Headers header",
  248. )
  249. def test_unknown_options_request(self) -> None:
  250. """An OPTIONS requests to an unknown URL still returns 204 No Content."""
  251. channel = self._make_request(b"OPTIONS", b"/foo/")
  252. self.assertEqual(channel.code, 204)
  253. self.assertNotIn("body", channel.result)
  254. self._check_cors_standard_headers(channel)
  255. def test_known_options_request(self) -> None:
  256. """An OPTIONS requests to an known URL still returns 204 No Content."""
  257. channel = self._make_request(b"OPTIONS", b"/res/")
  258. self.assertEqual(channel.code, 204)
  259. self.assertNotIn("body", channel.result)
  260. self._check_cors_standard_headers(channel)
  261. def test_known_options_request_msc3886(self) -> None:
  262. """An OPTIONS requests to an known URL still returns 204 No Content."""
  263. channel = self._make_request(
  264. b"OPTIONS", b"/res/", experimental_cors_msc3886=True
  265. )
  266. self.assertEqual(channel.code, 204)
  267. self.assertNotIn("body", channel.result)
  268. self._check_cors_msc3886_headers(channel)
  269. def test_unknown_request(self) -> None:
  270. """A non-OPTIONS request to an unknown URL should 404."""
  271. channel = self._make_request(b"GET", b"/foo/")
  272. self.assertEqual(channel.code, 404)
  273. def test_known_request(self) -> None:
  274. """A non-OPTIONS request to an known URL should query the proper resource."""
  275. channel = self._make_request(b"GET", b"/res/")
  276. self.assertEqual(channel.code, 200)
  277. self.assertEqual(channel.result["body"], b"/res/")
  278. class WrapHtmlRequestHandlerTests(unittest.TestCase):
  279. class TestResource(DirectServeHtmlResource):
  280. callback: Optional[Callable[..., Awaitable[None]]]
  281. async def _async_render_GET(self, request: SynapseRequest) -> None:
  282. assert self.callback is not None
  283. await self.callback(request)
  284. def setUp(self) -> None:
  285. self.reactor = ThreadedMemoryReactorClock()
  286. def test_good_response(self) -> None:
  287. async def callback(request: SynapseRequest) -> None:
  288. request.write(b"response")
  289. request.finish()
  290. res = WrapHtmlRequestHandlerTests.TestResource()
  291. res.callback = callback
  292. channel = make_request(
  293. self.reactor, FakeSite(res, self.reactor), b"GET", b"/path"
  294. )
  295. self.assertEqual(channel.code, 200)
  296. body = channel.result["body"]
  297. self.assertEqual(body, b"response")
  298. def test_redirect_exception(self) -> None:
  299. """
  300. If the callback raises a RedirectException, it is turned into a 30x
  301. with the right location.
  302. """
  303. async def callback(request: SynapseRequest, **kwargs: object) -> None:
  304. raise RedirectException(b"/look/an/eagle", 301)
  305. res = WrapHtmlRequestHandlerTests.TestResource()
  306. res.callback = callback
  307. channel = make_request(
  308. self.reactor, FakeSite(res, self.reactor), b"GET", b"/path"
  309. )
  310. self.assertEqual(channel.code, 301)
  311. headers = channel.result["headers"]
  312. location_headers = [v for k, v in headers if k == b"Location"]
  313. self.assertEqual(location_headers, [b"/look/an/eagle"])
  314. def test_redirect_exception_with_cookie(self) -> None:
  315. """
  316. If the callback raises a RedirectException which sets a cookie, that is
  317. returned too
  318. """
  319. async def callback(request: SynapseRequest, **kwargs: object) -> NoReturn:
  320. e = RedirectException(b"/no/over/there", 304)
  321. e.cookies.append(b"session=yespls")
  322. raise e
  323. res = WrapHtmlRequestHandlerTests.TestResource()
  324. res.callback = callback
  325. channel = make_request(
  326. self.reactor, FakeSite(res, self.reactor), b"GET", b"/path"
  327. )
  328. self.assertEqual(channel.code, 304)
  329. headers = channel.result["headers"]
  330. location_headers = [v for k, v in headers if k == b"Location"]
  331. self.assertEqual(location_headers, [b"/no/over/there"])
  332. cookies_headers = [v for k, v in headers if k == b"Set-Cookie"]
  333. self.assertEqual(cookies_headers, [b"session=yespls"])
  334. def test_head_request(self) -> None:
  335. """A head request should work by being turned into a GET request."""
  336. async def callback(request: SynapseRequest) -> None:
  337. request.write(b"response")
  338. request.finish()
  339. res = WrapHtmlRequestHandlerTests.TestResource()
  340. res.callback = callback
  341. channel = make_request(
  342. self.reactor, FakeSite(res, self.reactor), b"HEAD", b"/path"
  343. )
  344. self.assertEqual(channel.code, 200)
  345. self.assertNotIn("body", channel.result)
  346. class CancellableDirectServeJsonResource(DirectServeJsonResource):
  347. def __init__(self, clock: Clock):
  348. super().__init__()
  349. self.clock = clock
  350. @cancellable
  351. async def _async_render_GET(self, request: SynapseRequest) -> Tuple[int, JsonDict]:
  352. await self.clock.sleep(1.0)
  353. return HTTPStatus.OK, {"result": True}
  354. async def _async_render_POST(self, request: SynapseRequest) -> Tuple[int, JsonDict]:
  355. await self.clock.sleep(1.0)
  356. return HTTPStatus.OK, {"result": True}
  357. class CancellableDirectServeHtmlResource(DirectServeHtmlResource):
  358. ERROR_TEMPLATE = "{code} {msg}"
  359. def __init__(self, clock: Clock):
  360. super().__init__()
  361. self.clock = clock
  362. @cancellable
  363. async def _async_render_GET(self, request: SynapseRequest) -> Tuple[int, bytes]:
  364. await self.clock.sleep(1.0)
  365. return HTTPStatus.OK, b"ok"
  366. async def _async_render_POST(self, request: SynapseRequest) -> Tuple[int, bytes]:
  367. await self.clock.sleep(1.0)
  368. return HTTPStatus.OK, b"ok"
  369. class DirectServeJsonResourceCancellationTests(unittest.TestCase):
  370. """Tests for `DirectServeJsonResource` cancellation."""
  371. def setUp(self) -> None:
  372. self.reactor = ThreadedMemoryReactorClock()
  373. self.clock = Clock(self.reactor)
  374. self.resource = CancellableDirectServeJsonResource(self.clock)
  375. self.site = FakeSite(self.resource, self.reactor)
  376. def test_cancellable_disconnect(self) -> None:
  377. """Test that handlers with the `@cancellable` flag can be cancelled."""
  378. channel = make_request(
  379. self.reactor, self.site, "GET", "/sleep", await_result=False
  380. )
  381. test_disconnect(
  382. self.reactor,
  383. channel,
  384. expect_cancellation=True,
  385. expected_body={"error": "Request cancelled", "errcode": Codes.UNKNOWN},
  386. )
  387. def test_uncancellable_disconnect(self) -> None:
  388. """Test that handlers without the `@cancellable` flag cannot be cancelled."""
  389. channel = make_request(
  390. self.reactor, self.site, "POST", "/sleep", await_result=False
  391. )
  392. test_disconnect(
  393. self.reactor,
  394. channel,
  395. expect_cancellation=False,
  396. expected_body={"result": True},
  397. )
  398. class DirectServeHtmlResourceCancellationTests(unittest.TestCase):
  399. """Tests for `DirectServeHtmlResource` cancellation."""
  400. def setUp(self) -> None:
  401. self.reactor = ThreadedMemoryReactorClock()
  402. self.clock = Clock(self.reactor)
  403. self.resource = CancellableDirectServeHtmlResource(self.clock)
  404. self.site = FakeSite(self.resource, self.reactor)
  405. def test_cancellable_disconnect(self) -> None:
  406. """Test that handlers with the `@cancellable` flag can be cancelled."""
  407. channel = make_request(
  408. self.reactor, self.site, "GET", "/sleep", await_result=False
  409. )
  410. test_disconnect(
  411. self.reactor,
  412. channel,
  413. expect_cancellation=True,
  414. expected_body=b"499 Request cancelled",
  415. )
  416. def test_uncancellable_disconnect(self) -> None:
  417. """Test that handlers without the `@cancellable` flag cannot be cancelled."""
  418. channel = make_request(
  419. self.reactor, self.site, "POST", "/sleep", await_result=False
  420. )
  421. test_disconnect(
  422. self.reactor, channel, expect_cancellation=False, expected_body=b"ok"
  423. )