test_server.py 11 KB

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