Resolve a path before checking its containment
A string prefix is not a filesystem containment check: a sibling named root-backup can share the same prefix as root. Resolve the root and candidate with pathlib, then compare their path ancestry. Absolute names and explicit traversal components should be rejected at the input boundary.
This exercise returns a validated path without opening it. Resolution can follow existing symbolic links, but a later filesystem mutation can create a time-of-check/time-of-use race. Production file serving needs descriptor-based opening or equivalent platform controls; a correct path check by itself is not a race-free sandbox.
from pathlib import Path
root=Path("/tmp/root")
sibling=Path("/tmp/root-backup/file")
print(root in sibling.parents)Review the design
Path containment validation catches structural traversal and existing symlink escapes at resolution time. It does not protect an open performed later from filesystem races; the operating system must enforce the final resource boundary.
Your task
Resolve safe_path(root,name) to an absolute Path inside resolved root. Reject absolute names, any .. path component, backslashes, NUL and resolved paths outside root. Relative ordinary names may identify a missing file. This function validates only; it does not open the path.
The explanation opens here once every check passes.