Skip to content
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

Appropriately handle urllib3's InvalidHeader exception #5914

Merged
merged 1 commit into from Aug 27, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
5 changes: 4 additions & 1 deletion requests/adapters.py
Expand Up @@ -19,6 +19,7 @@
from urllib3.exceptions import ClosedPoolError
from urllib3.exceptions import ConnectTimeoutError
from urllib3.exceptions import HTTPError as _HTTPError
from urllib3.exceptions import InvalidHeader as _InvalidHeader
from urllib3.exceptions import MaxRetryError
from urllib3.exceptions import NewConnectionError
from urllib3.exceptions import ProxyError as _ProxyError
Expand All @@ -37,7 +38,7 @@
from .cookies import extract_cookies_to_jar
from .exceptions import (ConnectionError, ConnectTimeout, ReadTimeout, SSLError,
ProxyError, RetryError, InvalidSchema, InvalidProxyURL,
InvalidURL)
InvalidURL, InvalidHeader)
from .auth import _basic_auth_str

try:
Expand Down Expand Up @@ -527,6 +528,8 @@ def send(self, request, stream=False, timeout=None, verify=True, cert=None, prox
raise SSLError(e, request=request)
elif isinstance(e, ReadTimeoutError):
raise ReadTimeout(e, request=request)
elif isinstance(e, _InvalidHeader):
raise InvalidHeader(e, request=request)
else:
raise

Expand Down
26 changes: 26 additions & 0 deletions tests/test_lowlevel.py
Expand Up @@ -46,6 +46,32 @@ def incomplete_chunked_response_handler(sock):
close_server.set() # release server block


def test_conflicting_content_lengths():
"""Ensure we correctly throw an InvalidHeader error if multiple
conflicting Content-Length headers are returned.
"""

def multiple_content_length_response_handler(sock):
request_content = consume_socket_content(sock, timeout=0.5)

sock.send(b"HTTP/1.1 200 OK\r\n" +
b"Content-Type: text/plain\r\n" +
b"Content-Length: 16\r\n" +
b"Content-Length: 32\r\n\r\n" +
b"-- Bad Actor -- Original Content\r\n")

return request_content

close_server = threading.Event()
server = Server(multiple_content_length_response_handler)

with server as (host, port):
url = 'http://{}:{}/'.format(host, port)
with pytest.raises(requests.exceptions.InvalidHeader):
r = requests.get(url)
close_server.set()


def test_digestauth_401_count_reset_on_redirect():
"""Ensure we correctly reset num_401_calls after a successful digest auth,
followed by a 302 redirect to another digest auth prompt.
Expand Down