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
(#4716). Based on with RFC 7235 section 2.2, the header is now stripped
if the "canonical root URL" (scheme+authority) has changed.
  • Loading branch information
bmerry committed Jun 28, 2018
1 parent ef88b9f commit f8b45f0
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 3 deletions.
6 changes: 3 additions & 3 deletions requests/sessions.py
Original file line number Diff line number Diff line change
Expand Up @@ -239,10 +239,10 @@ def rebuild_auth(self, prepared_request, response):
if 'Authorization' in headers:
# If we get redirected to a new host, we should strip out any
# authentication headers.
original_parsed = urlparse(response.request.url)
redirect_parsed = urlparse(url)
original_root = urljoin(response.request.url, '/')
redirect_root = urljoin(url, '/')

if (original_parsed.hostname != redirect_parsed.hostname):
if (original_root != redirect_root):
del headers['Authorization']

# .netrc might have more auth for us on our new host.
Expand Down
10 changes: 10 additions & 0 deletions tests/test_requests.py
Original file line number Diff line number Diff line change
Expand Up @@ -1577,6 +1577,16 @@ def test_auth_is_stripped_on_redirect_off_host(self, httpbin):
assert r.history[0].request.headers['Authorization']
assert not r.request.headers.get('Authorization', '')

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 not r.request.headers.get('Authorization', '')

def test_auth_is_retained_for_redirect_on_host(self, httpbin):
r = requests.get(httpbin('redirect/1'), auth=('user', 'pass'))
h1 = r.history[0].request.headers['Authorization']
Expand Down

0 comments on commit f8b45f0

Please sign in to comment.