1
0

test_server.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339
  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", [re.compile("^/_matrix/foo$")], _callback, "test_servlet",
  135. )
  136. # The path was registered as GET, but this is a HEAD request.
  137. channel = make_request(self.reactor, FakeSite(res), b"HEAD", b"/_matrix/foo")
  138. self.assertEqual(channel.result["code"], b"200")
  139. self.assertNotIn("body", channel.result)
  140. class OptionsResourceTests(unittest.TestCase):
  141. def setUp(self):
  142. self.reactor = ThreadedMemoryReactorClock()
  143. class DummyResource(Resource):
  144. isLeaf = True
  145. def render(self, request):
  146. return request.path
  147. # Setup a resource with some children.
  148. self.resource = OptionsResource()
  149. self.resource.putChild(b"res", DummyResource())
  150. def _make_request(self, method, path):
  151. """Create a request from the method/path and return a channel with the response."""
  152. # Create a site and query for the resource.
  153. site = SynapseSite(
  154. "test",
  155. "site_tag",
  156. parse_listener_def({"type": "http", "port": 0}),
  157. self.resource,
  158. "1.0",
  159. )
  160. # render the request and return the channel
  161. channel = make_request(self.reactor, site, method, path, shorthand=False)
  162. return channel
  163. def test_unknown_options_request(self):
  164. """An OPTIONS requests to an unknown URL still returns 204 No Content."""
  165. channel = self._make_request(b"OPTIONS", b"/foo/")
  166. self.assertEqual(channel.result["code"], b"204")
  167. self.assertNotIn("body", channel.result)
  168. # Ensure the correct CORS headers have been added
  169. self.assertTrue(
  170. channel.headers.hasHeader(b"Access-Control-Allow-Origin"),
  171. "has CORS Origin header",
  172. )
  173. self.assertTrue(
  174. channel.headers.hasHeader(b"Access-Control-Allow-Methods"),
  175. "has CORS Methods header",
  176. )
  177. self.assertTrue(
  178. channel.headers.hasHeader(b"Access-Control-Allow-Headers"),
  179. "has CORS Headers header",
  180. )
  181. def test_known_options_request(self):
  182. """An OPTIONS requests to an known URL still returns 204 No Content."""
  183. channel = self._make_request(b"OPTIONS", b"/res/")
  184. self.assertEqual(channel.result["code"], b"204")
  185. self.assertNotIn("body", channel.result)
  186. # Ensure the correct CORS headers have been added
  187. self.assertTrue(
  188. channel.headers.hasHeader(b"Access-Control-Allow-Origin"),
  189. "has CORS Origin header",
  190. )
  191. self.assertTrue(
  192. channel.headers.hasHeader(b"Access-Control-Allow-Methods"),
  193. "has CORS Methods header",
  194. )
  195. self.assertTrue(
  196. channel.headers.hasHeader(b"Access-Control-Allow-Headers"),
  197. "has CORS Headers header",
  198. )
  199. def test_unknown_request(self):
  200. """A non-OPTIONS request to an unknown URL should 404."""
  201. channel = self._make_request(b"GET", b"/foo/")
  202. self.assertEqual(channel.result["code"], b"404")
  203. def test_known_request(self):
  204. """A non-OPTIONS request to an known URL should query the proper resource."""
  205. channel = self._make_request(b"GET", b"/res/")
  206. self.assertEqual(channel.result["code"], b"200")
  207. self.assertEqual(channel.result["body"], b"/res/")
  208. class WrapHtmlRequestHandlerTests(unittest.TestCase):
  209. class TestResource(DirectServeHtmlResource):
  210. callback = None
  211. async def _async_render_GET(self, request):
  212. await self.callback(request)
  213. def setUp(self):
  214. self.reactor = ThreadedMemoryReactorClock()
  215. def test_good_response(self):
  216. async def callback(request):
  217. request.write(b"response")
  218. request.finish()
  219. res = WrapHtmlRequestHandlerTests.TestResource()
  220. res.callback = callback
  221. channel = make_request(self.reactor, FakeSite(res), b"GET", b"/path")
  222. self.assertEqual(channel.result["code"], b"200")
  223. body = channel.result["body"]
  224. self.assertEqual(body, b"response")
  225. def test_redirect_exception(self):
  226. """
  227. If the callback raises a RedirectException, it is turned into a 30x
  228. with the right location.
  229. """
  230. async def callback(request, **kwargs):
  231. raise RedirectException(b"/look/an/eagle", 301)
  232. res = WrapHtmlRequestHandlerTests.TestResource()
  233. res.callback = callback
  234. channel = make_request(self.reactor, FakeSite(res), b"GET", b"/path")
  235. self.assertEqual(channel.result["code"], b"301")
  236. headers = channel.result["headers"]
  237. location_headers = [v for k, v in headers if k == b"Location"]
  238. self.assertEqual(location_headers, [b"/look/an/eagle"])
  239. def test_redirect_exception_with_cookie(self):
  240. """
  241. If the callback raises a RedirectException which sets a cookie, that is
  242. returned too
  243. """
  244. async def callback(request, **kwargs):
  245. e = RedirectException(b"/no/over/there", 304)
  246. e.cookies.append(b"session=yespls")
  247. raise e
  248. res = WrapHtmlRequestHandlerTests.TestResource()
  249. res.callback = callback
  250. channel = make_request(self.reactor, FakeSite(res), b"GET", b"/path")
  251. self.assertEqual(channel.result["code"], b"304")
  252. headers = channel.result["headers"]
  253. location_headers = [v for k, v in headers if k == b"Location"]
  254. self.assertEqual(location_headers, [b"/no/over/there"])
  255. cookies_headers = [v for k, v in headers if k == b"Set-Cookie"]
  256. self.assertEqual(cookies_headers, [b"session=yespls"])
  257. def test_head_request(self):
  258. """A head request should work by being turned into a GET request."""
  259. async def callback(request):
  260. request.write(b"response")
  261. request.finish()
  262. res = WrapHtmlRequestHandlerTests.TestResource()
  263. res.callback = callback
  264. channel = make_request(self.reactor, FakeSite(res), b"HEAD", b"/path")
  265. self.assertEqual(channel.result["code"], b"200")
  266. self.assertNotIn("body", channel.result)