Respect Permissions and Symbolic Link Boundaries
Core idea
Filesystem access depends on OS policy and credentials. A symbolic link refers to another path, potentially outside the expected root. resolve() follows links and can help inspect a path in a controlled tree; is_symlink() examines the entry. Neither a precheck nor lexical path validation alone prevents races in hostile directories.
from pathlib import Pathfrom tempfile import TemporaryDirectory
with TemporaryDirectory() as folder: root = Path(folder) (root / "sub").mkdir() p = root / "sub" / "report" print(p.resolve().is_relative_to(root.resolve())) print((root / ".." / "outside").resolve().is_relative_to(root.resolve()))Resolved paths distinguish a child from a parent traversal in this controlled fixture.
Handle a failed open
from pathlib import Pathfrom tempfile import TemporaryDirectory
with TemporaryDirectory() as folder: root = Path(folder) try: with (root / "missing").open(encoding="utf-8") as f: f.read() except FileNotFoundError: print("missing") except PermissionError: print("denied")Handle actual errors from the operation; a permissions precheck is not authorization.
Common mistake
Do not demonstrate permission denial by changing real file permissions: administrator privileges and OS rules can change results. For hostile path handling, use platform-specific secure operations and avoid check-then-open races.
Practice
On a system that permits symlinks, create one only inside a private temporary directory targeting another fixture there. Compare is_symlink(), is_file() and resolve(); skip if unsupported.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Filesystem trust boundaries
Check your understanding of permissions and symlinks.
What is printed?
from pathlib import PurePosixPathprint(PurePosixPath("/data2/a").is_relative_to("/data"))What is printed?
from pathlib import Pathfrom tempfile import TemporaryDirectory
with TemporaryDirectory() as folder: root = Path(folder) p=root/"x" p.touch() print(p.is_symlink(), p.is_file())Can a symlink point outside an intended root?
Why is exists() followed by open() not a security guarantee?