Scrapy, a fast high-level web crawling & scraping framework for Python.
Improve handling of non-UTF8 headers in some handlers. (#8265)
Andrey Rakhmatulline49bc32d0ed8
diff --git a/scrapy/core/_http2/protocol.py b/scrapy/core/_http2/protocol.pyindex 2a557830e..3b1e8cac0 100644--- a/scrapy/core/_http2/protocol.py+++ b/scrapy/core/_http2/protocol.py@@ -4,7 +4,7 @@ import ipaddressimport itertoolsimport loggingfrom collections import deque-from typing import TYPE_CHECKING, Any, cast+from typing import TYPE_CHECKING, Anyfrom h2.config import H2Configurationfrom h2.connection import H2Connection@@ -108,7 +108,7 @@ class H2ClientProtocol(Protocol, TimeoutMixin):self._conn_lost_deferred: Deferred[None] = conn_lost_deferredself._tls_verbose_logging: bool = tls_verbose_logging- config = H2Configuration(client_side=True, header_encoding="utf-8")+ config = H2Configuration(client_side=True)self.conn = H2Connection(config=config)# ID of the next request stream@@ -421,7 +421,7 @@ class H2ClientProtocol(Protocol, TimeoutMixin):except KeyError:pass # We ignore server-initiated eventselse:- stream.receive_headers(cast("list[tuple[str, str]]", event.headers))+ stream.receive_headers(event.headers)def settings_acknowledged(self, event: SettingsAcknowledged) -> None:self.metadata["settings_acknowledged"] = Truediff --git a/scrapy/core/_http2/stream.py b/scrapy/core/_http2/stream.pyindex c6b004472..8dca37e2e 100644--- a/scrapy/core/_http2/stream.py+++ b/scrapy/core/_http2/stream.py@@ -214,7 +214,7 @@ class Stream:== f"{self._protocol.metadata['ip_address']}:{self._protocol.metadata['uri'].port}")- def _get_request_headers(self) -> list[tuple[str, str]]:+ def _get_request_headers(self) -> list[tuple[bytes, bytes]]:url = urlparse_cached(self._request)path = url.path@@ -230,26 +230,27 @@ class Stream:if not path:path = "*" if self._request.method == "OPTIONS" else "/"- # Make sure pseudo-headers comes before all the other headers- headers = [- (":method", self._request.method),- (":authority", url.netloc),+ # Make sure pseudo-headers come before all the other headers. All+ # names and values are bytes because h2 < 4.2.0 compares :authority+ # and Host without converting them to the same type first.+ headers: list[tuple[bytes, bytes]] = [+ (b":method", self._request.method.encode()),+ (b":authority", url.netloc.encode()),]# The ":scheme" and ":path" pseudo-header fields MUST# be omitted for CONNECT method (refer RFC 7540 - Section 8.3)if self._request.method != "CONNECT":headers += [- (":scheme", self._protocol.metadata["uri"].scheme),- (":path", path),+ (b":scheme", self._protocol.metadata["uri"].scheme),+ (b":path", path.encode()),]if b"Content-Length" not in self._request.headers:- headers.append(("Content-Length", str(len(self._request.body))))+ headers.append((b"Content-Length", str(len(self._request.body)).encode()))for name, values in self._request.headers.items():- for value_bytes in values:- headers.append((str(name, "utf-8"), str(value_bytes, "utf-8")))+ headers.extend((name, value) for value in values)return headers@@ -357,9 +358,9 @@ class Stream:self._response["flow_controlled_size"], self.stream_id)- def receive_headers(self, headers: list[tuple[str, str]]) -> None:+ def receive_headers(self, headers: list[tuple[bytes, bytes]]) -> None:for name, value in headers:- if name == ":status":+ if name == b":status":# it's a pseudo-headerself._response["status"] = int(value)else:diff --git a/scrapy/core/downloader/handlers/_aiohttp.py b/scrapy/core/downloader/handlers/_aiohttp.pyindex 679bfcbad..566575568 100644--- a/scrapy/core/downloader/handlers/_aiohttp.py+++ b/scrapy/core/downloader/handlers/_aiohttp.py@@ -82,7 +82,7 @@ class AiohttpDownloadHandler(BaseStreamingDownloadHandler[_ClientResponse]):timeout: float, # noqa: ASYNC109) -> AsyncIterator[_ClientResponse]:proxy = self._extract_proxy_url_with_creds(request)- headers = self._request_headers(request).to_tuple_list()+ headers = self._utf8_request_headers(request)url: str | yarl.URL = request.urlif request.meta.get("verbatim_url"):# encoded=True disables the percent-encoding normalization that@@ -118,7 +118,7 @@ class AiohttpDownloadHandler(BaseStreamingDownloadHandler[_ClientResponse]):@staticmethoddef _extract_headers(response: _ClientResponse) -> Headers:- return Headers(list(response.headers.items()))+ return Headers(response.raw_headers)@staticmethoddef _build_base_response_args(diff --git a/scrapy/core/downloader/handlers/_base_streaming.py b/scrapy/core/downloader/handlers/_base_streaming.pyindex cd9f4cbd7..596942169 100644--- a/scrapy/core/downloader/handlers/_base_streaming.py+++ b/scrapy/core/downloader/handlers/_base_streaming.py@@ -255,6 +255,28 @@ class BaseStreamingDownloadHandler(BaseHttpDownloadHandler, ABC, Generic[_Responheaders.pop(b"Proxy-Authorization", None)return headers+ def _utf8_request_headers(self, request: Request) -> list[tuple[str, str]]:+ """Get a prepared copy of the request headers as ``(name, value)`` str+ pairs, for libraries that can only send UTF-8.++ Bytes that are not valid UTF-8 are replaced with U+FFFD, with a+ warning.+ """+ pairs: list[tuple[str, str]] = []+ for name, values in self._request_headers(request).items():+ for value in values:+ try:+ pairs.append((name.decode(), value.decode()))+ except UnicodeDecodeError:+ str_name = name.decode(errors="replace")+ logger.warning(+ f"The {str_name} header of {request} is not valid UTF-8,"+ f" which {type(self).__name__} cannot send. Sending it"+ f" with U+FFFD in place of the invalid bytes."+ )+ pairs.append((str_name, value.decode(errors="replace")))+ return pairs+def _get_bind_address_host(self) -> str | None:"""Return the host portion of the bind address.diff --git a/scrapy/core/downloader/handlers/_httpx.py b/scrapy/core/downloader/handlers/_httpx.pyindex 3102d1bcd..a9e29e736 100644--- a/scrapy/core/downloader/handlers/_httpx.py+++ b/scrapy/core/downloader/handlers/_httpx.py@@ -158,7 +158,12 @@ class HttpxDownloadHandler(_Base):f"SOCKS proxy support in {type(self).__name__} requires the 'httpx2[socks]' extra to be installed.")client = self._get_client(proxy)- headers = self._request_headers(request).to_tuple_list()+ # httpx sends bytes as they are but encodes str values as ASCII.+ headers = [+ (name, value)+ for name, values in self._request_headers(request).items()+ for value in values+ ]try:async with client.stream(diff --git a/tests/mockserver/http_resources.py b/tests/mockserver/http_resources.pyindex c5fafb0cb..4413eac54 100644--- a/tests/mockserver/http_resources.py+++ b/tests/mockserver/http_resources.py@@ -273,7 +273,9 @@ class Echo(LeafResource):assert request.contentoutput = {"headers": {- to_unicode(k): [to_unicode(v) for v in vs]+ to_unicode(k, errors="surrogateescape"): [+ to_unicode(v, errors="surrogateescape") for v in vs+ ]for k, vs in request.requestHeaders.getAllRawHeaders()},"body": to_unicode(request.content.read()),@@ -444,7 +446,10 @@ class ResponseHeadersResource(BaseResource):assert request.contentbody = json.loads(request.content.read().decode())for header_name, header_value in body.items():- request.responseHeaders.setRawHeaders(header_name, [header_value])+ # surrogateescape lets tests send bytes that are not valid UTF-8+ request.responseHeaders.setRawHeaders(+ header_name, [header_value.encode("utf-8", "surrogateescape")]+ )return json.dumps(body).encode("utf-8")diff --git a/tests/test_downloader_handler_aiohttp.py b/tests/test_downloader_handler_aiohttp.pyindex 46b061fa1..72b0811d5 100644--- a/tests/test_downloader_handler_aiohttp.py+++ b/tests/test_downloader_handler_aiohttp.py@@ -45,11 +45,13 @@ class AiohttpDownloadHandlerMixin:class TestHttp(AiohttpDownloadHandlerMixin, TestHttpBase):handler_supports_bindaddress_meta = Falsehandler_bad_header_handling = "fail"+ handler_non_utf8_request_header_handling = "replace"class TestHttps(AiohttpDownloadHandlerMixin, TestHttpsBase):handler_supports_bindaddress_meta = Falsehandler_bad_header_handling = "fail"+ handler_non_utf8_request_header_handling = "replace"tls_log_message = "SSL connection to 127.0.0.1 using protocol TLSv1.3, cipher"@pytest.mark.skip(reason="The check is Twisted-specific")diff --git a/tests/utils/bases/download_handlers_http.py b/tests/utils/bases/download_handlers_http.pyindex dd807fd95..226cdb800 100644--- a/tests/utils/bases/download_handlers_http.py+++ b/tests/utils/bases/download_handlers_http.py@@ -61,6 +61,7 @@ if TYPE_CHECKING:BadHeaderHandling = Literal["skip-bad", "skip-rest", "fail"]+NonUtf8RequestHeaderHandling = Literal["send", "replace"]class TestHttpBase(ABC):@@ -81,6 +82,11 @@ class TestHttpBase(ABC):# whether the handler can request hostnames that the idna package rejects# (see IDNA_REJECTED_HOSTNAMES)handler_supports_idna_rejected_hostnames: bool = True+ # What the handler does with a request header value that is not valid+ # UTF-8:+ # "send": the value is sent as it is;+ # "replace": the invalid bytes are replaced with U+FFFD, with a warning.+ handler_non_utf8_request_header_handling: NonUtf8RequestHeaderHandling = "send"# What the handler does with a bad response header line, e.g. one with no# colon in it:# "skip-bad": the bad line is skipped and the header lines that follow it@@ -244,6 +250,39 @@ class TestHttpBase(ABC):assert "headers" in bodyassert body["headers"]["X-Custom-Header"] == ["foo", "bar"]+ @coroutine_test+ async def test_request_header_utf8(self, mockserver: MockServer) -> None:+ request = Request(+ mockserver.url("/echo", is_secure=self.is_secure),+ headers={"X-Custom-Header": "café"},+ )+ async with self.get_dh() as download_handler:+ response = await download_handler.download_request(request)+ assert response.status == HTTPStatus.OK+ body = json.loads(response.body.decode("utf-8"))+ assert body["headers"]["X-Custom-Header"] == ["café"]++ @coroutine_test+ async def test_request_header_non_utf8(+ self, caplog: pytest.LogCaptureFixture, mockserver: MockServer+ ) -> None:+ request = Request(+ mockserver.url("/echo", is_secure=self.is_secure),+ headers={"X-Custom-Header": b"caf\xe9"},+ )+ async with self.get_dh() as download_handler:+ response = await download_handler.download_request(request)+ assert response.status == HTTPStatus.OK+ body = json.loads(response.body.decode("utf-8"))+ # the mockserver decodes invalid UTF-8 with surrogateescape+ received = [+ value.encode("utf-8", "surrogateescape")+ for value in body["headers"]["X-Custom-Header"]+ ]+ replaced = self.handler_non_utf8_request_header_handling == "replace"+ assert received == [b"caf\xef\xbf\xbd" if replaced else b"caf\xe9"]+ assert ("is not valid UTF-8" in caplog.text) == replaced+@coroutine_testasync def test_server_receives_no_extra_headers(self, mockserver: MockServer@@ -281,6 +320,23 @@ class TestHttpBase(ABC):body = json.loads(response.body.decode("utf-8"))assert json.loads(body["body"]) == request_body+ @coroutine_test+ async def test_download_response_header_non_utf8(+ self, mockserver: MockServer+ ) -> None:+ value = b"caf\xe9"+ request = Request(+ mockserver.url("/response-headers", is_secure=self.is_secure),+ headers={"content-type": "application/json"},+ body=json.dumps(+ {"X-Custom-Header": value.decode("utf-8", "surrogateescape")}+ ),+ )+ async with self.get_dh() as download_handler:+ response = await download_handler.download_request(request)+ assert response.status == 200+ assert response.headers.getlist("X-Custom-Header") == [value]+@coroutine_testasync def test_download_has_correct_response_headers(self, mockserver: MockServer