test_matrix_federation_agent.py 44 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242
  1. # -*- coding: utf-8 -*-
  2. # Copyright 2019 New Vector Ltd
  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. import logging
  16. from mock import Mock
  17. import treq
  18. from service_identity import VerificationError
  19. from zope.interface import implementer
  20. from twisted.internet import defer
  21. from twisted.internet._sslverify import ClientTLSOptions, OpenSSLCertificateOptions
  22. from twisted.internet.protocol import Factory
  23. from twisted.protocols.tls import TLSMemoryBIOFactory
  24. from twisted.web._newclient import ResponseNeverReceived
  25. from twisted.web.client import Agent
  26. from twisted.web.http import HTTPChannel
  27. from twisted.web.http_headers import Headers
  28. from twisted.web.iweb import IPolicyForHTTPS
  29. from synapse.config.homeserver import HomeServerConfig
  30. from synapse.crypto.context_factory import ClientTLSOptionsFactory
  31. from synapse.http.federation.matrix_federation_agent import MatrixFederationAgent
  32. from synapse.http.federation.srv_resolver import Server
  33. from synapse.http.federation.well_known_resolver import (
  34. WellKnownResolver,
  35. _cache_period_from_headers,
  36. )
  37. from synapse.logging.context import LoggingContext
  38. from synapse.util.caches.ttlcache import TTLCache
  39. from tests import unittest
  40. from tests.http import TestServerTLSConnectionFactory, get_test_ca_cert_file
  41. from tests.server import FakeTransport, ThreadedMemoryReactorClock
  42. from tests.utils import default_config
  43. logger = logging.getLogger(__name__)
  44. test_server_connection_factory = None
  45. def get_connection_factory():
  46. # this needs to happen once, but not until we are ready to run the first test
  47. global test_server_connection_factory
  48. if test_server_connection_factory is None:
  49. test_server_connection_factory = TestServerTLSConnectionFactory(
  50. sanlist=[
  51. b"DNS:testserv",
  52. b"DNS:target-server",
  53. b"DNS:xn--bcher-kva.com",
  54. b"IP:1.2.3.4",
  55. b"IP:::1",
  56. ]
  57. )
  58. return test_server_connection_factory
  59. class MatrixFederationAgentTests(unittest.TestCase):
  60. def setUp(self):
  61. self.reactor = ThreadedMemoryReactorClock()
  62. self.mock_resolver = Mock()
  63. config_dict = default_config("test", parse=False)
  64. config_dict["federation_custom_ca_list"] = [get_test_ca_cert_file()]
  65. self._config = config = HomeServerConfig()
  66. config.parse_config_dict(config_dict, "", "")
  67. self.tls_factory = ClientTLSOptionsFactory(config)
  68. self.well_known_cache = TTLCache("test_cache", timer=self.reactor.seconds)
  69. self.had_well_known_cache = TTLCache("test_cache", timer=self.reactor.seconds)
  70. self.well_known_resolver = WellKnownResolver(
  71. self.reactor,
  72. Agent(self.reactor, contextFactory=self.tls_factory),
  73. well_known_cache=self.well_known_cache,
  74. had_well_known_cache=self.had_well_known_cache,
  75. )
  76. self.agent = MatrixFederationAgent(
  77. reactor=self.reactor,
  78. tls_client_options_factory=self.tls_factory,
  79. _srv_resolver=self.mock_resolver,
  80. _well_known_resolver=self.well_known_resolver,
  81. )
  82. def _make_connection(self, client_factory, expected_sni):
  83. """Builds a test server, and completes the outgoing client connection
  84. Returns:
  85. HTTPChannel: the test server
  86. """
  87. # build the test server
  88. server_tls_protocol = _build_test_server(get_connection_factory())
  89. # now, tell the client protocol factory to build the client protocol (it will be a
  90. # _WrappingProtocol, around a TLSMemoryBIOProtocol, around an
  91. # HTTP11ClientProtocol) and wire the output of said protocol up to the server via
  92. # a FakeTransport.
  93. #
  94. # Normally this would be done by the TCP socket code in Twisted, but we are
  95. # stubbing that out here.
  96. client_protocol = client_factory.buildProtocol(None)
  97. client_protocol.makeConnection(
  98. FakeTransport(server_tls_protocol, self.reactor, client_protocol)
  99. )
  100. # tell the server tls protocol to send its stuff back to the client, too
  101. server_tls_protocol.makeConnection(
  102. FakeTransport(client_protocol, self.reactor, server_tls_protocol)
  103. )
  104. # grab a hold of the TLS connection, in case it gets torn down
  105. server_tls_connection = server_tls_protocol._tlsConnection
  106. # fish the test server back out of the server-side TLS protocol.
  107. http_protocol = server_tls_protocol.wrappedProtocol
  108. # give the reactor a pump to get the TLS juices flowing.
  109. self.reactor.pump((0.1,))
  110. # check the SNI
  111. server_name = server_tls_connection.get_servername()
  112. self.assertEqual(
  113. server_name,
  114. expected_sni,
  115. "Expected SNI %s but got %s" % (expected_sni, server_name),
  116. )
  117. return http_protocol
  118. @defer.inlineCallbacks
  119. def _make_get_request(self, uri):
  120. """
  121. Sends a simple GET request via the agent, and checks its logcontext management
  122. """
  123. with LoggingContext("one") as context:
  124. fetch_d = self.agent.request(b"GET", uri)
  125. # Nothing happened yet
  126. self.assertNoResult(fetch_d)
  127. # should have reset logcontext to the sentinel
  128. _check_logcontext(LoggingContext.sentinel)
  129. try:
  130. fetch_res = yield fetch_d
  131. return fetch_res
  132. except Exception as e:
  133. logger.info("Fetch of %s failed: %s", uri.decode("ascii"), e)
  134. raise
  135. finally:
  136. _check_logcontext(context)
  137. def _handle_well_known_connection(
  138. self, client_factory, expected_sni, content, response_headers={}
  139. ):
  140. """Handle an outgoing HTTPs connection: wire it up to a server, check that the
  141. request is for a .well-known, and send the response.
  142. Args:
  143. client_factory (IProtocolFactory): outgoing connection
  144. expected_sni (bytes): SNI that we expect the outgoing connection to send
  145. content (bytes): content to send back as the .well-known
  146. Returns:
  147. HTTPChannel: server impl
  148. """
  149. # make the connection for .well-known
  150. well_known_server = self._make_connection(
  151. client_factory, expected_sni=expected_sni
  152. )
  153. # check the .well-known request and send a response
  154. self.assertEqual(len(well_known_server.requests), 1)
  155. request = well_known_server.requests[0]
  156. self._send_well_known_response(request, content, headers=response_headers)
  157. return well_known_server
  158. def _send_well_known_response(self, request, content, headers={}):
  159. """Check that an incoming request looks like a valid .well-known request, and
  160. send back the response.
  161. """
  162. self.assertEqual(request.method, b"GET")
  163. self.assertEqual(request.path, b"/.well-known/matrix/server")
  164. self.assertEqual(request.requestHeaders.getRawHeaders(b"host"), [b"testserv"])
  165. # send back a response
  166. for k, v in headers.items():
  167. request.setHeader(k, v)
  168. request.write(content)
  169. request.finish()
  170. self.reactor.pump((0.1,))
  171. def test_get(self):
  172. """
  173. happy-path test of a GET request with an explicit port
  174. """
  175. self.reactor.lookups["testserv"] = "1.2.3.4"
  176. test_d = self._make_get_request(b"matrix://testserv:8448/foo/bar")
  177. # Nothing happened yet
  178. self.assertNoResult(test_d)
  179. # Make sure treq is trying to connect
  180. clients = self.reactor.tcpClients
  181. self.assertEqual(len(clients), 1)
  182. (host, port, client_factory, _timeout, _bindAddress) = clients[0]
  183. self.assertEqual(host, "1.2.3.4")
  184. self.assertEqual(port, 8448)
  185. # make a test server, and wire up the client
  186. http_server = self._make_connection(client_factory, expected_sni=b"testserv")
  187. self.assertEqual(len(http_server.requests), 1)
  188. request = http_server.requests[0]
  189. self.assertEqual(request.method, b"GET")
  190. self.assertEqual(request.path, b"/foo/bar")
  191. self.assertEqual(
  192. request.requestHeaders.getRawHeaders(b"host"), [b"testserv:8448"]
  193. )
  194. content = request.content.read()
  195. self.assertEqual(content, b"")
  196. # Deferred is still without a result
  197. self.assertNoResult(test_d)
  198. # send the headers
  199. request.responseHeaders.setRawHeaders(b"Content-Type", [b"application/json"])
  200. request.write("")
  201. self.reactor.pump((0.1,))
  202. response = self.successResultOf(test_d)
  203. # that should give us a Response object
  204. self.assertEqual(response.code, 200)
  205. # Send the body
  206. request.write('{ "a": 1 }'.encode("ascii"))
  207. request.finish()
  208. self.reactor.pump((0.1,))
  209. # check it can be read
  210. json = self.successResultOf(treq.json_content(response))
  211. self.assertEqual(json, {"a": 1})
  212. def test_get_ip_address(self):
  213. """
  214. Test the behaviour when the server name contains an explicit IP (with no port)
  215. """
  216. # there will be a getaddrinfo on the IP
  217. self.reactor.lookups["1.2.3.4"] = "1.2.3.4"
  218. test_d = self._make_get_request(b"matrix://1.2.3.4/foo/bar")
  219. # Nothing happened yet
  220. self.assertNoResult(test_d)
  221. # Make sure treq is trying to connect
  222. clients = self.reactor.tcpClients
  223. self.assertEqual(len(clients), 1)
  224. (host, port, client_factory, _timeout, _bindAddress) = clients[0]
  225. self.assertEqual(host, "1.2.3.4")
  226. self.assertEqual(port, 8448)
  227. # make a test server, and wire up the client
  228. http_server = self._make_connection(client_factory, expected_sni=None)
  229. self.assertEqual(len(http_server.requests), 1)
  230. request = http_server.requests[0]
  231. self.assertEqual(request.method, b"GET")
  232. self.assertEqual(request.path, b"/foo/bar")
  233. self.assertEqual(request.requestHeaders.getRawHeaders(b"host"), [b"1.2.3.4"])
  234. # finish the request
  235. request.finish()
  236. self.reactor.pump((0.1,))
  237. self.successResultOf(test_d)
  238. def test_get_ipv6_address(self):
  239. """
  240. Test the behaviour when the server name contains an explicit IPv6 address
  241. (with no port)
  242. """
  243. # there will be a getaddrinfo on the IP
  244. self.reactor.lookups["::1"] = "::1"
  245. test_d = self._make_get_request(b"matrix://[::1]/foo/bar")
  246. # Nothing happened yet
  247. self.assertNoResult(test_d)
  248. # Make sure treq is trying to connect
  249. clients = self.reactor.tcpClients
  250. self.assertEqual(len(clients), 1)
  251. (host, port, client_factory, _timeout, _bindAddress) = clients[0]
  252. self.assertEqual(host, "::1")
  253. self.assertEqual(port, 8448)
  254. # make a test server, and wire up the client
  255. http_server = self._make_connection(client_factory, expected_sni=None)
  256. self.assertEqual(len(http_server.requests), 1)
  257. request = http_server.requests[0]
  258. self.assertEqual(request.method, b"GET")
  259. self.assertEqual(request.path, b"/foo/bar")
  260. self.assertEqual(request.requestHeaders.getRawHeaders(b"host"), [b"[::1]"])
  261. # finish the request
  262. request.finish()
  263. self.reactor.pump((0.1,))
  264. self.successResultOf(test_d)
  265. def test_get_ipv6_address_with_port(self):
  266. """
  267. Test the behaviour when the server name contains an explicit IPv6 address
  268. (with explicit port)
  269. """
  270. # there will be a getaddrinfo on the IP
  271. self.reactor.lookups["::1"] = "::1"
  272. test_d = self._make_get_request(b"matrix://[::1]:80/foo/bar")
  273. # Nothing happened yet
  274. self.assertNoResult(test_d)
  275. # Make sure treq is trying to connect
  276. clients = self.reactor.tcpClients
  277. self.assertEqual(len(clients), 1)
  278. (host, port, client_factory, _timeout, _bindAddress) = clients[0]
  279. self.assertEqual(host, "::1")
  280. self.assertEqual(port, 80)
  281. # make a test server, and wire up the client
  282. http_server = self._make_connection(client_factory, expected_sni=None)
  283. self.assertEqual(len(http_server.requests), 1)
  284. request = http_server.requests[0]
  285. self.assertEqual(request.method, b"GET")
  286. self.assertEqual(request.path, b"/foo/bar")
  287. self.assertEqual(request.requestHeaders.getRawHeaders(b"host"), [b"[::1]:80"])
  288. # finish the request
  289. request.finish()
  290. self.reactor.pump((0.1,))
  291. self.successResultOf(test_d)
  292. def test_get_hostname_bad_cert(self):
  293. """
  294. Test the behaviour when the certificate on the server doesn't match the hostname
  295. """
  296. self.mock_resolver.resolve_service.side_effect = lambda _: []
  297. self.reactor.lookups["testserv1"] = "1.2.3.4"
  298. test_d = self._make_get_request(b"matrix://testserv1/foo/bar")
  299. # Nothing happened yet
  300. self.assertNoResult(test_d)
  301. # No SRV record lookup yet
  302. self.mock_resolver.resolve_service.assert_not_called()
  303. # there should be an attempt to connect on port 443 for the .well-known
  304. clients = self.reactor.tcpClients
  305. self.assertEqual(len(clients), 1)
  306. (host, port, client_factory, _timeout, _bindAddress) = clients[0]
  307. self.assertEqual(host, "1.2.3.4")
  308. self.assertEqual(port, 443)
  309. # fonx the connection
  310. client_factory.clientConnectionFailed(None, Exception("nope"))
  311. # attemptdelay on the hostnameendpoint is 0.3, so takes that long before the
  312. # .well-known request fails.
  313. self.reactor.pump((0.4,))
  314. # now there should be a SRV lookup
  315. self.mock_resolver.resolve_service.assert_called_once_with(
  316. b"_matrix._tcp.testserv1"
  317. )
  318. # we should fall back to a direct connection
  319. self.assertEqual(len(clients), 2)
  320. (host, port, client_factory, _timeout, _bindAddress) = clients[1]
  321. self.assertEqual(host, "1.2.3.4")
  322. self.assertEqual(port, 8448)
  323. # make a test server, and wire up the client
  324. http_server = self._make_connection(client_factory, expected_sni=b"testserv1")
  325. # there should be no requests
  326. self.assertEqual(len(http_server.requests), 0)
  327. # ... and the request should have failed
  328. e = self.failureResultOf(test_d, ResponseNeverReceived)
  329. failure_reason = e.value.reasons[0]
  330. self.assertIsInstance(failure_reason.value, VerificationError)
  331. def test_get_ip_address_bad_cert(self):
  332. """
  333. Test the behaviour when the server name contains an explicit IP, but
  334. the server cert doesn't cover it
  335. """
  336. # there will be a getaddrinfo on the IP
  337. self.reactor.lookups["1.2.3.5"] = "1.2.3.5"
  338. test_d = self._make_get_request(b"matrix://1.2.3.5/foo/bar")
  339. # Nothing happened yet
  340. self.assertNoResult(test_d)
  341. # Make sure treq is trying to connect
  342. clients = self.reactor.tcpClients
  343. self.assertEqual(len(clients), 1)
  344. (host, port, client_factory, _timeout, _bindAddress) = clients[0]
  345. self.assertEqual(host, "1.2.3.5")
  346. self.assertEqual(port, 8448)
  347. # make a test server, and wire up the client
  348. http_server = self._make_connection(client_factory, expected_sni=None)
  349. # there should be no requests
  350. self.assertEqual(len(http_server.requests), 0)
  351. # ... and the request should have failed
  352. e = self.failureResultOf(test_d, ResponseNeverReceived)
  353. failure_reason = e.value.reasons[0]
  354. self.assertIsInstance(failure_reason.value, VerificationError)
  355. def test_get_no_srv_no_well_known(self):
  356. """
  357. Test the behaviour when the server name has no port, no SRV, and no well-known
  358. """
  359. self.mock_resolver.resolve_service.side_effect = lambda _: []
  360. self.reactor.lookups["testserv"] = "1.2.3.4"
  361. test_d = self._make_get_request(b"matrix://testserv/foo/bar")
  362. # Nothing happened yet
  363. self.assertNoResult(test_d)
  364. # No SRV record lookup yet
  365. self.mock_resolver.resolve_service.assert_not_called()
  366. # there should be an attempt to connect on port 443 for the .well-known
  367. clients = self.reactor.tcpClients
  368. self.assertEqual(len(clients), 1)
  369. (host, port, client_factory, _timeout, _bindAddress) = clients[0]
  370. self.assertEqual(host, "1.2.3.4")
  371. self.assertEqual(port, 443)
  372. # fonx the connection
  373. client_factory.clientConnectionFailed(None, Exception("nope"))
  374. # attemptdelay on the hostnameendpoint is 0.3, so takes that long before the
  375. # .well-known request fails.
  376. self.reactor.pump((0.4,))
  377. # now there should be a SRV lookup
  378. self.mock_resolver.resolve_service.assert_called_once_with(
  379. b"_matrix._tcp.testserv"
  380. )
  381. # we should fall back to a direct connection
  382. self.assertEqual(len(clients), 2)
  383. (host, port, client_factory, _timeout, _bindAddress) = clients[1]
  384. self.assertEqual(host, "1.2.3.4")
  385. self.assertEqual(port, 8448)
  386. # make a test server, and wire up the client
  387. http_server = self._make_connection(client_factory, expected_sni=b"testserv")
  388. self.assertEqual(len(http_server.requests), 1)
  389. request = http_server.requests[0]
  390. self.assertEqual(request.method, b"GET")
  391. self.assertEqual(request.path, b"/foo/bar")
  392. self.assertEqual(request.requestHeaders.getRawHeaders(b"host"), [b"testserv"])
  393. # finish the request
  394. request.finish()
  395. self.reactor.pump((0.1,))
  396. self.successResultOf(test_d)
  397. def test_get_well_known(self):
  398. """Test the behaviour when the .well-known delegates elsewhere
  399. """
  400. self.mock_resolver.resolve_service.side_effect = lambda _: []
  401. self.reactor.lookups["testserv"] = "1.2.3.4"
  402. self.reactor.lookups["target-server"] = "1::f"
  403. test_d = self._make_get_request(b"matrix://testserv/foo/bar")
  404. # Nothing happened yet
  405. self.assertNoResult(test_d)
  406. # there should be an attempt to connect on port 443 for the .well-known
  407. clients = self.reactor.tcpClients
  408. self.assertEqual(len(clients), 1)
  409. (host, port, client_factory, _timeout, _bindAddress) = clients[0]
  410. self.assertEqual(host, "1.2.3.4")
  411. self.assertEqual(port, 443)
  412. self._handle_well_known_connection(
  413. client_factory,
  414. expected_sni=b"testserv",
  415. content=b'{ "m.server": "target-server" }',
  416. )
  417. # there should be a SRV lookup
  418. self.mock_resolver.resolve_service.assert_called_once_with(
  419. b"_matrix._tcp.target-server"
  420. )
  421. # now we should get a connection to the target server
  422. self.assertEqual(len(clients), 2)
  423. (host, port, client_factory, _timeout, _bindAddress) = clients[1]
  424. self.assertEqual(host, "1::f")
  425. self.assertEqual(port, 8448)
  426. # make a test server, and wire up the client
  427. http_server = self._make_connection(
  428. client_factory, expected_sni=b"target-server"
  429. )
  430. self.assertEqual(len(http_server.requests), 1)
  431. request = http_server.requests[0]
  432. self.assertEqual(request.method, b"GET")
  433. self.assertEqual(request.path, b"/foo/bar")
  434. self.assertEqual(
  435. request.requestHeaders.getRawHeaders(b"host"), [b"target-server"]
  436. )
  437. # finish the request
  438. request.finish()
  439. self.reactor.pump((0.1,))
  440. self.successResultOf(test_d)
  441. self.assertEqual(self.well_known_cache[b"testserv"], b"target-server")
  442. # check the cache expires
  443. self.reactor.pump((48 * 3600,))
  444. self.well_known_cache.expire()
  445. self.assertNotIn(b"testserv", self.well_known_cache)
  446. def test_get_well_known_redirect(self):
  447. """Test the behaviour when the server name has no port and no SRV record, but
  448. the .well-known has a 300 redirect
  449. """
  450. self.mock_resolver.resolve_service.side_effect = lambda _: []
  451. self.reactor.lookups["testserv"] = "1.2.3.4"
  452. self.reactor.lookups["target-server"] = "1::f"
  453. test_d = self._make_get_request(b"matrix://testserv/foo/bar")
  454. # Nothing happened yet
  455. self.assertNoResult(test_d)
  456. # there should be an attempt to connect on port 443 for the .well-known
  457. clients = self.reactor.tcpClients
  458. self.assertEqual(len(clients), 1)
  459. (host, port, client_factory, _timeout, _bindAddress) = clients.pop()
  460. self.assertEqual(host, "1.2.3.4")
  461. self.assertEqual(port, 443)
  462. redirect_server = self._make_connection(
  463. client_factory, expected_sni=b"testserv"
  464. )
  465. # send a 302 redirect
  466. self.assertEqual(len(redirect_server.requests), 1)
  467. request = redirect_server.requests[0]
  468. request.redirect(b"https://testserv/even_better_known")
  469. request.finish()
  470. self.reactor.pump((0.1,))
  471. # now there should be another connection
  472. clients = self.reactor.tcpClients
  473. self.assertEqual(len(clients), 1)
  474. (host, port, client_factory, _timeout, _bindAddress) = clients.pop()
  475. self.assertEqual(host, "1.2.3.4")
  476. self.assertEqual(port, 443)
  477. well_known_server = self._make_connection(
  478. client_factory, expected_sni=b"testserv"
  479. )
  480. self.assertEqual(len(well_known_server.requests), 1, "No request after 302")
  481. request = well_known_server.requests[0]
  482. self.assertEqual(request.method, b"GET")
  483. self.assertEqual(request.path, b"/even_better_known")
  484. request.write(b'{ "m.server": "target-server" }')
  485. request.finish()
  486. self.reactor.pump((0.1,))
  487. # there should be a SRV lookup
  488. self.mock_resolver.resolve_service.assert_called_once_with(
  489. b"_matrix._tcp.target-server"
  490. )
  491. # now we should get a connection to the target server
  492. self.assertEqual(len(clients), 1)
  493. (host, port, client_factory, _timeout, _bindAddress) = clients[0]
  494. self.assertEqual(host, "1::f")
  495. self.assertEqual(port, 8448)
  496. # make a test server, and wire up the client
  497. http_server = self._make_connection(
  498. client_factory, expected_sni=b"target-server"
  499. )
  500. self.assertEqual(len(http_server.requests), 1)
  501. request = http_server.requests[0]
  502. self.assertEqual(request.method, b"GET")
  503. self.assertEqual(request.path, b"/foo/bar")
  504. self.assertEqual(
  505. request.requestHeaders.getRawHeaders(b"host"), [b"target-server"]
  506. )
  507. # finish the request
  508. request.finish()
  509. self.reactor.pump((0.1,))
  510. self.successResultOf(test_d)
  511. self.assertEqual(self.well_known_cache[b"testserv"], b"target-server")
  512. # check the cache expires
  513. self.reactor.pump((48 * 3600,))
  514. self.well_known_cache.expire()
  515. self.assertNotIn(b"testserv", self.well_known_cache)
  516. def test_get_invalid_well_known(self):
  517. """
  518. Test the behaviour when the server name has an *invalid* well-known (and no SRV)
  519. """
  520. self.mock_resolver.resolve_service.side_effect = lambda _: []
  521. self.reactor.lookups["testserv"] = "1.2.3.4"
  522. test_d = self._make_get_request(b"matrix://testserv/foo/bar")
  523. # Nothing happened yet
  524. self.assertNoResult(test_d)
  525. # No SRV record lookup yet
  526. self.mock_resolver.resolve_service.assert_not_called()
  527. # there should be an attempt to connect on port 443 for the .well-known
  528. clients = self.reactor.tcpClients
  529. self.assertEqual(len(clients), 1)
  530. (host, port, client_factory, _timeout, _bindAddress) = clients.pop()
  531. self.assertEqual(host, "1.2.3.4")
  532. self.assertEqual(port, 443)
  533. self._handle_well_known_connection(
  534. client_factory, expected_sni=b"testserv", content=b"NOT JSON"
  535. )
  536. # now there should be a SRV lookup
  537. self.mock_resolver.resolve_service.assert_called_once_with(
  538. b"_matrix._tcp.testserv"
  539. )
  540. # we should fall back to a direct connection
  541. self.assertEqual(len(clients), 1)
  542. (host, port, client_factory, _timeout, _bindAddress) = clients.pop()
  543. self.assertEqual(host, "1.2.3.4")
  544. self.assertEqual(port, 8448)
  545. # make a test server, and wire up the client
  546. http_server = self._make_connection(client_factory, expected_sni=b"testserv")
  547. self.assertEqual(len(http_server.requests), 1)
  548. request = http_server.requests[0]
  549. self.assertEqual(request.method, b"GET")
  550. self.assertEqual(request.path, b"/foo/bar")
  551. self.assertEqual(request.requestHeaders.getRawHeaders(b"host"), [b"testserv"])
  552. # finish the request
  553. request.finish()
  554. self.reactor.pump((0.1,))
  555. self.successResultOf(test_d)
  556. def test_get_well_known_unsigned_cert(self):
  557. """Test the behaviour when the .well-known server presents a cert
  558. not signed by a CA
  559. """
  560. # we use the same test server as the other tests, but use an agent with
  561. # the config left to the default, which will not trust it (since the
  562. # presented cert is signed by a test CA)
  563. self.mock_resolver.resolve_service.side_effect = lambda _: []
  564. self.reactor.lookups["testserv"] = "1.2.3.4"
  565. config = default_config("test", parse=True)
  566. # Build a new agent and WellKnownResolver with a different tls factory
  567. tls_factory = ClientTLSOptionsFactory(config)
  568. agent = MatrixFederationAgent(
  569. reactor=self.reactor,
  570. tls_client_options_factory=tls_factory,
  571. _srv_resolver=self.mock_resolver,
  572. _well_known_resolver=WellKnownResolver(
  573. self.reactor,
  574. Agent(self.reactor, contextFactory=tls_factory),
  575. well_known_cache=self.well_known_cache,
  576. had_well_known_cache=self.had_well_known_cache,
  577. ),
  578. )
  579. test_d = agent.request(b"GET", b"matrix://testserv/foo/bar")
  580. # Nothing happened yet
  581. self.assertNoResult(test_d)
  582. # there should be an attempt to connect on port 443 for the .well-known
  583. clients = self.reactor.tcpClients
  584. self.assertEqual(len(clients), 1)
  585. (host, port, client_factory, _timeout, _bindAddress) = clients[0]
  586. self.assertEqual(host, "1.2.3.4")
  587. self.assertEqual(port, 443)
  588. http_proto = self._make_connection(client_factory, expected_sni=b"testserv")
  589. # there should be no requests
  590. self.assertEqual(len(http_proto.requests), 0)
  591. # and there should be a SRV lookup instead
  592. self.mock_resolver.resolve_service.assert_called_once_with(
  593. b"_matrix._tcp.testserv"
  594. )
  595. def test_get_hostname_srv(self):
  596. """
  597. Test the behaviour when there is a single SRV record
  598. """
  599. self.mock_resolver.resolve_service.side_effect = lambda _: [
  600. Server(host=b"srvtarget", port=8443)
  601. ]
  602. self.reactor.lookups["srvtarget"] = "1.2.3.4"
  603. test_d = self._make_get_request(b"matrix://testserv/foo/bar")
  604. # Nothing happened yet
  605. self.assertNoResult(test_d)
  606. # the request for a .well-known will have failed with a DNS lookup error.
  607. self.mock_resolver.resolve_service.assert_called_once_with(
  608. b"_matrix._tcp.testserv"
  609. )
  610. # Make sure treq is trying to connect
  611. clients = self.reactor.tcpClients
  612. self.assertEqual(len(clients), 1)
  613. (host, port, client_factory, _timeout, _bindAddress) = clients[0]
  614. self.assertEqual(host, "1.2.3.4")
  615. self.assertEqual(port, 8443)
  616. # make a test server, and wire up the client
  617. http_server = self._make_connection(client_factory, expected_sni=b"testserv")
  618. self.assertEqual(len(http_server.requests), 1)
  619. request = http_server.requests[0]
  620. self.assertEqual(request.method, b"GET")
  621. self.assertEqual(request.path, b"/foo/bar")
  622. self.assertEqual(request.requestHeaders.getRawHeaders(b"host"), [b"testserv"])
  623. # finish the request
  624. request.finish()
  625. self.reactor.pump((0.1,))
  626. self.successResultOf(test_d)
  627. def test_get_well_known_srv(self):
  628. """Test the behaviour when the .well-known redirects to a place where there
  629. is a SRV.
  630. """
  631. self.reactor.lookups["testserv"] = "1.2.3.4"
  632. self.reactor.lookups["srvtarget"] = "5.6.7.8"
  633. test_d = self._make_get_request(b"matrix://testserv/foo/bar")
  634. # Nothing happened yet
  635. self.assertNoResult(test_d)
  636. # there should be an attempt to connect on port 443 for the .well-known
  637. clients = self.reactor.tcpClients
  638. self.assertEqual(len(clients), 1)
  639. (host, port, client_factory, _timeout, _bindAddress) = clients[0]
  640. self.assertEqual(host, "1.2.3.4")
  641. self.assertEqual(port, 443)
  642. self.mock_resolver.resolve_service.side_effect = lambda _: [
  643. Server(host=b"srvtarget", port=8443)
  644. ]
  645. self._handle_well_known_connection(
  646. client_factory,
  647. expected_sni=b"testserv",
  648. content=b'{ "m.server": "target-server" }',
  649. )
  650. # there should be a SRV lookup
  651. self.mock_resolver.resolve_service.assert_called_once_with(
  652. b"_matrix._tcp.target-server"
  653. )
  654. # now we should get a connection to the target of the SRV record
  655. self.assertEqual(len(clients), 2)
  656. (host, port, client_factory, _timeout, _bindAddress) = clients[1]
  657. self.assertEqual(host, "5.6.7.8")
  658. self.assertEqual(port, 8443)
  659. # make a test server, and wire up the client
  660. http_server = self._make_connection(
  661. client_factory, expected_sni=b"target-server"
  662. )
  663. self.assertEqual(len(http_server.requests), 1)
  664. request = http_server.requests[0]
  665. self.assertEqual(request.method, b"GET")
  666. self.assertEqual(request.path, b"/foo/bar")
  667. self.assertEqual(
  668. request.requestHeaders.getRawHeaders(b"host"), [b"target-server"]
  669. )
  670. # finish the request
  671. request.finish()
  672. self.reactor.pump((0.1,))
  673. self.successResultOf(test_d)
  674. def test_idna_servername(self):
  675. """test the behaviour when the server name has idna chars in"""
  676. self.mock_resolver.resolve_service.side_effect = lambda _: []
  677. # the resolver is always called with the IDNA hostname as a native string.
  678. self.reactor.lookups["xn--bcher-kva.com"] = "1.2.3.4"
  679. # this is idna for bücher.com
  680. test_d = self._make_get_request(b"matrix://xn--bcher-kva.com/foo/bar")
  681. # Nothing happened yet
  682. self.assertNoResult(test_d)
  683. # No SRV record lookup yet
  684. self.mock_resolver.resolve_service.assert_not_called()
  685. # there should be an attempt to connect on port 443 for the .well-known
  686. clients = self.reactor.tcpClients
  687. self.assertEqual(len(clients), 1)
  688. (host, port, client_factory, _timeout, _bindAddress) = clients[0]
  689. self.assertEqual(host, "1.2.3.4")
  690. self.assertEqual(port, 443)
  691. # fonx the connection
  692. client_factory.clientConnectionFailed(None, Exception("nope"))
  693. # attemptdelay on the hostnameendpoint is 0.3, so takes that long before the
  694. # .well-known request fails.
  695. self.reactor.pump((0.4,))
  696. # now there should have been a SRV lookup
  697. self.mock_resolver.resolve_service.assert_called_once_with(
  698. b"_matrix._tcp.xn--bcher-kva.com"
  699. )
  700. # We should fall back to port 8448
  701. clients = self.reactor.tcpClients
  702. self.assertEqual(len(clients), 2)
  703. (host, port, client_factory, _timeout, _bindAddress) = clients[1]
  704. self.assertEqual(host, "1.2.3.4")
  705. self.assertEqual(port, 8448)
  706. # make a test server, and wire up the client
  707. http_server = self._make_connection(
  708. client_factory, expected_sni=b"xn--bcher-kva.com"
  709. )
  710. self.assertEqual(len(http_server.requests), 1)
  711. request = http_server.requests[0]
  712. self.assertEqual(request.method, b"GET")
  713. self.assertEqual(request.path, b"/foo/bar")
  714. self.assertEqual(
  715. request.requestHeaders.getRawHeaders(b"host"), [b"xn--bcher-kva.com"]
  716. )
  717. # finish the request
  718. request.finish()
  719. self.reactor.pump((0.1,))
  720. self.successResultOf(test_d)
  721. def test_idna_srv_target(self):
  722. """test the behaviour when the target of a SRV record has idna chars"""
  723. self.mock_resolver.resolve_service.side_effect = lambda _: [
  724. Server(host=b"xn--trget-3qa.com", port=8443) # târget.com
  725. ]
  726. self.reactor.lookups["xn--trget-3qa.com"] = "1.2.3.4"
  727. test_d = self._make_get_request(b"matrix://xn--bcher-kva.com/foo/bar")
  728. # Nothing happened yet
  729. self.assertNoResult(test_d)
  730. self.mock_resolver.resolve_service.assert_called_once_with(
  731. b"_matrix._tcp.xn--bcher-kva.com"
  732. )
  733. # Make sure treq is trying to connect
  734. clients = self.reactor.tcpClients
  735. self.assertEqual(len(clients), 1)
  736. (host, port, client_factory, _timeout, _bindAddress) = clients[0]
  737. self.assertEqual(host, "1.2.3.4")
  738. self.assertEqual(port, 8443)
  739. # make a test server, and wire up the client
  740. http_server = self._make_connection(
  741. client_factory, expected_sni=b"xn--bcher-kva.com"
  742. )
  743. self.assertEqual(len(http_server.requests), 1)
  744. request = http_server.requests[0]
  745. self.assertEqual(request.method, b"GET")
  746. self.assertEqual(request.path, b"/foo/bar")
  747. self.assertEqual(
  748. request.requestHeaders.getRawHeaders(b"host"), [b"xn--bcher-kva.com"]
  749. )
  750. # finish the request
  751. request.finish()
  752. self.reactor.pump((0.1,))
  753. self.successResultOf(test_d)
  754. def test_well_known_cache(self):
  755. self.reactor.lookups["testserv"] = "1.2.3.4"
  756. fetch_d = self.well_known_resolver.get_well_known(b"testserv")
  757. # there should be an attempt to connect on port 443 for the .well-known
  758. clients = self.reactor.tcpClients
  759. self.assertEqual(len(clients), 1)
  760. (host, port, client_factory, _timeout, _bindAddress) = clients.pop(0)
  761. self.assertEqual(host, "1.2.3.4")
  762. self.assertEqual(port, 443)
  763. well_known_server = self._handle_well_known_connection(
  764. client_factory,
  765. expected_sni=b"testserv",
  766. response_headers={b"Cache-Control": b"max-age=1000"},
  767. content=b'{ "m.server": "target-server" }',
  768. )
  769. r = self.successResultOf(fetch_d)
  770. self.assertEqual(r.delegated_server, b"target-server")
  771. # close the tcp connection
  772. well_known_server.loseConnection()
  773. # repeat the request: it should hit the cache
  774. fetch_d = self.well_known_resolver.get_well_known(b"testserv")
  775. r = self.successResultOf(fetch_d)
  776. self.assertEqual(r.delegated_server, b"target-server")
  777. # expire the cache
  778. self.reactor.pump((1000.0,))
  779. # now it should connect again
  780. fetch_d = self.well_known_resolver.get_well_known(b"testserv")
  781. self.assertEqual(len(clients), 1)
  782. (host, port, client_factory, _timeout, _bindAddress) = clients.pop(0)
  783. self.assertEqual(host, "1.2.3.4")
  784. self.assertEqual(port, 443)
  785. self._handle_well_known_connection(
  786. client_factory,
  787. expected_sni=b"testserv",
  788. content=b'{ "m.server": "other-server" }',
  789. )
  790. r = self.successResultOf(fetch_d)
  791. self.assertEqual(r.delegated_server, b"other-server")
  792. def test_well_known_cache_with_temp_failure(self):
  793. """Test that we refetch well-known before the cache expires, and that
  794. it ignores transient errors.
  795. """
  796. self.reactor.lookups["testserv"] = "1.2.3.4"
  797. fetch_d = self.well_known_resolver.get_well_known(b"testserv")
  798. # there should be an attempt to connect on port 443 for the .well-known
  799. clients = self.reactor.tcpClients
  800. self.assertEqual(len(clients), 1)
  801. (host, port, client_factory, _timeout, _bindAddress) = clients.pop(0)
  802. self.assertEqual(host, "1.2.3.4")
  803. self.assertEqual(port, 443)
  804. well_known_server = self._handle_well_known_connection(
  805. client_factory,
  806. expected_sni=b"testserv",
  807. response_headers={b"Cache-Control": b"max-age=1000"},
  808. content=b'{ "m.server": "target-server" }',
  809. )
  810. r = self.successResultOf(fetch_d)
  811. self.assertEqual(r.delegated_server, b"target-server")
  812. # close the tcp connection
  813. well_known_server.loseConnection()
  814. # Get close to the cache expiry, this will cause the resolver to do
  815. # another lookup.
  816. self.reactor.pump((900.0,))
  817. fetch_d = self.well_known_resolver.get_well_known(b"testserv")
  818. # The resolver may retry a few times, so fonx all requests that come along
  819. attempts = 0
  820. while self.reactor.tcpClients:
  821. clients = self.reactor.tcpClients
  822. (host, port, client_factory, _timeout, _bindAddress) = clients.pop(0)
  823. attempts += 1
  824. # fonx the connection attempt, this will be treated as a temporary
  825. # failure.
  826. client_factory.clientConnectionFailed(None, Exception("nope"))
  827. # There's a few sleeps involved, so we have to pump the reactor a
  828. # bit.
  829. self.reactor.pump((1.0, 1.0))
  830. # We expect to see more than one attempt as there was previously a valid
  831. # well known.
  832. self.assertGreater(attempts, 1)
  833. # Resolver should return cached value, despite the lookup failing.
  834. r = self.successResultOf(fetch_d)
  835. self.assertEqual(r.delegated_server, b"target-server")
  836. # Expire both caches and repeat the request
  837. self.reactor.pump((10000.0,))
  838. # Repated the request, this time it should fail if the lookup fails.
  839. fetch_d = self.well_known_resolver.get_well_known(b"testserv")
  840. clients = self.reactor.tcpClients
  841. (host, port, client_factory, _timeout, _bindAddress) = clients.pop(0)
  842. client_factory.clientConnectionFailed(None, Exception("nope"))
  843. self.reactor.pump((0.4,))
  844. r = self.successResultOf(fetch_d)
  845. self.assertEqual(r.delegated_server, None)
  846. def test_srv_fallbacks(self):
  847. """Test that other SRV results are tried if the first one fails.
  848. """
  849. self.mock_resolver.resolve_service.side_effect = lambda _: [
  850. Server(host=b"target.com", port=8443),
  851. Server(host=b"target.com", port=8444),
  852. ]
  853. self.reactor.lookups["target.com"] = "1.2.3.4"
  854. test_d = self._make_get_request(b"matrix://testserv/foo/bar")
  855. # Nothing happened yet
  856. self.assertNoResult(test_d)
  857. self.mock_resolver.resolve_service.assert_called_once_with(
  858. b"_matrix._tcp.testserv"
  859. )
  860. # We should see an attempt to connect to the first server
  861. clients = self.reactor.tcpClients
  862. self.assertEqual(len(clients), 1)
  863. (host, port, client_factory, _timeout, _bindAddress) = clients.pop(0)
  864. self.assertEqual(host, "1.2.3.4")
  865. self.assertEqual(port, 8443)
  866. # Fonx the connection
  867. client_factory.clientConnectionFailed(None, Exception("nope"))
  868. # There's a 300ms delay in HostnameEndpoint
  869. self.reactor.pump((0.4,))
  870. # Hasn't failed yet
  871. self.assertNoResult(test_d)
  872. # We shouldnow see an attempt to connect to the second server
  873. clients = self.reactor.tcpClients
  874. self.assertEqual(len(clients), 1)
  875. (host, port, client_factory, _timeout, _bindAddress) = clients.pop(0)
  876. self.assertEqual(host, "1.2.3.4")
  877. self.assertEqual(port, 8444)
  878. # make a test server, and wire up the client
  879. http_server = self._make_connection(client_factory, expected_sni=b"testserv")
  880. self.assertEqual(len(http_server.requests), 1)
  881. request = http_server.requests[0]
  882. self.assertEqual(request.method, b"GET")
  883. self.assertEqual(request.path, b"/foo/bar")
  884. self.assertEqual(request.requestHeaders.getRawHeaders(b"host"), [b"testserv"])
  885. # finish the request
  886. request.finish()
  887. self.reactor.pump((0.1,))
  888. self.successResultOf(test_d)
  889. class TestCachePeriodFromHeaders(unittest.TestCase):
  890. def test_cache_control(self):
  891. # uppercase
  892. self.assertEqual(
  893. _cache_period_from_headers(
  894. Headers({b"Cache-Control": [b"foo, Max-Age = 100, bar"]})
  895. ),
  896. 100,
  897. )
  898. # missing value
  899. self.assertIsNone(
  900. _cache_period_from_headers(Headers({b"Cache-Control": [b"max-age=, bar"]}))
  901. )
  902. # hackernews: bogus due to semicolon
  903. self.assertIsNone(
  904. _cache_period_from_headers(
  905. Headers({b"Cache-Control": [b"private; max-age=0"]})
  906. )
  907. )
  908. # github
  909. self.assertEqual(
  910. _cache_period_from_headers(
  911. Headers({b"Cache-Control": [b"max-age=0, private, must-revalidate"]})
  912. ),
  913. 0,
  914. )
  915. # google
  916. self.assertEqual(
  917. _cache_period_from_headers(
  918. Headers({b"cache-control": [b"private, max-age=0"]})
  919. ),
  920. 0,
  921. )
  922. def test_expires(self):
  923. self.assertEqual(
  924. _cache_period_from_headers(
  925. Headers({b"Expires": [b"Wed, 30 Jan 2019 07:35:33 GMT"]}),
  926. time_now=lambda: 1548833700,
  927. ),
  928. 33,
  929. )
  930. # cache-control overrides expires
  931. self.assertEqual(
  932. _cache_period_from_headers(
  933. Headers(
  934. {
  935. b"cache-control": [b"max-age=10"],
  936. b"Expires": [b"Wed, 30 Jan 2019 07:35:33 GMT"],
  937. }
  938. ),
  939. time_now=lambda: 1548833700,
  940. ),
  941. 10,
  942. )
  943. # invalid expires means immediate expiry
  944. self.assertEqual(_cache_period_from_headers(Headers({b"Expires": [b"0"]})), 0)
  945. def _check_logcontext(context):
  946. current = LoggingContext.current_context()
  947. if current is not context:
  948. raise AssertionError("Expected logcontext %s but was %s" % (context, current))
  949. def _build_test_server(connection_creator):
  950. """Construct a test server
  951. This builds an HTTP channel, wrapped with a TLSMemoryBIOProtocol
  952. Args:
  953. connection_creator (IOpenSSLServerConnectionCreator): thing to build
  954. SSL connections
  955. sanlist (list[bytes]): list of the SAN entries for the cert returned
  956. by the server
  957. Returns:
  958. TLSMemoryBIOProtocol
  959. """
  960. server_factory = Factory.forProtocol(HTTPChannel)
  961. # Request.finish expects the factory to have a 'log' method.
  962. server_factory.log = _log_request
  963. server_tls_factory = TLSMemoryBIOFactory(
  964. connection_creator, isClient=False, wrappedFactory=server_factory
  965. )
  966. return server_tls_factory.buildProtocol(None)
  967. def _log_request(request):
  968. """Implements Factory.log, which is expected by Request.finish"""
  969. logger.info("Completed request %s", request)
  970. @implementer(IPolicyForHTTPS)
  971. class TrustingTLSPolicyForHTTPS(object):
  972. """An IPolicyForHTTPS which checks that the certificate belongs to the
  973. right server, but doesn't check the certificate chain."""
  974. def creatorForNetloc(self, hostname, port):
  975. certificateOptions = OpenSSLCertificateOptions()
  976. return ClientTLSOptions(hostname, certificateOptions.getContext())