test_server.py 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288
  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 logging
  15. import re
  16. from six import StringIO
  17. from twisted.internet.defer import Deferred
  18. from twisted.python.failure import Failure
  19. from twisted.test.proto_helpers import AccumulatingProtocol
  20. from twisted.web.resource import Resource
  21. from twisted.web.server import NOT_DONE_YET
  22. from synapse.api.errors import Codes, RedirectException, SynapseError
  23. from synapse.http.server import (
  24. DirectServeResource,
  25. JsonResource,
  26. wrap_html_request_handler,
  27. )
  28. from synapse.http.site import SynapseSite, logger
  29. from synapse.logging.context import make_deferred_yieldable
  30. from synapse.util import Clock
  31. from tests import unittest
  32. from tests.server import (
  33. FakeTransport,
  34. ThreadedMemoryReactorClock,
  35. make_request,
  36. render,
  37. setup_test_homeserver,
  38. )
  39. class JsonResourceTests(unittest.TestCase):
  40. def setUp(self):
  41. self.reactor = ThreadedMemoryReactorClock()
  42. self.hs_clock = Clock(self.reactor)
  43. self.homeserver = setup_test_homeserver(
  44. self.addCleanup, http_client=None, clock=self.hs_clock, reactor=self.reactor
  45. )
  46. def test_handler_for_request(self):
  47. """
  48. JsonResource.handler_for_request gives correctly decoded URL args to
  49. the callback, while Twisted will give the raw bytes of URL query
  50. arguments.
  51. """
  52. got_kwargs = {}
  53. def _callback(request, **kwargs):
  54. got_kwargs.update(kwargs)
  55. return 200, kwargs
  56. res = JsonResource(self.homeserver)
  57. res.register_paths(
  58. "GET",
  59. [re.compile("^/_matrix/foo/(?P<room_id>[^/]*)$")],
  60. _callback,
  61. "test_servlet",
  62. )
  63. request, channel = make_request(
  64. self.reactor, b"GET", b"/_matrix/foo/%E2%98%83?a=%E2%98%83"
  65. )
  66. render(request, res, self.reactor)
  67. self.assertEqual(request.args, {b"a": ["\N{SNOWMAN}".encode("utf8")]})
  68. self.assertEqual(got_kwargs, {"room_id": "\N{SNOWMAN}"})
  69. def test_callback_direct_exception(self):
  70. """
  71. If the web callback raises an uncaught exception, it will be translated
  72. into a 500.
  73. """
  74. def _callback(request, **kwargs):
  75. raise Exception("boo")
  76. res = JsonResource(self.homeserver)
  77. res.register_paths(
  78. "GET", [re.compile("^/_matrix/foo$")], _callback, "test_servlet"
  79. )
  80. request, channel = make_request(self.reactor, b"GET", b"/_matrix/foo")
  81. render(request, res, self.reactor)
  82. self.assertEqual(channel.result["code"], b"500")
  83. def test_callback_indirect_exception(self):
  84. """
  85. If the web callback raises an uncaught exception in a Deferred, it will
  86. be translated into a 500.
  87. """
  88. def _throw(*args):
  89. raise Exception("boo")
  90. def _callback(request, **kwargs):
  91. d = Deferred()
  92. d.addCallback(_throw)
  93. self.reactor.callLater(1, d.callback, True)
  94. return make_deferred_yieldable(d)
  95. res = JsonResource(self.homeserver)
  96. res.register_paths(
  97. "GET", [re.compile("^/_matrix/foo$")], _callback, "test_servlet"
  98. )
  99. request, channel = make_request(self.reactor, b"GET", b"/_matrix/foo")
  100. render(request, res, self.reactor)
  101. self.assertEqual(channel.result["code"], b"500")
  102. def test_callback_synapseerror(self):
  103. """
  104. If the web callback raises a SynapseError, it returns the appropriate
  105. status code and message set in it.
  106. """
  107. def _callback(request, **kwargs):
  108. raise SynapseError(403, "Forbidden!!one!", Codes.FORBIDDEN)
  109. res = JsonResource(self.homeserver)
  110. res.register_paths(
  111. "GET", [re.compile("^/_matrix/foo$")], _callback, "test_servlet"
  112. )
  113. request, channel = make_request(self.reactor, b"GET", b"/_matrix/foo")
  114. render(request, res, self.reactor)
  115. self.assertEqual(channel.result["code"], b"403")
  116. self.assertEqual(channel.json_body["error"], "Forbidden!!one!")
  117. self.assertEqual(channel.json_body["errcode"], "M_FORBIDDEN")
  118. def test_no_handler(self):
  119. """
  120. If there is no handler to process the request, Synapse will return 400.
  121. """
  122. def _callback(request, **kwargs):
  123. """
  124. Not ever actually called!
  125. """
  126. self.fail("shouldn't ever get here")
  127. res = JsonResource(self.homeserver)
  128. res.register_paths(
  129. "GET", [re.compile("^/_matrix/foo$")], _callback, "test_servlet"
  130. )
  131. request, channel = make_request(self.reactor, b"GET", b"/_matrix/foobar")
  132. render(request, res, self.reactor)
  133. self.assertEqual(channel.result["code"], b"400")
  134. self.assertEqual(channel.json_body["error"], "Unrecognized request")
  135. self.assertEqual(channel.json_body["errcode"], "M_UNRECOGNIZED")
  136. class WrapHtmlRequestHandlerTests(unittest.TestCase):
  137. class TestResource(DirectServeResource):
  138. callback = None
  139. @wrap_html_request_handler
  140. async def _async_render_GET(self, request):
  141. return await self.callback(request)
  142. def setUp(self):
  143. self.reactor = ThreadedMemoryReactorClock()
  144. def test_good_response(self):
  145. def callback(request):
  146. request.write(b"response")
  147. request.finish()
  148. res = WrapHtmlRequestHandlerTests.TestResource()
  149. res.callback = callback
  150. request, channel = make_request(self.reactor, b"GET", b"/path")
  151. render(request, res, self.reactor)
  152. self.assertEqual(channel.result["code"], b"200")
  153. body = channel.result["body"]
  154. self.assertEqual(body, b"response")
  155. def test_redirect_exception(self):
  156. """
  157. If the callback raises a RedirectException, it is turned into a 30x
  158. with the right location.
  159. """
  160. def callback(request, **kwargs):
  161. raise RedirectException(b"/look/an/eagle", 301)
  162. res = WrapHtmlRequestHandlerTests.TestResource()
  163. res.callback = callback
  164. request, channel = make_request(self.reactor, b"GET", b"/path")
  165. render(request, res, self.reactor)
  166. self.assertEqual(channel.result["code"], b"301")
  167. headers = channel.result["headers"]
  168. location_headers = [v for k, v in headers if k == b"Location"]
  169. self.assertEqual(location_headers, [b"/look/an/eagle"])
  170. def test_redirect_exception_with_cookie(self):
  171. """
  172. If the callback raises a RedirectException which sets a cookie, that is
  173. returned too
  174. """
  175. def callback(request, **kwargs):
  176. e = RedirectException(b"/no/over/there", 304)
  177. e.cookies.append(b"session=yespls")
  178. raise e
  179. res = WrapHtmlRequestHandlerTests.TestResource()
  180. res.callback = callback
  181. request, channel = make_request(self.reactor, b"GET", b"/path")
  182. render(request, res, self.reactor)
  183. self.assertEqual(channel.result["code"], b"304")
  184. headers = channel.result["headers"]
  185. location_headers = [v for k, v in headers if k == b"Location"]
  186. self.assertEqual(location_headers, [b"/no/over/there"])
  187. cookies_headers = [v for k, v in headers if k == b"Set-Cookie"]
  188. self.assertEqual(cookies_headers, [b"session=yespls"])
  189. class SiteTestCase(unittest.HomeserverTestCase):
  190. def test_lose_connection(self):
  191. """
  192. We log the URI correctly redacted when we lose the connection.
  193. """
  194. class HangingResource(Resource):
  195. """
  196. A Resource that strategically hangs, as if it were processing an
  197. answer.
  198. """
  199. def render(self, request):
  200. return NOT_DONE_YET
  201. # Set up a logging handler that we can inspect afterwards
  202. output = StringIO()
  203. handler = logging.StreamHandler(output)
  204. logger.addHandler(handler)
  205. old_level = logger.level
  206. logger.setLevel(10)
  207. self.addCleanup(logger.setLevel, old_level)
  208. self.addCleanup(logger.removeHandler, handler)
  209. # Make a resource and a Site, the resource will hang and allow us to
  210. # time out the request while it's 'processing'
  211. base_resource = Resource()
  212. base_resource.putChild(b"", HangingResource())
  213. site = SynapseSite("test", "site_tag", {}, base_resource, "1.0")
  214. server = site.buildProtocol(None)
  215. client = AccumulatingProtocol()
  216. client.makeConnection(FakeTransport(server, self.reactor))
  217. server.makeConnection(FakeTransport(client, self.reactor))
  218. # Send a request with an access token that will get redacted
  219. server.dataReceived(b"GET /?access_token=bar HTTP/1.0\r\n\r\n")
  220. self.pump()
  221. # Lose the connection
  222. e = Failure(Exception("Failed123"))
  223. server.connectionLost(e)
  224. handler.flush()
  225. # Our access token is redacted and the failure reason is logged.
  226. self.assertIn("/?access_token=<redacted>", output.getvalue())
  227. self.assertIn("Failed123", output.getvalue())