test_matrixfederationclient.py 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936
  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. from typing import Any, Dict, Generator
  15. from unittest.mock import ANY, Mock, create_autospec
  16. from netaddr import IPSet
  17. from parameterized import parameterized
  18. from twisted.internet import defer
  19. from twisted.internet.defer import Deferred, TimeoutError
  20. from twisted.internet.error import ConnectingCancelledError, DNSLookupError
  21. from twisted.test.proto_helpers import MemoryReactor, StringTransport
  22. from twisted.web.client import Agent, ResponseNeverReceived
  23. from twisted.web.http import HTTPChannel
  24. from twisted.web.http_headers import Headers
  25. from synapse.api.errors import HttpResponseException, RequestSendFailed
  26. from synapse.config._base import ConfigError
  27. from synapse.http.matrixfederationclient import (
  28. ByteParser,
  29. MatrixFederationHttpClient,
  30. MatrixFederationRequest,
  31. )
  32. from synapse.logging.context import (
  33. SENTINEL_CONTEXT,
  34. LoggingContext,
  35. LoggingContextOrSentinel,
  36. current_context,
  37. )
  38. from synapse.server import HomeServer
  39. from synapse.util import Clock
  40. from tests.replication._base import BaseMultiWorkerStreamTestCase
  41. from tests.server import FakeTransport
  42. from tests.test_utils import FakeResponse
  43. from tests.unittest import HomeserverTestCase, override_config
  44. def check_logcontext(context: LoggingContextOrSentinel) -> None:
  45. current = current_context()
  46. if current is not context:
  47. raise AssertionError("Expected logcontext %s but was %s" % (context, current))
  48. class FederationClientTests(HomeserverTestCase):
  49. def make_homeserver(self, reactor: MemoryReactor, clock: Clock) -> HomeServer:
  50. hs = self.setup_test_homeserver(reactor=reactor, clock=clock)
  51. return hs
  52. def prepare(
  53. self, reactor: MemoryReactor, clock: Clock, homeserver: HomeServer
  54. ) -> None:
  55. self.cl = MatrixFederationHttpClient(self.hs, None)
  56. self.reactor.lookups["testserv"] = "1.2.3.4"
  57. def test_client_get(self) -> None:
  58. """
  59. happy-path test of a GET request
  60. """
  61. @defer.inlineCallbacks
  62. def do_request() -> Generator["Deferred[object]", object, object]:
  63. with LoggingContext("one") as context:
  64. fetch_d = defer.ensureDeferred(
  65. self.cl.get_json("testserv:8008", "foo/bar")
  66. )
  67. # Nothing happened yet
  68. self.assertNoResult(fetch_d)
  69. # should have reset logcontext to the sentinel
  70. check_logcontext(SENTINEL_CONTEXT)
  71. try:
  72. fetch_res = yield fetch_d
  73. return fetch_res
  74. finally:
  75. check_logcontext(context)
  76. test_d = do_request()
  77. self.pump()
  78. # Nothing happened yet
  79. self.assertNoResult(test_d)
  80. # Make sure treq is trying to connect
  81. clients = self.reactor.tcpClients
  82. self.assertEqual(len(clients), 1)
  83. (host, port, factory, _timeout, _bindAddress) = clients[0]
  84. self.assertEqual(host, "1.2.3.4")
  85. self.assertEqual(port, 8008)
  86. # complete the connection and wire it up to a fake transport
  87. protocol = factory.buildProtocol(None)
  88. transport = StringTransport()
  89. protocol.makeConnection(transport)
  90. # that should have made it send the request to the transport
  91. self.assertRegex(transport.value(), b"^GET /foo/bar")
  92. self.assertRegex(transport.value(), b"Host: testserv:8008")
  93. # Deferred is still without a result
  94. self.assertNoResult(test_d)
  95. # Send it the HTTP response
  96. res_json = b'{ "a": 1 }'
  97. protocol.dataReceived(
  98. b"HTTP/1.1 200 OK\r\n"
  99. b"Server: Fake\r\n"
  100. b"Content-Type: application/json\r\n"
  101. b"Content-Length: %i\r\n"
  102. b"\r\n"
  103. b"%s" % (len(res_json), res_json)
  104. )
  105. self.pump()
  106. res = self.successResultOf(test_d)
  107. # check the response is as expected
  108. self.assertEqual(res, {"a": 1})
  109. def test_dns_error(self) -> None:
  110. """
  111. If the DNS lookup returns an error, it will bubble up.
  112. """
  113. d = defer.ensureDeferred(
  114. self.cl.get_json("testserv2:8008", "foo/bar", timeout=10000)
  115. )
  116. self.pump()
  117. f = self.failureResultOf(d)
  118. self.assertIsInstance(f.value, RequestSendFailed)
  119. self.assertIsInstance(f.value.inner_exception, DNSLookupError)
  120. def test_client_connection_refused(self) -> None:
  121. d = defer.ensureDeferred(
  122. self.cl.get_json("testserv:8008", "foo/bar", timeout=10000)
  123. )
  124. self.pump()
  125. # Nothing happened yet
  126. self.assertNoResult(d)
  127. clients = self.reactor.tcpClients
  128. self.assertEqual(len(clients), 1)
  129. (host, port, factory, _timeout, _bindAddress) = clients[0]
  130. self.assertEqual(host, "1.2.3.4")
  131. self.assertEqual(port, 8008)
  132. e = Exception("go away")
  133. factory.clientConnectionFailed(None, e)
  134. self.pump(0.5)
  135. f = self.failureResultOf(d)
  136. self.assertIsInstance(f.value, RequestSendFailed)
  137. self.assertIs(f.value.inner_exception, e)
  138. def test_client_never_connect(self) -> None:
  139. """
  140. If the HTTP request is not connected and is timed out, it'll give a
  141. ConnectingCancelledError or TimeoutError.
  142. """
  143. d = defer.ensureDeferred(
  144. self.cl.get_json("testserv:8008", "foo/bar", timeout=10000)
  145. )
  146. self.pump()
  147. # Nothing happened yet
  148. self.assertNoResult(d)
  149. # Make sure treq is trying to connect
  150. clients = self.reactor.tcpClients
  151. self.assertEqual(len(clients), 1)
  152. self.assertEqual(clients[0][0], "1.2.3.4")
  153. self.assertEqual(clients[0][1], 8008)
  154. # Deferred is still without a result
  155. self.assertNoResult(d)
  156. # Push by enough to time it out
  157. self.reactor.advance(10.5)
  158. f = self.failureResultOf(d)
  159. self.assertIsInstance(f.value, RequestSendFailed)
  160. self.assertIsInstance(
  161. f.value.inner_exception, (ConnectingCancelledError, TimeoutError)
  162. )
  163. def test_client_connect_no_response(self) -> None:
  164. """
  165. If the HTTP request is connected, but gets no response before being
  166. timed out, it'll give a ResponseNeverReceived.
  167. """
  168. d = defer.ensureDeferred(
  169. self.cl.get_json("testserv:8008", "foo/bar", timeout=10000)
  170. )
  171. self.pump()
  172. # Nothing happened yet
  173. self.assertNoResult(d)
  174. # Make sure treq is trying to connect
  175. clients = self.reactor.tcpClients
  176. self.assertEqual(len(clients), 1)
  177. self.assertEqual(clients[0][0], "1.2.3.4")
  178. self.assertEqual(clients[0][1], 8008)
  179. conn = Mock()
  180. client = clients[0][2].buildProtocol(None)
  181. client.makeConnection(conn)
  182. # Deferred is still without a result
  183. self.assertNoResult(d)
  184. # Push by enough to time it out
  185. self.reactor.advance(10.5)
  186. f = self.failureResultOf(d)
  187. self.assertIsInstance(f.value, RequestSendFailed)
  188. self.assertIsInstance(f.value.inner_exception, ResponseNeverReceived)
  189. def test_client_ip_range_blocklist(self) -> None:
  190. """Ensure that Synapse does not try to connect to blocked IPs"""
  191. # Set up the ip_range blocklist
  192. self.hs.config.server.federation_ip_range_blocklist = IPSet(
  193. ["127.0.0.0/8", "fe80::/64"]
  194. )
  195. self.reactor.lookups["internal"] = "127.0.0.1"
  196. self.reactor.lookups["internalv6"] = "fe80:0:0:0:0:8a2e:370:7337"
  197. self.reactor.lookups["fine"] = "10.20.30.40"
  198. cl = MatrixFederationHttpClient(self.hs, None)
  199. # Try making a GET request to a blocked IPv4 address
  200. # ------------------------------------------------------
  201. # Make the request
  202. d = defer.ensureDeferred(cl.get_json("internal:8008", "foo/bar", timeout=10000))
  203. # Nothing happened yet
  204. self.assertNoResult(d)
  205. self.pump(1)
  206. # Check that it was unable to resolve the address
  207. clients = self.reactor.tcpClients
  208. self.assertEqual(len(clients), 0)
  209. f = self.failureResultOf(d)
  210. self.assertIsInstance(f.value, RequestSendFailed)
  211. self.assertIsInstance(f.value.inner_exception, DNSLookupError)
  212. # Try making a POST request to a blocked IPv6 address
  213. # -------------------------------------------------------
  214. # Make the request
  215. d = defer.ensureDeferred(
  216. cl.post_json("internalv6:8008", "foo/bar", timeout=10000)
  217. )
  218. # Nothing has happened yet
  219. self.assertNoResult(d)
  220. # Move the reactor forwards
  221. self.pump(1)
  222. # Check that it was unable to resolve the address
  223. clients = self.reactor.tcpClients
  224. self.assertEqual(len(clients), 0)
  225. # Check that it was due to a blocked DNS lookup
  226. f = self.failureResultOf(d, RequestSendFailed)
  227. self.assertIsInstance(f.value.inner_exception, DNSLookupError)
  228. # Try making a GET request to an allowed IPv4 address
  229. # ----------------------------------------------------------
  230. # Make the request
  231. d = defer.ensureDeferred(cl.post_json("fine:8008", "foo/bar", timeout=10000))
  232. # Nothing has happened yet
  233. self.assertNoResult(d)
  234. # Move the reactor forwards
  235. self.pump(1)
  236. # Check that it was able to resolve the address
  237. clients = self.reactor.tcpClients
  238. self.assertNotEqual(len(clients), 0)
  239. # Connection will still fail as this IP address does not resolve to anything
  240. f = self.failureResultOf(d, RequestSendFailed)
  241. self.assertIsInstance(f.value.inner_exception, ConnectingCancelledError)
  242. def test_client_gets_headers(self) -> None:
  243. """
  244. Once the client gets the headers, _request returns successfully.
  245. """
  246. request = MatrixFederationRequest(
  247. method="GET", destination="testserv:8008", path="foo/bar"
  248. )
  249. d = defer.ensureDeferred(self.cl._send_request(request, timeout=10000))
  250. self.pump()
  251. conn = Mock()
  252. clients = self.reactor.tcpClients
  253. client = clients[0][2].buildProtocol(None)
  254. client.makeConnection(conn)
  255. # Deferred does not have a result
  256. self.assertNoResult(d)
  257. # Send it the HTTP response
  258. client.dataReceived(b"HTTP/1.1 200 OK\r\nServer: Fake\r\n\r\n")
  259. # We should get a successful response
  260. r = self.successResultOf(d)
  261. self.assertEqual(r.code, 200)
  262. @parameterized.expand(["get_json", "post_json", "delete_json", "put_json"])
  263. def test_timeout_reading_body(self, method_name: str) -> None:
  264. """
  265. If the HTTP request is connected, but gets no response before being
  266. timed out, it'll give a RequestSendFailed with can_retry.
  267. """
  268. method = getattr(self.cl, method_name)
  269. d = defer.ensureDeferred(method("testserv:8008", "foo/bar", timeout=10000))
  270. self.pump()
  271. conn = Mock()
  272. clients = self.reactor.tcpClients
  273. client = clients[0][2].buildProtocol(None)
  274. client.makeConnection(conn)
  275. # Deferred does not have a result
  276. self.assertNoResult(d)
  277. # Send it the HTTP response
  278. client.dataReceived(
  279. b"HTTP/1.1 200 OK\r\nContent-Type: application/json\r\n"
  280. b"Server: Fake\r\n\r\n"
  281. )
  282. # Push by enough to time it out
  283. self.reactor.advance(10.5)
  284. f = self.failureResultOf(d)
  285. self.assertIsInstance(f.value, RequestSendFailed)
  286. self.assertTrue(f.value.can_retry)
  287. self.assertIsInstance(f.value.inner_exception, defer.TimeoutError)
  288. def test_client_requires_trailing_slashes(self) -> None:
  289. """
  290. If a connection is made to a client but the client rejects it due to
  291. requiring a trailing slash. We need to retry the request with a
  292. trailing slash. Workaround for Synapse <= v0.99.3, explained in #3622.
  293. """
  294. d = defer.ensureDeferred(
  295. self.cl.get_json("testserv:8008", "foo/bar", try_trailing_slash_on_400=True)
  296. )
  297. # Send the request
  298. self.pump()
  299. # there should have been a call to connectTCP
  300. clients = self.reactor.tcpClients
  301. self.assertEqual(len(clients), 1)
  302. (_host, _port, factory, _timeout, _bindAddress) = clients[0]
  303. # complete the connection and wire it up to a fake transport
  304. client = factory.buildProtocol(None)
  305. conn = StringTransport()
  306. client.makeConnection(conn)
  307. # that should have made it send the request to the connection
  308. self.assertRegex(conn.value(), b"^GET /foo/bar")
  309. # Clear the original request data before sending a response
  310. conn.clear()
  311. # Send the HTTP response
  312. client.dataReceived(
  313. b"HTTP/1.1 400 Bad Request\r\n"
  314. b"Content-Type: application/json\r\n"
  315. b"Content-Length: 59\r\n"
  316. b"\r\n"
  317. b'{"errcode":"M_UNRECOGNIZED","error":"Unrecognized request"}'
  318. )
  319. # We should get another request with a trailing slash
  320. self.assertRegex(conn.value(), b"^GET /foo/bar/")
  321. # Send a happy response this time
  322. client.dataReceived(
  323. b"HTTP/1.1 200 OK\r\n"
  324. b"Content-Type: application/json\r\n"
  325. b"Content-Length: 2\r\n"
  326. b"\r\n"
  327. b"{}"
  328. )
  329. # We should get a successful response
  330. r = self.successResultOf(d)
  331. self.assertEqual(r, {})
  332. def test_client_does_not_retry_on_400_plus(self) -> None:
  333. """
  334. Another test for trailing slashes but now test that we don't retry on
  335. trailing slashes on a non-400/M_UNRECOGNIZED response.
  336. See test_client_requires_trailing_slashes() for context.
  337. """
  338. d = defer.ensureDeferred(
  339. self.cl.get_json("testserv:8008", "foo/bar", try_trailing_slash_on_400=True)
  340. )
  341. # Send the request
  342. self.pump()
  343. # there should have been a call to connectTCP
  344. clients = self.reactor.tcpClients
  345. self.assertEqual(len(clients), 1)
  346. (_host, _port, factory, _timeout, _bindAddress) = clients[0]
  347. # complete the connection and wire it up to a fake transport
  348. client = factory.buildProtocol(None)
  349. conn = StringTransport()
  350. client.makeConnection(conn)
  351. # that should have made it send the request to the connection
  352. self.assertRegex(conn.value(), b"^GET /foo/bar")
  353. # Clear the original request data before sending a response
  354. conn.clear()
  355. # Send the HTTP response
  356. client.dataReceived(
  357. b"HTTP/1.1 404 Not Found\r\n"
  358. b"Content-Type: application/json\r\n"
  359. b"Content-Length: 2\r\n"
  360. b"\r\n"
  361. b"{}"
  362. )
  363. # We should not get another request
  364. self.assertEqual(conn.value(), b"")
  365. # We should get a 404 failure response
  366. self.failureResultOf(d)
  367. def test_client_sends_body(self) -> None:
  368. defer.ensureDeferred(
  369. self.cl.post_json(
  370. "testserv:8008", "foo/bar", timeout=10000, data={"a": "b"}
  371. )
  372. )
  373. self.pump()
  374. clients = self.reactor.tcpClients
  375. self.assertEqual(len(clients), 1)
  376. client = clients[0][2].buildProtocol(None)
  377. server = HTTPChannel()
  378. client.makeConnection(FakeTransport(server, self.reactor))
  379. server.makeConnection(FakeTransport(client, self.reactor))
  380. self.pump(0.1)
  381. self.assertEqual(len(server.requests), 1)
  382. request = server.requests[0]
  383. content = request.content.read()
  384. self.assertEqual(content, b'{"a":"b"}')
  385. def test_closes_connection(self) -> None:
  386. """Check that the client closes unused HTTP connections"""
  387. d = defer.ensureDeferred(self.cl.get_json("testserv:8008", "foo/bar"))
  388. self.pump()
  389. # there should have been a call to connectTCP
  390. clients = self.reactor.tcpClients
  391. self.assertEqual(len(clients), 1)
  392. (_host, _port, factory, _timeout, _bindAddress) = clients[0]
  393. # complete the connection and wire it up to a fake transport
  394. client = factory.buildProtocol(None)
  395. conn = StringTransport()
  396. client.makeConnection(conn)
  397. # that should have made it send the request to the connection
  398. self.assertRegex(conn.value(), b"^GET /foo/bar")
  399. # Send the HTTP response
  400. client.dataReceived(
  401. b"HTTP/1.1 200 OK\r\n"
  402. b"Content-Type: application/json\r\n"
  403. b"Content-Length: 2\r\n"
  404. b"\r\n"
  405. b"{}"
  406. )
  407. # We should get a successful response
  408. r = self.successResultOf(d)
  409. self.assertEqual(r, {})
  410. self.assertFalse(conn.disconnecting)
  411. # wait for a while
  412. self.reactor.advance(120)
  413. self.assertTrue(conn.disconnecting)
  414. @parameterized.expand([(b"",), (b"foo",), (b'{"a": Infinity}',)])
  415. def test_json_error(self, return_value: bytes) -> None:
  416. """
  417. Test what happens if invalid JSON is returned from the remote endpoint.
  418. """
  419. test_d = defer.ensureDeferred(self.cl.get_json("testserv:8008", "foo/bar"))
  420. self.pump()
  421. # Nothing happened yet
  422. self.assertNoResult(test_d)
  423. # Make sure treq is trying to connect
  424. clients = self.reactor.tcpClients
  425. self.assertEqual(len(clients), 1)
  426. (host, port, factory, _timeout, _bindAddress) = clients[0]
  427. self.assertEqual(host, "1.2.3.4")
  428. self.assertEqual(port, 8008)
  429. # complete the connection and wire it up to a fake transport
  430. protocol = factory.buildProtocol(None)
  431. transport = StringTransport()
  432. protocol.makeConnection(transport)
  433. # that should have made it send the request to the transport
  434. self.assertRegex(transport.value(), b"^GET /foo/bar")
  435. self.assertRegex(transport.value(), b"Host: testserv:8008")
  436. # Deferred is still without a result
  437. self.assertNoResult(test_d)
  438. # Send it the HTTP response
  439. protocol.dataReceived(
  440. b"HTTP/1.1 200 OK\r\n"
  441. b"Server: Fake\r\n"
  442. b"Content-Type: application/json\r\n"
  443. b"Content-Length: %i\r\n"
  444. b"\r\n"
  445. b"%s" % (len(return_value), return_value)
  446. )
  447. self.pump()
  448. f = self.failureResultOf(test_d)
  449. self.assertIsInstance(f.value, RequestSendFailed)
  450. def test_too_big(self) -> None:
  451. """
  452. Test what happens if a huge response is returned from the remote endpoint.
  453. """
  454. test_d = defer.ensureDeferred(self.cl.get_json("testserv:8008", "foo/bar"))
  455. self.pump()
  456. # Nothing happened yet
  457. self.assertNoResult(test_d)
  458. # Make sure treq is trying to connect
  459. clients = self.reactor.tcpClients
  460. self.assertEqual(len(clients), 1)
  461. (host, port, factory, _timeout, _bindAddress) = clients[0]
  462. self.assertEqual(host, "1.2.3.4")
  463. self.assertEqual(port, 8008)
  464. # complete the connection and wire it up to a fake transport
  465. protocol = factory.buildProtocol(None)
  466. transport = StringTransport()
  467. protocol.makeConnection(transport)
  468. # that should have made it send the request to the transport
  469. self.assertRegex(transport.value(), b"^GET /foo/bar")
  470. self.assertRegex(transport.value(), b"Host: testserv:8008")
  471. # Deferred is still without a result
  472. self.assertNoResult(test_d)
  473. # Send it a huge HTTP response
  474. protocol.dataReceived(
  475. b"HTTP/1.1 200 OK\r\n"
  476. b"Server: Fake\r\n"
  477. b"Content-Type: application/json\r\n"
  478. b"\r\n"
  479. )
  480. self.pump()
  481. # should still be waiting
  482. self.assertNoResult(test_d)
  483. sent = 0
  484. chunk_size = 1024 * 512
  485. while not test_d.called:
  486. protocol.dataReceived(b"a" * chunk_size)
  487. sent += chunk_size
  488. self.assertLessEqual(sent, ByteParser.MAX_RESPONSE_SIZE)
  489. self.assertEqual(sent, ByteParser.MAX_RESPONSE_SIZE)
  490. f = self.failureResultOf(test_d)
  491. self.assertIsInstance(f.value, RequestSendFailed)
  492. self.assertTrue(transport.disconnecting)
  493. def test_build_auth_headers_rejects_falsey_destinations(self) -> None:
  494. with self.assertRaises(ValueError):
  495. self.cl.build_auth_headers(None, b"GET", b"https://example.com")
  496. with self.assertRaises(ValueError):
  497. self.cl.build_auth_headers(b"", b"GET", b"https://example.com")
  498. with self.assertRaises(ValueError):
  499. self.cl.build_auth_headers(
  500. None, b"GET", b"https://example.com", destination_is=b""
  501. )
  502. with self.assertRaises(ValueError):
  503. self.cl.build_auth_headers(
  504. b"", b"GET", b"https://example.com", destination_is=b""
  505. )
  506. @override_config(
  507. {
  508. "federation": {
  509. "client_timeout": "180s",
  510. "max_long_retry_delay": "100s",
  511. "max_short_retry_delay": "7s",
  512. "max_long_retries": 20,
  513. "max_short_retries": 5,
  514. }
  515. }
  516. )
  517. def test_configurable_retry_and_delay_values(self) -> None:
  518. self.assertEqual(self.cl.default_timeout_seconds, 180)
  519. self.assertEqual(self.cl.max_long_retry_delay_seconds, 100)
  520. self.assertEqual(self.cl.max_short_retry_delay_seconds, 7)
  521. self.assertEqual(self.cl.max_long_retries, 20)
  522. self.assertEqual(self.cl.max_short_retries, 5)
  523. class FederationClientProxyTests(BaseMultiWorkerStreamTestCase):
  524. def default_config(self) -> Dict[str, Any]:
  525. conf = super().default_config()
  526. conf["instance_map"] = {
  527. "main": {"host": "testserv", "port": 8765},
  528. "federation_sender": {"host": "testserv", "port": 1001},
  529. }
  530. return conf
  531. @override_config(
  532. {
  533. "outbound_federation_restricted_to": ["federation_sender"],
  534. "worker_replication_secret": "secret",
  535. }
  536. )
  537. def test_proxy_requests_through_federation_sender_worker(self) -> None:
  538. """
  539. Test that all outbound federation requests go through the `federation_sender`
  540. worker
  541. """
  542. # Mock out the `MatrixFederationHttpClient` of the `federation_sender` instance
  543. # so we can act like some remote server responding to requests
  544. mock_client_on_federation_sender = Mock()
  545. mock_agent_on_federation_sender = create_autospec(Agent, spec_set=True)
  546. mock_client_on_federation_sender.agent = mock_agent_on_federation_sender
  547. # Create the `federation_sender` worker
  548. self.make_worker_hs(
  549. "synapse.app.generic_worker",
  550. {"worker_name": "federation_sender"},
  551. federation_http_client=mock_client_on_federation_sender,
  552. )
  553. # Fake `remoteserv:8008` responding to requests
  554. mock_agent_on_federation_sender.request.side_effect = (
  555. lambda *args, **kwargs: defer.succeed(
  556. FakeResponse.json(
  557. payload={
  558. "foo": "bar",
  559. }
  560. )
  561. )
  562. )
  563. # This federation request from the main process should be proxied through the
  564. # `federation_sender` worker off to the remote server
  565. test_request_from_main_process_d = defer.ensureDeferred(
  566. self.hs.get_federation_http_client().get_json("remoteserv:8008", "foo/bar")
  567. )
  568. # Pump the reactor so our deferred goes through the motions
  569. self.pump()
  570. # Make sure that the request was proxied through the `federation_sender` worker
  571. mock_agent_on_federation_sender.request.assert_called_once_with(
  572. b"GET",
  573. b"matrix-federation://remoteserv:8008/foo/bar",
  574. headers=ANY,
  575. bodyProducer=ANY,
  576. )
  577. # Make sure the response is as expected back on the main worker
  578. res = self.successResultOf(test_request_from_main_process_d)
  579. self.assertEqual(res, {"foo": "bar"})
  580. @override_config(
  581. {
  582. "outbound_federation_restricted_to": ["federation_sender"],
  583. "worker_replication_secret": "secret",
  584. }
  585. )
  586. def test_proxy_request_with_network_error_through_federation_sender_worker(
  587. self,
  588. ) -> None:
  589. """
  590. Test that when the outbound federation request fails with a network related
  591. error, a sensible error makes its way back to the main process.
  592. """
  593. # Mock out the `MatrixFederationHttpClient` of the `federation_sender` instance
  594. # so we can act like some remote server responding to requests
  595. mock_client_on_federation_sender = Mock()
  596. mock_agent_on_federation_sender = create_autospec(Agent, spec_set=True)
  597. mock_client_on_federation_sender.agent = mock_agent_on_federation_sender
  598. # Create the `federation_sender` worker
  599. self.make_worker_hs(
  600. "synapse.app.generic_worker",
  601. {"worker_name": "federation_sender"},
  602. federation_http_client=mock_client_on_federation_sender,
  603. )
  604. # Fake `remoteserv:8008` responding to requests
  605. mock_agent_on_federation_sender.request.side_effect = (
  606. lambda *args, **kwargs: defer.fail(ResponseNeverReceived("fake error"))
  607. )
  608. # This federation request from the main process should be proxied through the
  609. # `federation_sender` worker off to the remote server
  610. test_request_from_main_process_d = defer.ensureDeferred(
  611. self.hs.get_federation_http_client().get_json("remoteserv:8008", "foo/bar")
  612. )
  613. # Pump the reactor so our deferred goes through the motions. We pump with 10
  614. # seconds (0.1 * 100) so the `MatrixFederationHttpClient` runs out of retries
  615. # and finally passes along the error response.
  616. self.pump(0.1)
  617. # Make sure that the request was proxied through the `federation_sender` worker
  618. mock_agent_on_federation_sender.request.assert_called_with(
  619. b"GET",
  620. b"matrix-federation://remoteserv:8008/foo/bar",
  621. headers=ANY,
  622. bodyProducer=ANY,
  623. )
  624. # Make sure we get some sort of error back on the main worker
  625. failure_res = self.failureResultOf(test_request_from_main_process_d)
  626. self.assertIsInstance(failure_res.value, RequestSendFailed)
  627. self.assertIsInstance(failure_res.value.inner_exception, HttpResponseException)
  628. self.assertEqual(failure_res.value.inner_exception.code, 502)
  629. @override_config(
  630. {
  631. "outbound_federation_restricted_to": ["federation_sender"],
  632. "worker_replication_secret": "secret",
  633. }
  634. )
  635. def test_proxy_requests_and_discards_hop_by_hop_headers(self) -> None:
  636. """
  637. Test to make sure hop-by-hop headers and addional headers defined in the
  638. `Connection` header are discarded when proxying requests
  639. """
  640. # Mock out the `MatrixFederationHttpClient` of the `federation_sender` instance
  641. # so we can act like some remote server responding to requests
  642. mock_client_on_federation_sender = Mock()
  643. mock_agent_on_federation_sender = create_autospec(Agent, spec_set=True)
  644. mock_client_on_federation_sender.agent = mock_agent_on_federation_sender
  645. # Create the `federation_sender` worker
  646. self.make_worker_hs(
  647. "synapse.app.generic_worker",
  648. {"worker_name": "federation_sender"},
  649. federation_http_client=mock_client_on_federation_sender,
  650. )
  651. # Fake `remoteserv:8008` responding to requests
  652. mock_agent_on_federation_sender.request.side_effect = lambda *args, **kwargs: defer.succeed(
  653. FakeResponse(
  654. code=200,
  655. body=b'{"foo": "bar"}',
  656. headers=Headers(
  657. {
  658. "Content-Type": ["application/json"],
  659. "Connection": ["close, X-Foo, X-Bar"],
  660. # Should be removed because it's defined in the `Connection` header
  661. "X-Foo": ["foo"],
  662. "X-Bar": ["bar"],
  663. # Should be removed because it's a hop-by-hop header
  664. "Proxy-Authorization": "abcdef",
  665. }
  666. ),
  667. )
  668. )
  669. # This federation request from the main process should be proxied through the
  670. # `federation_sender` worker off to the remote server
  671. test_request_from_main_process_d = defer.ensureDeferred(
  672. self.hs.get_federation_http_client().get_json_with_headers(
  673. "remoteserv:8008", "foo/bar"
  674. )
  675. )
  676. # Pump the reactor so our deferred goes through the motions
  677. self.pump()
  678. # Make sure that the request was proxied through the `federation_sender` worker
  679. mock_agent_on_federation_sender.request.assert_called_once_with(
  680. b"GET",
  681. b"matrix-federation://remoteserv:8008/foo/bar",
  682. headers=ANY,
  683. bodyProducer=ANY,
  684. )
  685. res, headers = self.successResultOf(test_request_from_main_process_d)
  686. header_names = set(headers.keys())
  687. # Make sure the response does not include the hop-by-hop headers
  688. self.assertNotIn(b"X-Foo", header_names)
  689. self.assertNotIn(b"X-Bar", header_names)
  690. self.assertNotIn(b"Proxy-Authorization", header_names)
  691. # Make sure the response is as expected back on the main worker
  692. self.assertEqual(res, {"foo": "bar"})
  693. @override_config(
  694. {
  695. "outbound_federation_restricted_to": ["federation_sender"],
  696. # `worker_replication_secret` is set here so that the test setup is able to pass
  697. # but the actual homserver creation test is in the test body below
  698. "worker_replication_secret": "secret",
  699. }
  700. )
  701. def test_not_able_to_proxy_requests_through_federation_sender_worker_when_no_secret_configured(
  702. self,
  703. ) -> None:
  704. """
  705. Test that we aren't able to proxy any outbound federation requests when
  706. `worker_replication_secret` is not configured.
  707. """
  708. with self.assertRaises(ConfigError):
  709. # Create the `federation_sender` worker
  710. self.make_worker_hs(
  711. "synapse.app.generic_worker",
  712. {
  713. "worker_name": "federation_sender",
  714. # Test that we aren't able to proxy any outbound federation requests
  715. # when `worker_replication_secret` is not configured.
  716. "worker_replication_secret": None,
  717. },
  718. )
  719. @override_config(
  720. {
  721. "outbound_federation_restricted_to": ["federation_sender"],
  722. "worker_replication_secret": "secret",
  723. }
  724. )
  725. def test_not_able_to_proxy_requests_through_federation_sender_worker_when_wrong_auth_given(
  726. self,
  727. ) -> None:
  728. """
  729. Test that we aren't able to proxy any outbound federation requests when the
  730. wrong authorization is given.
  731. """
  732. # Mock out the `MatrixFederationHttpClient` of the `federation_sender` instance
  733. # so we can act like some remote server responding to requests
  734. mock_client_on_federation_sender = Mock()
  735. mock_agent_on_federation_sender = create_autospec(Agent, spec_set=True)
  736. mock_client_on_federation_sender.agent = mock_agent_on_federation_sender
  737. # Create the `federation_sender` worker
  738. self.make_worker_hs(
  739. "synapse.app.generic_worker",
  740. {
  741. "worker_name": "federation_sender",
  742. # Test that we aren't able to proxy any outbound federation requests
  743. # when `worker_replication_secret` is wrong.
  744. "worker_replication_secret": "wrong",
  745. },
  746. federation_http_client=mock_client_on_federation_sender,
  747. )
  748. # This federation request from the main process should be proxied through the
  749. # `federation_sender` worker off but will fail here because it's using the wrong
  750. # authorization.
  751. test_request_from_main_process_d = defer.ensureDeferred(
  752. self.hs.get_federation_http_client().get_json("remoteserv:8008", "foo/bar")
  753. )
  754. # Pump the reactor so our deferred goes through the motions. We pump with 10
  755. # seconds (0.1 * 100) so the `MatrixFederationHttpClient` runs out of retries
  756. # and finally passes along the error response.
  757. self.pump(0.1)
  758. # Make sure that the request was *NOT* proxied through the `federation_sender`
  759. # worker
  760. mock_agent_on_federation_sender.request.assert_not_called()
  761. failure_res = self.failureResultOf(test_request_from_main_process_d)
  762. self.assertIsInstance(failure_res.value, HttpResponseException)
  763. self.assertEqual(failure_res.value.code, 401)