Using pathlib resolve() to contain user-supplied paths
Resolve the trusted base and the user path, then check containment with is_relative_to before reading. This blocks lexical traversal and symlink escapes, but not races after the check.
On this page
Key idea
Resolve both the trusted base and the joined user path, then reject the result unless it is relative to the resolved base. Use strict=True for the base so a missing root fails early; use strict=False for the target when it may not exist yet. This is a containment check, not a sandbox.
Normalize user paths to absolute
The pathlib documentation states that resolve() makes a path absolute, resolves symlinks, and eliminates .. components. That last property matters because joining a user string such as ../secret.txt to a base directory can otherwise leave a path that still points outside the base. Resolve the trusted base first with strict=True so a missing or broken root fails immediately. Then join the user input and resolve the result with strict=False when the target may not exist yet.
Joining an absolute user path discards the base during the / operation, so the containment check must happen after resolution, not before. The same documentation notes that strict=True raises OSError for a missing path or a symlink loop; strict=False resolves as far as possible and appends the remainder without checking existence. Python 3.6 added the strict parameter, and Python 3.13 changed symlink-loop handling to raise OSError.
Verify containment after resolution
After resolution, use target.is_relative_to(base), available since Python 3.9, rather than a string prefix test. A string test on /srv/app would incorrectly accept /srv/app2, while is_relative_to compares path components. The base itself is considered relative to itself, so add a separate file-type or permission check if the operation must target a regular file.
The check must use the resolved base and the resolved target. If the target is a symlink that points outside the base, resolve() follows it and the containment test rejects the result. If the target does not exist, strict=False still produces a normalized path, but the later read or open can raise FileNotFoundError. Treat that as a separate error from a containment violation.
Example workflow for safe file access
The example creates a temporary base, writes one file, and calls safe_read with a normal relative name and with a traversal attempt. It requires Python 3.9 or newer for is_relative_to and uses only the standard library. The base directory exists before resolution. The illustrative output is hello followed by ValueError Path escape detected.
The containment failure is raised before read_text, so the traversal attempt does not read the outside path. The normal call returns the file contents. The code does not prove that the target is a regular file, nor does it close the race between the check and the read.
from pathlib import Path
from tempfile import TemporaryDirectory
def safe_read(base, user_path):
base = Path(base).resolve(strict=True)
target = (base / user_path).resolve(strict=False)
if not target.is_relative_to(base):
raise ValueError("Path escape detected")
return target.read_text(encoding="utf-8")
with TemporaryDirectory() as d:
root = Path(d)
(root / "notes.txt").write_text("hello", encoding="utf-8")
print(safe_read(root, "notes.txt"))
try:
safe_read(root, "../outside.txt")
except ValueError as exc:
print(type(exc).__name__, str(exc))Where this approach does not apply
This pattern does not protect against time-of-check to time-of-use races. After resolve() and is_relative_to() succeed, an attacker who can modify the filesystem can replace a path component with a symlink before read_text() opens it. For hostile local users, use OS-level confinement or descriptor-relative opens with no-follow semantics rather than a path check alone.
It also does not validate file type, permissions, hard links, or content. A hard link inside the base can reference data that also has a name outside the base, and containment does not detect that. Symlink loops are another boundary: strict=True raises OSError, and Python 3.13 and later treat loops as errors, but older non-strict behavior can differ, so test the target Python version. The base itself must be trusted; resolving a user-controlled base only canonicalizes it, it does not make it safe.
Applicability
- Does the trusted base directory exist before resolution?
- Is the runtime Python 3.9 or newer for is_relative_to?
- Can the target legitimately be absent at check time, requiring strict=False?
- Can an attacker modify path components between the containment check and the open?
- Do you need to reject symlinks inside the base, not only escapes outside it?
- Does the application need to reject hard links or non-regular files?
- Are you relying on symlink-loop behavior that differs before Python 3.13?
- Is the base directory itself controlled by a trusted party?
Where this applies
This check is not a sandbox and does not close time-of-check to time-of-use races. It also does not validate file type, permissions, hard links, or content. Use OS-level confinement for hostile users.