Scrapy, a fast high-level web crawling & scraping framework for Python.
Support HTTPS proxies with Twisted (#7776)
Adrian48590c105d48
diff --git a/docs/topics/download-handlers.rst b/docs/topics/download-handlers.rstindex 7e7cdaf9b..e3bb83a71 100644--- a/docs/topics/download-handlers.rst+++ b/docs/topics/download-handlers.rst@@ -389,8 +389,6 @@ Other limitations:- IPv6 support requires setting :setting:`TWISTED_DNS_RESOLVER`to ``scrapy.resolver.CachingHostnameResolver``.-- HTTPS proxies to HTTPS destinations are not supported.-- A ``Content-Length`` request header is sent in addition to the one builtfrom the request body, and most servers reject requests with two.diff --git a/docs/topics/downloader-middleware.rst b/docs/topics/downloader-middleware.rstindex 2668ed03d..195b939f3 100644--- a/docs/topics/downloader-middleware.rst+++ b/docs/topics/downloader-middleware.rst@@ -843,12 +843,8 @@ HttpProxyMiddleware.. note::Usually a proxy URL uses the ``http://`` scheme. More rarely, it uses the- ``https://`` one. While both kinds of proxy URLs can be used with both HTTP- and HTTPS destination URLs, the specifics of the network exchange are- different for all 4 cases and it's possible that HTTPS proxies are fully or- partially unsupported by a given download handler. Currently,- :class:`~scrapy.core.downloader.handlers.http11.HTTP11DownloadHandler`- supports HTTPS proxies only for HTTP destinations.+ ``https://`` one. Both kinds of proxy URLs can be used with both HTTP and+ HTTPS destination URLs... note::diff --git a/scrapy/core/downloader/handlers/http11.py b/scrapy/core/downloader/handlers/http11.pyindex c5a1649b9..591957521 100644--- a/scrapy/core/downloader/handlers/http11.py+++ b/scrapy/core/downloader/handlers/http11.py@@ -15,9 +15,13 @@ from urllib.parse import urldefragfrom twisted.internet import sslfrom twisted.internet.defer import Deferred, succeed-from twisted.internet.endpoints import HostnameEndpoint, TCP6ClientEndpoint+from twisted.internet.endpoints import (+ HostnameEndpoint,+ TCP6ClientEndpoint,+ wrapClientTLS,+)from twisted.internet.interfaces import IStreamClientEndpoint-from twisted.internet.protocol import Factory, Protocol, connectionDone+from twisted.internet.protocol import ClientFactory, Factory, Protocol, connectionDonefrom twisted.python.failure import Failurefrom twisted.web._newclient import (HEADER,@@ -74,7 +78,7 @@ if TYPE_CHECKING:from collections.abc import Callablefrom twisted.internet.base import ReactorBase- from twisted.internet.interfaces import IAddress, IConsumer+ from twisted.internet.interfaces import IAddress, IConsumer, IProtocolfrom twisted.web._newclient import Request as TxRequestfrom scrapy.crawler import Crawler@@ -358,14 +362,15 @@ def _is_ipv6_literal(host: str) -> bool:return False-@implementer(IStreamClientEndpoint)-class _TunnelingEndpoint:- """An endpoint that tunnels through proxies to allow HTTPS downloads. To- accomplish that, this endpoint sends an HTTP CONNECT to the proxy.- The HTTP CONNECT is always sent when using this endpoint, I think this could- be improved as the CONNECT will be redundant if the connection associated- with this endpoint comes from the pool and a CONNECT has already been issued- for it.+class _TunnelProtocol(Protocol):+ """Sends an HTTP CONNECT request to a proxy and, once the tunnel is open,+ hands the connection over to a wrapped protocol.++ It plays the role of Twisted's ``_WrappingProtocol`` but performs a CONNECT+ handshake before connecting the wrapped protocol. The wrapped protocol is+ the destination TLS protocol, so its handshake is negotiated inside the+ tunnel; when the proxy itself is reached over TLS this results in a+ TLS-in-TLS connection."""_truncatedLength = 1000@@ -376,37 +381,23 @@ class _TunnelingEndpoint:def __init__(self,- reactor: ReactorBase,+ connectedDeferred: Deferred[IProtocol],+ wrappedProtocol: IProtocol,host: bytes,port: int,- proxyConf: tuple[str, int, tuple[tuple[str, str], ...]],- contextFactory: IPolicyForHTTPS,- timeout: float = 30,- bindAddress: tuple[str, int] | None = None,+ proxyHost: str,+ proxyPort: int,+ proxyHeaders: tuple[tuple[str, str], ...] = (),):- proxyHost, proxyPort, self._proxyHeaders = proxyConf- self._proxyHost: str = proxyHost- self._proxyPort: int = proxyPort- # Reach a proxy given as a name through a HostnameEndpoint, the same- # endpoint Twisted's Agent uses: it resolves the name with- # reactor.nameResolver and picks the address family from the result, so- # proxies that only have AAAA records work, given an IPv6-capable- # TWISTED_DNS_RESOLVER. A literal IPv6 address skips name resolution- # instead, as the default resolver would fail to resolve it.- self._proxyEndpoint: IStreamClientEndpoint = (- TCP6ClientEndpoint(reactor, proxyHost, proxyPort, timeout, bindAddress)- if _is_ipv6_literal(proxyHost)- else HostnameEndpoint(- reactor, proxyHost, proxyPort, timeout=timeout, bindAddress=bindAddress- )- )- self._tunnelReadyDeferred: Deferred[Protocol] = Deferred(self._cancelTunnel)- self._connectDeferred: Deferred[Protocol] | None = None- self._protocol: Protocol | None = None- self._tunneledHost: bytes = host- self._tunneledPort: int = port- self._contextFactory: IPolicyForHTTPS = contextFactory+ self._connectedDeferred = connectedDeferred+ self._wrappedProtocol = wrappedProtocol+ self._host = host+ self._port = port+ self._proxyHost = proxyHost+ self._proxyPort = proxyPort+ self._proxyHeaders = proxyHeadersself._connectBuffer: bytearray = bytearray()+ self._tunnelReady = False@staticmethoddef _format_host(host: bytes) -> bytes:@@ -417,27 +408,25 @@ class _TunnelingEndpoint:# colons.return b"[" + host + b"]" if b":" in host else host- def requestTunnel(self, protocol: Protocol) -> Protocol:+ def logPrefix(self) -> str:+ return type(self._wrappedProtocol).__name__++ def connectionMade(self) -> None:"""Asks the proxy to open a tunnel."""- assert protocol.transport- tunnelReq = _tunnel_request_data(- self._format_host(self._tunneledHost),- self._tunneledPort,- self._proxyHeaders,+ assert self.transport+ self.transport.write(+ _tunnel_request_data(+ self._format_host(self._host), self._port, self._proxyHeaders+ ))- protocol.transport.write(tunnelReq)- self._protocolDataReceived = protocol.dataReceived- protocol.dataReceived = self.processProxyResponse # type: ignore[method-assign]- self._protocol = protocol- return protocol- def processProxyResponse(self, data: bytes) -> None:- """Processes the response from the proxy. If the tunnel is successfully- created, notifies the client that we are ready to send requests. If not- raises a TunnelError.- """- assert self._protocol- assert self._protocol.transport+ def dataReceived(self, data: bytes) -> None:+ if self._tunnelReady:+ self._wrappedProtocol.dataReceived(data)+ return+ if self._connectedDeferred.called:+ # The tunnel was cancelled while waiting for the CONNECT response.+ returnself._connectBuffer += data# make sure that enough (all) bytes are consumed# and that we've got all HTTP headers (ending with a blank line)@@ -446,16 +435,17 @@ class _TunnelingEndpoint:# see https://github.com/scrapy/scrapy/issues/2491if b"\r\n\r\n" not in self._connectBuffer:return- self._protocol.dataReceived = self._protocolDataReceived # type: ignore[method-assign]- respm = _TunnelingEndpoint._responseMatcher.match(self._connectBuffer)+ header, _, remaining = bytes(self._connectBuffer).partition(b"\r\n\r\n")+ respm = self._responseMatcher.match(header)if respm and int(respm.group("status")) == 200:- # set proper Server Name Indication extension- sslOptions = self._contextFactory.creatorForNetloc(- self._tunneledHost, # type: ignore[arg-type]- self._tunneledPort, # type: ignore[call-arg,misc]- )- self._protocol.transport.startTLS(sslOptions, self._protocolFactory)- self._tunnelReadyDeferred.callback(self._protocol)+ self._tunnelReady = True+ # Hand the connection over to the wrapped (destination TLS)+ # protocol, which starts its handshake through the tunnel.+ assert self.transport is not None+ self._wrappedProtocol.makeConnection(self.transport)+ self._connectedDeferred.callback(self._wrappedProtocol)+ if remaining:+ self._wrappedProtocol.dataReceived(remaining)else:extra: Anyif respm:@@ -464,41 +454,136 @@ class _TunnelingEndpoint:"reason": respm.group("reason").strip(),}else:- extra = data[: self._truncatedLength]- self._tunnelReadyDeferred.errback(+ extra = header[: self._truncatedLength]+ self._connectedDeferred.errback(TunnelError("Could not open CONNECT tunnel with proxy "f"{self._proxyHost}:{self._proxyPort} [{extra!r}]"))- def connectFailed(self, reason: Failure) -> None:- """Propagates the errback to the appropriate deferred."""- self._tunnelReadyDeferred.errback(reason)-- def _cancelTunnel(self, deferred: Deferred[Protocol]) -> None:- """Tear down the connection to the proxy when the deferred returned by- :meth:`connect` is cancelled, e.g. on a download timeout."""- if self._protocol is not None:- # The proxy connection is up; drop it, and stop intercepting data- # in case the proxy answers the CONNECT after this point.- self._protocol.dataReceived = self._protocolDataReceived # type: ignore[method-assign]- assert self._protocol.transport- self._protocol.transport.loseConnection()- else:- # Still connecting to the proxy; stop the connection attempt. This- # errbacks _tunnelReadyDeferred through connectFailed().- assert self._connectDeferred is not None- self._connectDeferred.cancel()-- def connect(self, protocolFactory: Factory) -> Deferred[Protocol]:- self._protocolFactory = protocolFactory- self._connectDeferred = connectDeferred = self._proxyEndpoint.connect(- protocolFactory+ def connectionLost(self, reason: Failure = connectionDone) -> None:+ if self._tunnelReady:+ self._wrappedProtocol.connectionLost(reason)+ elif not self._connectedDeferred.called:+ # The connection was lost before the tunnel was established (e.g.+ # the proxy closed the connection in response to CONNECT).+ self._connectedDeferred.errback(reason)+++class _TunnelFactory(ClientFactory):+ """Builds :class:`_TunnelProtocol` instances wrapping the protocols built+ by another factory."""++ def __init__(+ self,+ connectedDeferred: Deferred[IProtocol],+ wrappedFactory: Factory,+ host: bytes,+ port: int,+ proxyHost: str,+ proxyPort: int,+ proxyHeaders: tuple[tuple[str, str], ...] = (),+ ):+ self._connectedDeferred = connectedDeferred+ self._wrappedFactory = wrappedFactory+ self._host = host+ self._port = port+ self._proxyHost = proxyHost+ self._proxyPort = proxyPort+ self._proxyHeaders = proxyHeaders++ def doStart(self) -> None:+ self._wrappedFactory.doStart()++ def doStop(self) -> None:+ self._wrappedFactory.doStop()++ def buildProtocol(self, addr: IAddress) -> _TunnelProtocol:+ wrappedProtocol = self._wrappedFactory.buildProtocol(addr)+ # The wrapped factory is always the destination TLS factory built by+ # wrapClientTLS, whose buildProtocol never returns None.+ assert wrappedProtocol is not None+ return _TunnelProtocol(+ self._connectedDeferred,+ wrappedProtocol,+ self._host,+ self._port,+ self._proxyHost,+ self._proxyPort,+ self._proxyHeaders,+ )+++@implementer(IStreamClientEndpoint)+class _TunnelEndpoint:+ """A wrapper endpoint that opens an HTTP CONNECT tunnel over the connection+ established by the wrapped endpoint before delivering it to the protocol+ factory.++ The wrapped endpoint connects to the proxy (over plain TCP for ``http://``+ proxies, or over TLS via :func:`~twisted.internet.endpoints.wrapClientTLS`+ for ``https://`` proxies). Wrapping this endpoint in turn with+ ``wrapClientTLS`` negotiates the destination TLS session inside the tunnel.+ """++ def __init__(+ self,+ wrappedEndpoint: IStreamClientEndpoint,+ host: bytes,+ port: int,+ proxyHost: str,+ proxyPort: int,+ proxyHeaders: tuple[tuple[str, str], ...] = (),+ ):+ self._wrappedEndpoint = wrappedEndpoint+ self._host = host+ self._port = port+ self._proxyHost = proxyHost+ self._proxyPort = proxyPort+ self._proxyHeaders = proxyHeaders++ def connect(self, protocolFactory: Factory) -> Deferred[IProtocol]:+ proxyProtocol: IProtocol | None = None++ def proxyConnected(protocol: IProtocol) -> None:+ nonlocal proxyProtocol+ proxyProtocol = protocol++ def cancel(_: Deferred[IProtocol]) -> None:+ # Tear down the connection to the proxy, e.g. on a download timeout.+ if proxyProtocol is None:+ # Still connecting to the proxy. This errbacks+ # connectedDeferred through _connectFailed().+ proxyDeferred.cancel()+ else:+ assert isinstance(proxyProtocol, _TunnelProtocol)+ assert proxyProtocol.transport+ proxyProtocol.transport.loseConnection()++ connectedDeferred: Deferred[IProtocol] = Deferred(cancel)+ tunnelFactory = _TunnelFactory(+ connectedDeferred,+ protocolFactory,+ self._host,+ self._port,+ self._proxyHost,+ self._proxyPort,+ self._proxyHeaders,+ )+ proxyDeferred = self._wrappedEndpoint.connect(tunnelFactory)+ proxyDeferred.addCallbacks(+ proxyConnected, self._connectFailed, errbackArgs=(connectedDeferred,))- connectDeferred.addCallback(self.requestTunnel)- connectDeferred.addErrback(self.connectFailed)- return self._tunnelReadyDeferred+ return connectedDeferred++ @staticmethod+ def _connectFailed(+ failure: Failure, connectedDeferred: Deferred[IProtocol]+ ) -> None:+ # Reached only when connecting to the proxy fails, i.e. before the+ # tunnel deferred has been fired.+ connectedDeferred.errback(failure)def _tunnel_request_data(@@ -553,37 +638,72 @@ class _BindAddressAgent(Agent):class _TunnelingAgent(_BindAddressAgent):- """An agent that uses a ``_TunnelingEndpoint`` to make HTTPS- downloads. It may look strange that we have chosen to subclass Agent and not+ """An agent that tunnels HTTPS downloads through a proxy using HTTP+ CONNECT. It may look strange that we have chosen to subclass Agent and notProxyAgent but consider that after the tunnel is opened the proxy istransparent to the client; thus the agent should behave like there is noproxy involved.++ ``proxyConf`` is a ``(host, port, headers, tls)`` tuple, where ``tls``+ indicates whether the connection to the proxy itself must be made over TLS+ (an ``https://`` proxy). When it is, the destination TLS session runs inside+ the proxy TLS session (TLS-in-TLS)."""def __init__(self,*,reactor: ReactorBase,- proxyConf: tuple[str, int, tuple[tuple[str, str], ...]],+ proxyConf: tuple[str, int, tuple[tuple[str, str], ...], bool],contextFactory: IPolicyForHTTPS,connectTimeout: float | None = None,bindAddress: tuple[str, int] | None = None,pool: HTTPConnectionPool | None = None,):super().__init__(reactor, contextFactory, connectTimeout, bindAddress, pool)- self._proxyConf: tuple[str, int, tuple[tuple[str, str], ...]] = proxyConf+ self._proxyConf: tuple[str, int, tuple[tuple[str, str], ...], bool] = proxyConfself._contextFactory: IPolicyForHTTPS = contextFactory- def _getEndpoint(self, uri: URI) -> _TunnelingEndpoint:- return _TunnelingEndpoint(- reactor=self._reactor,- host=uri.host,- port=uri.port,- proxyConf=self._proxyConf,- contextFactory=self._contextFactory,- timeout=self._endpointFactory._connectTimeout,- bindAddress=self._endpointFactory._bindAddress,+ def _getEndpoint(self, uri: URI) -> IStreamClientEndpoint:+ proxyHost, proxyPort, proxyHeaders, proxyTLS = self._proxyConf+ timeout = self._endpointFactory._connectTimeout+ bindAddress = self._endpointFactory._bindAddress+ # Reach a proxy given as a name through a HostnameEndpoint, the same+ # endpoint Twisted's Agent uses: it resolves the name with+ # reactor.nameResolver and picks the address family from the result, so+ # proxies that only have AAAA records work, given an IPv6-capable+ # TWISTED_DNS_RESOLVER. A literal IPv6 address skips name resolution+ # instead, as the default resolver would fail to resolve it.+ endpoint: IStreamClientEndpoint = (+ TCP6ClientEndpoint(+ self._reactor, proxyHost, proxyPort, timeout, bindAddress+ )+ if _is_ipv6_literal(proxyHost)+ else HostnameEndpoint(+ self._reactor,+ proxyHost,+ proxyPort,+ timeout=timeout,+ bindAddress=bindAddress,+ ))+ if proxyTLS:+ # Set up TLS with the proxy itself, so that the CONNECT request and+ # the tunneled traffic are sent over it (TLS-in-TLS).+ proxyCreator = self._contextFactory.creatorForNetloc( # type: ignore[call-arg,misc]+ proxyHost.encode("ascii"), # type: ignore[arg-type]+ proxyPort,+ )+ endpoint = wrapClientTLS(proxyCreator, endpoint)+ endpoint = _TunnelEndpoint(+ endpoint, uri.host, uri.port, proxyHost, proxyPort, proxyHeaders+ )+ # Set proper Server Name Indication extension for the destination.+ destCreator = self._contextFactory.creatorForNetloc( # type: ignore[call-arg,misc]+ uri.host,+ uri.port,+ )+ return wrapClientTLS(destCreator, endpoint)def _requestWithEndpoint(self,@@ -692,10 +812,6 @@ class _ScrapyAgent:if not proxy_port:proxy_port = 443 if proxy_parsed.scheme == "https" else 80if urlparse_cached(request).scheme == "https":- if proxy_parsed.scheme == "https": # pragma: no cover- raise NotImplementedError(- "HTTPS proxies for HTTPS destinations are not supported"- )assert proxy_host is not Noneproxy_headers = get_proxy_headers(request)proxyAuth = request.headers.get(b"Proxy-Authorization", None)@@ -706,7 +822,12 @@ class _ScrapyAgent:("Proxy-Authorization", proxyAuth.decode()),*proxy_headers,)- proxyConf = (proxy_host, proxy_port, proxy_headers)+ proxyConf = (+ proxy_host,+ proxy_port,+ proxy_headers,+ proxy_parsed.scheme == "https",+ )return _TunnelingAgent(reactor=reactor,proxyConf=proxyConf,diff --git a/tests/test_downloader_handler_twisted_http11.py b/tests/test_downloader_handler_twisted_http11.pyindex af71f3415..97f84ac1f 100644--- a/tests/test_downloader_handler_twisted_http11.py+++ b/tests/test_downloader_handler_twisted_http11.py@@ -6,7 +6,9 @@ from typing import TYPE_CHECKING, Any, castimport pytestfrom twisted.internet.address import IPv6Address-from twisted.internet.error import ConnectingCancelledError+from twisted.internet.defer import CancelledError+from twisted.internet.endpoints import TCP4ClientEndpoint+from twisted.internet.error import ConnectingCancelledError, ConnectionClosedfrom twisted.internet.interfaces import (IAddress,IHostnameResolver,@@ -15,7 +17,7 @@ from twisted.internet.interfaces import (IResolutionReceiver,)from twisted.internet.protocol import Factory, Protocol-from twisted.internet.testing import MemoryReactorClock+from twisted.internet.testing import MemoryReactorClock, StringTransportfrom twisted.python.failure import Failurefrom twisted.web.client import URI, BrowserLikePolicyForHTTPSfrom zope.interface import implementer@@ -33,13 +35,15 @@ from scrapy.core.downloader.handlers.http11 import (TunnelError,_ScrapyAgent,_tunnel_request_data,+ _TunnelEndpoint,_TunnelingAgent,- _TunnelingEndpoint,+ _TunnelProtocol,)from scrapy.crawler import Crawlerfrom scrapy.exceptions import (CannotResolveHostError,DownloadConnectionRefusedError,+ DownloadFailedError,NotConfigured,)from scrapy.resolver import HostResolution@@ -69,6 +73,7 @@ if TYPE_CHECKING:from collections.abc import AsyncGenerator, Generator, Sequencefrom twisted.internet.base import ReactorBase+ from twisted.internet.interfaces import IProtocol, IStreamClientEndpointfrom twisted.web.iweb import IPolicyForHTTPSfrom scrapy.core.downloader.handlers import DownloadHandlerProtocol@@ -102,6 +107,16 @@ def test_not_configured_without_reactor() -> None:build_from_crawler(HTTP11DownloadHandler, crawler)+def _tunnel_endpoint(reactor: MemoryReactorClock) -> _TunnelEndpoint:+ return _TunnelEndpoint(+ TCP4ClientEndpoint(reactor, "127.0.0.1", 8080),+ host=b"example.com",+ port=443,+ proxyHost="127.0.0.1",+ proxyPort=8080,+ )++@asynccontextmanagerasync def _get_dh(settings_dict: dict[str, Any] | None = None,@@ -203,7 +218,7 @@ def test_tunnel_proxy_headers()tunneling_agent = agent._get_agent(request, 10)assert isinstance(tunneling_agent, _TunnelingAgent)- assert tunneling_agent._proxyConf == ("proxy.example", 8080, expected)+ assert tunneling_agent._proxyConf == ("proxy.example", 8080, expected, False)def test_tunneling_cancelled_before_connected() -> None:@@ -217,24 +232,39 @@ def test_tunneling_cancelled_before_connected() -> None:the connection to the proxy is established."""reactor = MemoryReactorClock()- endpoint = _TunnelingEndpoint(- reactor=cast("ReactorBase", reactor),- host=b"example.com",- port=443,- proxyConf=("::1", 8080, ()),- contextFactory=_load_context_factory_from_settings(get_crawler()),- timeout=30,- )- results: list[Protocol | Failure] = []- endpoint.connect(Factory()).addBoth(results.append)+ results: list[IProtocol | Failure] = []+ d = _tunnel_endpoint(reactor).connect(Factory.forProtocol(Protocol))+ d.addBoth(results.append)- endpoint._tunnelReadyDeferred.cancel()+ d.cancel()assert reactor.connectors[0].stoppedConnectingassert isinstance(results[0], Failure)assert isinstance(results[0].value, ConnectingCancelledError)+def test_tunneling_cancelled_before_connect_response() -> None:+ """A CONNECT response received after cancelling the tunnel, but before the+ connection to the proxy is closed, is ignored."""+ reactor = MemoryReactorClock()+ results: list[IProtocol | Failure] = []+ d = _tunnel_endpoint(reactor).connect(Factory.forProtocol(Protocol))+ d.addBoth(results.append)+ factory = reactor.tcpClients[0][2]+ protocol = factory.buildProtocol(None)+ assert protocol is not None+ transport = StringTransport()+ protocol.makeConnection(transport)++ d.cancel()+ protocol.dataReceived(b"HTTP/1.1 200 OK\r\n\r\n")++ assert transport.disconnecting+ assert len(results) == 1+ assert isinstance(results[0], Failure)+ assert isinstance(results[0].value, CancelledError)++class TestHttp(HTTP11DownloadHandlerMixin, TestHttpBase):pass@@ -283,14 +313,11 @@ class TestHttpProxy(HTTP11DownloadHandlerMixin, TestHttpProxyBase):class TestHttpsProxy(HTTP11DownloadHandlerMixin, TestHttpProxyBase):is_secure = True- # not implemented- handler_supports_tls_in_tls = False@pytest.mark.requires_mitmproxyclass TestMitmProxy(HTTP11DownloadHandlerMixin, TestMitmProxyBase):- # not implemented- handler_supports_tls_in_tls = False+ pass@pytest.mark.skipif(@@ -311,9 +338,7 @@ class TestMitmProxyIPv6(TestMitmProxy):)def test_connect_authority(url: bytes, expected_authority: bytes) -> None:uri = URI.fromBytes(url)- tunnel_req = _tunnel_request_data(- _TunnelingEndpoint._format_host(uri.host), uri.port- )+ tunnel_req = _tunnel_request_data(_TunnelProtocol._format_host(uri.host), uri.port)assert tunnel_req == (b"CONNECT " + expected_authority + b" HTTP/1.1\r\n"b"Host: " + expected_authority + b"\r\n\r\n"@@ -443,6 +468,18 @@ def ipv6_only_proxy(fake_proxy_port: int) -> tuple[ReactorBase, str, int]:)+def _proxy_tunnel_endpoint(+ reactor: ReactorBase, proxy_host: str, proxy_port: int+) -> IStreamClientEndpoint:+ agent = _TunnelingAgent(+ reactor=reactor,+ proxyConf=(proxy_host, proxy_port, (), False),+ contextFactory=cast("IPolicyForHTTPS", BrowserLikePolicyForHTTPS()),+ connectTimeout=10,+ )+ return agent._getEndpoint(URI.fromBytes(b"https://example.com"))++@pytest.mark.skipif(not ipv6_loopback_available(), reason="IPv6 loopback is not available")@@ -457,14 +494,7 @@ async def test_tunnel_to_proxy_reachable_only_over_ipv6(family for the proxy."""reactor, proxy_host, proxy_port = ipv6_only_proxy- endpoint = _TunnelingEndpoint(- reactor=reactor,- host=b"example.com",- port=443,- proxyConf=(proxy_host, proxy_port, ()),- contextFactory=cast("IPolicyForHTTPS", BrowserLikePolicyForHTTPS()),- timeout=10,- )+ endpoint = _proxy_tunnel_endpoint(reactor, proxy_host, proxy_port)with pytest.raises(TunnelError, match="Could not open CONNECT tunnel"):await maybe_deferred_to_future(endpoint.connect(Factory.forProtocol(Protocol)))@@ -480,13 +510,10 @@ async def test_tunnel_to_ipv6_literal_proxy(fake_proxy_port: int) -> None:from twisted.internet import reactorresolver = _UnresolvingResolver()- endpoint = _TunnelingEndpoint(- reactor=cast("ReactorBase", _ReactorWithNameResolver(reactor, resolver)),- host=b"example.com",- port=443,- proxyConf=("::1", fake_proxy_port, ()),- contextFactory=cast("IPolicyForHTTPS", BrowserLikePolicyForHTTPS()),- timeout=10,+ endpoint = _proxy_tunnel_endpoint(+ cast("ReactorBase", _ReactorWithNameResolver(reactor, resolver)),+ "::1",+ fake_proxy_port,)with pytest.raises(TunnelError, match="Could not open CONNECT tunnel"):await maybe_deferred_to_future(endpoint.connect(Factory.forProtocol(Protocol)))@@ -501,7 +528,8 @@ class TestRealWebsite(HTTP11DownloadHandlerMixin, TestRealWebsiteBase):class _CannedConnectProxy(Protocol):- """Answers any request with a canned response."""+ """Answers any request with a canned response, or drops the connection when+ the response is ``None``."""factory: _CannedConnectProxyFactory@@ -510,6 +538,9 @@ class _CannedConnectProxy(Protocol):assert self.transportresponse = self.factory.response+ if response is None:+ self.transport.loseConnection()+ returnif not self.factory.split_at:self.transport.write(response)return@@ -520,13 +551,15 @@ class _CannedConnectProxy(Protocol):class _CannedConnectProxyFactory(Factory):protocol = _CannedConnectProxy # type: ignore[assignment]- def __init__(self, response: bytes, split_at: int = 0):+ def __init__(self, response: bytes | None, split_at: int = 0):self.response = responseself.split_at = split_at@asynccontextmanager-async def _canned_proxy(response: bytes, split_at: int = 0) -> AsyncGenerator[str]:+async def _canned_proxy(+ response: bytes | None, split_at: int = 0+) -> AsyncGenerator[str]:from twisted.internet import reactorport = reactor.listenTCP(@@ -557,6 +590,26 @@ class TestTunnelingErrors:with pytest.raises(TunnelError, match="not an HTTP response"):await dh.download_request(request)+ @coroutine_test+ async def test_proxy_closes_connection(self) -> None:+ """The proxy drops the connection instead of answering CONNECT."""+ async with _canned_proxy(None) as proxy:+ request = Request("https://example.com", meta={"proxy": proxy})+ async with _get_dh() as dh:+ with pytest.raises(ConnectionClosed):+ await dh.download_request(request)++ @coroutine_test+ async def test_trailing_bytes(self) -> None:+ """Bytes right after a successful CONNECT response belong to the+ tunneled protocol, whose TLS handshake they corrupt."""+ response = b"HTTP/1.1 200 Connection established\r\n\r\ntrailing-bytes"+ async with _canned_proxy(response) as proxy:+ request = Request("https://example.com", meta={"proxy": proxy})+ async with _get_dh() as dh:+ with pytest.raises(DownloadFailedError):+ await dh.download_request(request)+@coroutine_testasync def test_proxy_connection_refused(self) -> None:request = Request(