How can I check that a relative input path points inside my sample folder?
Quick answer
Resolve the sample folder, join it with the user’s relative input, and resolve the result. Then use relative_to() to check whether the resolved candidate is inside the resolved folder; reject it if that raises ValueError. For an input that must already exist, use strict resolution. This helps catch .. traversal and symlinks pointing outside, but the check alone is not a complete security boundary.
The question, the details, the next step.
A practical checklist
Resolve the intended sample directory and confirm it exists.
Join the relative user input to that directory, then resolve the candidate before checking containment.
Reject absolute inputs if the interface requires relative paths.
Reject the candidate when
relative_to(sample_dir)raisesValueError.Use strict resolution when the requested input must already exist, and handle resolution errors.
Do not treat check-then-open as race-free protection if filesystem contents may change.
A few more useful answers
Why not check whether the input string starts with the sample folder name?
String prefixes compare spelling, not resolved filesystem locations. Resolve the paths and check their path relationship instead. [S1]
What does `strict=True` do in this example?
It makes resolution require the path to exist, which fits an existing input. If it does not exist, resolution fails, so the example rejects it. [S1]
Does this validate that the candidate is a file?
No. It checks whether the resolved candidate is inside the sample directory. Add a separate file-type check if your task requires a regular file.
Sources
References used for this guide.
- [S1] Python 3.15 pathlib: resolving and comparing filesystem paths docs.python.org · Checked
