Skip to content
Myr

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

3 files+102 added−24 removed

modified:requests/sessions.py+70 added-14 removed
10 unmodified lines
11import os12from collections import Mapping13from datetime import datetime1415from .auth import _basic_auth_str16from .compat import cookielib, OrderedDict, urljoin, urlparse, builtin_str17from .cookies import (18 cookiejar_from_dict, extract_cookies_to_jar, RequestsCookieJar, merge_cookies)19from .models import Request, PreparedRequest, DEFAULT_REDIRECT_LIMIT
3 unmodified lines
23from .structures import CaseInsensitiveDict2425from .adapters import HTTPAdapter2626from .utils import requote_uri, get_environ_proxies, get_netrc_auth27from .utils import (28 requote_uri, get_environ_proxies, get_netrc_auth, should_bypass_proxies,29 get_auth_from_url30)3132from .status_codes import codes3334# formerly defined here, reexposed here for backward compatibility
122 unmodified lines
157 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)160157 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)164163 if (original_parsed.hostname != redirect_parsed.hostname):164 del headers['Authorization']165166 # .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)170165 resp = self.send(166 prepared_request,167 stream=stream,168 timeout=timeout,
7 unmodified lines
176177 i += 1178 yield resp179180 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.url188189 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)194195 if (original_parsed.hostname != redirect_parsed.hostname):196 del headers['Authorization']197198 # .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)202203 return204205 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).212213 This method also replaces the Proxy-Authorization header where214 necessary.215 """216 headers = prepared_request.headers217 url = prepared_request.url218 new_proxies = {}219220 if not should_bypass_proxies(url):221 environ_proxies = get_environ_proxies(url)222 scheme = urlparse(url).scheme223224 proxy = environ_proxies.get(scheme)225226 if proxy:227 new_proxies.setdefault(scheme, environ_proxies[scheme])228229 if 'Proxy-Authorization' in headers:230 del headers['Proxy-Authorization']231232 try:233 username, password = get_auth_from_url(new_proxies[scheme])234 except KeyError:235 username, password = None, None236237 if username and password:238 headers['Proxy-Authorization'] = _basic_auth_str(username, password)239240 return new_proxies241242243class Session(SessionRedirectMixin):244 """A Requests session.245246 Provides cookie persistence, connection-pooling, and configuration.
381 unmodified lines
modified:requests/utils.py+15 added-10 removed
464 unmodified lines
465 return False466 return True467468469def get_environ_proxies(url):470 """Return a dict of environment proxies."""471469def 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())474475 # 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 lines
486 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 True497498 # 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 versions
5 unmodified lines
506 except (TypeError, socket.gaierror):507 bypass = False508509 if bypass:509 return {}510 return True511511 # 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 False513514def get_environ_proxies(url):515 """Return a dict of environment proxies."""516 if should_bypass_proxies(url):517 return {}518 else:519 return getproxies()520521522def default_user_agent(name="python-requests"):523 """Return a string representing the default user agent."""524 _implementation = platform.python_implementation()525
143 unmodified lines
modified:test_requests.py+17 added
15 unmodified lines
16from requests.compat import (17 Morsel, cookielib, getproxies, str, urljoin, urlparse)18from requests.cookies import cookiejar_from_dict, morsel_to_cookie19from requests.exceptions import InvalidURL, MissingSchema20from requests.models import PreparedRequest, Response21from requests.structures import CaseInsensitiveDict2223try:24 import StringIO
840 unmodified lines
865 req = requests.Request('GET', test_url)866 preq = req.prepare()867 assert test_url == preq.url868869 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', '')877878 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']882883 assert h1 == h2884885886class TestContentEncodingDetection(unittest.TestCase):887888 def test_none(self):889 encodings = requests.utils.get_encodings_from_content('')
319 unmodified lines