Skip to content

Commit 4bfbdbc

Browse files
[3.12] gh-157579: Fix TemporaryDirectory cleanup fallbacks with bytes paths (GH-162116)
Co-authored-by: Stan Ulbrych <stan@python.org> (cherry picked from commit aa17c68)
1 parent 40533a4 commit 4bfbdbc

4 files changed

Lines changed: 180 additions & 9 deletions

File tree

‎Lib/tempfile.py‎

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -948,10 +948,13 @@ def __init__(self, suffix=None, prefix=None, dir=None,
948948
@classmethod
949949
def _rmtree(cls, name, ignore_errors=False, repeated=False, dir_fd=None,
950950
fullname=None):
951-
if fullname is None:
952-
fullname = name
951+
952+
# work with str paths throughout
953+
name = _os.fsdecode(name)
954+
fullname = name if fullname is None else _os.fsdecode(fullname)
953955

954956
def onexc(func, path, exc, direntry=None, dir_fd=None):
957+
path = _os.fsdecode(path)
955958
if isinstance(exc, PermissionError):
956959
if repeated and path == name:
957960
if ignore_errors:

‎Lib/test/test_shutil.py‎

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -568,6 +568,63 @@ def onexc(*args):
568568
self.assertTrue(onexc_called)
569569
self.assertFalse(onerror_called)
570570

571+
@unittest.skipUnless(shutil.rmtree.avoids_symlink_attacks,
572+
'requires the fd based implementation of rmtree()')
573+
def test_onexc_kwargs_dir_fd(self):
574+
os.mkdir(TESTFN)
575+
self.addCleanup(os_helper.rmtree, TESTFN)
576+
top_name = os.path.join(TESTFN, 'top')
577+
child_name = os.path.join(TESTFN, 'top', 'child')
578+
os.mkdir(top_name)
579+
os.mkdir(child_name)
580+
parent_fd = os.open(TESTFN, os.O_RDONLY)
581+
self.addCleanup(os.close, parent_fd)
582+
583+
errors = []
584+
def onexc(func, path, err, direntry=None, dir_fd=None):
585+
errors.append((func, path.replace(os.path.sep, '/')))
586+
name = path if direntry is None else direntry.name
587+
self.assertEqual(name, os.path.basename(path))
588+
self.assertTrue(os.path.samestat(
589+
os.stat(os.path.join(TESTFN, path)),
590+
os.stat(name, dir_fd=dir_fd)))
591+
592+
def failing_rmdir(path, *, dir_fd=None):
593+
raise PermissionError(errno.EACCES, 'simulated')
594+
with unittest.mock.patch('os.rmdir', failing_rmdir):
595+
shutil.rmtree('top', dir_fd=parent_fd, onexc=onexc,
596+
_onexc_kwargs=True)
597+
self.assertEqual(
598+
errors,
599+
[(failing_rmdir, 'top/child'), (failing_rmdir, 'top')])
600+
601+
child_stat = os.stat(child_name)
602+
scandir = os.scandir
603+
604+
# Fail for the top-level directory
605+
errors.clear()
606+
def failing_scandir(fd):
607+
raise PermissionError(errno.EACCES, 'simulated')
608+
with unittest.mock.patch('os.scandir', failing_scandir):
609+
shutil.rmtree('top', dir_fd=parent_fd, onexc=onexc,
610+
_onexc_kwargs=True)
611+
self.assertEqual(
612+
errors,
613+
[(failing_scandir, 'top'), (os.rmdir, 'top')])
614+
self.assertTrue(os.path.exists(top_name))
615+
616+
# Fail for the child (which is empty, so the rmdir succeeds)
617+
errors.clear()
618+
def failing_scandir_2(fd):
619+
if not os.path.samestat(os.fstat(fd), child_stat):
620+
return scandir(fd)
621+
raise PermissionError(errno.EACCES, 'simulated')
622+
with unittest.mock.patch('os.scandir', failing_scandir_2):
623+
shutil.rmtree('top', dir_fd=parent_fd, onexc=onexc,
624+
_onexc_kwargs=True)
625+
self.assertEqual(errors, [(failing_scandir_2, 'top/child')])
626+
self.assertFalse(os.path.exists(top_name))
627+
571628
def test_rmtree_does_not_choke_on_failing_lstat(self):
572629
try:
573630
orig_lstat = os.lstat

‎Lib/test/test_tempfile.py‎

Lines changed: 115 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1623,10 +1623,14 @@ def __exit__(self, *exc_info):
16231623
class TestTemporaryDirectory(BaseTestCase):
16241624
"""Test TemporaryDirectory()."""
16251625

1626-
def do_create(self, dir=None, pre="", suf="", recurse=1, dirs=1, files=1,
1626+
def do_create(self, dir=None, pre=None, suf=None, recurse=1, dirs=1, files=1,
16271627
ignore_cleanup_errors=False):
16281628
if dir is None:
16291629
dir = tempfile.gettempdir()
1630+
if pre is None:
1631+
pre = type(dir)()
1632+
if suf is None:
1633+
suf = type(dir)()
16301634
tmp = tempfile.TemporaryDirectory(
16311635
dir=dir, prefix=pre, suffix=suf,
16321636
ignore_cleanup_errors=ignore_cleanup_errors)
@@ -1636,13 +1640,17 @@ def do_create(self, dir=None, pre="", suf="", recurse=1, dirs=1, files=1,
16361640

16371641
def do_create2(self, path, recurse=1, dirs=1, files=1):
16381642
# Create subdirectories and some files
1643+
def join(name):
1644+
if isinstance(path, bytes):
1645+
name = os.fsencode(name)
1646+
return os.path.join(path, name)
16391647
if recurse:
16401648
for i in range(dirs):
1641-
name = os.path.join(path, "dir%d" % i)
1649+
name = join("dir%d" % i)
16421650
os.mkdir(name)
16431651
self.do_create2(name, recurse-1, dirs, files)
16441652
for i in range(files):
1645-
with open(os.path.join(path, "test%d.txt" % i), "wb") as f:
1653+
with open(join("test%d.txt" % i), "wb") as f:
16461654
f.write(b"Hello world!")
16471655

16481656
def test_mkdtemp_failure(self):
@@ -1668,6 +1676,15 @@ def test_explicit_cleanup(self):
16681676
finally:
16691677
os.rmdir(dir)
16701678

1679+
def test_explicit_cleanup_bytes(self):
1680+
# A TemporaryDirectory with a bytes name is deleted when cleaned up
1681+
with tempfile.TemporaryDirectory() as working_dir:
1682+
d = self.do_create(dir=os.fsencode(working_dir), recurse=2)
1683+
self.assertIsInstance(d.name, bytes)
1684+
self.assertTrue(os.path.exists(d.name))
1685+
d.cleanup()
1686+
self.assertFalse(os.path.exists(d.name))
1687+
16711688
def test_explicit_cleanup_ignore_errors(self):
16721689
"""Test that cleanup doesn't return an error when ignoring them."""
16731690
with tempfile.TemporaryDirectory() as working_dir:
@@ -1880,6 +1897,87 @@ def hook(path, *, dir_fd=None):
18801897
self.assertTrue(os.path.exists(target_file))
18811898
self.assertEqual(os.stat(target_file).st_mode, target_mode)
18821899

1900+
def _make_unopenable_subdir(self):
1901+
# Create the following structure:
1902+
# work/ - top-level
1903+
# <d>/ - tempdir to clean up (random name)
1904+
# sub/ - an unopenable dir
1905+
# subsub/
1906+
# file
1907+
# Return:
1908+
# - `work` name (str)
1909+
# - `d` (TemporaryDirectory)
1910+
# - `subsub` stat result
1911+
work = self.enterContext(os_helper.temp_dir())
1912+
d = tempfile.TemporaryDirectory(dir=work)
1913+
sub = os.path.join(d.name, 'sub')
1914+
subsub = os.path.join(sub, 'subsub')
1915+
os.mkdir(sub)
1916+
os.mkdir(subsub)
1917+
subsub_stat = os.lstat(subsub)
1918+
with open(os.path.join(subsub, 'file'), 'w') as f:
1919+
f.write("rm me pls")
1920+
os.chmod(sub, 0)
1921+
# If the test fails, make sure everything can still be removed.
1922+
self.addCleanup(d.cleanup)
1923+
@self.addCleanup
1924+
def _clean():
1925+
if os.path.isdir(sub):
1926+
os.chmod(sub, 0o700)
1927+
return work, d, subsub_stat
1928+
1929+
@os_helper.skip_unless_working_chmod
1930+
@support.requires_non_root_user
1931+
@unittest.skipUnless(tempfile._rmtree_use_dir_fd
1932+
and shutil.rmtree.avoids_symlink_attacks,
1933+
'requires the fd based cleanup')
1934+
def test_cleanup_nested_toplevel_error(self):
1935+
# rmtree() reports errors relative to the correct parent directory
1936+
work, d, subsub_stat = self._make_unopenable_subdir()
1937+
# An unrelated directory with the same name; should not be touched
1938+
unrelated = os.path.join(work, 'sub')
1939+
os.mkdir(unrelated)
1940+
1941+
rmdir = os.rmdir
1942+
failed_path = None
1943+
def failing_rmdir(path, *, dir_fd=None):
1944+
nonlocal failed_path
1945+
if path == 'sub' and dir_fd is not None and failed_path is None:
1946+
failed_path = path
1947+
raise PermissionError(errno.EPERM, 'simulated', path)
1948+
return rmdir(path, dir_fd=dir_fd)
1949+
with os_helper.change_cwd(work), mock.patch('os.rmdir', failing_rmdir):
1950+
d.cleanup()
1951+
self.assertEqual(failed_path, 'sub')
1952+
self.assertFalse(os.path.exists(d.name))
1953+
self.assertTrue(os.path.exists(unrelated))
1954+
1955+
@os_helper.skip_unless_working_chmod
1956+
@support.requires_non_root_user
1957+
@unittest.skipUnless(tempfile._rmtree_use_dir_fd
1958+
and shutil.rmtree.avoids_symlink_attacks,
1959+
'requires the fd based cleanup')
1960+
def test_cleanup_nested_scandir_error(self):
1961+
# A scandir() error is reported relative to the parent directory.
1962+
work, d, subsub_stat = self._make_unopenable_subdir()
1963+
1964+
scandir = os.scandir
1965+
failed = False
1966+
def failing_scandir(path='.'):
1967+
nonlocal failed
1968+
if (
1969+
not failed
1970+
and isinstance(path, int)
1971+
and os.path.samestat(os.fstat(path), subsub_stat)
1972+
):
1973+
failed = True
1974+
raise PermissionError(errno.EACCES, 'simulated')
1975+
return scandir(path)
1976+
with os_helper.change_cwd(work), mock.patch('os.scandir', failing_scandir):
1977+
d.cleanup()
1978+
self.assertTrue(failed)
1979+
self.assertFalse(os.path.exists(d.name))
1980+
18831981
@support.cpython_only
18841982
def test_del_on_collection(self):
18851983
# A TemporaryDirectory is deleted when garbage collected
@@ -2038,11 +2136,17 @@ def test_context_manager(self):
20382136
self.assertEqual(name, d.name)
20392137
self.assertFalse(os.path.exists(name))
20402138

2041-
def test_modes(self):
2139+
@support.subTests('bytes_name', (False, True))
2140+
def test_modes(self, bytes_name):
20422141
for mode in range(8):
20432142
mode <<= 6
20442143
with self.subTest(mode=format(mode, '03o')):
2045-
d = self.do_create(recurse=3, dirs=2, files=2)
2144+
if bytes_name:
2145+
d = self.do_create(recurse=3, dirs=2, files=2,
2146+
dir=tempfile.gettempdirb())
2147+
else:
2148+
d = self.do_create(recurse=3, dirs=2, files=2)
2149+
self.assertIsInstance(d.name, bytes if bytes_name else str)
20462150
with d:
20472151
# Change files and directories mode recursively.
20482152
for root, dirs, files in os.walk(d.name, topdown=False):
@@ -2053,13 +2157,17 @@ def test_modes(self):
20532157
self.assertFalse(os.path.exists(d.name))
20542158

20552159
@support.subTests('ignore_errors', (True, False))
2056-
def test_parent_mode_preserved(self, ignore_errors):
2160+
@support.subTests('bytes_name', (False, True))
2161+
def test_parent_mode_preserved(self, ignore_errors, bytes_name):
20572162
# Test that cleanup does not touch the parent directory,
20582163
# even if that prevents removal.
20592164
for mode in range(8):
20602165
mode <<= 6
20612166
with self.subTest(mode=format(mode, '03o')):
2062-
outer = self.do_create()
2167+
if bytes_name:
2168+
outer = self.do_create(dir=tempfile.gettempdirb())
2169+
else:
2170+
outer = self.do_create()
20632171
with outer:
20642172
d = self.do_create(dir=outer.name, dirs=2, files=2,
20652173
ignore_cleanup_errors=ignore_errors)
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
The error handler :class:`~tempfile.TemporaryDirectory` uses to clean up
2+
unreadable and inaccessible files no longer fails for temporary directories
3+
created using :class:`bytes` paths.

0 commit comments

Comments
 (0)