PythiloLesson 12 of 12 · progress kept in this browser

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)
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.

All lessons