Skip to content

Commit

Permalink
Strip Authorization header whenever root URL changes
Browse files Browse the repository at this point in the history
Previously the header was stripped only if the hostname changed, but in
an https -> http redirect that can leak the credentials on the wire
(psf#4716). Based on with RFC 7235 section 2.2, the header is now stripped
if the "canonical root URL" (scheme+authority) has changed, by checking
scheme, hostname and port.
  • Loading branch information
bmerry committed Sep 5, 2018
1 parent 33b41c7 commit be32cb8
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 2 deletions.
4 changes: 3 additions & 1 deletion requests/sessions.py
Original file line number Diff line number Diff line change
Expand Up @@ -242,7 +242,9 @@ def rebuild_auth(self, prepared_request, response):
original_parsed = urlparse(response.request.url)
redirect_parsed = urlparse(url)

if (original_parsed.hostname != redirect_parsed.hostname):
if (original_parsed.hostname != redirect_parsed.hostname
or original_parsed.port != redirect_parsed.port
or original_parsed.scheme != redirect_parsed.scheme):
del headers['Authorization']

# .netrc might have more auth for us on our new host.
Expand Down
12 changes: 11 additions & 1 deletion tests/test_requests.py
Original file line number Diff line number Diff line change
Expand Up @@ -1581,7 +1581,17 @@ def test_auth_is_stripped_on_redirect_off_host(self, httpbin):
auth=('user', 'pass'),
)
assert r.history[0].request.headers['Authorization']
assert not r.request.headers.get('Authorization', '')
assert 'Authorization' not in r.request.headers

def test_auth_is_stripped_on_scheme_redirect(self, httpbin, httpbin_secure, httpbin_ca_bundle):
r = requests.get(
httpbin_secure('redirect-to'),
params={'url': httpbin('get')},
auth=('user', 'pass'),
verify=httpbin_ca_bundle
)
assert r.history[0].request.headers['Authorization']
assert 'Authorization' not in r.request.headers

def test_auth_is_retained_for_redirect_on_host(self, httpbin):
r = requests.get(httpbin('redirect/1'), auth=('user', 'pass'))
Expand Down

0 comments on commit be32cb8

Please sign in to comment.