test_matrix_federation_agent.py 46 KB

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