Skip to content

Commit f2f4555

Browse files
authored
bpo-10496: posixpath.expanduser() catchs pwd.getpwuid() error (GH-10919)
* posixpath.expanduser() now returns the input path unchanged if the HOME environment variable is not set and pwd.getpwuid() raises KeyError (the current user identifier doesn't exist in the password database). * Add test_no_home_directory() to test_site.
1 parent 398bd27 commit f2f4555

File tree

4 files changed

+99
-30
lines changed

4 files changed

+99
-30
lines changed

‎Lib/posixpath.py‎

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -246,7 +246,12 @@ def expanduser(path):
246246
if i == 1:
247247
if 'HOME' not in os.environ:
248248
import pwd
249-
userhome = pwd.getpwuid(os.getuid()).pw_dir
249+
try:
250+
userhome = pwd.getpwuid(os.getuid()).pw_dir
251+
except KeyError:
252+
# bpo-10496: if the current user identifier doesn't exist in the
253+
# password database, return the path unchanged
254+
return path
250255
else:
251256
userhome = os.environ['HOME']
252257
else:
@@ -257,6 +262,8 @@ def expanduser(path):
257262
try:
258263
pwent = pwd.getpwnam(name)
259264
except KeyError:
265+
# bpo-10496: if the user name from the path doesn't exist in the
266+
# password database, return the path unchanged
260267
return path
261268
userhome = pwent.pw_dir
262269
if isinstance(path, bytes):

‎Lib/test/test_posixpath.py‎

Lines changed: 49 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
from posixpath import realpath, abspath, dirname, basename
66
from test import support, test_genericpath
77
from test.support import FakePath
8+
from unittest import mock
89

910
try:
1011
import posix
@@ -242,42 +243,61 @@ def fake_lstat(path):
242243
def test_expanduser(self):
243244
self.assertEqual(posixpath.expanduser("foo"), "foo")
244245
self.assertEqual(posixpath.expanduser(b"foo"), b"foo")
246+
247+
def test_expanduser_home_envvar(self):
245248
with support.EnvironmentVarGuard() as env:
249+
env['HOME'] = '/home/victor'
250+
self.assertEqual(posixpath.expanduser("~"), "/home/victor")
251+
252+
# expanduser() strips trailing slash
253+
env['HOME'] = '/home/victor/'
254+
self.assertEqual(posixpath.expanduser("~"), "/home/victor")
255+
246256
for home in '/', '', '//', '///':
247257
with self.subTest(home=home):
248258
env['HOME'] = home
249259
self.assertEqual(posixpath.expanduser("~"), "/")
250260
self.assertEqual(posixpath.expanduser("~/"), "/")
251261
self.assertEqual(posixpath.expanduser("~/foo"), "/foo")
252-
try:
253-
import pwd
254-
except ImportError:
255-
pass
256-
else:
257-
self.assertIsInstance(posixpath.expanduser("~/"), str)
258-
self.assertIsInstance(posixpath.expanduser(b"~/"), bytes)
259-
# if home directory == root directory, this test makes no sense
260-
if posixpath.expanduser("~") != '/':
261-
self.assertEqual(
262-
posixpath.expanduser("~") + "/",
263-
posixpath.expanduser("~/")
264-
)
265-
self.assertEqual(
266-
posixpath.expanduser(b"~") + b"/",
267-
posixpath.expanduser(b"~/")
268-
)
269-
self.assertIsInstance(posixpath.expanduser("~root/"), str)
270-
self.assertIsInstance(posixpath.expanduser("~foo/"), str)
271-
self.assertIsInstance(posixpath.expanduser(b"~root/"), bytes)
272-
self.assertIsInstance(posixpath.expanduser(b"~foo/"), bytes)
273-
274-
with support.EnvironmentVarGuard() as env:
275-
# expanduser should fall back to using the password database
276-
del env['HOME']
277-
home = pwd.getpwuid(os.getuid()).pw_dir
278-
# $HOME can end with a trailing /, so strip it (see #17809)
279-
home = home.rstrip("/") or '/'
280-
self.assertEqual(posixpath.expanduser("~"), home)
262+
263+
def test_expanduser_pwd(self):
264+
pwd = support.import_module('pwd')
265+
266+
self.assertIsInstance(posixpath.expanduser("~/"), str)
267+
self.assertIsInstance(posixpath.expanduser(b"~/"), bytes)
268+
269+
# if home directory == root directory, this test makes no sense
270+
if posixpath.expanduser("~") != '/':
271+
self.assertEqual(
272+
posixpath.expanduser("~") + "/",
273+
posixpath.expanduser("~/")
274+
)
275+
self.assertEqual(
276+
posixpath.expanduser(b"~") + b"/",
277+
posixpath.expanduser(b"~/")
278+
)
279+
self.assertIsInstance(posixpath.expanduser("~root/"), str)
280+
self.assertIsInstance(posixpath.expanduser("~foo/"), str)
281+
self.assertIsInstance(posixpath.expanduser(b"~root/"), bytes)
282+
self.assertIsInstance(posixpath.expanduser(b"~foo/"), bytes)
283+
284+
with support.EnvironmentVarGuard() as env:
285+
# expanduser should fall back to using the password database
286+
del env['HOME']
287+
288+
home = pwd.getpwuid(os.getuid()).pw_dir
289+
# $HOME can end with a trailing /, so strip it (see #17809)
290+
home = home.rstrip("/") or '/'
291+
self.assertEqual(posixpath.expanduser("~"), home)
292+
293+
# bpo-10496: If the HOME environment variable is not set and the
294+
# user (current identifier or name in the path) doesn't exist in
295+
# the password database (pwd.getuid() or pwd.getpwnam() fail),
296+
# expanduser() must return the path unchanged.
297+
with mock.patch.object(pwd, 'getpwuid', side_effect=KeyError), \
298+
mock.patch.object(pwd, 'getpwnam', side_effect=KeyError):
299+
for path in ('~', '~/.local', '~vstinner/'):
300+
self.assertEqual(posixpath.expanduser(path), path)
281301

282302
def test_normpath(self):
283303
self.assertEqual(posixpath.normpath(""), ".")

‎Lib/test/test_site.py‎

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
"""
77
import unittest
88
import test.support
9+
from test import support
910
from test.support import (captured_stderr, TESTFN, EnvironmentVarGuard,
1011
change_cwd)
1112
import builtins
@@ -19,6 +20,7 @@
1920
import subprocess
2021
import sysconfig
2122
import tempfile
23+
from unittest import mock
2224
from copy import copy
2325

2426
# These tests are not particularly useful if Python was invoked with -S.
@@ -256,6 +258,7 @@ def test_getusersitepackages(self):
256258
# the call sets USER_BASE *and* USER_SITE
257259
self.assertEqual(site.USER_SITE, user_site)
258260
self.assertTrue(user_site.startswith(site.USER_BASE), user_site)
261+
self.assertEqual(site.USER_BASE, site.getuserbase())
259262

260263
def test_getsitepackages(self):
261264
site.PREFIXES = ['xoxo']
@@ -274,6 +277,40 @@ def test_getsitepackages(self):
274277
wanted = os.path.join('xoxo', 'lib', 'site-packages')
275278
self.assertEqual(dirs[1], wanted)
276279

280+
def test_no_home_directory(self):
281+
# bpo-10496: getuserbase() and getusersitepackages() must not fail if
282+
# the current user has no home directory (if expanduser() returns the
283+
# path unchanged).
284+
site.USER_SITE = None
285+
site.USER_BASE = None
286+
287+
with EnvironmentVarGuard() as environ, \
288+
mock.patch('os.path.expanduser', lambda path: path):
289+
290+
del environ['PYTHONUSERBASE']
291+
del environ['APPDATA']
292+
293+
user_base = site.getuserbase()
294+
self.assertTrue(user_base.startswith('~' + os.sep),
295+
user_base)
296+
297+
user_site = site.getusersitepackages()
298+
self.assertTrue(user_site.startswith(user_base), user_site)
299+
300+
with mock.patch('os.path.isdir', return_value=False) as mock_isdir, \
301+
mock.patch.object(site, 'addsitedir') as mock_addsitedir, \
302+
support.swap_attr(site, 'ENABLE_USER_SITE', True):
303+
304+
# addusersitepackages() must not add user_site to sys.path
305+
# if it is not an existing directory
306+
known_paths = set()
307+
site.addusersitepackages(known_paths)
308+
309+
mock_isdir.assert_called_once_with(user_site)
310+
mock_addsitedir.assert_not_called()
311+
self.assertFalse(known_paths)
312+
313+
277314
class PthFile(object):
278315
"""Helper class for handling testing of .pth files"""
279316

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
:func:`posixpath.expanduser` now returns the input *path* unchanged if the
2+
``HOME`` environment variable is not set and the current user has no home
3+
directory (if the current user identifier doesn't exist in the password
4+
database). This change fix the :mod:`site` module if the current user doesn't
5+
exist in the password database (if the user has no home directory).

0 commit comments

Comments
 (0)