123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464 |
- # -*- coding: utf-8 -*-
- # Copyright 2019 The Matrix.org Foundation C.I.C.
- #
- # Licensed under the Apache License, Version 2.0 (the "License");
- # you may not use this file except in compliance with the License.
- # You may obtain a copy of the License at
- #
- # http://www.apache.org/licenses/LICENSE-2.0
- #
- # Unless required by applicable law or agreed to in writing, software
- # distributed under the License is distributed on an "AS IS" BASIS,
- # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- # See the License for the specific language governing permissions and
- # limitations under the License.
- import logging
- import treq
- from netaddr import IPSet
- from twisted.internet import interfaces # noqa: F401
- from twisted.internet.protocol import Factory
- from twisted.protocols.tls import TLSMemoryBIOFactory
- from twisted.web.http import HTTPChannel
- from synapse.http.client import BlacklistingReactorWrapper
- from synapse.http.proxyagent import ProxyAgent
- from tests.http import TestServerTLSConnectionFactory, get_test_https_policy
- from tests.server import FakeTransport, ThreadedMemoryReactorClock
- from tests.unittest import TestCase
- logger = logging.getLogger(__name__)
- HTTPFactory = Factory.forProtocol(HTTPChannel)
- class MatrixFederationAgentTests(TestCase):
- def setUp(self):
- self.reactor = ThreadedMemoryReactorClock()
- def _make_connection(
- self, client_factory, server_factory, ssl=False, expected_sni=None
- ):
- """Builds a test server, and completes the outgoing client connection
- Args:
- client_factory (interfaces.IProtocolFactory): the the factory that the
- application is trying to use to make the outbound connection. We will
- invoke it to build the client Protocol
- server_factory (interfaces.IProtocolFactory): a factory to build the
- server-side protocol
- ssl (bool): If true, we will expect an ssl connection and wrap
- server_factory with a TLSMemoryBIOFactory
- expected_sni (bytes|None): the expected SNI value
- Returns:
- IProtocol: the server Protocol returned by server_factory
- """
- if ssl:
- server_factory = _wrap_server_factory_for_tls(server_factory)
- server_protocol = server_factory.buildProtocol(None)
- # now, tell the client protocol factory to build the client protocol,
- # and wire the output of said protocol up to the server via
- # a FakeTransport.
- #
- # Normally this would be done by the TCP socket code in Twisted, but we are
- # stubbing that out here.
- client_protocol = client_factory.buildProtocol(None)
- client_protocol.makeConnection(
- FakeTransport(server_protocol, self.reactor, client_protocol)
- )
- # tell the server protocol to send its stuff back to the client, too
- server_protocol.makeConnection(
- FakeTransport(client_protocol, self.reactor, server_protocol)
- )
- if ssl:
- http_protocol = server_protocol.wrappedProtocol
- tls_connection = server_protocol._tlsConnection
- else:
- http_protocol = server_protocol
- tls_connection = None
- # give the reactor a pump to get the TLS juices flowing (if needed)
- self.reactor.advance(0)
- if expected_sni is not None:
- server_name = tls_connection.get_servername()
- self.assertEqual(
- server_name,
- expected_sni,
- "Expected SNI %s but got %s" % (expected_sni, server_name),
- )
- return http_protocol
- def test_http_request(self):
- agent = ProxyAgent(self.reactor)
- self.reactor.lookups["test.com"] = "1.2.3.4"
- d = agent.request(b"GET", b"http://test.com")
- # there should be a pending TCP connection
- clients = self.reactor.tcpClients
- self.assertEqual(len(clients), 1)
- (host, port, client_factory, _timeout, _bindAddress) = clients[0]
- self.assertEqual(host, "1.2.3.4")
- self.assertEqual(port, 80)
- # make a test server, and wire up the client
- http_server = self._make_connection(
- client_factory, _get_test_protocol_factory()
- )
- # the FakeTransport is async, so we need to pump the reactor
- self.reactor.advance(0)
- # now there should be a pending request
- self.assertEqual(len(http_server.requests), 1)
- request = http_server.requests[0]
- self.assertEqual(request.method, b"GET")
- self.assertEqual(request.path, b"/")
- self.assertEqual(request.requestHeaders.getRawHeaders(b"host"), [b"test.com"])
- request.write(b"result")
- request.finish()
- self.reactor.advance(0)
- resp = self.successResultOf(d)
- body = self.successResultOf(treq.content(resp))
- self.assertEqual(body, b"result")
- def test_https_request(self):
- agent = ProxyAgent(self.reactor, contextFactory=get_test_https_policy())
- self.reactor.lookups["test.com"] = "1.2.3.4"
- d = agent.request(b"GET", b"https://test.com/abc")
- # there should be a pending TCP connection
- clients = self.reactor.tcpClients
- self.assertEqual(len(clients), 1)
- (host, port, client_factory, _timeout, _bindAddress) = clients[0]
- self.assertEqual(host, "1.2.3.4")
- self.assertEqual(port, 443)
- # make a test server, and wire up the client
- http_server = self._make_connection(
- client_factory,
- _get_test_protocol_factory(),
- ssl=True,
- expected_sni=b"test.com",
- )
- # the FakeTransport is async, so we need to pump the reactor
- self.reactor.advance(0)
- # now there should be a pending request
- self.assertEqual(len(http_server.requests), 1)
- request = http_server.requests[0]
- self.assertEqual(request.method, b"GET")
- self.assertEqual(request.path, b"/abc")
- self.assertEqual(request.requestHeaders.getRawHeaders(b"host"), [b"test.com"])
- request.write(b"result")
- request.finish()
- self.reactor.advance(0)
- resp = self.successResultOf(d)
- body = self.successResultOf(treq.content(resp))
- self.assertEqual(body, b"result")
- def test_http_request_via_proxy(self):
- agent = ProxyAgent(self.reactor, http_proxy=b"proxy.com:8888")
- self.reactor.lookups["proxy.com"] = "1.2.3.5"
- d = agent.request(b"GET", b"http://test.com")
- # there should be a pending TCP connection
- clients = self.reactor.tcpClients
- self.assertEqual(len(clients), 1)
- (host, port, client_factory, _timeout, _bindAddress) = clients[0]
- self.assertEqual(host, "1.2.3.5")
- self.assertEqual(port, 8888)
- # make a test server, and wire up the client
- http_server = self._make_connection(
- client_factory, _get_test_protocol_factory()
- )
- # the FakeTransport is async, so we need to pump the reactor
- self.reactor.advance(0)
- # now there should be a pending request
- self.assertEqual(len(http_server.requests), 1)
- request = http_server.requests[0]
- self.assertEqual(request.method, b"GET")
- self.assertEqual(request.path, b"http://test.com")
- self.assertEqual(request.requestHeaders.getRawHeaders(b"host"), [b"test.com"])
- request.write(b"result")
- request.finish()
- self.reactor.advance(0)
- resp = self.successResultOf(d)
- body = self.successResultOf(treq.content(resp))
- self.assertEqual(body, b"result")
- def test_https_request_via_proxy(self):
- agent = ProxyAgent(
- self.reactor,
- contextFactory=get_test_https_policy(),
- https_proxy=b"proxy.com",
- )
- self.reactor.lookups["proxy.com"] = "1.2.3.5"
- d = agent.request(b"GET", b"https://test.com/abc")
- # there should be a pending TCP connection
- clients = self.reactor.tcpClients
- self.assertEqual(len(clients), 1)
- (host, port, client_factory, _timeout, _bindAddress) = clients[0]
- self.assertEqual(host, "1.2.3.5")
- self.assertEqual(port, 1080)
- # make a test HTTP server, and wire up the client
- proxy_server = self._make_connection(
- client_factory, _get_test_protocol_factory()
- )
- # fish the transports back out so that we can do the old switcheroo
- s2c_transport = proxy_server.transport
- client_protocol = s2c_transport.other
- c2s_transport = client_protocol.transport
- # the FakeTransport is async, so we need to pump the reactor
- self.reactor.advance(0)
- # now there should be a pending CONNECT request
- self.assertEqual(len(proxy_server.requests), 1)
- request = proxy_server.requests[0]
- self.assertEqual(request.method, b"CONNECT")
- self.assertEqual(request.path, b"test.com:443")
- # tell the proxy server not to close the connection
- proxy_server.persistent = True
- # this just stops the http Request trying to do a chunked response
- # request.setHeader(b"Content-Length", b"0")
- request.finish()
- # now we can replace the proxy channel with a new, SSL-wrapped HTTP channel
- ssl_factory = _wrap_server_factory_for_tls(_get_test_protocol_factory())
- ssl_protocol = ssl_factory.buildProtocol(None)
- http_server = ssl_protocol.wrappedProtocol
- ssl_protocol.makeConnection(
- FakeTransport(client_protocol, self.reactor, ssl_protocol)
- )
- c2s_transport.other = ssl_protocol
- self.reactor.advance(0)
- server_name = ssl_protocol._tlsConnection.get_servername()
- expected_sni = b"test.com"
- self.assertEqual(
- server_name,
- expected_sni,
- "Expected SNI %s but got %s" % (expected_sni, server_name),
- )
- # now there should be a pending request
- self.assertEqual(len(http_server.requests), 1)
- request = http_server.requests[0]
- self.assertEqual(request.method, b"GET")
- self.assertEqual(request.path, b"/abc")
- self.assertEqual(request.requestHeaders.getRawHeaders(b"host"), [b"test.com"])
- request.write(b"result")
- request.finish()
- self.reactor.advance(0)
- resp = self.successResultOf(d)
- body = self.successResultOf(treq.content(resp))
- self.assertEqual(body, b"result")
- def test_http_request_via_proxy_with_blacklist(self):
- # The blacklist includes the configured proxy IP.
- agent = ProxyAgent(
- BlacklistingReactorWrapper(
- self.reactor, ip_whitelist=None, ip_blacklist=IPSet(["1.0.0.0/8"])
- ),
- self.reactor,
- http_proxy=b"proxy.com:8888",
- )
- self.reactor.lookups["proxy.com"] = "1.2.3.5"
- d = agent.request(b"GET", b"http://test.com")
- # there should be a pending TCP connection
- clients = self.reactor.tcpClients
- self.assertEqual(len(clients), 1)
- (host, port, client_factory, _timeout, _bindAddress) = clients[0]
- self.assertEqual(host, "1.2.3.5")
- self.assertEqual(port, 8888)
- # make a test server, and wire up the client
- http_server = self._make_connection(
- client_factory, _get_test_protocol_factory()
- )
- # the FakeTransport is async, so we need to pump the reactor
- self.reactor.advance(0)
- # now there should be a pending request
- self.assertEqual(len(http_server.requests), 1)
- request = http_server.requests[0]
- self.assertEqual(request.method, b"GET")
- self.assertEqual(request.path, b"http://test.com")
- self.assertEqual(request.requestHeaders.getRawHeaders(b"host"), [b"test.com"])
- request.write(b"result")
- request.finish()
- self.reactor.advance(0)
- resp = self.successResultOf(d)
- body = self.successResultOf(treq.content(resp))
- self.assertEqual(body, b"result")
- def test_https_request_via_proxy_with_blacklist(self):
- # The blacklist includes the configured proxy IP.
- agent = ProxyAgent(
- BlacklistingReactorWrapper(
- self.reactor, ip_whitelist=None, ip_blacklist=IPSet(["1.0.0.0/8"])
- ),
- self.reactor,
- contextFactory=get_test_https_policy(),
- https_proxy=b"proxy.com",
- )
- self.reactor.lookups["proxy.com"] = "1.2.3.5"
- d = agent.request(b"GET", b"https://test.com/abc")
- # there should be a pending TCP connection
- clients = self.reactor.tcpClients
- self.assertEqual(len(clients), 1)
- (host, port, client_factory, _timeout, _bindAddress) = clients[0]
- self.assertEqual(host, "1.2.3.5")
- self.assertEqual(port, 1080)
- # make a test HTTP server, and wire up the client
- proxy_server = self._make_connection(
- client_factory, _get_test_protocol_factory()
- )
- # fish the transports back out so that we can do the old switcheroo
- s2c_transport = proxy_server.transport
- client_protocol = s2c_transport.other
- c2s_transport = client_protocol.transport
- # the FakeTransport is async, so we need to pump the reactor
- self.reactor.advance(0)
- # now there should be a pending CONNECT request
- self.assertEqual(len(proxy_server.requests), 1)
- request = proxy_server.requests[0]
- self.assertEqual(request.method, b"CONNECT")
- self.assertEqual(request.path, b"test.com:443")
- # tell the proxy server not to close the connection
- proxy_server.persistent = True
- # this just stops the http Request trying to do a chunked response
- # request.setHeader(b"Content-Length", b"0")
- request.finish()
- # now we can replace the proxy channel with a new, SSL-wrapped HTTP channel
- ssl_factory = _wrap_server_factory_for_tls(_get_test_protocol_factory())
- ssl_protocol = ssl_factory.buildProtocol(None)
- http_server = ssl_protocol.wrappedProtocol
- ssl_protocol.makeConnection(
- FakeTransport(client_protocol, self.reactor, ssl_protocol)
- )
- c2s_transport.other = ssl_protocol
- self.reactor.advance(0)
- server_name = ssl_protocol._tlsConnection.get_servername()
- expected_sni = b"test.com"
- self.assertEqual(
- server_name,
- expected_sni,
- "Expected SNI %s but got %s" % (expected_sni, server_name),
- )
- # now there should be a pending request
- self.assertEqual(len(http_server.requests), 1)
- request = http_server.requests[0]
- self.assertEqual(request.method, b"GET")
- self.assertEqual(request.path, b"/abc")
- self.assertEqual(request.requestHeaders.getRawHeaders(b"host"), [b"test.com"])
- request.write(b"result")
- request.finish()
- self.reactor.advance(0)
- resp = self.successResultOf(d)
- body = self.successResultOf(treq.content(resp))
- self.assertEqual(body, b"result")
- def _wrap_server_factory_for_tls(factory, sanlist=None):
- """Wrap an existing Protocol Factory with a test TLSMemoryBIOFactory
- The resultant factory will create a TLS server which presents a certificate
- signed by our test CA, valid for the domains in `sanlist`
- Args:
- factory (interfaces.IProtocolFactory): protocol factory to wrap
- sanlist (iterable[bytes]): list of domains the cert should be valid for
- Returns:
- interfaces.IProtocolFactory
- """
- if sanlist is None:
- sanlist = [b"DNS:test.com"]
- connection_creator = TestServerTLSConnectionFactory(sanlist=sanlist)
- return TLSMemoryBIOFactory(
- connection_creator, isClient=False, wrappedFactory=factory
- )
- def _get_test_protocol_factory():
- """Get a protocol Factory which will build an HTTPChannel
- Returns:
- interfaces.IProtocolFactory
- """
- server_factory = Factory.forProtocol(HTTPChannel)
- # Request.finish expects the factory to have a 'log' method.
- server_factory.log = _log_request
- return server_factory
- def _log_request(request):
- """Implements Factory.log, which is expected by Request.finish"""
- logger.info("Completed request %s", request)
|