Merge pull request #1951 from Lukasa/proxyauth
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Re-evaluate proxy authorization.
authored by Kenneth Reitz · committed by Kenneth Reitz · parents 110048f, 90f7337 · Browse files · 3 files·+102 added−24 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
3 files+102 added−24 removed
- other:+102 added−24 removed
Provenance
- Commit
fe4c4f1- Tree
0bce94a- Author
Kenneth Reitz <me@kennethreitz.org>- Committer
Kenneth Reitz <me@kennethreitz.org>- Parent 1
110048f- Parent 2
90f7337
3 files changed+102 added−24 removed
modified:requests/sessions.py+70 added-14 removed
10 unmodified lines11 import os12 from collections import Mapping13 from datetime import datetime14 15+from .auth import _basic_auth_str16 from .compat import cookielib, OrderedDict, urljoin, urlparse, builtin_str17 from .cookies import (18 cookiejar_from_dict, extract_cookies_to_jar, RequestsCookieJar, merge_cookies)19 from .models import Request, PreparedRequest, DEFAULT_REDIRECT_LIMIT3 unmodified lines23 from .structures import CaseInsensitiveDict24 25 from .adapters import HTTPAdapter26 26-from .utils import requote_uri, get_environ_proxies, get_netrc_auth27+from .utils import (28+ requote_uri, get_environ_proxies, get_netrc_auth, should_bypass_proxies,29+ get_auth_from_url30+)31 32 from .status_codes import codes33 34 # formerly defined here, reexposed here for backward compatibility122 unmodified lines157 extract_cookies_to_jar(prepared_request._cookies, prepared_request, resp.raw)158 prepared_request._cookies.update(self.cookies)159 prepared_request.prepare_cookies(prepared_request._cookies)160 157- if 'Authorization' in headers:158- # If we get redirected to a new host, we should strip out any159- # authentication headers.160- original_parsed = urlparse(resp.request.url)161- redirect_parsed = urlparse(url)161+ # Rebuild auth and proxy information.162+ proxies = self.rebuild_proxies(prepared_request, proxies)163+ self.rebuild_auth(prepared_request, resp)164 163- if (original_parsed.hostname != redirect_parsed.hostname):164- del headers['Authorization']165-166- # .netrc might have more auth for us.167- new_auth = get_netrc_auth(url) if self.trust_env else None168- if new_auth is not None:169- prepared_request.prepare_auth(new_auth)170-165 resp = self.send(166 prepared_request,167 stream=stream,168 timeout=timeout,7 unmodified lines176 177 i += 1178 yield resp179 180+ def rebuild_auth(self, prepared_request, response):181+ """182+ When being redirected we may want to strip authentication from the183+ request to avoid leaking credentials. This method intelligently removes184+ and reapplies authentication where possible to avoid credential loss.185+ """186+ headers = prepared_request.headers187+ url = prepared_request.url188 189+ if 'Authorization' in headers:190+ # If we get redirected to a new host, we should strip out any191+ # authentication headers.192+ original_parsed = urlparse(response.request.url)193+ redirect_parsed = urlparse(url)194+195+ if (original_parsed.hostname != redirect_parsed.hostname):196+ del headers['Authorization']197+198+ # .netrc might have more auth for us on our new host.199+ new_auth = get_netrc_auth(url) if self.trust_env else None200+ if new_auth is not None:201+ prepared_request.prepare_auth(new_auth)202+203+ return204+205+ def rebuild_proxies(self, prepared_request, proxies):206+ """207+ This method re-evaluates the proxy configuration by considering the208+ environment variables. If we are redirected to a URL covered by209+ NO_PROXY, we strip the proxy configuration. Otherwise, we set missing210+ proxy keys for this URL (in case they were stripped by a previous211+ redirect).212+213+ This method also replaces the Proxy-Authorization header where214+ necessary.215+ """216+ headers = prepared_request.headers217+ url = prepared_request.url218+ new_proxies = {}219+220+ if not should_bypass_proxies(url):221+ environ_proxies = get_environ_proxies(url)222+ scheme = urlparse(url).scheme223+224+ proxy = environ_proxies.get(scheme)225+226+ if proxy:227+ new_proxies.setdefault(scheme, environ_proxies[scheme])228+229+ if 'Proxy-Authorization' in headers:230+ del headers['Proxy-Authorization']231+232+ try:233+ username, password = get_auth_from_url(new_proxies[scheme])234+ except KeyError:235+ username, password = None, None236+237+ if username and password:238+ headers['Proxy-Authorization'] = _basic_auth_str(username, password)239+240+ return new_proxies241+242+243 class Session(SessionRedirectMixin):244 """A Requests session.245 246 Provides cookie persistence, connection-pooling, and configuration.381 unmodified linesmodified:requests/utils.py+15 added-10 removed
464 unmodified lines465 return False466 return True467 468 469-def get_environ_proxies(url):470- """Return a dict of environment proxies."""471-469+def should_bypass_proxies(url):470+ """471+ Returns whether we should bypass proxies or not.472+ """473 get_proxy = lambda k: os.environ.get(k) or os.environ.get(k.upper())474 475 # First check whether no_proxy is defined. If it is, check that the URL476 # we're getting isn't in the no_proxy list.9 unmodified lines486 if is_ipv4_address(ip):487 for proxy_ip in no_proxy:488 if is_valid_cidr(proxy_ip):489 if address_in_network(ip, proxy_ip):489- return {}490+ return True491 else:492 for host in no_proxy:493 if netloc.endswith(host) or netloc.split(':')[0].endswith(host):494 # The URL does match something in no_proxy, so we don't want495 # to apply the proxies on this URL.495- return {}496+ return True497 498 # If the system proxy settings indicate that this URL should be bypassed,499 # don't proxy.500 # The proxy_bypass function is incredibly buggy on OS X in early versions5 unmodified lines506 except (TypeError, socket.gaierror):507 bypass = False508 509 if bypass:509- return {}510+ return True511 511- # If we get here, we either didn't have no_proxy set or we're not going512- # anywhere that no_proxy applies to, and the system settings don't require513- # bypassing the proxy for the current URL.514- return getproxies()512+ return False513 514+def get_environ_proxies(url):515+ """Return a dict of environment proxies."""516+ if should_bypass_proxies(url):517+ return {}518+ else:519+ return getproxies()520 521+522 def default_user_agent(name="python-requests"):523 """Return a string representing the default user agent."""524 _implementation = platform.python_implementation()525 143 unmodified linesmodified:test_requests.py+17 added
15 unmodified lines16 from requests.compat import (17 Morsel, cookielib, getproxies, str, urljoin, urlparse)18 from requests.cookies import cookiejar_from_dict, morsel_to_cookie19 from requests.exceptions import InvalidURL, MissingSchema20+from requests.models import PreparedRequest, Response21 from requests.structures import CaseInsensitiveDict22 23 try:24 import StringIO840 unmodified lines865 req = requests.Request('GET', test_url)866 preq = req.prepare()867 assert test_url == preq.url868 869+ def test_auth_is_stripped_on_redirect_off_host(self):870+ r = requests.get(871+ httpbin('redirect-to'),872+ params={'url': 'http://www.google.co.uk'},873+ auth=('user', 'pass'),874+ )875+ assert r.history[0].request.headers['Authorization']876+ assert not r.request.headers.get('Authorization', '')877 878+ def test_auth_is_retained_for_redirect_on_host(self):879+ r = requests.get(httpbin('redirect/1'), auth=('user', 'pass'))880+ h1 = r.history[0].request.headers['Authorization']881+ h2 = r.request.headers['Authorization']882+883+ assert h1 == h2884+885+886 class TestContentEncodingDetection(unittest.TestCase):887 888 def test_none(self):889 encodings = requests.utils.get_encodings_from_content('')319 unmodified lines