New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
httpcompression middleware: warn of unexpected and prevent manual unupported encodings #6145
Open
cakemd
wants to merge
5
commits into
scrapy:master
Choose a base branch
from
cakemd:feature/unsupported_middleware_encoding_behaviour
base: master
Could not load branches
Branch not found: {{ refName }}
Could not load tags
Nothing to show
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
137ba34
httpcompression middleware: warn of unexpected and prevent manual uns…
heorhiikorzh 123c8ab
httpcompression middleware: empty body in bytes, not str
heorhiikorzh fcbc7fa
pylint related change
heorhiikorzh cc8d9e1
kept raising exceptions for br only and fixed tests this way
heorhiikorzh fc2b410
fixed typing error
heorhiikorzh File filter
Filter by extension
Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,12 +1,13 @@ | ||
from __future__ import annotations | ||
|
||
import io | ||
import logging | ||
import zlib | ||
from typing import TYPE_CHECKING, List, Optional, Union | ||
from typing import TYPE_CHECKING, List, Optional, Tuple, Union | ||
|
||
from scrapy import Request, Spider | ||
from scrapy.crawler import Crawler | ||
from scrapy.exceptions import NotConfigured | ||
from scrapy.exceptions import NotConfigured, NotSupported | ||
from scrapy.http import Response, TextResponse | ||
from scrapy.responsetypes import responsetypes | ||
from scrapy.statscollectors import StatsCollector | ||
|
@@ -17,6 +18,10 @@ | |
from typing_extensions import Self | ||
|
||
ACCEPTED_ENCODINGS: List[bytes] = [b"gzip", b"deflate"] | ||
ENCODINGS_DELIMETER: bytes = b", " | ||
|
||
logger = logging.getLogger(__name__) | ||
|
||
|
||
try: | ||
import brotli | ||
|
@@ -35,7 +40,7 @@ | |
|
||
class HttpCompressionMiddleware: | ||
"""This middleware allows compressed (gzip, deflate) traffic to be | ||
sent/received from web sites""" | ||
sent/received from websites""" | ||
|
||
def __init__(self, stats: Optional[StatsCollector] = None): | ||
self.stats = stats | ||
|
@@ -49,7 +54,10 @@ def from_crawler(cls, crawler: Crawler) -> Self: | |
def process_request( | ||
self, request: Request, spider: Spider | ||
) -> Union[Request, Response, None]: | ||
request.headers.setdefault("Accept-Encoding", b", ".join(ACCEPTED_ENCODINGS)) | ||
self._raise_unsupported_compressors(request) | ||
request.headers.setdefault( | ||
"Accept-Encoding", ENCODINGS_DELIMETER.join(ACCEPTED_ENCODINGS) | ||
) | ||
return None | ||
|
||
def process_response( | ||
|
@@ -85,6 +93,22 @@ def process_response( | |
|
||
return response | ||
|
||
@property | ||
def _raise_unsupported(self) -> Tuple[bytes]: | ||
return (b"br",) | ||
|
||
def _raise_unsupported_compressors(self, request: Request): | ||
encodings = request.headers.getlist("Accept-Encoding") | ||
if encodings and len(encodings): | ||
encodings = encodings.pop().split(ENCODINGS_DELIMETER) | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Not sure why is this doing |
||
unsupported = [key for key in encodings if key not in ACCEPTED_ENCODINGS] | ||
for unsupp in unsupported: | ||
if unsupp in self._raise_unsupported: | ||
raise NotSupported( | ||
f"Request is configured with Accept-Encoding header with unsupported encoding(s): " | ||
f"{unsupp.decode()}" | ||
) | ||
|
||
def _decode(self, body: bytes, encoding: bytes) -> bytes: | ||
if encoding == b"gzip" or encoding == b"x-gzip": | ||
body = gunzip(body) | ||
|
@@ -99,8 +123,13 @@ def _decode(self, body: bytes, encoding: bytes) -> bytes: | |
# http://www.port80software.com/200ok/archive/2005/10/31/868.aspx | ||
# http://www.gzip.org/zlib/zlib_faq.html#faq38 | ||
body = zlib.decompress(body, -15) | ||
if encoding == b"br" and b"br" in ACCEPTED_ENCODINGS: | ||
body = brotli.decompress(body) | ||
if encoding == b"br": | ||
if b"br" in ACCEPTED_ENCODINGS: | ||
body = brotli.decompress(body) | ||
else: | ||
logger.warning( | ||
"Brotli encoding received. Cannot decompress the body as Brotli is not installed." | ||
) | ||
if encoding == b"zstd" and b"zstd" in ACCEPTED_ENCODINGS: | ||
# Using its streaming API since its simple API could handle only cases | ||
# where there is content size data embedded in the frame | ||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I think the
len
check here is not needed.