diff --git a/requests/sessions.py b/requests/sessions.py index a0a23ee..9a51f33 100644 --- a/requests/sessions.py +++ b/requests/sessions.py @@ -18,7 +18,7 @@ from .cookies import ( cookiejar_from_dict, extract_cookies_to_jar, RequestsCookieJar, merge_cookies) from .models import Request, PreparedRequest, DEFAULT_REDIRECT_LIMIT from .hooks import default_hooks, dispatch_hook -from .utils import to_key_val_list, default_headers, to_native_string +from .utils import to_key_val_list, default_headers, to_native_string, DEFAULT_PORTS from .exceptions import ( TooManyRedirects, InvalidSchema, ChunkedEncodingError, ContentDecodingError) from .packages.urllib3._collections import RecentlyUsedContainer @@ -103,8 +103,17 @@ class SessionRedirectMixin(object): if (old_parsed.scheme == 'http' and old_parsed.port in (80, None) and new_parsed.scheme == 'https' and new_parsed.port in (443, None)): return False + + # Handle default port usage corresponding to scheme. + changed_port = old_parsed.port != new_parsed.port + changed_scheme = old_parsed.scheme != new_parsed.scheme + default_port = (DEFAULT_PORTS.get(old_parsed.scheme, None), None) + if (not changed_scheme and old_parsed.port in default_port + and new_parsed.port in default_port): + return False + # Standard case: root URI must match - return old_parsed.port != new_parsed.port or old_parsed.scheme != new_parsed.scheme + return changed_port or changed_scheme def resolve_redirects(self, resp, req, stream=False, timeout=None, verify=True, cert=None, proxies=None): diff --git a/requests/utils.py b/requests/utils.py index 8fba62d..14c94bd 100644 --- a/requests/utils.py +++ b/requests/utils.py @@ -37,6 +37,8 @@ NETRC_FILES = ('.netrc', '_netrc') DEFAULT_CA_BUNDLE_PATH = certs.where() +DEFAULT_PORTS = {'http': 80, 'https': 443} + def dict_to_sequence(d): """Returns an internal sequence dictionary update.""" diff --git a/test_requests.py b/test_requests.py index e19b436..b76d2a4 100755 --- a/test_requests.py +++ b/test_requests.py @@ -1012,6 +1012,17 @@ class RequestsTestCase(unittest.TestCase): s = requests.Session() assert s.should_strip_auth('http://example.com:1234/foo', 'https://example.com:4321/bar') + @pytest.mark.parametrize( + 'old_uri, new_uri', ( + ('https://example.com:443/foo', 'https://example.com/bar'), + ('http://example.com:80/foo', 'http://example.com/bar'), + ('https://example.com/foo', 'https://example.com:443/bar'), + ('http://example.com/foo', 'http://example.com:80/bar') + )) + def test_should_strip_auth_default_port(self, old_uri, new_uri): + s = requests.Session() + assert not s.should_strip_auth(old_uri, new_uri) + def test_manual_redirect_with_partial_body_read(self): s = requests.Session() r1 = s.get(httpbin('redirect/2'), allow_redirects=False, stream=True)