1
0

test_server.py 12 KB

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