test_server.py 18 KB

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