Skip to content

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

Never fail decoding headers in to_unicode_dict() and to_tuple_list() (#8192)

Adrian40dc14296108
diff --git a/scrapy/http/headers.py b/scrapy/http/headers.py
index dedfc1eff..fb26d5f18 100644
--- a/scrapy/http/headers.py
+++ b/scrapy/http/headers.py
@@ -148,12 +148,13 @@ class Headers(dict): # type: ignore[type-arg]
def to_unicode_dict(self) -> CaseInsensitiveDict:
"""Return headers as a CaseInsensitiveDict with str keys
- and str values. Multiple values are joined with ','.
+ and str values. Multiple values are joined with ','. Bytes that
+ cannot be decoded are replaced with U+FFFD.
"""
return CaseInsensitiveDict(
(
- to_unicode(key, encoding=self.encoding),
- to_unicode(b",".join(value), encoding=self.encoding),
+ to_unicode(key, encoding=self.encoding, errors="replace"),
+ to_unicode(b",".join(value), encoding=self.encoding, errors="replace"),
)
for key, value in self.items()
)
@@ -162,9 +163,13 @@ class Headers(dict): # type: ignore[type-arg]
"""Return headers as a list of ``(key, value)`` tuples.
Multiple values are represented as multiple tuples with the same key.
+ Bytes that cannot be decoded are replaced with U+FFFD.
"""
return [
- (key.decode(self.encoding), value.decode(self.encoding))
+ (
+ key.decode(self.encoding, errors="replace"),
+ value.decode(self.encoding, errors="replace"),
+ )
for key, values in self.items()
for value in values
]
diff --git a/tests/test_http_headers.py b/tests/test_http_headers.py
index a35f51cd8..514ab2513 100644
--- a/tests/test_http_headers.py
+++ b/tests/test_http_headers.py
@@ -182,3 +182,19 @@ def test_invalid_value() -> None:
Headers().setdefault("foo", object())
with pytest.raises(TypeError, match="Unsupported value type"):
Headers().setlist("foo", [object()]) # type: ignore[list-item]
+
+
+def test_to_unicode_dict_undecodable() -> None:
+ h = Headers({b"Public-Key-Pins": b'pin-sha256=\x94"a"', b"X-\xff": b"ok"})
+ assert h.to_unicode_dict() == {
+ "Public-Key-Pins": 'pin-sha256=�"a"',
+ "X-�": "ok",
+ }
+
+
+def test_to_tuple_list_undecodable() -> None:
+ h = Headers({b"Public-Key-Pins": b'pin-sha256=\x94"a"', b"X-\xff": b"ok"})
+ assert h.to_tuple_list() == [
+ ("Public-Key-Pins", 'pin-sha256=�"a"'),
+ ("X-�", "ok"),
+ ]