test_server.py 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213
  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.logging.context import make_deferred_yieldable
  26. from synapse.util import Clock
  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",
  55. [re.compile("^/_matrix/foo/(?P<room_id>[^/]*)$")],
  56. _callback,
  57. "test_servlet",
  58. )
  59. request, channel = make_request(
  60. self.reactor, b"GET", b"/_matrix/foo/%E2%98%83?a=%E2%98%83"
  61. )
  62. render(request, res, self.reactor)
  63. self.assertEqual(request.args, {b"a": ["\N{SNOWMAN}".encode("utf8")]})
  64. self.assertEqual(got_kwargs, {"room_id": "\N{SNOWMAN}"})
  65. def test_callback_direct_exception(self):
  66. """
  67. If the web callback raises an uncaught exception, it will be translated
  68. into a 500.
  69. """
  70. def _callback(request, **kwargs):
  71. raise Exception("boo")
  72. res = JsonResource(self.homeserver)
  73. res.register_paths(
  74. "GET", [re.compile("^/_matrix/foo$")], _callback, "test_servlet"
  75. )
  76. request, channel = make_request(self.reactor, b"GET", b"/_matrix/foo")
  77. render(request, res, self.reactor)
  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(1, 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. request, channel = make_request(self.reactor, b"GET", b"/_matrix/foo")
  96. render(request, res, self.reactor)
  97. self.assertEqual(channel.result["code"], b"500")
  98. def test_callback_synapseerror(self):
  99. """
  100. If the web callback raises a SynapseError, it returns the appropriate
  101. status code and message set in it.
  102. """
  103. def _callback(request, **kwargs):
  104. raise SynapseError(403, "Forbidden!!one!", Codes.FORBIDDEN)
  105. res = JsonResource(self.homeserver)
  106. res.register_paths(
  107. "GET", [re.compile("^/_matrix/foo$")], _callback, "test_servlet"
  108. )
  109. request, channel = make_request(self.reactor, b"GET", b"/_matrix/foo")
  110. render(request, res, self.reactor)
  111. self.assertEqual(channel.result["code"], b"403")
  112. self.assertEqual(channel.json_body["error"], "Forbidden!!one!")
  113. self.assertEqual(channel.json_body["errcode"], "M_FORBIDDEN")
  114. def test_no_handler(self):
  115. """
  116. If there is no handler to process the request, Synapse will return 400.
  117. """
  118. def _callback(request, **kwargs):
  119. """
  120. Not ever actually called!
  121. """
  122. self.fail("shouldn't ever get here")
  123. res = JsonResource(self.homeserver)
  124. res.register_paths(
  125. "GET", [re.compile("^/_matrix/foo$")], _callback, "test_servlet"
  126. )
  127. request, channel = make_request(self.reactor, b"GET", b"/_matrix/foobar")
  128. render(request, res, self.reactor)
  129. self.assertEqual(channel.result["code"], b"400")
  130. self.assertEqual(channel.json_body["error"], "Unrecognized request")
  131. self.assertEqual(channel.json_body["errcode"], "M_UNRECOGNIZED")
  132. class SiteTestCase(unittest.HomeserverTestCase):
  133. def test_lose_connection(self):
  134. """
  135. We log the URI correctly redacted when we lose the connection.
  136. """
  137. class HangingResource(Resource):
  138. """
  139. A Resource that strategically hangs, as if it were processing an
  140. answer.
  141. """
  142. def render(self, request):
  143. return NOT_DONE_YET
  144. # Set up a logging handler that we can inspect afterwards
  145. output = StringIO()
  146. handler = logging.StreamHandler(output)
  147. logger.addHandler(handler)
  148. old_level = logger.level
  149. logger.setLevel(10)
  150. self.addCleanup(logger.setLevel, old_level)
  151. self.addCleanup(logger.removeHandler, handler)
  152. # Make a resource and a Site, the resource will hang and allow us to
  153. # time out the request while it's 'processing'
  154. base_resource = Resource()
  155. base_resource.putChild(b"", HangingResource())
  156. site = SynapseSite("test", "site_tag", {}, base_resource, "1.0")
  157. server = site.buildProtocol(None)
  158. client = AccumulatingProtocol()
  159. client.makeConnection(FakeTransport(server, self.reactor))
  160. server.makeConnection(FakeTransport(client, self.reactor))
  161. # Send a request with an access token that will get redacted
  162. server.dataReceived(b"GET /?access_token=bar HTTP/1.0\r\n\r\n")
  163. self.pump()
  164. # Lose the connection
  165. e = Failure(Exception("Failed123"))
  166. server.connectionLost(e)
  167. handler.flush()
  168. # Our access token is redacted and the failure reason is logged.
  169. self.assertIn("/?access_token=<redacted>", output.getvalue())
  170. self.assertIn("Failed123", output.getvalue())