1
0

test_matrix_federation_agent.py 44 KB

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