From 0b41cec7a42682da52a24c87ff6b2c341f101005 Mon Sep 17 00:00:00 2001 From: Chris Adams Date: Tue, 7 Jan 2014 11:34:51 -0500 Subject: [PATCH 1/2] get_netrc_auth: handle os.path.expanduser failure os.path.expanduser can raise a KeyError when $HOME is not set and the POSIX getpwuid() call fails, which can happen when running under a UID which is not in /etc/passwd or when the password file cannot be read. The upstream bug report http://bugs.python.org/issue20164 is unlikely to be backported to Python 2.x even if fixed so this change handles KeyError by skipping netrc authentication. Closes #1846 --- requests/utils.py | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/requests/utils.py b/requests/utils.py index c7e2b089..580e5fc9 100644 --- a/requests/utils.py +++ b/requests/utils.py @@ -64,16 +64,24 @@ def super_len(o): # e.g. BytesIO, cStringIO.StringI return len(o.getvalue()) + def get_netrc_auth(url): """Returns the Requests tuple auth for a given url from netrc.""" try: from netrc import netrc, NetrcParseError - locations = (os.path.expanduser('~/{0}'.format(f)) for f in NETRC_FILES) netrc_path = None - for loc in locations: + for f in NETRC_FILES: + try: + loc = os.path.expanduser('~/{0}'.format(f)) + except KeyError: + # os.path.expanduser can fail when $HOME is undefined and + # getpwuid fails. See http://bugs.python.org/issue20164 & + # https://github.com/kennethreitz/requests/issues/1846 + return + if os.path.exists(loc) and not netrc_path: netrc_path = loc From a80bd7708d620ba1797aed1ca0840996fa137517 Mon Sep 17 00:00:00 2001 From: Chris Adams Date: Tue, 7 Jan 2014 12:23:11 -0500 Subject: [PATCH 2/2] get_netrc_auth: code cleanup * Stop iterating as soon as we find a netrc file * More obvious return None --- requests/utils.py | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/requests/utils.py b/requests/utils.py index 580e5fc9..04e5a2b3 100644 --- a/requests/utils.py +++ b/requests/utils.py @@ -82,12 +82,13 @@ def get_netrc_auth(url): # https://github.com/kennethreitz/requests/issues/1846 return - if os.path.exists(loc) and not netrc_path: + if os.path.exists(loc): netrc_path = loc + break # Abort early if there isn't one. if netrc_path is None: - return netrc_path + return ri = urlparse(url)