test_simple_client.py 5.9 KB

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