Scrapy, a fast high-level web crawling & scraping framework for Python.
Limit response headers size like browsers (#7813)
Adrian47c83aa964b7
diff --git a/docs/topics/download-handlers.rst b/docs/topics/download-handlers.rstindex ea2e2aa77..a995f55d0 100644--- a/docs/topics/download-handlers.rst+++ b/docs/topics/download-handlers.rst@@ -154,6 +154,8 @@ these exceptions... autoexception:: scrapy.exceptions.ResponseDataLossError+.. autoexception:: scrapy.exceptions.ResponseHeadersTooLargeError+.. autoexception:: scrapy.exceptions.UnsupportedURLSchemeError.. _download-handlers-ref:@@ -180,6 +182,7 @@ individual handler docs for more differences:- Requirements- HTTP- Proxies+ - Headers limit- Bad headers- TLS- IPv6@@ -188,6 +191,7 @@ individual handler docs for more differences:- asyncio- 1.1- HTTP+ - :setting:`DOWNLOAD_HEADERS_MAXSIZE`- Fail- Stdlib ``ssl``- Yes@@ -196,6 +200,7 @@ individual handler docs for more differences:- Reactor, :ref:`twisted-http2 <extras>` extra- 2- None+ - :setting:`DOWNLOAD_HEADERS_MAXSIZE`- Not applicable- ``cryptography``- Needs a setting@@ -204,6 +209,7 @@ individual handler docs for more differences:- Reactor- 1.1- HTTP+ - :setting:`DOWNLOAD_HEADERS_MAXSIZE`- Skip bad- ``cryptography``- Needs a setting@@ -212,6 +218,8 @@ individual handler docs for more differences:- asyncio, :ref:`httpx <extras>` extra- 1.1, 2- HTTP, SOCKS+ - | HTTP/1.1: 100 KiB+ | HTTP/2: 64 KiB- Fail- Stdlib ``ssl``- Yes, except through a proxy@@ -292,6 +300,11 @@ Per-request ``bindaddress`` No (not supported by the library)TLS implementation Standard library ``ssl``=========================== =======================================+Other limitations:++- Responses with more than 128 header lines are rejected, regardless of+ :setting:`DOWNLOAD_HEADERS_MAXSIZE`.+.. _twisted-http2-handler:H2DownloadHandler@@ -451,6 +464,12 @@ Other limitations:limitations of ``httpx``) which may lead to higher resource usage whenusing proxy rotation.+- ``httpx`` does not allow configuring the response header size limit of its+ HTTP client, so :setting:`DOWNLOAD_HEADERS_MAXSIZE` and+ :setting:`DOWNLOAD_HEADERS_WARNSIZE` have no effect. Over HTTP/1.1 the+ limit is also approximate, as it only applies while the response head is+ still incomplete, so a complete head slightly above it is accepted.+- Requests to a URL with an IPv6 address literal, such as``https://[::1]/``, `do not work through a proxy<https://github.com/pydantic/httpx2/pull/1091>`__.diff --git a/docs/topics/settings.rst b/docs/topics/settings.rstindex 68a8a6cf7..f56942fc5 100644--- a/docs/topics/settings.rst+++ b/docs/topics/settings.rst@@ -1322,6 +1322,70 @@ non-zero handler-specific value will be used instead.handler <topics-download-handlers>`, so it's not guaranteed to be supportedby all 3rd-party handlers.+.. setting:: DOWNLOAD_HEADERS_MAXSIZE++DOWNLOAD_HEADERS_MAXSIZE+------------------------++.. versionadded:: VERSION++Default: ``393216`` (384 KiB)++The maximum response header size (in bytes) allowed. Responses with bigger+headers are aborted and raise+:exc:`~scrapy.exceptions.ResponseHeadersTooLargeError`.++This limit applies to the response head as a whole, i.e. to the status line+plus every header line, rather than to individual headers. That mirrors what+web browsers do; the default value matches the limit of Firefox_, the most+lenient of them.++Use ``0`` to disable this limit.++.. _Firefox: https://searchfox.org/mozilla-central/search?q=network.http.max_response_header_size++.. note::++ Over HTTP/2 this limit is applied as+ ``SETTINGS_MAX_HEADER_LIST_SIZE``, which `RFC 9113 §6.5.2`_ defines in+ terms of the uncompressed size of every header field plus an overhead of 32+ bytes each, rather than in terms of the bytes read from the connection.+ Web browsers use the same value for both protocols regardless of that+ difference, and so does Scrapy.++.. _RFC 9113 §6.5.2: https://datatracker.ietf.org/doc/html/rfc9113#section-6.5.2++.. note::++ Handling of this setting needs to be implemented inside the :ref:`download+ handler <topics-download-handlers>`, so it's not guaranteed to be supported+ by all handlers. See :ref:`download-handlers-ref`.++.. setting:: DOWNLOAD_HEADERS_WARNSIZE++DOWNLOAD_HEADERS_WARNSIZE+-------------------------++.. versionadded:: VERSION++Default: ``262144`` (256 KiB)++If the size of the headers of a response exceeds this value, a warning will be+logged about it. The default value matches the limit of Chromium_, the least+lenient of the web browsers used as a reference for+:setting:`DOWNLOAD_HEADERS_MAXSIZE`, so that responses that some web browsers+would reject are reported even though Scrapy accepts them.++Use ``0`` to disable this limit.++.. _Chromium: https://source.chromium.org/chromium/chromium/src/+/main:net/http/http_stream_parser.h++.. note::++ Handling of this setting needs to be implemented inside the :ref:`download+ handler <topics-download-handlers>`, so it's not guaranteed to be supported+ by all handlers. See :ref:`download-handlers-ref`.+.. setting:: DOWNLOAD_MAXSIZE.. reqmeta:: download_maxsizediff --git a/scrapy/core/_http2/protocol.py b/scrapy/core/_http2/protocol.pyindex bcdbfe88c..8f2415556 100644--- a/scrapy/core/_http2/protocol.py+++ b/scrapy/core/_http2/protocol.py@@ -20,7 +20,7 @@ from h2.events import (UnknownFrameReceived,WindowUpdated,)-from h2.exceptions import FrameTooLargeError, H2Error+from h2.exceptions import DenialOfServiceError, FrameTooLargeError, H2Errorfrom h2.settings import SettingCodesfrom twisted.internet.interfaces import (IAddress,@@ -33,8 +33,9 @@ from twisted.protocols.policies import TimeoutMixinfrom zope.interface import implementerfrom scrapy.core._http2.stream import Stream, StreamCloseReason-from scrapy.exceptions import DownloadTimeoutError+from scrapy.exceptions import DownloadTimeoutError, ResponseHeadersTooLargeErrorfrom scrapy.http import Request, Response+from scrapy.utils._download_handlers import get_headers_maxsize_msgfrom scrapy.utils._ssl import _log_ssl_conn_debug_infofrom scrapy.utils.deprecate import warn_on_deprecated_spider_attribute@@ -113,6 +114,26 @@ class H2ClientProtocol(Protocol, TimeoutMixin):config = H2Configuration(client_side=True)self.conn = H2Connection(config=config)+ # Unlike HTTP/1.1, where we count the bytes of the response head as+ # they come from the wire, HTTP/2 uses the accounting that RFC 9113+ # §6.5.2 defines for SETTINGS_MAX_HEADER_LIST_SIZE: the uncompressed+ # size of every header field plus 32 bytes of overhead each. Web+ # browsers use the same limit for both protocols despite that+ # difference, so we do the same.+ self._headers_maxsize: int = crawler.settings.getint("DOWNLOAD_HEADERS_MAXSIZE")+ # SETTINGS values are 32-bit, so the maximum stands for "no limit".+ max_header_list_size = self._headers_maxsize or 2**32 - 1+ # local_settings is what we advertise to the remote peer, while the+ # decoder is what enforces the limit on the headers we do receive.+ self.conn.local_settings.max_header_list_size = max_header_list_size+ # Setting a value only queues it; acknowledging it here, before the+ # connection is initiated, makes the initial SETTINGS frame carry it.+ self.conn.local_settings.acknowledge()+ self.conn.decoder.max_header_list_size = max_header_list_size+ self.headers_warnsize: int = crawler.settings.getint(+ "DOWNLOAD_HEADERS_WARNSIZE"+ )+# ID of the next request stream# Following the convention - 'Streams initiated by a client MUST# use odd-numbered stream identifiers' (RFC 7540 - Section 5.1.1)@@ -320,6 +341,22 @@ class H2ClientProtocol(Protocol, TimeoutMixin):events = self.conn.receive_data(data)self._handle_events(events)except H2Error as e:+ if isinstance(e, DenialOfServiceError):+ # h2 only raises this when the remote peer disregards the+ # SETTINGS_MAX_HEADER_LIST_SIZE that we advertised.+ self._lose_connection_with_error(+ [+ ResponseHeadersTooLargeError(+ get_headers_maxsize_msg(+ None,+ self._headers_maxsize,+ self.metadata["uri"].toBytes().decode(),+ )+ )+ ]+ )+ return+if isinstance(e, FrameTooLargeError):# hyper-h2 does not drop the connection in this scenario, we# need to abort the connection manually.diff --git a/scrapy/core/_http2/stream.py b/scrapy/core/_http2/stream.pyindex 022650c7c..830efff0f 100644--- a/scrapy/core/_http2/stream.py+++ b/scrapy/core/_http2/stream.py@@ -21,6 +21,7 @@ from scrapy.exceptions import (from scrapy.http.headers import Headersfrom scrapy.utils._download_handlers import (check_stop_download,+ get_headers_warnsize_msg,get_maxsize_msg,get_warnsize,get_warnsize_msg,@@ -378,6 +379,19 @@ class Stream:else:self._response["headers"].appendlist(name, value)+ # DOWNLOAD_HEADERS_MAXSIZE is enforced by the HPACK decoder, which has+ # no equivalent hook for a warning, so the warning happens here instead,+ # using the same accounting that RFC 9113 §6.5.2 defines.+ headers_warnsize = self._protocol.headers_warnsize+ if headers_warnsize:+ headers_size = sum(len(name) + len(value) + 32 for name, value in headers)+ if headers_size > headers_warnsize:+ logger.warning(+ get_headers_warnsize_msg(+ headers_size, headers_warnsize, self._request.url+ )+ )+expected_size = int(self._response["headers"].get(b"Content-Length", -1))if stop_download := check_stop_download(diff --git a/scrapy/core/downloader/handlers/_aiohttp.py b/scrapy/core/downloader/handlers/_aiohttp.pyindex 2804208aa..70aa14877 100644--- a/scrapy/core/downloader/handlers/_aiohttp.py+++ b/scrapy/core/downloader/handlers/_aiohttp.py@@ -1,6 +1,7 @@from __future__ import annotationsimport ipaddress+import loggingimport socketimport sslimport sys@@ -16,11 +17,17 @@ from scrapy.exceptions import (DownloadConnectionRefusedError,DownloadFailedError,DownloadTimeoutError,+ ResponseHeadersTooLargeError,UnsupportedURLSchemeError,)from scrapy.http import Headers-from scrapy.utils._download_handlers import get_proxy_headers+from scrapy.utils._download_handlers import (+ get_headers_maxsize_msg,+ get_headers_warnsize_msg,+ get_proxy_headers,+)from scrapy.utils._ssl import _log_sslobj_debug_info, _make_ssl_context+from scrapy.utils.python import _iter_exc_causesfrom ._base_streaming import BaseStreamingDownloadHandler, _BaseResponseArgs@@ -36,6 +43,9 @@ if TYPE_CHECKING:from scrapy.crawler import Crawler+logger = logging.getLogger(__name__)++class _AsyncResolver(aiohttp.AsyncResolver):"""Resolves only the host and sets the requested port on the results.@@ -118,11 +128,17 @@ class AiohttpDownloadHandler(BaseStreamingDownloadHandler[_ClientResponse]):keepalive_timeout=self._keepalive_timeout or None,force_close=not self._keepalive_timeout,)+ # aiohttp limits the size of each line of the response head; the size+ # of the head as a whole is checked in _check_headers_size() once it+ # has been received.+ line_maxsize = self._headers_maxsize or sys.maxsizeself._session: aiohttp.ClientSession = aiohttp.ClientSession(connector=connector,cookie_jar=aiohttp.DummyCookieJar(),auto_decompress=False,response_class=_ClientResponse,+ max_line_size=line_maxsize,+ max_field_size=line_maxsize,skip_auto_headers=("Accept","Accept-Encoding",@@ -162,6 +178,7 @@ class AiohttpDownloadHandler(BaseStreamingDownloadHandler[_ClientResponse]):proxy=proxy,proxy_headers=dict(proxy_headers) or None,) as response:+ self._check_headers_size(response, request)yield cast("_ClientResponse", response)except TimeoutError as e:raise DownloadTimeoutError(@@ -176,9 +193,31 @@ class AiohttpDownloadHandler(BaseStreamingDownloadHandler[_ClientResponse]):raise CannotResolveHostError(str(e)) from eexcept aiohttp.ClientConnectorError as e:raise DownloadConnectionRefusedError(str(e)) from e+ except aiohttp.ClientResponseError as e:+ if any(+ isinstance(cause, aiohttp.http_exceptions.LineTooLong)+ for cause in _iter_exc_causes(e)+ ):+ raise ResponseHeadersTooLargeError(+ get_headers_maxsize_msg(None, self._headers_maxsize, request.url)+ ) from e+ raise DownloadFailedError(str(e)) from eexcept aiohttp.ClientError as e:raise DownloadFailedError(str(e)) from e+ def _check_headers_size(+ self, response: aiohttp.ClientResponse, request: Request+ ) -> None:+ size = sum(len(name) + len(value) + 4 for name, value in response.raw_headers)+ if self._headers_maxsize and size > self._headers_maxsize:+ raise ResponseHeadersTooLargeError(+ get_headers_maxsize_msg(size, self._headers_maxsize, request.url)+ )+ if self._headers_warnsize and size > self._headers_warnsize:+ logger.warning(+ get_headers_warnsize_msg(size, self._headers_warnsize, request.url)+ )+@staticmethoddef _extract_headers(response: _ClientResponse) -> Headers:return Headers(response.raw_headers)diff --git a/scrapy/core/downloader/handlers/_base_http.py b/scrapy/core/downloader/handlers/_base_http.pyindex 930c22285..c92b8104d 100644--- a/scrapy/core/downloader/handlers/_base_http.py+++ b/scrapy/core/downloader/handlers/_base_http.py@@ -59,6 +59,10 @@ class BaseHttpDownloadHandler(BaseDownloadHandler, ABC):super().__init__(crawler)self._default_maxsize: int = crawler.settings.getint("DOWNLOAD_MAXSIZE")self._default_warnsize: int = crawler.settings.getint("DOWNLOAD_WARNSIZE")+ self._headers_maxsize: int = crawler.settings.getint("DOWNLOAD_HEADERS_MAXSIZE")+ self._headers_warnsize: int = crawler.settings.getint(+ "DOWNLOAD_HEADERS_WARNSIZE"+ )self._fail_on_dataloss: bool = crawler.settings.getbool("DOWNLOAD_FAIL_ON_DATALOSS")diff --git a/scrapy/core/downloader/handlers/_httpx.py b/scrapy/core/downloader/handlers/_httpx.pyindex 43e2dced2..bece7ba27 100644--- a/scrapy/core/downloader/handlers/_httpx.py+++ b/scrapy/core/downloader/handlers/_httpx.py@@ -15,6 +15,7 @@ from scrapy.exceptions import (DownloadFailedError,DownloadTimeoutError,NotConfigured,+ ResponseHeadersTooLargeError,UnsupportedURLSchemeError,)from scrapy.http import Headers@@ -73,6 +74,22 @@ else:pass+def _is_headers_too_large_exception(exc: BaseException) -> bool:+ """Return whether *exc* was caused by response headers exceeding the limit+ of the underlying HTTP client, which httpx does not let us configure and+ reports as a generic protocol error."""+ for cause in _iter_exc_causes(exc):+ # h11 reports it as a protocol error hinting at the 431 status, which+ # it uses for nothing else.+ if getattr(cause, "error_status_hint", None) == 431:+ return True+ # h2 reports it as a symptom of an HPACK bomb, which is what exceeding+ # SETTINGS_MAX_HEADER_LIST_SIZE looks like from its point of view.+ if HAS_HTTP2 and isinstance(cause, h2.exceptions.DenialOfServiceError):+ return True+ return False++if TYPE_CHECKING:_Base = BaseStreamingDownloadHandler[httpx.Response]else:@@ -217,6 +234,11 @@ class HttpxDownloadHandler(_Base):except httpx.ProxyError as e:raise DownloadConnectionRefusedError(str(e)) from eexcept DOWNLOAD_FAILED_EXCEPTIONS as e:+ if _is_headers_too_large_exception(e):+ raise ResponseHeadersTooLargeError(+ f"Received response headers larger than the limit of the "+ f"HTTP client while requesting {request.url}: {e}"+ ) from eraise DownloadFailedError(str(e)) from e@staticmethoddiff --git a/scrapy/core/downloader/handlers/http11.py b/scrapy/core/downloader/handlers/http11.pyindex 0850759d7..b744a00b7 100644--- a/scrapy/core/downloader/handlers/http11.py+++ b/scrapy/core/downloader/handlers/http11.py@@ -5,6 +5,7 @@ from __future__ import annotationsimport ipaddressimport loggingimport re+import sysfrom contextlib import suppressfrom functools import partialfrom io import BytesIO@@ -52,12 +53,15 @@ from scrapy.exceptions import (DownloadTimeoutError,NotConfigured,ResponseDataLossError,+ ResponseHeadersTooLargeError,StopDownload,)from scrapy.http import Headers, Responsefrom scrapy.utils._download_handlers import (check_stop_download,get_dataloss_msg,+ get_headers_maxsize_msg,+ get_headers_warnsize_msg,get_maxsize_msg,get_proxy_headers,get_warnsize,@@ -99,6 +103,57 @@ class _ResultT(TypedDict):stop_download: NotRequired[StopDownload | None]+def _limit_response_headers(+ parser: HTTPClientParser, maxsize: int, warnsize: int+) -> None:+ """Make *parser* enforce *maxsize* and *warnsize* on the total size of the+ response head, i.e. the status line plus the header lines plus their line+ delimiters.++ Twisted limits the length of *individual* lines instead+ (:attr:`~twisted.protocols.basic.LineReceiver.MAX_LENGTH`, 16 KiB), and+ silently drops the connection when a line exceeds it, which makes the+ resulting error impossible to tell apart from an unrelated disconnection.+ Web browsers instead limit the total size of the response head, which is+ what this function reproduces. See+ https://github.com/twisted/twisted/issues/8570.++ Twisted builds its response parser without offering a way to configure it,+ hence the instance-level overrides below.+ """+ url = (parser.request.absoluteURI or parser.request.uri).decode()+ # Keep the Twisted line length limit, which cannot report a meaningful+ # error, from ever triggering before our own limit does.+ parser.MAX_LENGTH = maxsize or sys.maxsize+ delimiter_size = len(parser.delimiter)+ line_received = parser.lineReceived+ size = 0+ warned = False++ def lineReceived(line: bytes) -> None:+ nonlocal size, warned+ size += len(line) + delimiter_size+ if maxsize and size > maxsize:+ raise ResponseHeadersTooLargeError(+ get_headers_maxsize_msg(size, maxsize, url)+ )+ if warnsize and size > warnsize and not warned:+ warned = True+ logger.warning(get_headers_warnsize_msg(size, warnsize, url))+ line_received(line) # type: ignore[no-untyped-call]++ def lineLengthExceeded(line: bytes) -> None:+ # A single line went over MAX_LENGTH, so lineReceived() never saw it.+ # line holds the whole unparsed remainder of the buffer, so the+ # reported size is a lower bound.+ raise ResponseHeadersTooLargeError(+ get_headers_maxsize_msg(size + len(line), maxsize, url)+ )++ parser.lineReceived = lineReceived # type: ignore[method-assign]+ parser.lineLengthExceeded = lineLengthExceeded # type: ignore[method-assign]++class _LenientHTTPClientParser(HTTPClientParser):"""Response parser that skips bad response header lines, those with nocolon in them, instead of failing to parse the whole response.@@ -146,20 +201,39 @@ class _LenientHTTPClientParser(HTTPClientParser):self._partialHeader.append(line) # type: ignore[union-attr]-class _LenientHTTP11ClientProtocol(HTTP11ClientProtocol):- """Protocol that parses responses with :class:`_LenientHTTPClientParser`."""+class _ScrapyHTTP11ClientProtocol(HTTP11ClientProtocol):+ """:class:`~twisted.web._newclient.HTTP11ClientProtocol` subclass that+ parses responses with :class:`_LenientHTTPClientParser` and limits the size+ of response headers."""++ def __init__(+ self,+ quiescentCallback: Callable[[HTTP11ClientProtocol], None],+ headers_maxsize: int,+ headers_warnsize: int,+ ):+ super().__init__(quiescentCallback) # type: ignore[no-untyped-call]+ self._headers_maxsize: int = headers_maxsize+ self._headers_warnsize: int = headers_warnsizedef request(self, request: TxRequest) -> Deferred[IResponse]:+ previous_parser = self._parserd: Deferred[IResponse] = super().request(request)- # HTTP11ClientProtocol.request() hardcodes the parser class, so the- # only way to use a different one is to replace the class of the parser- # object that it creates. This is safe because- # _LenientHTTPClientParser defines no additional state. The parser is- # always there because HTTPConnectionPool only reuses connections whose- # protocol is in the QUIESCENT state, for which request() always- # creates a parser.- assert self._parser is not None- self._parser.__class__ = _LenientHTTPClientParser+ # super() builds a new response parser for every request it accepts, so+ # the size counter resets as intended on pooled connections. It can also+ # refuse a request, e.g. on a pooled connection that just died, in which+ # case it leaves the parser of the previous request in place, and+ # limiting that one again would reset its counter mid-response.+ parser = self._parser+ if parser is not None and parser is not previous_parser:+ # HTTP11ClientProtocol.request() hardcodes the parser class, so the+ # only way to use a different one is to replace the class of the+ # parser object that it creates. This is safe because+ # _LenientHTTPClientParser defines no additional state.+ parser.__class__ = _LenientHTTPClientParser+ _limit_response_headers(+ parser, self._headers_maxsize, self._headers_warnsize+ )# For responses without a body, twisted.web.client.Response never# hands its transport to a protocol, so the certificate and IP@@ -186,7 +260,7 @@ class _LenientHTTP11ClientProtocol(HTTP11ClientProtocol):return d-class _TrackedHTTP11ClientProtocol(_LenientHTTP11ClientProtocol):+class _TrackedHTTP11ClientProtocol(_ScrapyHTTP11ClientProtocol):"""Connection that tells the pool that opened it when it closes, whether itwas cached at the time or in use."""@@ -213,7 +287,11 @@ class _BoundedHTTP11ClientFactory(_HTTP11ClientFactory):self._key: Any = keydef buildProtocol(self, addr: IAddress | None) -> _TrackedHTTP11ClientProtocol:- protocol = _TrackedHTTP11ClientProtocol(self._quiescentCallback) # type: ignore[no-untyped-call]+ protocol = _TrackedHTTP11ClientProtocol(+ self._quiescentCallback,+ self._pool._headers_maxsize,+ self._pool._headers_warnsize,+ )protocol._pool = self._poolprotocol._pool_key = self._keyself._pool._open.add(protocol)@@ -232,10 +310,19 @@ class _BoundedHTTPConnectionPool(HTTPConnectionPool):_factory = _BoundedHTTP11ClientFactory # type: ignore[assignment]- def __init__(self, reactor: ReactorBase, limit: int, keepalive_timeout: float):+ def __init__(+ self,+ reactor: ReactorBase,+ limit: int,+ keepalive_timeout: float,+ headers_maxsize: int,+ headers_warnsize: int,+ ):super().__init__(reactor, persistent=bool(keepalive_timeout)) # type: ignore[no-untyped-call]self.cachedConnectionTimeout = keepalive_timeout # type: ignore[assignment]self._limit: int = limit+ self._headers_maxsize: int = headers_maxsize+ self._headers_warnsize: int = headers_warnsizeself._open: set[_TrackedHTTP11ClientProtocol] = set()def _newConnection(@@ -286,7 +373,11 @@ class HTTP11DownloadHandler(BaseHttpDownloadHandler):from twisted.internet import reactorself._pool: _BoundedHTTPConnectionPool = _BoundedHTTPConnectionPool(- reactor, self._pool_size_total, self._keepalive_timeout+ reactor,+ self._pool_size_total,+ self._keepalive_timeout,+ self._headers_maxsize,+ self._headers_warnsize,)self._pool.maxPersistentPerHost = self._pool_size_per_host@@ -314,6 +405,7 @@ class HTTP11DownloadHandler(BaseHttpDownloadHandler):warnsize=getattr(self._crawler.spider, "download_warnsize", self._default_warnsize),+ headers_maxsize=self._headers_maxsize,fail_on_dataloss=self._fail_on_dataloss,crawler=self._crawler,tls_verbose_logging=self._tls_verbose_logging,@@ -389,6 +481,7 @@ class _TunnelProtocol(Protocol):proxyHost: str,proxyPort: int,proxyHeaders: tuple[tuple[str, str], ...] = (),+ headersMaxsize: int = 0,):self._connectedDeferred = connectedDeferredself._wrappedProtocol = wrappedProtocol@@ -397,6 +490,7 @@ class _TunnelProtocol(Protocol):self._proxyHost = proxyHostself._proxyPort = proxyPortself._proxyHeaders = proxyHeaders+ self._headersMaxsize = headersMaxsizeself._connectBuffer: bytearray = bytearray()self._tunnelReady = False@@ -435,6 +529,20 @@ class _TunnelProtocol(Protocol):## see https://github.com/scrapy/scrapy/issues/2491if b"\r\n\r\n" not in self._connectBuffer:+ if self._headersMaxsize and len(self._connectBuffer) > self._headersMaxsize:+ # A proxy that never ends its response head would otherwise+ # make _connectBuffer grow without bound.+ self._connectedDeferred.errback(+ ResponseHeadersTooLargeError(+ get_headers_maxsize_msg(+ len(self._connectBuffer),+ self._headersMaxsize,+ f"CONNECT {self._format_host(self._host).decode()}:{self._port}",+ )+ )+ )+ assert self.transport is not None+ self.transport.loseConnection()returnheader, _, remaining = bytes(self._connectBuffer).partition(b"\r\n\r\n")respm = self._responseMatcher.match(header)@@ -485,6 +593,7 @@ class _TunnelFactory(ClientFactory):proxyHost: str,proxyPort: int,proxyHeaders: tuple[tuple[str, str], ...] = (),+ headersMaxsize: int = 0,):self._connectedDeferred = connectedDeferredself._wrappedFactory = wrappedFactory@@ -493,6 +602,7 @@ class _TunnelFactory(ClientFactory):self._proxyHost = proxyHostself._proxyPort = proxyPortself._proxyHeaders = proxyHeaders+ self._headersMaxsize = headersMaxsizedef doStart(self) -> None:self._wrappedFactory.doStart()@@ -513,6 +623,7 @@ class _TunnelFactory(ClientFactory):self._proxyHost,self._proxyPort,self._proxyHeaders,+ self._headersMaxsize,)@@ -536,6 +647,7 @@ class _TunnelEndpoint:proxyHost: str,proxyPort: int,proxyHeaders: tuple[tuple[str, str], ...] = (),+ headersMaxsize: int = 0,):self._wrappedEndpoint = wrappedEndpointself._host = host@@ -543,6 +655,7 @@ class _TunnelEndpoint:self._proxyHost = proxyHostself._proxyPort = proxyPortself._proxyHeaders = proxyHeaders+ self._headersMaxsize = headersMaxsizedef connect(self, protocolFactory: Factory) -> Deferred[IProtocol]:proxyProtocol: IProtocol | None = None@@ -571,6 +684,7 @@ class _TunnelEndpoint:self._proxyHost,self._proxyPort,self._proxyHeaders,+ self._headersMaxsize,)proxyDeferred = self._wrappedEndpoint.connect(tunnelFactory)proxyDeferred.addCallbacks(@@ -660,10 +774,12 @@ class _TunnelingAgent(_BindAddressAgent):connectTimeout: float | None = None,bindAddress: tuple[str, int] | None = None,pool: HTTPConnectionPool | None = None,+ headersMaxsize: int = 0,):super().__init__(reactor, contextFactory, connectTimeout, bindAddress, pool)self._proxyConf: tuple[str, int, tuple[tuple[str, str], ...], bool] = proxyConfself._contextFactory: _PolicyForHTTPS = contextFactory+ self._headersMaxsize: int = headersMaxsizedef _getEndpoint(self, uri: URI) -> IStreamClientEndpoint:proxyHost, proxyPort, proxyHeaders, proxyTLS = self._proxyConf@@ -696,7 +812,13 @@ class _TunnelingAgent(_BindAddressAgent):)endpoint = wrapClientTLS(proxyCreator, endpoint)endpoint = _TunnelEndpoint(- endpoint, uri.host, uri.port, proxyHost, proxyPort, proxyHeaders+ endpoint,+ uri.host,+ uri.port,+ proxyHost,+ proxyPort,+ proxyHeaders,+ self._headersMaxsize,)# Set proper Server Name Indication extension for the destination.destCreator = self._contextFactory.creatorForNetloc(uri.host, uri.port)@@ -780,6 +902,7 @@ class _ScrapyAgent:pool: HTTPConnectionPool | None = None,maxsize: int = 0,warnsize: int = 0,+ headers_maxsize: int = 0,fail_on_dataloss: bool = True,crawler: Crawler,tls_verbose_logging: bool = False,@@ -790,6 +913,7 @@ class _ScrapyAgent:self._pool: HTTPConnectionPool | None = poolself._maxsize: int = maxsizeself._warnsize: int = warnsize+ self._headers_maxsize: int = headers_maxsizeself._fail_on_dataloss: bool = fail_on_datalossself._txresponse: TxResponse | None = Noneself._crawler: Crawler = crawler@@ -832,6 +956,7 @@ class _ScrapyAgent:connectTimeout=timeout,bindAddress=bindaddress,pool=self._pool,+ headersMaxsize=self._headers_maxsize,)return _ScrapyProxyAgent(reactor=reactor,diff --git a/scrapy/exceptions.py b/scrapy/exceptions.pyindex 691e12563..ff520757f 100644--- a/scrapy/exceptions.py+++ b/scrapy/exceptions.py@@ -143,6 +143,13 @@ class ResponseDataLossError(Exception):"""Indicates that Scrapy couldn't get a complete response."""+class ResponseHeadersTooLargeError(DownloadFailedError):+ """Indicates that the response headers exceeded+ :setting:`DOWNLOAD_HEADERS_MAXSIZE`, or the equivalent limit of the+ underlying HTTP client for :ref:`download handlers+ <download-handlers-ref>` that do not support that setting."""++class DecompressionError(Exception):"""Raised by:class:`~scrapy.downloadermiddlewares.httpcompression.HttpCompressionMiddleware`diff --git a/scrapy/settings/default_settings.py b/scrapy/settings/default_settings.pyindex 7e42347da..9377fee3a 100644--- a/scrapy/settings/default_settings.py+++ b/scrapy/settings/default_settings.py@@ -77,6 +77,8 @@ __all__ = ["DOWNLOAD_HANDLERS","DOWNLOAD_HANDLERS_BASE","DOWNLOAD_HANDLERS_BY_NAME",+ "DOWNLOAD_HEADERS_MAXSIZE",+ "DOWNLOAD_HEADERS_WARNSIZE","DOWNLOAD_MAXSIZE","DOWNLOAD_SLOTS","DOWNLOAD_TIMEOUT",@@ -332,6 +334,11 @@ DOWNLOAD_HANDLERS_BASE = {}DOWNLOAD_HANDLERS_BY_NAME: dict[str, str] = {}+# Firefox, the most lenient of the reference web browsers, allows 384k.+DOWNLOAD_HEADERS_MAXSIZE = 384 * 1024 # 384k+# Chromium, the least lenient of the reference web browsers, allows 256k.+DOWNLOAD_HEADERS_WARNSIZE = 256 * 1024 # 256k+DOWNLOAD_MAXSIZE = 1024 * 1024 * 1024 # 1024mDOWNLOAD_WARNSIZE = 32 * 1024 * 1024 # 32mdiff --git a/scrapy/utils/_download_handlers.py b/scrapy/utils/_download_handlers.pyindex 79b56bd2c..99a5e02ca 100644--- a/scrapy/utils/_download_handlers.py+++ b/scrapy/utils/_download_handlers.py@@ -21,6 +21,7 @@ from scrapy.exceptions import (DownloadConnectionRefusedError,DownloadFailedError,DownloadTimeoutError,+ ResponseHeadersTooLargeError,StopDownload,UnsupportedURLSchemeError,)@@ -64,6 +65,13 @@ def wrap_twisted_exceptions() -> Iterator[None]:except DNSLookupError as e:raise CannotResolveHostError(str(e)) from eexcept ResponseFailed as e:+ # Twisted reports parsing errors as the underlying reason of a generic+ # failure; report the ones we raise ourselves as themselves. Reasons may+ # be either Failure objects or plain exceptions.+ for reason in e.reasons:+ value = reason.value if isinstance(reason, Failure) else reason+ if isinstance(value, ResponseHeadersTooLargeError):+ raise value from eraise DownloadFailedError(str(e)) from eexcept TxTimeoutError as e:raise DownloadTimeoutError(str(e)) from e@@ -161,6 +169,27 @@ def get_warnsize_msg(size: int, limit: int, request: Request, *, expected: bool))+def get_headers_maxsize_msg(size: int | None, limit: int, url: str) -> str:+ # size is None when the underlying HTTP client only reports that the limit+ # was exceeded, and not by how much.+ prefix = (+ "Received response headers"+ if size is None+ else f"Received {size} bytes of response headers"+ )+ return (+ f"{prefix}, which is larger than the download headers max size "+ f"({limit}), while requesting {url}."+ )+++def get_headers_warnsize_msg(size: int, limit: int, url: str) -> str:+ return (+ f"Received {size} bytes of response headers, which is larger than the "+ f"download headers warn size ({limit}), while requesting {url}."+ )++def get_dataloss_msg(url: str) -> str:return (f"Got data loss in {url}. If you want to process broken "diff --git a/tests/mockserver/http.py b/tests/mockserver/http.pyindex eadcf34bf..5326a4925 100644--- a/tests/mockserver/http.py+++ b/tests/mockserver/http.py@@ -37,6 +37,7 @@ from .http_resources import (H2ResetStream,HostHeaderResource,LargeChunkedFileResource,+ LargeHeadersResource,NoMetaRefreshRedirect,Partial,PayloadResource,@@ -109,6 +110,7 @@ class Root(BaseResource):put_child(self, b"largechunkedfile", LargeChunkedFileResource())put_child(self, b"compress", Compress())put_child(self, b"duplicate-header", DuplicateHeaderResource())+ put_child(self, b"large-headers", LargeHeadersResource())put_child(self, b"response-headers", ResponseHeadersResource())put_child(self, b"set-cookie", SetCookie())put_child(self, b"uri", UriResource())diff --git a/tests/mockserver/http_resources.py b/tests/mockserver/http_resources.pyindex 1c728f0cc..71583e769 100644--- a/tests/mockserver/http_resources.py+++ b/tests/mockserver/http_resources.py@@ -452,6 +452,20 @@ class DuplicateHeaderResource(BaseResource):return b""+class LargeHeadersResource(BaseResource):+ """Return a response with ``count`` headers whose values are ``size`` bytes+ long each."""++ def render(self, request: Request) -> bytes:+ size = getarg(request, b"size", 100, type_=int)+ count = getarg(request, b"count", 1, type_=int)+ for index in range(count):+ request.responseHeaders.setRawHeaders(+ f"X-Large-{index}".encode(), [b"a" * size]+ )+ return b""++class UriResource(BaseResource):"""Return the full uri that was requested"""diff --git a/tests/test_downloader_handler_httpx.py b/tests/test_downloader_handler_httpx.pyindex c0564f52f..acc37f620 100644--- a/tests/test_downloader_handler_httpx.py+++ b/tests/test_downloader_handler_httpx.py@@ -62,6 +62,11 @@ else:class HttpxDownloadHandlerMixin:+ # httpx does not expose the response head size limit of its HTTP client, so+ # DOWNLOAD_HEADERS_MAXSIZE and DOWNLOAD_HEADERS_WARNSIZE do not apply. Over+ # HTTP/1.1 the limit is httpcore's MAX_INCOMPLETE_EVENT_SIZE (100 KiB),+ # which h11 only enforces once the head exceeds it and is still incomplete.+ headers_maxsize: int | None = 100 * 1024handler_supports_partial_response_on_timeout = True@property@@ -115,6 +120,8 @@ class TestHttps(HttpxDownloadHandlerMixin, TestHttpsBase):@pytest.mark.skipif(not HAS_HTTP2, reason="No HTTP/2 support in HttpxDownloadHandler")class TestHttp2(TestHttps):http2 = True+ # Over HTTP/2 the limit is instead h2's DEFAULT_MAX_HEADER_LIST_SIZE.+ headers_maxsize = 64 * 1024default_handler_settings: ClassVar[dict[str, Any]] = {"HTTPX_HTTP2_ENABLED": True,diff --git a/tests/test_downloader_handler_twisted_http11.py b/tests/test_downloader_handler_twisted_http11.pyindex c600481f8..7ca265a02 100644--- a/tests/test_downloader_handler_twisted_http11.py+++ b/tests/test_downloader_handler_twisted_http11.py@@ -3,10 +3,11 @@ from __future__ import annotationsimport sysfrom contextlib import asynccontextmanagerfrom typing import TYPE_CHECKING, Any, cast+from unittest.mock import Mockimport pytestfrom twisted.internet.address import IPv6Address-from twisted.internet.defer import CancelledError+from twisted.internet.defer import CancelledError, Deferredfrom twisted.internet.endpoints import TCP4ClientEndpointfrom twisted.internet.error import ConnectingCancelledError, ConnectionClosedfrom twisted.internet.interfaces import (@@ -19,7 +20,10 @@ from twisted.internet.interfaces import (from twisted.internet.protocol import Factory, Protocolfrom twisted.internet.testing import MemoryReactorClock, StringTransportfrom twisted.python.failure import Failure+from twisted.web._newclient import Request as TxClientRequest+from twisted.web._newclient import RequestNotSentfrom twisted.web.client import URI, BrowserLikePolicyForHTTPS+from twisted.web.http_headers import Headers as TxHeadersfrom zope.interface import implementertry:@@ -34,6 +38,7 @@ from scrapy.core.downloader.handlers.http11 import (HTTP11DownloadHandler,TunnelError,_ScrapyAgent,+ _ScrapyHTTP11ClientProtocol,_tunnel_request_data,_TunnelEndpoint,_TunnelingAgent,@@ -45,6 +50,7 @@ from scrapy.exceptions import (DownloadConnectionRefusedError,DownloadFailedError,NotConfigured,+ ResponseHeadersTooLargeError,)from scrapy.resolver import HostResolutionfrom scrapy.utils.defer import maybe_deferred_to_future@@ -530,6 +536,110 @@ class TestRealWebsite(HTTP11DownloadHandlerMixin, TestRealWebsiteBase):return sys.platform != "win32"+class TestTunnelingHeadersMaxsize:+ """Tests for the DOWNLOAD_HEADERS_MAXSIZE limit that ``_TunnelProtocol``+ applies to the response head of the proxy, which no HTTP client parses for+ us."""++ @staticmethod+ def _get_protocol(+ headers_maxsize: int,+ ) -> tuple[_TunnelProtocol, StringTransport, list[Failure]]:+ deferred: Deferred[IProtocol] = Deferred()+ failures: list[Failure] = []+ deferred.addErrback(failures.append)+ protocol = _TunnelProtocol(+ deferred,+ Mock(),+ b"example.com",+ 443,+ "proxy.example.com",+ 8080,+ headersMaxsize=headers_maxsize,+ )+ transport = StringTransport()+ protocol.makeConnection(transport) # type: ignore[no-untyped-call]+ return protocol, transport, failures++ def test_over_maxsize(self) -> None:+ protocol, transport, failures = self._get_protocol(1024)++ # A proxy response head that never ends.+ for _ in range(3):+ protocol.dataReceived(b"a" * 512)++ assert len(failures) == 1+ assert failures[0].check(ResponseHeadersTooLargeError)+ assert "1024" in str(failures[0].value)+ assert "CONNECT example.com:443" in str(failures[0].value)+ assert transport.disconnecting++ def test_under_maxsize(self) -> None:+ protocol, transport, failures = self._get_protocol(1024)++ protocol.dataReceived(b"a" * 512)++ assert not failures+ assert not transport.disconnecting++ def test_maxsize_disabled(self) -> None:+ protocol, transport, failures = self._get_protocol(0)++ for _ in range(3):+ protocol.dataReceived(b"a" * 512)++ assert not failures+ assert not transport.disconnecting+++class TestScrapyHTTP11ClientProtocol:+ """Tests for the response header size limiting that+ ``_ScrapyHTTP11ClientProtocol`` installs on the response parser that+ Twisted builds for each request."""++ @staticmethod+ def _get_protocol() -> _ScrapyHTTP11ClientProtocol:+ protocol = _ScrapyHTTP11ClientProtocol(lambda _: None, 64 * 1024, 32 * 1024)+ protocol.makeConnection(StringTransport()) # type: ignore[no-untyped-call]+ return protocol++ @staticmethod+ def _get_request() -> TxClientRequest:+ return TxClientRequest(+ b"GET", b"/", TxHeaders({b"host": [b"example.com"]}), None+ )++ def test_parser_is_limited(self) -> None:+ protocol = self._get_protocol()+ protocol.request(self._get_request())+ assert protocol._parser is not None+ assert protocol._parser.MAX_LENGTH == 64 * 1024+ # _limit_response_headers() overrides these on the instance.+ assert "lineReceived" in vars(protocol._parser)+ assert "lineLengthExceeded" in vars(protocol._parser)++ def test_refused_request_keeps_previous_parser_limits(self) -> None:+ """A request that Twisted refuses leaves the parser of the previous+ request untouched, so that its size counter is not reset while its+ response is still being read."""+ protocol = self._get_protocol()+ protocol.request(self._get_request())+ parser = protocol._parser+ assert parser is not None+ line_received = vars(parser)["lineReceived"]++ # A second request over the same connection is refused, as the first one+ # is still in progress.+ deferred = protocol.request(self._get_request())+ failures: list[Failure] = []+ deferred.addErrback(failures.append)++ assert len(failures) == 1+ assert failures[0].check(RequestNotSent)+ assert protocol._parser is parser+ assert vars(parser)["lineReceived"] is line_received++class _CannedConnectProxy(Protocol):"""Answers any request with a canned response, or drops the connection whenthe response is ``None``."""diff --git a/tests/utils/bases/download_handlers_http.py b/tests/utils/bases/download_handlers_http.pyindex d63717bd8..6b37a57be 100644--- a/tests/utils/bases/download_handlers_http.py+++ b/tests/utils/bases/download_handlers_http.py@@ -28,6 +28,7 @@ from scrapy.exceptions import (DownloadFailedError,DownloadTimeoutError,ResponseDataLossError,+ ResponseHeadersTooLargeError,ScrapyDeprecationWarning,StopDownload,UnsupportedURLSchemeError,@@ -72,6 +73,10 @@ if TYPE_CHECKING:from tests.mockserver.http import MockServer+# Value that the tests set DOWNLOAD_HEADERS_MAXSIZE to for handlers that honor+# it, so that they do not depend on its default value and stay reasonably fast.+CONFIGURED_HEADERS_MAXSIZE = 64 * 1024+BadHeaderHandling = Literal["skip-bad", "skip-rest", "fail"]NonUtf8RequestHeaderHandling = Literal["send", "replace"]HeaderNameCase = Literal["as-is", "canonical"]@@ -117,6 +122,15 @@ class TestHttpBase(ABC):# default headers added by the underlying library that cannot be suppressedalways_present_req_headers: ClassVar[frozenset[str]] = frozenset()default_handler_settings: ClassVar[dict[str, Any]] = {}+ # Limit that the underlying HTTP client applies to the size of a single+ # response header line, on top of headers_maxsize. 0 means that only+ # headers_maxsize applies, which is what web browsers do.+ header_line_maxsize: int = 0+ # Limit that applies to the size of the response head as a whole: None if+ # the handler honors DOWNLOAD_HEADERS_MAXSIZE and DOWNLOAD_HEADERS_WARNSIZE,+ # 0 if its HTTP client applies no limit at all, or else the hard-coded limit+ # of that client.+ headers_maxsize: int | None = None@property@abstractmethod@@ -856,6 +870,120 @@ class TestHttpBase(ABC):response = await download_handler.download_request(request)assert response.headers.getlist(b"Set-Cookie") == [b"a=b", b"c=d"]+ @property+ def _effective_headers_maxsize(self) -> int:+ """Limit that the tests should expect the handler to apply, 0 for+ none."""+ if self.headers_maxsize is None:+ return CONFIGURED_HEADERS_MAXSIZE+ return self.headers_maxsize++ @property+ def _headers_maxsize_settings(self) -> dict[str, Any]:+ if self.headers_maxsize is None:+ return {"DOWNLOAD_HEADERS_MAXSIZE": CONFIGURED_HEADERS_MAXSIZE}+ return {}++ @coroutine_test+ async def test_get_long_header(self, mockserver: MockServer) -> None:+ """A single header larger than the 16 KiB line length limit that+ Twisted applies by default is still read. See+ https://github.com/scrapy/scrapy/issues/355."""+ size = 32 * 1024+ if self.header_line_maxsize:+ size = min(size, self.header_line_maxsize)+ request = Request(+ mockserver.url(f"/large-headers?size={size}", is_secure=self.is_secure)+ )+ async with self.get_dh() as download_handler:+ response = await download_handler.download_request(request)+ assert response.headers[b"X-Large-0"] == b"a" * size++ @coroutine_test+ async def test_get_headers_over_maxsize_single_header(+ self, mockserver: MockServer+ ) -> None:+ if not self._effective_headers_maxsize:+ pytest.skip(f"{type(self).__name__} does not limit response head size")+ # Twice the limit, because some HTTP clients only enforce it once the+ # unparsed head exceeds it by a whole read buffer.+ size = self._effective_headers_maxsize * 2+ request = Request(+ mockserver.url(f"/large-headers?size={size}", is_secure=self.is_secure)+ )+ async with self.get_dh(self._headers_maxsize_settings) as download_handler:+ with pytest.raises(ResponseHeadersTooLargeError):+ await download_handler.download_request(request)++ @coroutine_test+ async def test_get_headers_over_maxsize_many_headers(+ self, mockserver: MockServer+ ) -> None:+ if not self._effective_headers_maxsize:+ pytest.skip(f"{type(self).__name__} does not limit response head size")+ size = 8 * 1024+ count = self._effective_headers_maxsize * 2 // size+ request = Request(+ mockserver.url(+ f"/large-headers?size={size}&count={count}", is_secure=self.is_secure+ )+ )+ async with self.get_dh(self._headers_maxsize_settings) as download_handler:+ with pytest.raises(ResponseHeadersTooLargeError):+ await download_handler.download_request(request)++ @coroutine_test+ async def test_get_headers_maxsize_disabled(self, mockserver: MockServer) -> None:+ if self.headers_maxsize is not None:+ pytest.skip(+ f"{type(self).__name__} does not support DOWNLOAD_HEADERS_MAXSIZE"+ )+ size = self._effective_headers_maxsize * 2+ request = Request(+ mockserver.url(f"/large-headers?size={size}", is_secure=self.is_secure)+ )+ async with self.get_dh({"DOWNLOAD_HEADERS_MAXSIZE": 0}) as download_handler:+ response = await download_handler.download_request(request)+ assert response.headers[b"X-Large-0"] == b"a" * size++ @coroutine_test+ async def test_get_headers_over_warnsize(+ self, mockserver: MockServer, caplog: pytest.LogCaptureFixture+ ) -> None:+ if self.headers_maxsize is not None:+ pytest.skip(+ f"{type(self).__name__} does not support DOWNLOAD_HEADERS_WARNSIZE"+ )+ size = 32 * 1024+ request = Request(+ mockserver.url(f"/large-headers?size={size}", is_secure=self.is_secure)+ )+ settings = {"DOWNLOAD_HEADERS_WARNSIZE": size // 2}+ with caplog.at_level(logging.WARNING):+ async with self.get_dh(settings) as download_handler:+ response = await download_handler.download_request(request)+ assert response.headers[b"X-Large-0"] == b"a" * size+ assert "download headers warn size" in caplog.text++ @coroutine_test+ async def test_get_headers_warnsize_disabled(+ self, mockserver: MockServer, caplog: pytest.LogCaptureFixture+ ) -> None:+ if self.headers_maxsize is not None:+ pytest.skip(+ f"{type(self).__name__} does not support DOWNLOAD_HEADERS_WARNSIZE"+ )+ size = 32 * 1024+ request = Request(+ mockserver.url(f"/large-headers?size={size}", is_secure=self.is_secure)+ )+ settings = {"DOWNLOAD_HEADERS_WARNSIZE": 0}+ with caplog.at_level(logging.WARNING):+ async with self.get_dh(settings) as download_handler:+ response = await download_handler.download_request(request)+ assert response.headers[b"X-Large-0"] == b"a" * size+ assert "download headers warn size" not in caplog.text+@coroutine_testasync def test_download_is_not_automatically_gzip_decoded(self, mockserver: MockServer