Skip to content

🐛 fix(util): make safe_delete's error handler actually run - #3222

Merged
gaborbernat merged 4 commits into
pypa:mainfrom
darrenhuai:fix/safe-delete-onerror
Aug 25, 2026
Merged

gaborbernat merged 4 commits into
pypa:mainfrom
darrenhuai:fix/safe-delete-onerror

Conversation

@darrenhuai

Copy link
Copy Markdown
Contributor

Thanks for contributing, make sure you address all the checklists (for details on how see development documentation)

  • ran the linter to address style issues (tox -e fix)
  • wrote descriptive pull request text
  • ensured there are test(s) validating the fix
  • added news fragment in docs/changelog folder
  • updated/extended the documentation

safe_delete hands shutil.rmtree a chmod-and-retry handler and sets ignore_errors=True at the same time:

def onerror(func, path, exc_info):
    if not os.access(path, os.W_OK):
        os.chmod(path, S_IWUSR)
        func(path)
    else:
        raise

shutil.rmtree(str(dest), ignore_errors=True, onexc=onerror)

rmtree overwrites whatever handler it is given when ignore_errors is set — onexc = _onexc = lambda *args: None — so this handler has never run. Every deletion failure was swallowed and safe_delete returned as if it had worked.

That matters on Windows, where the read-only attribute blocks os.unlink, and virtualenv marks every file in a wheel image read-only itself via set_tree. So:

  • --reset-app-data kept the image trees it reported removing
  • recreating an env with --clear could leave read-only files from the old one behind
  • replacing a seed package could leave a mix of old and new files

I found this by asking what the # ty: ignore[call-non-callable] on the func(path) line was hiding. The suppression was there because func is annotated object, and func is annotated object because nothing ever called it. Before the fix, on Windows, rmtree left the tree in place and the handler was invoked zero times.

Dropping ignore_errors lets the handler do what it was written to do: clear the read-only bit, retry, and surface anything it genuinely cannot delete instead of pretending the delete succeeded. Typing func properly removes the ty suppression — ty check src/virtualenv still passes without it.

One caller needed a guard. AppDataDiskFolder.reset is the only one that calls safe_delete without an exists() check first, so a missing directory used to be absorbed by ignore_errors. onerror now returns early on FileNotFoundError to keep that a no-op.

Three tests: a read-only tree is actually removed, a missing path stays a no-op, and an undeletable entry now raises instead of being swallowed. The first and third fail on main. The third is Windows-only, since it needs an open file handle to block deletion; the first passes on POSIX either way, because there deleting a file depends on the parent directory's permissions rather than the file's own.

tests/unit is green locally on Windows / 3.13 (296 passed, 31 skipped), along with ruff and ty.

darrenhuai and others added 4 commits August 24, 2026 18:44
safe_delete passes a chmod-and-retry handler to shutil.rmtree while
also setting ignore_errors=True — and rmtree unconditionally replaces
any handler with a no-op when ignore_errors is set, so the handler has
never run. Every deletion failure was silently swallowed instead.

This matters most on Windows, where the read-only attribute blocks
os.unlink, and virtualenv itself marks every wheel-image file read-only
via set_tree. So --reset-app-data quietly kept the image trees it
claimed to remove, recreating an environment with --clear could leave
read-only files from the old one behind, and uninstalling a previous
seed package could leave a mix of old and new files. Found by asking
what the ty: ignore[call-non-callable] on the retry call was hiding;
reproduced on Windows before the fix (rmtree left the tree, handler
invoked zero times).

Dropping ignore_errors lets the handler do what it was written to do:
clear the read-only bit and retry, and surface anything it cannot fix
instead of pretending the delete worked. A FileNotFoundError guard
keeps AppDataDiskFolder.reset a no-op when nothing was ever cached —
the one caller without an exists() check. Typing func as a real
callable removes the ty suppression that was papering over all this.
Now that the handler runs, its retry is reachable - and rmtree does not
only report os.unlink and os.rmdir. On Linux and macOS it deletes
through directory file descriptors and reports os.open, so func(path)
raised "TypeError: open() missing required argument 'flags'" on top of
the PermissionError that caused it. os.scandir and os.lstat take a lone
path but delete nothing, so retrying one of those returned from the
handler and told rmtree the failure was dealt with - the swallowing this
fix set out to remove, through another door.

Retry only the two callables a path can replay and re-raise the rest.
Clearing the read-only bit now keeps the other mode bits instead of
replacing the mode with S_IWUSR, which left a directory at 0o200 -
neither listable nor traversable - whenever the retry went on to fail.

Both new tests are POSIX-only and fail before this change: the first on
TypeError instead of PermissionError, the second on the discarded mode.
@gaborbernat
gaborbernat enabled auto-merge (squash) August 25, 2026 04:08
@gaborbernat
gaborbernat merged commit a48bf4b into pypa:main Aug 25, 2026
57 checks passed
halstead pushed a commit to openembedded/meta-openembedded that referenced this pull request Nov 10, 2026
Analysis:
- The advisory [1] describes a deletion-error callback changing the
  permissions of a symlink target.
- In 21.2.1, safe_delete() always passes ignore_errors=True to
  shutil.rmtree(), which disables the supplied error callback.
  This remains true after the existing security backports.
- Upstream enabled that callback later in [2]. The chmod recovery
  path fixed by [3] is therefore unreachable in this recipe.

Reference:
[1] GHSA-43mp-35q3-x3fq
[2] pypa/virtualenv#3222
[3] pypa/virtualenv@2bfdc02

Signed-off-by: Hetvi Thakar <[email protected]>
Signed-off-by: Anuj Mittal <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants