Skip to content

Scrapy, a fast high-level web crawling & scraping framework for Python.

Ipv6 proxy support (#8116)

Adriand2810adf6d59
diff --git a/conftest.py b/conftest.py
index 1f6b7c7b3..cd0fd6fce 100644
--- a/conftest.py
+++ b/conftest.py
@@ -88,8 +88,18 @@ def mockserver() -> Generator[MockServer]:
@pytest.fixture(scope="session")
-def _mitm_proxies() -> Generator[dict[str, tuple[MitmProxy, str]]]:
- proxies: dict[str, tuple[MitmProxy, str]] = {}
+def mockserver_ipv6() -> Generator[MockServer]:
+ """A mockserver reachable only over the IPv6 loopback.
+
+ Tests using this must skip when :func:`ipv6_loopback_available` is False.
+ """
+ with MockServer("::1") as mockserver:
+ yield mockserver
+
+
[email protected](scope="session")
+def _mitm_proxies() -> Generator[dict[tuple[str, str], tuple[MitmProxy, str]]]:
+ proxies: dict[tuple[str, str], tuple[MitmProxy, str]] = {}
try:
yield proxies
finally:
@@ -101,13 +111,16 @@ def _mitm_proxies() -> Generator[dict[str, tuple[MitmProxy, str]]]:
def proxy_server(
request: pytest.FixtureRequest,
monkeypatch: pytest.MonkeyPatch,
- _mitm_proxies: dict[str, tuple[MitmProxy, str]],
+ _mitm_proxies: dict[tuple[str, str], tuple[MitmProxy, str]],
) -> str:
kind: str = request.param
- if kind not in _mitm_proxies:
- proxy = MitmProxy(mode="socks5" if kind == "socks5" else None)
- _mitm_proxies[kind] = (proxy, proxy.start())
- _, url = _mitm_proxies[kind]
+ # test classes can make the proxy listen on a different address, e.g. "::1"
+ host = getattr(request.cls, "proxy_host", "127.0.0.1")
+ cache_key = (kind, host)
+ if cache_key not in _mitm_proxies:
+ proxy = MitmProxy(mode="socks5" if kind == "socks5" else None, host=host)
+ _mitm_proxies[cache_key] = (proxy, proxy.start())
+ _, url = _mitm_proxies[cache_key]
if kind == "https":
url = url.replace("http://", "https://")
monkeypatch.setenv("http_proxy", url)
diff --git a/docs/topics/download-handlers.rst b/docs/topics/download-handlers.rst
index 6ba2dc903..9159467eb 100644
--- a/docs/topics/download-handlers.rst
+++ b/docs/topics/download-handlers.rst
@@ -222,8 +222,8 @@ line, e.g. one with no colon in it, which some servers send. Handlers that skip
bad header lines, like web browsers do, still parse the header lines that follow
them; other handlers also lose those, or cannot download such responses at all.
-Handlers that require a reactor resolve hosts, including IPv6 address literals
-such as ``https://[::1]/``, with the resolver set in
+Handlers that require a reactor resolve hosts, including proxy hosts and IPv6
+address literals such as ``https://[::1]/``, with the resolver set in
:setting:`TWISTED_DNS_RESOLVER`, whose default value only supports IPv4. To use
IPv6 with them, set it to ``scrapy.resolver.CachingHostnameResolver``.
@@ -450,6 +450,11 @@ Other limitations:
``https://[::1]/``, `do not work through a proxy
<https://github.com/pydantic/httpx2/pull/1091>`__.
+Unlike the Twisted-based handlers, this handler does not use the resolver
+configured with :setting:`TWISTED_DNS_RESOLVER`, so it resolves IPv6 hosts
+without needing that setting changed, and it is not affected by
+:setting:`DNS_TIMEOUT` or by the :setting:`DNSCACHE_ENABLED` cache.
+
.. setting:: HTTPX_HTTP2_ENABLED
HTTPX_HTTP2_ENABLED
diff --git a/scrapy/core/downloader/handlers/http11.py b/scrapy/core/downloader/handlers/http11.py
index af6317030..edd84b3fe 100644
--- a/scrapy/core/downloader/handlers/http11.py
+++ b/scrapy/core/downloader/handlers/http11.py
@@ -14,7 +14,8 @@ from urllib.parse import urldefrag
from twisted.internet import ssl
from twisted.internet.defer import Deferred, succeed
-from twisted.internet.endpoints import TCP4ClientEndpoint
+from twisted.internet.endpoints import HostnameEndpoint, TCP6ClientEndpoint
+from twisted.internet.interfaces import IStreamClientEndpoint
from twisted.internet.protocol import Factory, Protocol, connectionDone
from twisted.python.failure import Failure
from twisted.web._newclient import (
@@ -170,7 +171,15 @@ class TunnelError(Exception):
"""An HTTP CONNECT tunnel could not be established by the proxy."""
-class _TunnelingTCP4ClientEndpoint(TCP4ClientEndpoint):
+def _is_ipv6_literal(host: str) -> bool:
+ try:
+ return isinstance(ipaddress.ip_address(host), ipaddress.IPv6Address)
+ except ValueError: # a hostname
+ 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
@@ -196,7 +205,21 @@ class _TunnelingTCP4ClientEndpoint(TCP4ClientEndpoint):
bindAddress: tuple[str, int] | None = None,
):
proxyHost, proxyPort, self._proxyAuthHeader = proxyConf
- super().__init__(reactor, proxyHost, proxyPort, timeout, bindAddress)
+ 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
@@ -244,7 +267,7 @@ class _TunnelingTCP4ClientEndpoint(TCP4ClientEndpoint):
if b"\r\n\r\n" not in self._connectBuffer:
return
self._protocol.dataReceived = self._protocolDataReceived # type: ignore[method-assign]
- respm = _TunnelingTCP4ClientEndpoint._responseMatcher.match(self._connectBuffer)
+ respm = _TunnelingEndpoint._responseMatcher.match(self._connectBuffer)
if respm and int(respm.group("status")) == 200:
# set proper Server Name Indication extension
sslOptions = self._contextFactory.creatorForNetloc(
@@ -265,7 +288,7 @@ class _TunnelingTCP4ClientEndpoint(TCP4ClientEndpoint):
self._tunnelReadyDeferred.errback(
TunnelError(
"Could not open CONNECT tunnel with proxy "
- f"{self._host}:{self._port} [{extra!r}]"
+ f"{self._proxyHost}:{self._proxyPort} [{extra!r}]"
)
)
@@ -290,7 +313,9 @@ class _TunnelingTCP4ClientEndpoint(TCP4ClientEndpoint):
def connect(self, protocolFactory: Factory) -> Deferred[Protocol]:
self._protocolFactory = protocolFactory
- self._connectDeferred = connectDeferred = super().connect(protocolFactory)
+ self._connectDeferred = connectDeferred = self._proxyEndpoint.connect(
+ protocolFactory
+ )
connectDeferred.addCallback(self.requestTunnel)
connectDeferred.addErrback(self.connectFailed)
return self._tunnelReadyDeferred
@@ -334,7 +359,7 @@ class _BindAddressAgent(Agent):
def _requestWithEndpoint(
self,
key: tuple[Any, ...],
- endpoint: TCP4ClientEndpoint,
+ endpoint: IStreamClientEndpoint,
method: bytes,
parsedURI: URI,
headers: TxHeaders | None,
@@ -348,7 +373,7 @@ class _BindAddressAgent(Agent):
class _TunnelingAgent(_BindAddressAgent):
- """An agent that uses a ``_TunnelingTCP4ClientEndpoint`` to make HTTPS
+ """An agent that uses a ``_TunnelingEndpoint`` to make HTTPS
downloads. It may look strange that we have chosen to subclass Agent and not
ProxyAgent but consider that after the tunnel is opened the proxy is
transparent to the client; thus the agent should behave like there is no
@@ -369,8 +394,8 @@ class _TunnelingAgent(_BindAddressAgent):
self._proxyConf: tuple[str, int, bytes | None] = proxyConf
self._contextFactory: IPolicyForHTTPS = contextFactory
- def _getEndpoint(self, uri: URI) -> _TunnelingTCP4ClientEndpoint:
- return _TunnelingTCP4ClientEndpoint(
+ def _getEndpoint(self, uri: URI) -> _TunnelingEndpoint:
+ return _TunnelingEndpoint(
reactor=self._reactor,
host=uri.host,
port=uri.port,
@@ -383,7 +408,7 @@ class _TunnelingAgent(_BindAddressAgent):
def _requestWithEndpoint(
self,
key: Any,
- endpoint: TCP4ClientEndpoint,
+ endpoint: IStreamClientEndpoint,
method: bytes,
parsedURI: URI,
headers: TxHeaders | None,
diff --git a/scrapy/utils/_deps_compat.py b/scrapy/utils/_deps_compat.py
index f76e92c79..31d75af75 100644
--- a/scrapy/utils/_deps_compat.py
+++ b/scrapy/utils/_deps_compat.py
@@ -5,6 +5,7 @@ from packaging.version import Version
from parsel import __version__ as PARSEL_VERSION_STRING
from twisted import version as TWISTED_VERSION
from twisted.python.versions import Version as TxVersion
+from w3lib import __version__ as W3LIB_VERSION_STRING
# improved urllib.robotparser, https://github.com/python/cpython/pull/149374
STDLIB_IMPROVED_ROBOTFILEPARSER = sys.version_info >= (3, 14, 5) or (
@@ -24,3 +25,8 @@ PARSEL_BODY_ENCODING_FIXED = PARSEL_VERSION >= Version("1.12.0")
PYOPENSSL_VERSION = Version(PYOPENSSL_VERSION_STRING)
# SSL.Context.set_cipher_list() creates a temporary connection, making the context immutable
PYOPENSSL_SET_CIPHER_LIST_TMP_CONN = PYOPENSSL_VERSION < Version("25.2.0")
+
+W3LIB_VERSION = Version(W3LIB_VERSION_STRING)
+# safe_url_string() drops the brackets of an IPv6 address literal in the
+# netloc, https://github.com/scrapy/w3lib/pull/253
+W3LIB_STRIPS_IPV6_BRACKETS = Version("2.0.0") <= W3LIB_VERSION < Version("2.4.1")
diff --git a/tests/mockserver/http_base.py b/tests/mockserver/http_base.py
index dafa71329..8b93b767a 100644
--- a/tests/mockserver/http_base.py
+++ b/tests/mockserver/http_base.py
@@ -31,18 +31,35 @@ class BaseMockServer(ABC):
def module_name(self) -> str:
raise NotImplementedError
- def __init__(self) -> None:
+ def __init__(self, host: str | None = None) -> None:
+ """Start a mockserver.
+
+ *host* is the address to listen on; by default every interface is bound
+ and requests are made to 127.0.0.1. Pass e.g. ``"::1"`` to test over
+ IPv6.
+ """
if not self.listen_http and not self.listen_https:
raise ValueError("At least one of listen_http and listen_https must be set")
self.proc: Popen[str] | None = None
- self.host: str = "127.0.0.1"
+ self.host: str = host if host is not None else "127.0.0.1"
+ self._listen_host: str | None = host
self.http_port: int | None = None
self.https_port: int | None = None
def __enter__(self) -> Self:
+ host_args = (
+ ["--host", self._listen_host] if self._listen_host is not None else []
+ )
self.proc = Popen(
- [sys.executable, "-u", "-m", self.module_name, *self.get_additional_args()],
+ [
+ sys.executable,
+ "-u",
+ "-m",
+ self.module_name,
+ *host_args,
+ *self.get_additional_args(),
+ ],
stdout=PIPE,
env=get_script_run_env(),
text=True,
@@ -83,7 +100,8 @@ class BaseMockServer(ABC):
def url(self, path: str, is_secure: bool = False) -> str:
port = self.port(is_secure)
scheme = "https" if is_secure else "http"
- return f"{scheme}://{self.host}:{port}{path}"
+ host = f"[{self.host}]" if ":" in self.host else self.host
+ return f"{scheme}://{host}:{port}{path}"
def main_factory(
@@ -98,32 +116,39 @@ def main_factory(
def main() -> None:
from twisted.internet import reactor
+ parser = argparse.ArgumentParser()
+ parser.add_argument(
+ "--host",
+ default="",
+ help="Address to listen on, e.g. ::1 for the IPv6 loopback. "
+ "Every interface is bound by default.",
+ )
+ parser.add_argument("--keyfile", help="SSL key file")
+ parser.add_argument("--certfile", help="SSL certificate file")
+ parser.add_argument(
+ "--cipher-string",
+ default=None,
+ help="SSL cipher string (optional)",
+ )
+ parser.add_argument(
+ "--tls-min-version",
+ default=None,
+ help="Minimum accepted TLS version (optional)",
+ )
+ parser.add_argument(
+ "--tls-max-version",
+ default=None,
+ help="Maximum accepted TLS version (optional)",
+ )
+ args = parser.parse_args()
+
root = resource_class()
factory = Site(root)
if listen_http:
- http_port = reactor.listenTCP(0, factory)
+ http_port = reactor.listenTCP(0, factory, interface=args.host)
if listen_https:
- parser = argparse.ArgumentParser()
- parser.add_argument("--keyfile", help="SSL key file")
- parser.add_argument("--certfile", help="SSL certificate file")
- parser.add_argument(
- "--cipher-string",
- default=None,
- help="SSL cipher string (optional)",
- )
- parser.add_argument(
- "--tls-min-version",
- default=None,
- help="Minimum accepted TLS version (optional)",
- )
- parser.add_argument(
- "--tls-max-version",
- default=None,
- help="Maximum accepted TLS version (optional)",
- )
- args = parser.parse_args()
context_factory_kw = {}
if args.keyfile:
context_factory_kw["keyfile"] = args.keyfile
@@ -136,17 +161,22 @@ def main_factory(
if args.tls_max_version:
context_factory_kw["tls_max_version"] = args.tls_max_version
context_factory = ssl_context_factory(**context_factory_kw)
- https_port = reactor.listenSSL(0, factory, context_factory)
+ https_port = reactor.listenSSL(
+ 0, factory, context_factory, interface=args.host
+ )
def print_listening() -> None:
+ def address(scheme: str, listening_port) -> str:
+ listening_host = listening_port.getHost()
+ host = listening_host.host
+ if ":" in host: # IPv6 literal
+ host = f"[{host}]"
+ return f"{scheme}://{host}:{listening_host.port}"
+
if listen_http:
- http_host = http_port.getHost()
- http_address = f"http://{http_host.host}:{http_host.port}"
- print(http_address)
+ print(address("http", http_port))
if listen_https:
- https_host = https_port.getHost()
- https_address = f"https://{https_host.host}:{https_host.port}"
- print(https_address)
+ print(address("https", https_port))
reactor.callWhenRunning(print_listening)
reactor.run()
diff --git a/tests/mockserver/mitm_proxy.py b/tests/mockserver/mitm_proxy.py
index 8a1025b37..066dd1c64 100644
--- a/tests/mockserver/mitm_proxy.py
+++ b/tests/mockserver/mitm_proxy.py
@@ -42,8 +42,9 @@ class MitmProxy:
auth_user = "scrapy"
auth_pass = "scrapy"
- def __init__(self, mode: str | None = None) -> None:
+ def __init__(self, mode: str | None = None, host: str = "127.0.0.1") -> None:
self.mode = mode
+ self.host = host
def start(self) -> str:
cmd = mitmdump_cmd()
@@ -55,7 +56,7 @@ class MitmProxy:
# Choose a free port ourselves instead of reading the mitmdump output
# as there is no easy way to disable stdout buffering for all kinds of
# mitmdump installs that we support.
- host = "127.0.0.1"
+ host = self.host
port = _free_port()
args = [
"--listen-host",
@@ -79,6 +80,7 @@ class MitmProxy:
start_new_session=True, # needed for killpg() to make sense
)
scheme = "socks5" if self.mode == "socks5" else "http"
+ authority_host = f"[{host}]" if ":" in host else host
deadline = time.monotonic() + 60
while True:
if self.proc.poll() is not None:
@@ -88,7 +90,10 @@ class MitmProxy:
)
try:
with socket.create_connection((host, port), timeout=1):
- return f"{scheme}://{self.auth_user}:{self.auth_pass}@{host}:{port}"
+ return (
+ f"{scheme}://{self.auth_user}:{self.auth_pass}"
+ f"@{authority_host}:{port}"
+ )
except OSError:
if time.monotonic() >= deadline:
break
diff --git a/tests/test_downloader_handler_httpx.py b/tests/test_downloader_handler_httpx.py
index 72d2ce834..6cdb13489 100644
--- a/tests/test_downloader_handler_httpx.py
+++ b/tests/test_downloader_handler_httpx.py
@@ -193,6 +193,10 @@ class TestHttpsProxy(TestHttpProxy):
@pytest.mark.requires_mitmproxy
class TestMitmProxy(HttpxDownloadHandlerMixin, TestMitmProxyBase):
handler_supports_socks = HAS_SOCKS
+ # httpx sends an unbracketed IPv6 authority to the proxy, so the proxy
+ # answers 400; reproducible with httpx alone, without Scrapy involved.
+ # https://github.com/pydantic/httpx2/pull/1091
+ handler_supports_ipv6_destination = False
@pytest.mark.requires_internet
diff --git a/tests/test_downloader_handler_twisted_http11.py b/tests/test_downloader_handler_twisted_http11.py
index e956d1c09..794986c37 100644
--- a/tests/test_downloader_handler_twisted_http11.py
+++ b/tests/test_downloader_handler_twisted_http11.py
@@ -5,11 +5,20 @@ from contextlib import asynccontextmanager
from typing import TYPE_CHECKING, Any, cast
import pytest
+from twisted.internet.address import IPv6Address
from twisted.internet.error import ConnectingCancelledError
+from twisted.internet.interfaces import (
+ IAddress,
+ IHostnameResolver,
+ IHostResolution,
+ IReactorPluggableNameResolver,
+ IResolutionReceiver,
+)
from twisted.internet.protocol import Factory, Protocol
from twisted.internet.testing import MemoryReactorClock
from twisted.python.failure import Failure
-from twisted.web.client import URI
+from twisted.web.client import URI, BrowserLikePolicyForHTTPS
+from zope.interface import implementer
from scrapy import Request, Spider
from scrapy.core.downloader.contextfactory import _load_context_factory_from_settings
@@ -17,7 +26,7 @@ from scrapy.core.downloader.handlers.http11 import (
HTTP11DownloadHandler,
TunnelError,
_tunnel_request_data,
- _TunnelingTCP4ClientEndpoint,
+ _TunnelingEndpoint,
)
from scrapy.crawler import Crawler
from scrapy.exceptions import (
@@ -25,11 +34,13 @@ from scrapy.exceptions import (
DownloadConnectionRefusedError,
NotConfigured,
)
+from scrapy.resolver import HostResolution
from scrapy.utils.defer import maybe_deferred_to_future
from scrapy.utils.misc import build_from_crawler
from scrapy.utils.spider import DefaultSpider
from scrapy.utils.test import get_crawler
from tests import NON_EXISTING_RESOLVABLE
+from tests.utils import ipv6_loopback_available
from tests.utils.bases.download_handlers_http import (
TestHttpBase,
TestHttpProxyBase,
@@ -47,9 +58,10 @@ from tests.utils.bases.download_handlers_http import (
from tests.utils.decorators import coroutine_test
if TYPE_CHECKING:
- from collections.abc import AsyncGenerator
+ from collections.abc import AsyncGenerator, Generator, Sequence
from twisted.internet.base import ReactorBase
+ from twisted.web.iweb import IPolicyForHTTPS
from scrapy.core.downloader.handlers import DownloadHandlerProtocol
@@ -93,11 +105,11 @@ def test_tunneling_cancelled_before_connected() -> None:
the connection to the proxy is established.
"""
reactor = MemoryReactorClock()
- endpoint = _TunnelingTCP4ClientEndpoint(
+ endpoint = _TunnelingEndpoint(
reactor=cast("ReactorBase", reactor),
host=b"example.com",
port=443,
- proxyConf=("127.0.0.1", 8080, None),
+ proxyConf=("::1", 8080, None),
contextFactory=_load_context_factory_from_settings(get_crawler()),
timeout=30,
)
@@ -169,6 +181,13 @@ class TestMitmProxy(HTTP11DownloadHandlerMixin, TestMitmProxyBase):
handler_supports_tls_in_tls = False
+ not ipv6_loopback_available(), reason="IPv6 loopback is not available"
+)
+class TestMitmProxyIPv6(TestMitmProxy):
+ proxy_host = "::1"
+
+
@pytest.mark.parametrize(
("url", "expected_authority"),
[
@@ -181,7 +200,7 @@ class TestMitmProxy(HTTP11DownloadHandlerMixin, TestMitmProxyBase):
def test_connect_authority(url: bytes, expected_authority: bytes) -> None:
uri = URI.fromBytes(url)
tunnel_req = _tunnel_request_data(
- _TunnelingTCP4ClientEndpoint._format_host(uri.host), uri.port
+ _TunnelingEndpoint._format_host(uri.host), uri.port
)
assert tunnel_req == (
b"CONNECT " + expected_authority + b" HTTP/1.1\r\n"
@@ -189,6 +208,179 @@ def test_connect_authority(url: bytes, expected_authority: bytes) -> None:
)
+@implementer(IHostnameResolver)
+class _SentinelIPv6Resolver:
+ """Resolves one sentinel hostname to ::1, delegating everything else.
+
+ There is no portable hostname that resolves only to an IPv6 address, so the
+ test that needs one provides it here.
+ """
+
+ hostname = "ipv6-only-proxy.invalid"
+
+ def __init__(self, original: IHostnameResolver):
+ self._original = original
+
+ def resolveHostName(
+ self,
+ resolutionReceiver: IResolutionReceiver,
+ hostName: str,
+ portNumber: int = 0,
+ addressTypes: Sequence[type[IAddress]] | None = None,
+ transportSemantics: str = "TCP",
+ ) -> IHostResolution:
+ if hostName != self.hostname:
+ return self._original.resolveHostName(
+ resolutionReceiver,
+ hostName,
+ portNumber,
+ addressTypes,
+ transportSemantics,
+ )
+ resolutionReceiver.resolutionBegan(HostResolution(hostName))
+ # Honor addressTypes, as a real resolver does: a caller that asks only
+ # for IPv4 addresses gets no results for this name.
+ if addressTypes is None or IPv6Address in addressTypes:
+ resolutionReceiver.addressResolved(IPv6Address("TCP", "::1", portNumber))
+ resolutionReceiver.resolutionComplete()
+ return resolutionReceiver
+
+
+@implementer(IHostnameResolver)
+class _UnresolvingResolver:
+ """Resolves nothing, and records what it was asked to resolve.
+
+ Stands in for Scrapy's default resolver, which cannot resolve an IPv6
+ literal: it only ever reports IPv4 addresses.
+ """
+
+ def __init__(self) -> None:
+ self.names: list[str] = []
+
+ def resolveHostName(
+ self,
+ resolutionReceiver: IResolutionReceiver,
+ hostName: str,
+ portNumber: int = 0,
+ addressTypes: Sequence[type[IAddress]] | None = None,
+ transportSemantics: str = "TCP",
+ ) -> IHostResolution:
+ self.names.append(hostName)
+ resolution = HostResolution(hostName)
+ resolutionReceiver.resolutionBegan(resolution)
+ resolutionReceiver.resolutionComplete()
+ return resolution
+
+
+@implementer(IReactorPluggableNameResolver)
+class _ReactorWithNameResolver:
+ """The given reactor, but resolving names with the given resolver.
+
+ ``HostnameEndpoint`` reads ``nameResolver`` off the reactor when it
+ connects, so injecting one here keeps the test from having to install a
+ resolver on the global reactor and restore it afterwards.
+ """
+
+ def __init__(self, reactor: object, nameResolver: IHostnameResolver):
+ self._reactor = reactor
+ self.nameResolver = nameResolver
+
+ def installNameResolver(
+ self, resolver: IHostnameResolver
+ ) -> IHostnameResolver: # pragma: no cover
+ raise NotImplementedError
+
+ def __getattr__(self, name: str) -> Any:
+ return getattr(self._reactor, name)
+
+
+class _FakeProxyProtocol(Protocol):
+ """Answers any CONNECT request with a refusal, so no TLS is attempted."""
+
+ def dataReceived(self, data: bytes) -> None:
+ assert self.transport
+ self.transport.write(b"HTTP/1.1 403 Forbidden\r\n\r\n")
+
+
+def fake_proxy_port() -> Generator[int]:
+ """The port of a CONNECT-answering server listening on ::1."""
+ from twisted.internet import reactor
+
+ listening_port = reactor.listenTCP(
+ 0, Factory.forProtocol(_FakeProxyProtocol), interface="::1"
+ )
+ try:
+ yield listening_port.getHost().port
+ finally:
+ listening_port.stopListening()
+
+
+def ipv6_only_proxy(fake_proxy_port: int) -> tuple[ReactorBase, str, int]:
+ """That server, reachable only by a name that resolves to ::1."""
+ from twisted.internet import reactor
+
+ resolving_reactor = _ReactorWithNameResolver(
+ reactor, _SentinelIPv6Resolver(reactor.nameResolver)
+ )
+ return (
+ cast("ReactorBase", resolving_reactor),
+ _SentinelIPv6Resolver.hostname,
+ fake_proxy_port,
+ )
+
+
+ not ipv6_loopback_available(), reason="IPv6 loopback is not available"
+)
+@coroutine_test
+async def test_tunnel_to_proxy_reachable_only_over_ipv6(
+ ipv6_only_proxy: tuple[ReactorBase, str, int],
+) -> None:
+ """The CONNECT tunnel must reach a proxy whose name resolves only to IPv6.
+
+ Getting as far as a TunnelError means the proxy was reached and answered; a
+ connection error instead would mean the endpoint picked the wrong address
+ 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, None),
+ contextFactory=cast("IPolicyForHTTPS", BrowserLikePolicyForHTTPS()),
+ timeout=10,
+ )
+ with pytest.raises(TunnelError, match="Could not open CONNECT tunnel"):
+ await maybe_deferred_to_future(endpoint.connect(Factory.forProtocol(Protocol)))
+
+
+ not ipv6_loopback_available(), reason="IPv6 loopback is not available"
+)
+@coroutine_test
+async def test_tunnel_to_ipv6_literal_proxy(fake_proxy_port: int) -> None:
+ """The CONNECT tunnel must reach a proxy given as an IPv6 address literal
+ without resolving it, as the default resolver cannot resolve one.
+ """
+ from twisted.internet import reactor
+
+ resolver = _UnresolvingResolver()
+ endpoint = _TunnelingEndpoint(
+ reactor=cast("ReactorBase", _ReactorWithNameResolver(reactor, resolver)),
+ host=b"example.com",
+ port=443,
+ proxyConf=("::1", fake_proxy_port, None),
+ contextFactory=cast("IPolicyForHTTPS", BrowserLikePolicyForHTTPS()),
+ timeout=10,
+ )
+ with pytest.raises(TunnelError, match="Could not open CONNECT tunnel"):
+ await maybe_deferred_to_future(endpoint.connect(Factory.forProtocol(Protocol)))
+ assert not resolver.names
+
+
@pytest.mark.requires_internet
class TestRealWebsite(HTTP11DownloadHandlerMixin, TestRealWebsiteBase):
@property
diff --git a/tests/utils/__init__.py b/tests/utils/__init__.py
index b27c5ade7..ea14f8212 100644
--- a/tests/utils/__init__.py
+++ b/tests/utils/__init__.py
@@ -1,6 +1,8 @@
from __future__ import annotations
+import contextlib
import os
+import socket
from pathlib import Path
from typing import TYPE_CHECKING
@@ -30,6 +32,29 @@ def get_script_run_env() -> dict[str, str]:
return env
+def ipv6_loopback_available() -> bool:
+ """Return True if the IPv6 loopback address (``::1``) can be bound on this host.
+
+ Meant to be used in skip conditions::
+
+ @pytest.mark.skipif(
+ not ipv6_loopback_available(), reason="IPv6 loopback is not available"
+ )
+ """
+ if not getattr(socket, "has_ipv6", False):
+ return False
+ try:
+ with contextlib.closing(
+ socket.socket(socket.AF_INET6, socket.SOCK_STREAM)
+ ) as s:
+ with contextlib.suppress(OSError, AttributeError):
+ s.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_V6ONLY, 1)
+ s.bind(("::1", 0))
+ return True
+ except OSError:
+ return False
+
+
class OneShotLoop:
"""Test stub for create_looping_call: run once immediately, no background task."""
diff --git a/tests/utils/bases/download_handlers_http.py b/tests/utils/bases/download_handlers_http.py
index 985a88276..d0b439128 100644
--- a/tests/utils/bases/download_handlers_http.py
+++ b/tests/utils/bases/download_handlers_http.py
@@ -32,7 +32,10 @@ from scrapy.exceptions import (
UnsupportedURLSchemeError,
)
from scrapy.http import Headers, HtmlResponse, Request, Response, TextResponse
-from scrapy.utils._deps_compat import TWISTED_TLS_LIMITS_OFFBY1
+from scrapy.utils._deps_compat import (
+ TWISTED_TLS_LIMITS_OFFBY1,
+ W3LIB_STRIPS_IPV6_BRACKETS,
+)
from scrapy.utils.defer import deferred_from_coro, maybe_deferred_to_future
from scrapy.utils.misc import build_from_crawler
from scrapy.utils.reactor import is_reactor_installed
@@ -51,6 +54,7 @@ from tests.spiders import (
SimpleSpider,
SingleRequestSpider,
)
+from tests.utils import ipv6_loopback_available
from tests.utils.decorators import coroutine_test
if TYPE_CHECKING:
@@ -131,6 +135,20 @@ class TestHttpBase(ABC):
response = await download_handler.download_request(request)
assert response.body == b"Works"
+ @pytest.mark.skipif(
+ not ipv6_loopback_available(), reason="IPv6 loopback is not available"
+ )
+ @pytest.mark.skipif(
+ W3LIB_STRIPS_IPV6_BRACKETS, reason="https://github.com/scrapy/w3lib/pull/253"
+ )
+ @coroutine_test
+ async def test_download_ipv6_literal(self, mockserver_ipv6: MockServer) -> None:
+ """Download from a URL whose host is an IPv6 address literal."""
+ request = Request(mockserver_ipv6.url("/text", is_secure=self.is_secure))
+ async with self.get_dh() as download_handler:
+ response = await download_handler.download_request(request)
+ assert response.body == b"Works"
+
@coroutine_test
async def test_download_head(self, mockserver: MockServer) -> None:
request = Request(
@@ -1724,6 +1742,10 @@ PROXY_KINDS = ["http", "https", "socks5"]
class TestMitmProxyBase(ABC):
handler_supports_socks: bool = False
+ # whether the handler supports proxying to an IPv6 literal destination
+ handler_supports_ipv6_destination: bool = True
+ # address the proxy listens on, read by the proxy_server fixture
+ proxy_host: str = "127.0.0.1"
# whether the handler supports HTTPS proxies with HTTPS destinations
handler_supports_tls_in_tls: bool = True
@@ -1850,6 +1872,41 @@ class TestMitmProxyBase(ABC):
self._assert_got_response_code(200, caplog.text)
self._assert_headers(responses[0].headers, https_dest)
+ @pytest.mark.skipif(
+ not ipv6_loopback_available(), reason="IPv6 loopback is not available"
+ )
+ @pytest.mark.skipif(
+ W3LIB_STRIPS_IPV6_BRACKETS, reason="https://github.com/scrapy/w3lib/pull/253"
+ )
+ @pytest.mark.parametrize("proxy_server", PROXY_KINDS, indirect=True)
+ @pytest.mark.parametrize(
+ "https_dest", [False, True], ids=["HTTP dest", "HTTPS dest"]
+ )
+ @coroutine_test
+ async def test_proxy_ipv6_destination(
+ self,
+ caplog: pytest.LogCaptureFixture,
+ proxy_server: str,
+ mockserver_ipv6: MockServer,
+ https_dest: bool,
+ ) -> None:
+ """HTTP/HTTPS/SOCKS5 proxy, destination addressed by an IPv6 literal.
+
+ For an HTTPS destination this needs the CONNECT authority to bracket the
+ address, otherwise the proxy sees a malformed ``CONNECT ::1:port``.
+ """
+ if not self.handler_supports_ipv6_destination:
+ pytest.skip("IPv6 literal destinations are not supported behind a proxy")
+ self._maybe_skip(proxy_server, https_dest)
+ crawler = get_crawler(SingleRequestSpider, self.settings_dict)
+ with caplog.at_level(logging.DEBUG):
+ await crawler.crawl_async(
+ seed=mockserver_ipv6.url("/status?n=200", is_secure=https_dest)
+ )
+ assert isinstance(crawler.spider, SingleRequestSpider)
+ self._assert_got_response_code(200, caplog.text)
+ self._assert_headers(crawler.spider.meta["responses"][0].headers, https_dest)
+
@staticmethod
def _assert_headers(headers: Headers, https_dest: bool) -> None:
assert b"X-Via-Mitmproxy" in headers