test_server.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352
  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 twisted.internet.defer import Deferred
  16. from twisted.web.resource import Resource
  17. from synapse.api.errors import Codes, RedirectException, SynapseError
  18. from synapse.config.server import parse_listener_def
  19. from synapse.http.server import DirectServeHtmlResource, JsonResource, OptionsResource
  20. from synapse.http.site import SynapseSite
  21. from synapse.logging.context import make_deferred_yieldable
  22. from synapse.util import Clock
  23. from tests import unittest
  24. from tests.server import (
  25. ThreadedMemoryReactorClock,
  26. make_request,
  27. render,
  28. setup_test_homeserver,
  29. )
  30. class JsonResourceTests(unittest.TestCase):
  31. def setUp(self):
  32. self.reactor = ThreadedMemoryReactorClock()
  33. self.hs_clock = Clock(self.reactor)
  34. self.homeserver = setup_test_homeserver(
  35. self.addCleanup, http_client=None, clock=self.hs_clock, reactor=self.reactor
  36. )
  37. def test_handler_for_request(self):
  38. """
  39. JsonResource.handler_for_request gives correctly decoded URL args to
  40. the callback, while Twisted will give the raw bytes of URL query
  41. arguments.
  42. """
  43. got_kwargs = {}
  44. def _callback(request, **kwargs):
  45. got_kwargs.update(kwargs)
  46. return 200, kwargs
  47. res = JsonResource(self.homeserver)
  48. res.register_paths(
  49. "GET",
  50. [re.compile("^/_matrix/foo/(?P<room_id>[^/]*)$")],
  51. _callback,
  52. "test_servlet",
  53. )
  54. request, channel = make_request(
  55. self.reactor, b"GET", b"/_matrix/foo/%E2%98%83?a=%E2%98%83"
  56. )
  57. render(request, res, self.reactor)
  58. self.assertEqual(request.args, {b"a": ["\N{SNOWMAN}".encode("utf8")]})
  59. self.assertEqual(got_kwargs, {"room_id": "\N{SNOWMAN}"})
  60. def test_callback_direct_exception(self):
  61. """
  62. If the web callback raises an uncaught exception, it will be translated
  63. into a 500.
  64. """
  65. def _callback(request, **kwargs):
  66. raise Exception("boo")
  67. res = JsonResource(self.homeserver)
  68. res.register_paths(
  69. "GET", [re.compile("^/_matrix/foo$")], _callback, "test_servlet"
  70. )
  71. request, channel = make_request(self.reactor, b"GET", b"/_matrix/foo")
  72. render(request, res, self.reactor)
  73. self.assertEqual(channel.result["code"], b"500")
  74. def test_callback_indirect_exception(self):
  75. """
  76. If the web callback raises an uncaught exception in a Deferred, it will
  77. be translated into a 500.
  78. """
  79. def _throw(*args):
  80. raise Exception("boo")
  81. def _callback(request, **kwargs):
  82. d = Deferred()
  83. d.addCallback(_throw)
  84. self.reactor.callLater(1, d.callback, True)
  85. return make_deferred_yieldable(d)
  86. res = JsonResource(self.homeserver)
  87. res.register_paths(
  88. "GET", [re.compile("^/_matrix/foo$")], _callback, "test_servlet"
  89. )
  90. request, channel = make_request(self.reactor, b"GET", b"/_matrix/foo")
  91. render(request, res, self.reactor)
  92. self.assertEqual(channel.result["code"], b"500")
  93. def test_callback_synapseerror(self):
  94. """
  95. If the web callback raises a SynapseError, it returns the appropriate
  96. status code and message set in it.
  97. """
  98. def _callback(request, **kwargs):
  99. raise SynapseError(403, "Forbidden!!one!", Codes.FORBIDDEN)
  100. res = JsonResource(self.homeserver)
  101. res.register_paths(
  102. "GET", [re.compile("^/_matrix/foo$")], _callback, "test_servlet"
  103. )
  104. request, channel = make_request(self.reactor, b"GET", b"/_matrix/foo")
  105. render(request, res, self.reactor)
  106. self.assertEqual(channel.result["code"], b"403")
  107. self.assertEqual(channel.json_body["error"], "Forbidden!!one!")
  108. self.assertEqual(channel.json_body["errcode"], "M_FORBIDDEN")
  109. def test_no_handler(self):
  110. """
  111. If there is no handler to process the request, Synapse will return 400.
  112. """
  113. def _callback(request, **kwargs):
  114. """
  115. Not ever actually called!
  116. """
  117. self.fail("shouldn't ever get here")
  118. res = JsonResource(self.homeserver)
  119. res.register_paths(
  120. "GET", [re.compile("^/_matrix/foo$")], _callback, "test_servlet"
  121. )
  122. request, channel = make_request(self.reactor, b"GET", b"/_matrix/foobar")
  123. render(request, res, self.reactor)
  124. self.assertEqual(channel.result["code"], b"400")
  125. self.assertEqual(channel.json_body["error"], "Unrecognized request")
  126. self.assertEqual(channel.json_body["errcode"], "M_UNRECOGNIZED")
  127. def test_head_request(self):
  128. """
  129. JsonResource.handler_for_request gives correctly decoded URL args to
  130. the callback, while Twisted will give the raw bytes of URL query
  131. arguments.
  132. """
  133. def _callback(request, **kwargs):
  134. return 200, {"result": True}
  135. res = JsonResource(self.homeserver)
  136. res.register_paths(
  137. "GET", [re.compile("^/_matrix/foo$")], _callback, "test_servlet",
  138. )
  139. # The path was registered as GET, but this is a HEAD request.
  140. request, channel = make_request(self.reactor, b"HEAD", b"/_matrix/foo")
  141. render(request, res, self.reactor)
  142. self.assertEqual(channel.result["code"], b"200")
  143. self.assertNotIn("body", channel.result)
  144. class OptionsResourceTests(unittest.TestCase):
  145. def setUp(self):
  146. self.reactor = ThreadedMemoryReactorClock()
  147. class DummyResource(Resource):
  148. isLeaf = True
  149. def render(self, request):
  150. return request.path
  151. # Setup a resource with some children.
  152. self.resource = OptionsResource()
  153. self.resource.putChild(b"res", DummyResource())
  154. def _make_request(self, method, path):
  155. """Create a request from the method/path and return a channel with the response."""
  156. request, channel = make_request(self.reactor, method, path, shorthand=False)
  157. request.prepath = [] # This doesn't get set properly by make_request.
  158. # Create a site and query for the resource.
  159. site = SynapseSite(
  160. "test",
  161. "site_tag",
  162. parse_listener_def({"type": "http", "port": 0}),
  163. self.resource,
  164. "1.0",
  165. )
  166. request.site = site
  167. resource = site.getResourceFor(request)
  168. # Finally, render the resource and return the channel.
  169. render(request, resource, self.reactor)
  170. return channel
  171. def test_unknown_options_request(self):
  172. """An OPTIONS requests to an unknown URL still returns 204 No Content."""
  173. channel = self._make_request(b"OPTIONS", b"/foo/")
  174. self.assertEqual(channel.result["code"], b"204")
  175. self.assertNotIn("body", channel.result)
  176. # Ensure the correct CORS headers have been added
  177. self.assertTrue(
  178. channel.headers.hasHeader(b"Access-Control-Allow-Origin"),
  179. "has CORS Origin header",
  180. )
  181. self.assertTrue(
  182. channel.headers.hasHeader(b"Access-Control-Allow-Methods"),
  183. "has CORS Methods header",
  184. )
  185. self.assertTrue(
  186. channel.headers.hasHeader(b"Access-Control-Allow-Headers"),
  187. "has CORS Headers header",
  188. )
  189. def test_known_options_request(self):
  190. """An OPTIONS requests to an known URL still returns 204 No Content."""
  191. channel = self._make_request(b"OPTIONS", b"/res/")
  192. self.assertEqual(channel.result["code"], b"204")
  193. self.assertNotIn("body", channel.result)
  194. # Ensure the correct CORS headers have been added
  195. self.assertTrue(
  196. channel.headers.hasHeader(b"Access-Control-Allow-Origin"),
  197. "has CORS Origin header",
  198. )
  199. self.assertTrue(
  200. channel.headers.hasHeader(b"Access-Control-Allow-Methods"),
  201. "has CORS Methods header",
  202. )
  203. self.assertTrue(
  204. channel.headers.hasHeader(b"Access-Control-Allow-Headers"),
  205. "has CORS Headers header",
  206. )
  207. def test_unknown_request(self):
  208. """A non-OPTIONS request to an unknown URL should 404."""
  209. channel = self._make_request(b"GET", b"/foo/")
  210. self.assertEqual(channel.result["code"], b"404")
  211. def test_known_request(self):
  212. """A non-OPTIONS request to an known URL should query the proper resource."""
  213. channel = self._make_request(b"GET", b"/res/")
  214. self.assertEqual(channel.result["code"], b"200")
  215. self.assertEqual(channel.result["body"], b"/res/")
  216. class WrapHtmlRequestHandlerTests(unittest.TestCase):
  217. class TestResource(DirectServeHtmlResource):
  218. callback = None
  219. async def _async_render_GET(self, request):
  220. await self.callback(request)
  221. def setUp(self):
  222. self.reactor = ThreadedMemoryReactorClock()
  223. def test_good_response(self):
  224. async def callback(request):
  225. request.write(b"response")
  226. request.finish()
  227. res = WrapHtmlRequestHandlerTests.TestResource()
  228. res.callback = callback
  229. request, channel = make_request(self.reactor, b"GET", b"/path")
  230. render(request, res, self.reactor)
  231. self.assertEqual(channel.result["code"], b"200")
  232. body = channel.result["body"]
  233. self.assertEqual(body, b"response")
  234. def test_redirect_exception(self):
  235. """
  236. If the callback raises a RedirectException, it is turned into a 30x
  237. with the right location.
  238. """
  239. async def callback(request, **kwargs):
  240. raise RedirectException(b"/look/an/eagle", 301)
  241. res = WrapHtmlRequestHandlerTests.TestResource()
  242. res.callback = callback
  243. request, channel = make_request(self.reactor, b"GET", b"/path")
  244. render(request, res, self.reactor)
  245. self.assertEqual(channel.result["code"], b"301")
  246. headers = channel.result["headers"]
  247. location_headers = [v for k, v in headers if k == b"Location"]
  248. self.assertEqual(location_headers, [b"/look/an/eagle"])
  249. def test_redirect_exception_with_cookie(self):
  250. """
  251. If the callback raises a RedirectException which sets a cookie, that is
  252. returned too
  253. """
  254. async def callback(request, **kwargs):
  255. e = RedirectException(b"/no/over/there", 304)
  256. e.cookies.append(b"session=yespls")
  257. raise e
  258. res = WrapHtmlRequestHandlerTests.TestResource()
  259. res.callback = callback
  260. request, channel = make_request(self.reactor, b"GET", b"/path")
  261. render(request, res, self.reactor)
  262. self.assertEqual(channel.result["code"], b"304")
  263. headers = channel.result["headers"]
  264. location_headers = [v for k, v in headers if k == b"Location"]
  265. self.assertEqual(location_headers, [b"/no/over/there"])
  266. cookies_headers = [v for k, v in headers if k == b"Set-Cookie"]
  267. self.assertEqual(cookies_headers, [b"session=yespls"])
  268. def test_head_request(self):
  269. """A head request should work by being turned into a GET request."""
  270. async def callback(request):
  271. request.write(b"response")
  272. request.finish()
  273. res = WrapHtmlRequestHandlerTests.TestResource()
  274. res.callback = callback
  275. request, channel = make_request(self.reactor, b"HEAD", b"/path")
  276. render(request, res, self.reactor)
  277. self.assertEqual(channel.result["code"], b"200")
  278. self.assertNotIn("body", channel.result)