test_server.py 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202
  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, SynapseError
  23. from synapse.http.server import JsonResource
  24. from synapse.http.site import SynapseSite, logger
  25. from synapse.util import Clock
  26. from synapse.util.logcontext import make_deferred_yieldable
  27. from tests import unittest
  28. from tests.server import (
  29. FakeTransport,
  30. ThreadedMemoryReactorClock,
  31. make_request,
  32. render,
  33. setup_test_homeserver,
  34. )
  35. class JsonResourceTests(unittest.TestCase):
  36. def setUp(self):
  37. self.reactor = ThreadedMemoryReactorClock()
  38. self.hs_clock = Clock(self.reactor)
  39. self.homeserver = setup_test_homeserver(
  40. self.addCleanup, http_client=None, clock=self.hs_clock, reactor=self.reactor
  41. )
  42. def test_handler_for_request(self):
  43. """
  44. JsonResource.handler_for_request gives correctly decoded URL args to
  45. the callback, while Twisted will give the raw bytes of URL query
  46. arguments.
  47. """
  48. got_kwargs = {}
  49. def _callback(request, **kwargs):
  50. got_kwargs.update(kwargs)
  51. return (200, kwargs)
  52. res = JsonResource(self.homeserver)
  53. res.register_paths(
  54. "GET", [re.compile("^/_matrix/foo/(?P<room_id>[^/]*)$")], _callback
  55. )
  56. request, channel = make_request(
  57. self.reactor, b"GET", b"/_matrix/foo/%E2%98%83?a=%E2%98%83"
  58. )
  59. render(request, res, self.reactor)
  60. self.assertEqual(request.args, {b'a': [u"\N{SNOWMAN}".encode('utf8')]})
  61. self.assertEqual(got_kwargs, {u"room_id": u"\N{SNOWMAN}"})
  62. def test_callback_direct_exception(self):
  63. """
  64. If the web callback raises an uncaught exception, it will be translated
  65. into a 500.
  66. """
  67. def _callback(request, **kwargs):
  68. raise Exception("boo")
  69. res = JsonResource(self.homeserver)
  70. res.register_paths("GET", [re.compile("^/_matrix/foo$")], _callback)
  71. request, channel = make_request(self.reactor, b"GET", b"/_matrix/foo")
  72. render(request, res, self.reactor)
  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("GET", [re.compile("^/_matrix/foo$")], _callback)
  88. request, channel = make_request(self.reactor, b"GET", b"/_matrix/foo")
  89. render(request, res, self.reactor)
  90. self.assertEqual(channel.result["code"], b'500')
  91. def test_callback_synapseerror(self):
  92. """
  93. If the web callback raises a SynapseError, it returns the appropriate
  94. status code and message set in it.
  95. """
  96. def _callback(request, **kwargs):
  97. raise SynapseError(403, "Forbidden!!one!", Codes.FORBIDDEN)
  98. res = JsonResource(self.homeserver)
  99. res.register_paths("GET", [re.compile("^/_matrix/foo$")], _callback)
  100. request, channel = make_request(self.reactor, b"GET", b"/_matrix/foo")
  101. render(request, res, self.reactor)
  102. self.assertEqual(channel.result["code"], b'403')
  103. self.assertEqual(channel.json_body["error"], "Forbidden!!one!")
  104. self.assertEqual(channel.json_body["errcode"], "M_FORBIDDEN")
  105. def test_no_handler(self):
  106. """
  107. If there is no handler to process the request, Synapse will return 400.
  108. """
  109. def _callback(request, **kwargs):
  110. """
  111. Not ever actually called!
  112. """
  113. self.fail("shouldn't ever get here")
  114. res = JsonResource(self.homeserver)
  115. res.register_paths("GET", [re.compile("^/_matrix/foo$")], _callback)
  116. request, channel = make_request(self.reactor, b"GET", b"/_matrix/foobar")
  117. render(request, res, self.reactor)
  118. self.assertEqual(channel.result["code"], b'400')
  119. self.assertEqual(channel.json_body["error"], "Unrecognized request")
  120. self.assertEqual(channel.json_body["errcode"], "M_UNRECOGNIZED")
  121. class SiteTestCase(unittest.HomeserverTestCase):
  122. def test_lose_connection(self):
  123. """
  124. We log the URI correctly redacted when we lose the connection.
  125. """
  126. class HangingResource(Resource):
  127. """
  128. A Resource that strategically hangs, as if it were processing an
  129. answer.
  130. """
  131. def render(self, request):
  132. return NOT_DONE_YET
  133. # Set up a logging handler that we can inspect afterwards
  134. output = StringIO()
  135. handler = logging.StreamHandler(output)
  136. logger.addHandler(handler)
  137. old_level = logger.level
  138. logger.setLevel(10)
  139. self.addCleanup(logger.setLevel, old_level)
  140. self.addCleanup(logger.removeHandler, handler)
  141. # Make a resource and a Site, the resource will hang and allow us to
  142. # time out the request while it's 'processing'
  143. base_resource = Resource()
  144. base_resource.putChild(b'', HangingResource())
  145. site = SynapseSite("test", "site_tag", {}, base_resource, "1.0")
  146. server = site.buildProtocol(None)
  147. client = AccumulatingProtocol()
  148. client.makeConnection(FakeTransport(server, self.reactor))
  149. server.makeConnection(FakeTransport(client, self.reactor))
  150. # Send a request with an access token that will get redacted
  151. server.dataReceived(b"GET /?access_token=bar HTTP/1.0\r\n\r\n")
  152. self.pump()
  153. # Lose the connection
  154. e = Failure(Exception("Failed123"))
  155. server.connectionLost(e)
  156. handler.flush()
  157. # Our access token is redacted and the failure reason is logged.
  158. self.assertIn("/?access_token=<redacted>", output.getvalue())
  159. self.assertIn("Failed123", output.getvalue())