python / python/cpython

pathlib.Path.copy() can copy a directory into itself via absolute paths or symlinks

Open
#154,690 0 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

stdlib type-bug
Dominant language
Python
Stars
77.2k
Forks
35.9k
PR merge metrics
PR metrics pending

Description

Bug report

Bug description:

Bug report

Path.copy() guards against copying a directory into itself with ensure_distinct_paths(), but the check is lexical only. Relative vs absolute paths and symlink aliases bypass it.

from pathlib import Path
import os

Path('src').mkdir()
(Path('src') / 'f').write_text('hello')

Path('src').copy('src/nested')  # OSError - OK

Path('src').copy(Path('src').resolve() / 'nested')  # succeeds - copies into itself

os.symlink('src', 'link')
Path('src').copy('link/nested')  # also succeeds

Same class of bug as gh-149835 that was fixed with `realpath`, but `pathlib` still uses a lexical comparison.

### CPython versions tested on:

CPython main branch

### Operating systems tested on:

Linux

<!-- gh-linked-prs -->
### Linked PRs
* gh-154689
<!-- /gh-linked-prs -->

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start at pathlib.Path.copy() and its ensure_distinct_paths() check, then reproduce the absolute-path and symlink examples from the issue on Linux. Done means both aliases are rejected as copying a directory into itself, while the existing relative-path behavior remains covered; review linked PR gh-154689 for work already in progress.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
operating-systems
Issue type
Bug
Difficulty
3/5
Estimated time
1-2 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.