1
0

test_server.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344
  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. max_request_body_size=1234,
  163. reactor=self.reactor,
  164. )
  165. # render the request and return the channel
  166. channel = make_request(self.reactor, site, method, path, shorthand=False)
  167. return channel
  168. def test_unknown_options_request(self):
  169. """An OPTIONS requests to an unknown URL still returns 204 No Content."""
  170. channel = self._make_request(b"OPTIONS", b"/foo/")
  171. self.assertEqual(channel.result["code"], b"204")
  172. self.assertNotIn("body", channel.result)
  173. # Ensure the correct CORS headers have been added
  174. self.assertTrue(
  175. channel.headers.hasHeader(b"Access-Control-Allow-Origin"),
  176. "has CORS Origin header",
  177. )
  178. self.assertTrue(
  179. channel.headers.hasHeader(b"Access-Control-Allow-Methods"),
  180. "has CORS Methods header",
  181. )
  182. self.assertTrue(
  183. channel.headers.hasHeader(b"Access-Control-Allow-Headers"),
  184. "has CORS Headers header",
  185. )
  186. def test_known_options_request(self):
  187. """An OPTIONS requests to an known URL still returns 204 No Content."""
  188. channel = self._make_request(b"OPTIONS", b"/res/")
  189. self.assertEqual(channel.result["code"], b"204")
  190. self.assertNotIn("body", channel.result)
  191. # Ensure the correct CORS headers have been added
  192. self.assertTrue(
  193. channel.headers.hasHeader(b"Access-Control-Allow-Origin"),
  194. "has CORS Origin header",
  195. )
  196. self.assertTrue(
  197. channel.headers.hasHeader(b"Access-Control-Allow-Methods"),
  198. "has CORS Methods header",
  199. )
  200. self.assertTrue(
  201. channel.headers.hasHeader(b"Access-Control-Allow-Headers"),
  202. "has CORS Headers header",
  203. )
  204. def test_unknown_request(self):
  205. """A non-OPTIONS request to an unknown URL should 404."""
  206. channel = self._make_request(b"GET", b"/foo/")
  207. self.assertEqual(channel.result["code"], b"404")
  208. def test_known_request(self):
  209. """A non-OPTIONS request to an known URL should query the proper resource."""
  210. channel = self._make_request(b"GET", b"/res/")
  211. self.assertEqual(channel.result["code"], b"200")
  212. self.assertEqual(channel.result["body"], b"/res/")
  213. class WrapHtmlRequestHandlerTests(unittest.TestCase):
  214. class TestResource(DirectServeHtmlResource):
  215. callback = None
  216. async def _async_render_GET(self, request):
  217. await self.callback(request)
  218. def setUp(self):
  219. self.reactor = ThreadedMemoryReactorClock()
  220. def test_good_response(self):
  221. async def callback(request):
  222. request.write(b"response")
  223. request.finish()
  224. res = WrapHtmlRequestHandlerTests.TestResource()
  225. res.callback = callback
  226. channel = make_request(self.reactor, FakeSite(res), b"GET", b"/path")
  227. self.assertEqual(channel.result["code"], b"200")
  228. body = channel.result["body"]
  229. self.assertEqual(body, b"response")
  230. def test_redirect_exception(self):
  231. """
  232. If the callback raises a RedirectException, it is turned into a 30x
  233. with the right location.
  234. """
  235. async def callback(request, **kwargs):
  236. raise RedirectException(b"/look/an/eagle", 301)
  237. res = WrapHtmlRequestHandlerTests.TestResource()
  238. res.callback = callback
  239. channel = make_request(self.reactor, FakeSite(res), b"GET", b"/path")
  240. self.assertEqual(channel.result["code"], b"301")
  241. headers = channel.result["headers"]
  242. location_headers = [v for k, v in headers if k == b"Location"]
  243. self.assertEqual(location_headers, [b"/look/an/eagle"])
  244. def test_redirect_exception_with_cookie(self):
  245. """
  246. If the callback raises a RedirectException which sets a cookie, that is
  247. returned too
  248. """
  249. async def callback(request, **kwargs):
  250. e = RedirectException(b"/no/over/there", 304)
  251. e.cookies.append(b"session=yespls")
  252. raise e
  253. res = WrapHtmlRequestHandlerTests.TestResource()
  254. res.callback = callback
  255. channel = make_request(self.reactor, FakeSite(res), b"GET", b"/path")
  256. self.assertEqual(channel.result["code"], b"304")
  257. headers = channel.result["headers"]
  258. location_headers = [v for k, v in headers if k == b"Location"]
  259. self.assertEqual(location_headers, [b"/no/over/there"])
  260. cookies_headers = [v for k, v in headers if k == b"Set-Cookie"]
  261. self.assertEqual(cookies_headers, [b"session=yespls"])
  262. def test_head_request(self):
  263. """A head request should work by being turned into a GET request."""
  264. async def callback(request):
  265. request.write(b"response")
  266. request.finish()
  267. res = WrapHtmlRequestHandlerTests.TestResource()
  268. res.callback = callback
  269. channel = make_request(self.reactor, FakeSite(res), b"HEAD", b"/path")
  270. self.assertEqual(channel.result["code"], b"200")
  271. self.assertNotIn("body", channel.result)