test_server.py 18 KB

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