test_simple_client.py 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179
  1. # Copyright 2020 The Matrix.org Foundation C.I.C.
  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. from unittest.mock import Mock
  15. from netaddr import IPSet
  16. from twisted.internet import defer
  17. from twisted.internet.error import DNSLookupError
  18. from synapse.http import RequestTimedOutError
  19. from synapse.http.client import SimpleHttpClient
  20. from synapse.server import HomeServer
  21. from tests.unittest import HomeserverTestCase
  22. class SimpleHttpClientTests(HomeserverTestCase):
  23. def prepare(self, reactor, clock, hs: "HomeServer"):
  24. # Add a DNS entry for a test server
  25. self.reactor.lookups["testserv"] = "1.2.3.4"
  26. self.cl = hs.get_simple_http_client()
  27. def test_dns_error(self):
  28. """
  29. If the DNS lookup returns an error, it will bubble up.
  30. """
  31. d = defer.ensureDeferred(self.cl.get_json("http://testserv2:8008/foo/bar"))
  32. self.pump()
  33. f = self.failureResultOf(d)
  34. self.assertIsInstance(f.value, DNSLookupError)
  35. def test_client_connection_refused(self):
  36. d = defer.ensureDeferred(self.cl.get_json("http://testserv:8008/foo/bar"))
  37. self.pump()
  38. # Nothing happened yet
  39. self.assertNoResult(d)
  40. clients = self.reactor.tcpClients
  41. self.assertEqual(len(clients), 1)
  42. (host, port, factory, _timeout, _bindAddress) = clients[0]
  43. self.assertEqual(host, "1.2.3.4")
  44. self.assertEqual(port, 8008)
  45. e = Exception("go away")
  46. factory.clientConnectionFailed(None, e)
  47. self.pump(0.5)
  48. f = self.failureResultOf(d)
  49. self.assertIs(f.value, e)
  50. def test_client_never_connect(self):
  51. """
  52. If the HTTP request is not connected and is timed out, it'll give a
  53. ConnectingCancelledError or TimeoutError.
  54. """
  55. d = defer.ensureDeferred(self.cl.get_json("http://testserv:8008/foo/bar"))
  56. self.pump()
  57. # Nothing happened yet
  58. self.assertNoResult(d)
  59. # Make sure treq is trying to connect
  60. clients = self.reactor.tcpClients
  61. self.assertEqual(len(clients), 1)
  62. self.assertEqual(clients[0][0], "1.2.3.4")
  63. self.assertEqual(clients[0][1], 8008)
  64. # Deferred is still without a result
  65. self.assertNoResult(d)
  66. # Push by enough to time it out
  67. self.reactor.advance(120)
  68. f = self.failureResultOf(d)
  69. self.assertIsInstance(f.value, RequestTimedOutError)
  70. def test_client_connect_no_response(self):
  71. """
  72. If the HTTP request is connected, but gets no response before being
  73. timed out, it'll give a ResponseNeverReceived.
  74. """
  75. d = defer.ensureDeferred(self.cl.get_json("http://testserv:8008/foo/bar"))
  76. self.pump()
  77. # Nothing happened yet
  78. self.assertNoResult(d)
  79. # Make sure treq is trying to connect
  80. clients = self.reactor.tcpClients
  81. self.assertEqual(len(clients), 1)
  82. self.assertEqual(clients[0][0], "1.2.3.4")
  83. self.assertEqual(clients[0][1], 8008)
  84. conn = Mock()
  85. client = clients[0][2].buildProtocol(None)
  86. client.makeConnection(conn)
  87. # Deferred is still without a result
  88. self.assertNoResult(d)
  89. # Push by enough to time it out
  90. self.reactor.advance(120)
  91. f = self.failureResultOf(d)
  92. self.assertIsInstance(f.value, RequestTimedOutError)
  93. def test_client_ip_range_blacklist(self):
  94. """Ensure that Synapse does not try to connect to blacklisted IPs"""
  95. # Add some DNS entries we'll blacklist
  96. self.reactor.lookups["internal"] = "127.0.0.1"
  97. self.reactor.lookups["internalv6"] = "fe80:0:0:0:0:8a2e:370:7337"
  98. ip_blacklist = IPSet(["127.0.0.0/8", "fe80::/64"])
  99. cl = SimpleHttpClient(self.hs, ip_blacklist=ip_blacklist)
  100. # Try making a GET request to a blacklisted IPv4 address
  101. # ------------------------------------------------------
  102. # Make the request
  103. d = defer.ensureDeferred(cl.get_json("http://internal:8008/foo/bar"))
  104. self.pump(1)
  105. # Check that it was unable to resolve the address
  106. clients = self.reactor.tcpClients
  107. self.assertEqual(len(clients), 0)
  108. self.failureResultOf(d, DNSLookupError)
  109. # Try making a POST request to a blacklisted IPv6 address
  110. # -------------------------------------------------------
  111. # Make the request
  112. d = defer.ensureDeferred(
  113. cl.post_json_get_json("http://internalv6:8008/foo/bar", {})
  114. )
  115. # Move the reactor forwards
  116. self.pump(1)
  117. # Check that it was unable to resolve the address
  118. clients = self.reactor.tcpClients
  119. self.assertEqual(len(clients), 0)
  120. # Check that it was due to a blacklisted DNS lookup
  121. self.failureResultOf(d, DNSLookupError)
  122. # Try making a GET request to a non-blacklisted IPv4 address
  123. # ----------------------------------------------------------
  124. # Make the request
  125. d = defer.ensureDeferred(cl.get_json("http://testserv:8008/foo/bar"))
  126. # Nothing has happened yet
  127. self.assertNoResult(d)
  128. # Move the reactor forwards
  129. self.pump(1)
  130. # Check that it was able to resolve the address
  131. clients = self.reactor.tcpClients
  132. self.assertNotEqual(len(clients), 0)
  133. # Connection will still fail as this IP address does not resolve to anything
  134. self.failureResultOf(d, RequestTimedOutError)